diff --git a/CMakeLists.txt b/CMakeLists.txt index d94444a85..9c4ad49ca 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -237,6 +237,7 @@ set(DUCKDB_SRC_FILES src/duckdb/src/main/extension/linked_extension_registry.cpp src/duckdb/src/main/http/http_client_httplib.cpp src/duckdb/src/optimizer/matcher/expression_matcher.cpp + src/duckdb/src/storage/block_allocator/block_allocator.cpp src/duckdb/third_party/brotli/common/constants.cpp src/duckdb/third_party/brotli/common/context.cpp src/duckdb/third_party/brotli/common/dictionary.cpp @@ -461,6 +462,7 @@ set(DUCKDB_SRC_FILES src/duckdb/ub_src_main_settings.cpp src/duckdb/ub_src_optimizer.cpp src/duckdb/ub_src_optimizer_compressed_materialization.cpp + src/duckdb/ub_src_optimizer_duplicate_eliminated_domain.cpp src/duckdb/ub_src_optimizer_join_order.cpp src/duckdb/ub_src_optimizer_pullup.cpp src/duckdb/ub_src_optimizer_pushdown.cpp diff --git a/duckdb_java.def b/duckdb_java.def index a230f3450..9853509ec 100644 --- a/duckdb_java.def +++ b/duckdb_java.def @@ -835,6 +835,7 @@ duckdb_v2_aggregate_function_finalize_get_state_count duckdb_v2_aggregate_function_finalize_get_states duckdb_v2_aggregate_function_finalize_get_user_data duckdb_v2_aggregate_function_get_docs +duckdb_v2_aggregate_function_get_generic_property duckdb_v2_aggregate_function_get_signature duckdb_v2_aggregate_function_init_get_bind_data duckdb_v2_aggregate_function_init_get_state_count @@ -844,15 +845,22 @@ duckdb_v2_aggregate_function_set_bind_callback duckdb_v2_aggregate_function_set_combine_callback duckdb_v2_aggregate_function_set_destroy_callback duckdb_v2_aggregate_function_set_finalize_callback +duckdb_v2_aggregate_function_set_generic_property duckdb_v2_aggregate_function_set_init_callback duckdb_v2_aggregate_function_set_name duckdb_v2_aggregate_function_set_property duckdb_v2_aggregate_function_set_size_callback +duckdb_v2_aggregate_function_set_stats_callback duckdb_v2_aggregate_function_set_update_callback duckdb_v2_aggregate_function_set_user_data duckdb_v2_aggregate_function_size_get_bind_data duckdb_v2_aggregate_function_size_get_user_data duckdb_v2_aggregate_function_size_set_state_size +duckdb_v2_aggregate_function_stats_get_arg_count +duckdb_v2_aggregate_function_stats_get_arg_stats +duckdb_v2_aggregate_function_stats_get_bind_data +duckdb_v2_aggregate_function_stats_get_result_stats +duckdb_v2_aggregate_function_stats_get_user_data duckdb_v2_aggregate_function_update_get_arg duckdb_v2_aggregate_function_update_get_arg_count duckdb_v2_aggregate_function_update_get_bind_data @@ -886,16 +894,11 @@ duckdb_v2_bignum_decode duckdb_v2_bignum_encode duckdb_v2_cast_function_create duckdb_v2_cast_function_destroy -duckdb_v2_cast_function_exec_get_input -duckdb_v2_cast_function_exec_get_mode -duckdb_v2_cast_function_exec_get_output -duckdb_v2_cast_function_exec_get_row_count -duckdb_v2_cast_function_exec_get_user_data -duckdb_v2_cast_function_set_exec_callback +duckdb_v2_cast_function_set_function duckdb_v2_cast_function_set_implicit_cast_cost duckdb_v2_cast_function_set_source_type duckdb_v2_cast_function_set_target_type -duckdb_v2_cast_function_set_user_data +duckdb_v2_cast_function_set_try_function duckdb_v2_column_data_collection_append duckdb_v2_column_data_collection_append_state_create duckdb_v2_column_data_collection_append_state_destroy @@ -922,15 +925,22 @@ duckdb_v2_config_get_option_value duckdb_v2_config_set_option_text duckdb_v2_config_set_option_value duckdb_v2_connection_create +duckdb_v2_connection_create_in_transaction +duckdb_v2_connection_create_secret duckdb_v2_connection_describe_table duckdb_v2_connection_destroy duckdb_v2_connection_enable_profiling duckdb_v2_connection_get_config duckdb_v2_connection_get_factory duckdb_v2_connection_get_file_system +duckdb_v2_connection_get_or_create_state +duckdb_v2_connection_get_profiling_information duckdb_v2_connection_get_query_metrics +duckdb_v2_connection_get_secret_by_name +duckdb_v2_connection_get_state duckdb_v2_connection_interrupt duckdb_v2_connection_log +duckdb_v2_connection_lookup_secret duckdb_v2_connection_progress_get duckdb_v2_connection_register_aggregate_function duckdb_v2_connection_register_cast_function @@ -941,11 +951,28 @@ duckdb_v2_connection_register_multi_file_function duckdb_v2_connection_register_pragma_function duckdb_v2_connection_register_replacement_scan duckdb_v2_connection_register_scalar_function +duckdb_v2_connection_register_secret_function duckdb_v2_connection_register_table_function +duckdb_v2_connection_remove_state +duckdb_v2_context_create_secret duckdb_v2_context_get_config duckdb_v2_context_get_factory duckdb_v2_context_get_file_system +duckdb_v2_context_get_object_cache +duckdb_v2_context_get_or_create_state +duckdb_v2_context_get_secret_by_name +duckdb_v2_context_get_state duckdb_v2_context_log +duckdb_v2_context_lookup_secret +duckdb_v2_context_remove_state +duckdb_v2_context_state_profile_write +duckdb_v2_context_state_set_profiling_callback +duckdb_v2_context_state_set_query_begin_callback +duckdb_v2_context_state_set_query_end_callback +duckdb_v2_context_state_set_transaction_begin_callback +duckdb_v2_context_state_set_transaction_commit_callback +duckdb_v2_context_state_set_transaction_rollback_callback +duckdb_v2_context_state_set_user_data duckdb_v2_copy_from_bind_get_column_count duckdb_v2_copy_from_bind_get_column_name duckdb_v2_copy_from_bind_get_column_type @@ -957,6 +984,7 @@ duckdb_v2_copy_from_bind_get_user_data duckdb_v2_copy_from_bind_set_bind_data duckdb_v2_copy_from_bind_set_cardinality duckdb_v2_copy_from_set_bind_callback +duckdb_v2_copy_from_set_data_source duckdb_v2_copy_function_create duckdb_v2_copy_function_destroy duckdb_v2_copy_function_set_file_extension @@ -1002,6 +1030,28 @@ duckdb_v2_copy_to_statistics_get_init_data duckdb_v2_copy_to_statistics_get_user_data duckdb_v2_copy_to_statistics_set_file_size duckdb_v2_copy_to_statistics_set_row_count +duckdb_v2_crypto_cipher_create +duckdb_v2_crypto_cipher_destroy +duckdb_v2_crypto_cipher_finalize +duckdb_v2_crypto_cipher_init +duckdb_v2_crypto_cipher_update +duckdb_v2_crypto_hash +duckdb_v2_crypto_hash_digest_size +duckdb_v2_crypto_hmac +duckdb_v2_crypto_provider_create +duckdb_v2_crypto_provider_destroy +duckdb_v2_crypto_provider_set_cipher_create_callback +duckdb_v2_crypto_provider_set_cipher_destroy_callback +duckdb_v2_crypto_provider_set_cipher_finalize_callback +duckdb_v2_crypto_provider_set_cipher_init_callback +duckdb_v2_crypto_provider_set_cipher_update_callback +duckdb_v2_crypto_provider_set_hash_callback +duckdb_v2_crypto_provider_set_hmac_callback +duckdb_v2_crypto_provider_set_random_callback +duckdb_v2_crypto_provider_set_user_data +duckdb_v2_crypto_random_bytes +duckdb_v2_crypto_supports_hash +duckdb_v2_crypto_supports_hmac duckdb_v2_custom_option_create duckdb_v2_custom_option_destroy duckdb_v2_custom_option_set_default_scope @@ -1029,6 +1079,60 @@ duckdb_v2_data_chunk_get_capacity duckdb_v2_data_chunk_get_size duckdb_v2_data_chunk_get_vector duckdb_v2_data_chunk_get_vector_count +duckdb_v2_data_source_claim_batch_get_bind_data +duckdb_v2_data_source_claim_batch_get_global_state +duckdb_v2_data_source_claim_batch_get_local_state +duckdb_v2_data_source_claim_batch_get_user_data +duckdb_v2_data_source_claim_batch_set_claimed +duckdb_v2_data_source_create +duckdb_v2_data_source_destroy +duckdb_v2_data_source_exec_add_task +duckdb_v2_data_source_exec_get_bind_data +duckdb_v2_data_source_exec_get_column_count +duckdb_v2_data_source_exec_get_column_index +duckdb_v2_data_source_exec_get_global_state +duckdb_v2_data_source_exec_get_local_state +duckdb_v2_data_source_exec_get_output_chunk +duckdb_v2_data_source_exec_get_user_data +duckdb_v2_data_source_exec_set_result +duckdb_v2_data_source_init_global_get_bind_data +duckdb_v2_data_source_init_global_get_column_count +duckdb_v2_data_source_init_global_get_column_index +duckdb_v2_data_source_init_global_get_user_data +duckdb_v2_data_source_init_global_set_global_state +duckdb_v2_data_source_init_global_set_max_threads +duckdb_v2_data_source_init_local_get_bind_data +duckdb_v2_data_source_init_local_get_column_count +duckdb_v2_data_source_init_local_get_column_index +duckdb_v2_data_source_init_local_get_global_state +duckdb_v2_data_source_init_local_get_user_data +duckdb_v2_data_source_init_local_set_local_state +duckdb_v2_data_source_metrics_get_bind_data +duckdb_v2_data_source_metrics_get_global_state +duckdb_v2_data_source_metrics_get_user_data +duckdb_v2_data_source_metrics_set +duckdb_v2_data_source_partition_data_get_bind_data +duckdb_v2_data_source_partition_data_get_global_state +duckdb_v2_data_source_partition_data_get_local_state +duckdb_v2_data_source_partition_data_get_partition_column_count +duckdb_v2_data_source_partition_data_get_partition_column_index +duckdb_v2_data_source_partition_data_get_user_data +duckdb_v2_data_source_partition_data_requires_batch_index +duckdb_v2_data_source_partition_data_requires_partition_columns +duckdb_v2_data_source_partition_data_set_batch_index +duckdb_v2_data_source_partition_data_set_partition_value +duckdb_v2_data_source_progress_get_bind_data +duckdb_v2_data_source_progress_get_global_state +duckdb_v2_data_source_progress_get_user_data +duckdb_v2_data_source_progress_set_progress +duckdb_v2_data_source_set_claim_batch_callback +duckdb_v2_data_source_set_exec_callback +duckdb_v2_data_source_set_init_global_callback +duckdb_v2_data_source_set_init_local_callback +duckdb_v2_data_source_set_metrics_callback +duckdb_v2_data_source_set_partition_data_callback +duckdb_v2_data_source_set_progress_callback +duckdb_v2_data_source_set_user_data duckdb_v2_environment_create duckdb_v2_environment_destroy duckdb_v2_environment_get_instance_count @@ -1039,6 +1143,7 @@ duckdb_v2_error_info_get_text duckdb_v2_error_info_set_code duckdb_v2_error_info_set_text duckdb_v2_expression_cast_get_mode +duckdb_v2_expression_check_statistics duckdb_v2_expression_column_ref_get_index duckdb_v2_expression_constant_get_value duckdb_v2_expression_function_get_name @@ -1050,6 +1155,7 @@ duckdb_v2_expression_get_type duckdb_v2_extension_register_aggregate_function duckdb_v2_extension_register_cast_function duckdb_v2_extension_register_copy_function +duckdb_v2_extension_register_crypto_provider duckdb_v2_extension_register_custom_option duckdb_v2_extension_register_custom_type duckdb_v2_extension_register_log_sink @@ -1058,6 +1164,7 @@ duckdb_v2_extension_register_multi_file_function duckdb_v2_extension_register_pragma_function duckdb_v2_extension_register_replacement_scan duckdb_v2_extension_register_scalar_function +duckdb_v2_extension_register_secret_function duckdb_v2_extension_register_table_function duckdb_v2_factory_create_common_type duckdb_v2_factory_create_type_from_id @@ -1106,7 +1213,10 @@ duckdb_v2_instance_detach duckdb_v2_instance_get_config duckdb_v2_instance_get_factory duckdb_v2_instance_get_file_system +duckdb_v2_instance_get_object_cache duckdb_v2_instance_log +duckdb_v2_instance_open_shared +duckdb_v2_instance_register_crypto_provider duckdb_v2_instance_register_log_sink duckdb_v2_instance_register_replacement_scan duckdb_v2_instance_set_default @@ -1141,6 +1251,40 @@ duckdb_v2_multi_file_function_set_file_extension duckdb_v2_multi_file_function_set_name duckdb_v2_multi_file_function_set_reader_type duckdb_v2_multi_file_function_set_single_file_function +duckdb_v2_object_cache_delete +duckdb_v2_object_cache_entry_destroy +duckdb_v2_object_cache_entry_get_data +duckdb_v2_object_cache_get +duckdb_v2_object_cache_get_or_create +duckdb_v2_object_cache_put +duckdb_v2_operator_create +duckdb_v2_operator_destroy +duckdb_v2_operator_execute_get_bind_data +duckdb_v2_operator_execute_get_global_state +duckdb_v2_operator_execute_get_input_chunk +duckdb_v2_operator_execute_get_local_state +duckdb_v2_operator_execute_get_output_chunk +duckdb_v2_operator_execute_get_user_data +duckdb_v2_operator_execute_set_result +duckdb_v2_operator_finalize_get_bind_data +duckdb_v2_operator_finalize_get_global_state +duckdb_v2_operator_finalize_get_local_state +duckdb_v2_operator_finalize_get_output_chunk +duckdb_v2_operator_finalize_get_user_data +duckdb_v2_operator_finalize_set_have_more_output +duckdb_v2_operator_init_global_get_bind_data +duckdb_v2_operator_init_global_get_user_data +duckdb_v2_operator_init_global_set_global_state +duckdb_v2_operator_init_global_set_max_threads +duckdb_v2_operator_init_local_get_bind_data +duckdb_v2_operator_init_local_get_global_state +duckdb_v2_operator_init_local_get_user_data +duckdb_v2_operator_init_local_set_local_state +duckdb_v2_operator_set_execute_callback +duckdb_v2_operator_set_finalize_callback +duckdb_v2_operator_set_init_global_callback +duckdb_v2_operator_set_init_local_callback +duckdb_v2_operator_set_user_data duckdb_v2_option_destroy duckdb_v2_option_get_alias duckdb_v2_option_get_alias_count @@ -1202,7 +1346,10 @@ duckdb_v2_result_get_statement_type duckdb_v2_result_render_box duckdb_v2_result_step duckdb_v2_result_wait +duckdb_v2_scalar_function_bind_replace_call +duckdb_v2_scalar_function_bind_set_argument_monotonicity duckdb_v2_scalar_function_bind_set_bind_data +duckdb_v2_scalar_function_bind_set_property duckdb_v2_scalar_function_create duckdb_v2_scalar_function_destroy duckdb_v2_scalar_function_exec_get_arg @@ -1213,21 +1360,53 @@ duckdb_v2_scalar_function_exec_get_result duckdb_v2_scalar_function_exec_get_row_count duckdb_v2_scalar_function_exec_get_user_data duckdb_v2_scalar_function_get_docs +duckdb_v2_scalar_function_get_generic_property duckdb_v2_scalar_function_get_signature duckdb_v2_scalar_function_init_get_bind_data duckdb_v2_scalar_function_init_get_user_data duckdb_v2_scalar_function_init_set_init_data duckdb_v2_scalar_function_resolve_types_set_return_type +duckdb_v2_scalar_function_set_argument_monotonicity duckdb_v2_scalar_function_set_bind_callback duckdb_v2_scalar_function_set_exec_callback +duckdb_v2_scalar_function_set_generic_property duckdb_v2_scalar_function_set_init_callback duckdb_v2_scalar_function_set_name duckdb_v2_scalar_function_set_property duckdb_v2_scalar_function_set_resolve_types_callback +duckdb_v2_scalar_function_set_schema +duckdb_v2_scalar_function_set_stats_callback duckdb_v2_scalar_function_set_user_data +duckdb_v2_scalar_function_stats_get_arg_count +duckdb_v2_scalar_function_stats_get_arg_stats +duckdb_v2_scalar_function_stats_get_bind_data +duckdb_v2_scalar_function_stats_get_result_stats +duckdb_v2_scalar_function_stats_get_user_data duckdb_v2_schema_destroy duckdb_v2_schema_get_count duckdb_v2_schema_get_field +duckdb_v2_secret_add_redacted_key +duckdb_v2_secret_add_scope +duckdb_v2_secret_clear_scope +duckdb_v2_secret_create +duckdb_v2_secret_destroy +duckdb_v2_secret_function_add_named_parameter +duckdb_v2_secret_function_create +duckdb_v2_secret_function_destroy +duckdb_v2_secret_function_set_create_callback +duckdb_v2_secret_function_set_default +duckdb_v2_secret_function_set_provider +duckdb_v2_secret_function_set_type +duckdb_v2_secret_function_set_user_data +duckdb_v2_secret_get_key +duckdb_v2_secret_get_key_count +duckdb_v2_secret_get_property +duckdb_v2_secret_get_scope +duckdb_v2_secret_get_scope_count +duckdb_v2_secret_get_value +duckdb_v2_secret_is_key_redacted +duckdb_v2_secret_set_property +duckdb_v2_secret_set_value duckdb_v2_sql_statement_destroy duckdb_v2_sql_statement_get_parameter_count duckdb_v2_sql_statement_get_parameter_name @@ -1239,12 +1418,26 @@ duckdb_v2_statement_execute duckdb_v2_statement_execute_arrow duckdb_v2_statement_iterator_destroy duckdb_v2_statement_iterator_next +duckdb_v2_stats_assign +duckdb_v2_stats_can_have_null +duckdb_v2_stats_can_have_valid +duckdb_v2_stats_create +duckdb_v2_stats_destroy +duckdb_v2_stats_get_value +duckdb_v2_stats_merge +duckdb_v2_stats_set_can_have_null +duckdb_v2_stats_set_can_have_valid +duckdb_v2_stats_set_value duckdb_v2_table_description_destroy duckdb_v2_table_description_get_column duckdb_v2_table_description_get_column_count duckdb_v2_table_description_get_qname duckdb_v2_table_description_is_readonly +duckdb_v2_table_function_add_virtual_column duckdb_v2_table_function_bind_add_result_column +duckdb_v2_table_function_bind_get_input_column_count +duckdb_v2_table_function_bind_get_input_column_name +duckdb_v2_table_function_bind_get_input_column_type duckdb_v2_table_function_bind_set_cardinality duckdb_v2_table_function_bind_set_order_preservation duckdb_v2_table_function_create @@ -1268,12 +1461,24 @@ duckdb_v2_table_function_partitioning_get_partition_column_index duckdb_v2_table_function_partitioning_get_user_data duckdb_v2_table_function_partitioning_set_partition_info duckdb_v2_table_function_set_bind_callback +duckdb_v2_table_function_set_data_source duckdb_v2_table_function_set_filter_pushdown_callback duckdb_v2_table_function_set_get_bind_info_callback duckdb_v2_table_function_set_name +duckdb_v2_table_function_set_operator duckdb_v2_table_function_set_partitioning_callback duckdb_v2_table_function_set_projection_pushdown +duckdb_v2_table_function_set_property +duckdb_v2_table_function_set_stats_callback +duckdb_v2_table_function_set_to_string_callback duckdb_v2_table_function_set_user_data +duckdb_v2_table_function_stats_get_bind_data +duckdb_v2_table_function_stats_get_column_index +duckdb_v2_table_function_stats_get_result_stats +duckdb_v2_table_function_stats_get_user_data +duckdb_v2_table_function_to_string_get_bind_data +duckdb_v2_table_function_to_string_get_user_data +duckdb_v2_table_function_to_string_set duckdb_v2_token_iterator_destroy duckdb_v2_token_iterator_ends_unterminated duckdb_v2_token_iterator_next @@ -1352,6 +1557,7 @@ duckdb_v2_value_get_uuid duckdb_v2_value_get_varchar duckdb_v2_value_is_null duckdb_v2_value_to_string +duckdb_v2_value_variant_to_value duckdb_v2_vector_cast duckdb_v2_vector_constant_set_valid duckdb_v2_vector_flat_get_validity_mutable diff --git a/duckdb_java.exp b/duckdb_java.exp index 0b735fff5..b466789e5 100644 --- a/duckdb_java.exp +++ b/duckdb_java.exp @@ -832,6 +832,7 @@ _duckdb_v2_aggregate_function_finalize_get_state_count _duckdb_v2_aggregate_function_finalize_get_states _duckdb_v2_aggregate_function_finalize_get_user_data _duckdb_v2_aggregate_function_get_docs +_duckdb_v2_aggregate_function_get_generic_property _duckdb_v2_aggregate_function_get_signature _duckdb_v2_aggregate_function_init_get_bind_data _duckdb_v2_aggregate_function_init_get_state_count @@ -841,15 +842,22 @@ _duckdb_v2_aggregate_function_set_bind_callback _duckdb_v2_aggregate_function_set_combine_callback _duckdb_v2_aggregate_function_set_destroy_callback _duckdb_v2_aggregate_function_set_finalize_callback +_duckdb_v2_aggregate_function_set_generic_property _duckdb_v2_aggregate_function_set_init_callback _duckdb_v2_aggregate_function_set_name _duckdb_v2_aggregate_function_set_property _duckdb_v2_aggregate_function_set_size_callback +_duckdb_v2_aggregate_function_set_stats_callback _duckdb_v2_aggregate_function_set_update_callback _duckdb_v2_aggregate_function_set_user_data _duckdb_v2_aggregate_function_size_get_bind_data _duckdb_v2_aggregate_function_size_get_user_data _duckdb_v2_aggregate_function_size_set_state_size +_duckdb_v2_aggregate_function_stats_get_arg_count +_duckdb_v2_aggregate_function_stats_get_arg_stats +_duckdb_v2_aggregate_function_stats_get_bind_data +_duckdb_v2_aggregate_function_stats_get_result_stats +_duckdb_v2_aggregate_function_stats_get_user_data _duckdb_v2_aggregate_function_update_get_arg _duckdb_v2_aggregate_function_update_get_arg_count _duckdb_v2_aggregate_function_update_get_bind_data @@ -883,16 +891,11 @@ _duckdb_v2_bignum_decode _duckdb_v2_bignum_encode _duckdb_v2_cast_function_create _duckdb_v2_cast_function_destroy -_duckdb_v2_cast_function_exec_get_input -_duckdb_v2_cast_function_exec_get_mode -_duckdb_v2_cast_function_exec_get_output -_duckdb_v2_cast_function_exec_get_row_count -_duckdb_v2_cast_function_exec_get_user_data -_duckdb_v2_cast_function_set_exec_callback +_duckdb_v2_cast_function_set_function _duckdb_v2_cast_function_set_implicit_cast_cost _duckdb_v2_cast_function_set_source_type _duckdb_v2_cast_function_set_target_type -_duckdb_v2_cast_function_set_user_data +_duckdb_v2_cast_function_set_try_function _duckdb_v2_column_data_collection_append _duckdb_v2_column_data_collection_append_state_create _duckdb_v2_column_data_collection_append_state_destroy @@ -919,15 +922,22 @@ _duckdb_v2_config_get_option_value _duckdb_v2_config_set_option_text _duckdb_v2_config_set_option_value _duckdb_v2_connection_create +_duckdb_v2_connection_create_in_transaction +_duckdb_v2_connection_create_secret _duckdb_v2_connection_describe_table _duckdb_v2_connection_destroy _duckdb_v2_connection_enable_profiling _duckdb_v2_connection_get_config _duckdb_v2_connection_get_factory _duckdb_v2_connection_get_file_system +_duckdb_v2_connection_get_or_create_state +_duckdb_v2_connection_get_profiling_information _duckdb_v2_connection_get_query_metrics +_duckdb_v2_connection_get_secret_by_name +_duckdb_v2_connection_get_state _duckdb_v2_connection_interrupt _duckdb_v2_connection_log +_duckdb_v2_connection_lookup_secret _duckdb_v2_connection_progress_get _duckdb_v2_connection_register_aggregate_function _duckdb_v2_connection_register_cast_function @@ -938,11 +948,28 @@ _duckdb_v2_connection_register_multi_file_function _duckdb_v2_connection_register_pragma_function _duckdb_v2_connection_register_replacement_scan _duckdb_v2_connection_register_scalar_function +_duckdb_v2_connection_register_secret_function _duckdb_v2_connection_register_table_function +_duckdb_v2_connection_remove_state +_duckdb_v2_context_create_secret _duckdb_v2_context_get_config _duckdb_v2_context_get_factory _duckdb_v2_context_get_file_system +_duckdb_v2_context_get_object_cache +_duckdb_v2_context_get_or_create_state +_duckdb_v2_context_get_secret_by_name +_duckdb_v2_context_get_state _duckdb_v2_context_log +_duckdb_v2_context_lookup_secret +_duckdb_v2_context_remove_state +_duckdb_v2_context_state_profile_write +_duckdb_v2_context_state_set_profiling_callback +_duckdb_v2_context_state_set_query_begin_callback +_duckdb_v2_context_state_set_query_end_callback +_duckdb_v2_context_state_set_transaction_begin_callback +_duckdb_v2_context_state_set_transaction_commit_callback +_duckdb_v2_context_state_set_transaction_rollback_callback +_duckdb_v2_context_state_set_user_data _duckdb_v2_copy_from_bind_get_column_count _duckdb_v2_copy_from_bind_get_column_name _duckdb_v2_copy_from_bind_get_column_type @@ -954,6 +981,7 @@ _duckdb_v2_copy_from_bind_get_user_data _duckdb_v2_copy_from_bind_set_bind_data _duckdb_v2_copy_from_bind_set_cardinality _duckdb_v2_copy_from_set_bind_callback +_duckdb_v2_copy_from_set_data_source _duckdb_v2_copy_function_create _duckdb_v2_copy_function_destroy _duckdb_v2_copy_function_set_file_extension @@ -999,6 +1027,28 @@ _duckdb_v2_copy_to_statistics_get_init_data _duckdb_v2_copy_to_statistics_get_user_data _duckdb_v2_copy_to_statistics_set_file_size _duckdb_v2_copy_to_statistics_set_row_count +_duckdb_v2_crypto_cipher_create +_duckdb_v2_crypto_cipher_destroy +_duckdb_v2_crypto_cipher_finalize +_duckdb_v2_crypto_cipher_init +_duckdb_v2_crypto_cipher_update +_duckdb_v2_crypto_hash +_duckdb_v2_crypto_hash_digest_size +_duckdb_v2_crypto_hmac +_duckdb_v2_crypto_provider_create +_duckdb_v2_crypto_provider_destroy +_duckdb_v2_crypto_provider_set_cipher_create_callback +_duckdb_v2_crypto_provider_set_cipher_destroy_callback +_duckdb_v2_crypto_provider_set_cipher_finalize_callback +_duckdb_v2_crypto_provider_set_cipher_init_callback +_duckdb_v2_crypto_provider_set_cipher_update_callback +_duckdb_v2_crypto_provider_set_hash_callback +_duckdb_v2_crypto_provider_set_hmac_callback +_duckdb_v2_crypto_provider_set_random_callback +_duckdb_v2_crypto_provider_set_user_data +_duckdb_v2_crypto_random_bytes +_duckdb_v2_crypto_supports_hash +_duckdb_v2_crypto_supports_hmac _duckdb_v2_custom_option_create _duckdb_v2_custom_option_destroy _duckdb_v2_custom_option_set_default_scope @@ -1026,6 +1076,60 @@ _duckdb_v2_data_chunk_get_capacity _duckdb_v2_data_chunk_get_size _duckdb_v2_data_chunk_get_vector _duckdb_v2_data_chunk_get_vector_count +_duckdb_v2_data_source_claim_batch_get_bind_data +_duckdb_v2_data_source_claim_batch_get_global_state +_duckdb_v2_data_source_claim_batch_get_local_state +_duckdb_v2_data_source_claim_batch_get_user_data +_duckdb_v2_data_source_claim_batch_set_claimed +_duckdb_v2_data_source_create +_duckdb_v2_data_source_destroy +_duckdb_v2_data_source_exec_add_task +_duckdb_v2_data_source_exec_get_bind_data +_duckdb_v2_data_source_exec_get_column_count +_duckdb_v2_data_source_exec_get_column_index +_duckdb_v2_data_source_exec_get_global_state +_duckdb_v2_data_source_exec_get_local_state +_duckdb_v2_data_source_exec_get_output_chunk +_duckdb_v2_data_source_exec_get_user_data +_duckdb_v2_data_source_exec_set_result +_duckdb_v2_data_source_init_global_get_bind_data +_duckdb_v2_data_source_init_global_get_column_count +_duckdb_v2_data_source_init_global_get_column_index +_duckdb_v2_data_source_init_global_get_user_data +_duckdb_v2_data_source_init_global_set_global_state +_duckdb_v2_data_source_init_global_set_max_threads +_duckdb_v2_data_source_init_local_get_bind_data +_duckdb_v2_data_source_init_local_get_column_count +_duckdb_v2_data_source_init_local_get_column_index +_duckdb_v2_data_source_init_local_get_global_state +_duckdb_v2_data_source_init_local_get_user_data +_duckdb_v2_data_source_init_local_set_local_state +_duckdb_v2_data_source_metrics_get_bind_data +_duckdb_v2_data_source_metrics_get_global_state +_duckdb_v2_data_source_metrics_get_user_data +_duckdb_v2_data_source_metrics_set +_duckdb_v2_data_source_partition_data_get_bind_data +_duckdb_v2_data_source_partition_data_get_global_state +_duckdb_v2_data_source_partition_data_get_local_state +_duckdb_v2_data_source_partition_data_get_partition_column_count +_duckdb_v2_data_source_partition_data_get_partition_column_index +_duckdb_v2_data_source_partition_data_get_user_data +_duckdb_v2_data_source_partition_data_requires_batch_index +_duckdb_v2_data_source_partition_data_requires_partition_columns +_duckdb_v2_data_source_partition_data_set_batch_index +_duckdb_v2_data_source_partition_data_set_partition_value +_duckdb_v2_data_source_progress_get_bind_data +_duckdb_v2_data_source_progress_get_global_state +_duckdb_v2_data_source_progress_get_user_data +_duckdb_v2_data_source_progress_set_progress +_duckdb_v2_data_source_set_claim_batch_callback +_duckdb_v2_data_source_set_exec_callback +_duckdb_v2_data_source_set_init_global_callback +_duckdb_v2_data_source_set_init_local_callback +_duckdb_v2_data_source_set_metrics_callback +_duckdb_v2_data_source_set_partition_data_callback +_duckdb_v2_data_source_set_progress_callback +_duckdb_v2_data_source_set_user_data _duckdb_v2_environment_create _duckdb_v2_environment_destroy _duckdb_v2_environment_get_instance_count @@ -1036,6 +1140,7 @@ _duckdb_v2_error_info_get_text _duckdb_v2_error_info_set_code _duckdb_v2_error_info_set_text _duckdb_v2_expression_cast_get_mode +_duckdb_v2_expression_check_statistics _duckdb_v2_expression_column_ref_get_index _duckdb_v2_expression_constant_get_value _duckdb_v2_expression_function_get_name @@ -1047,6 +1152,7 @@ _duckdb_v2_expression_get_type _duckdb_v2_extension_register_aggregate_function _duckdb_v2_extension_register_cast_function _duckdb_v2_extension_register_copy_function +_duckdb_v2_extension_register_crypto_provider _duckdb_v2_extension_register_custom_option _duckdb_v2_extension_register_custom_type _duckdb_v2_extension_register_log_sink @@ -1055,6 +1161,7 @@ _duckdb_v2_extension_register_multi_file_function _duckdb_v2_extension_register_pragma_function _duckdb_v2_extension_register_replacement_scan _duckdb_v2_extension_register_scalar_function +_duckdb_v2_extension_register_secret_function _duckdb_v2_extension_register_table_function _duckdb_v2_factory_create_common_type _duckdb_v2_factory_create_type_from_id @@ -1103,7 +1210,10 @@ _duckdb_v2_instance_detach _duckdb_v2_instance_get_config _duckdb_v2_instance_get_factory _duckdb_v2_instance_get_file_system +_duckdb_v2_instance_get_object_cache _duckdb_v2_instance_log +_duckdb_v2_instance_open_shared +_duckdb_v2_instance_register_crypto_provider _duckdb_v2_instance_register_log_sink _duckdb_v2_instance_register_replacement_scan _duckdb_v2_instance_set_default @@ -1138,6 +1248,40 @@ _duckdb_v2_multi_file_function_set_file_extension _duckdb_v2_multi_file_function_set_name _duckdb_v2_multi_file_function_set_reader_type _duckdb_v2_multi_file_function_set_single_file_function +_duckdb_v2_object_cache_delete +_duckdb_v2_object_cache_entry_destroy +_duckdb_v2_object_cache_entry_get_data +_duckdb_v2_object_cache_get +_duckdb_v2_object_cache_get_or_create +_duckdb_v2_object_cache_put +_duckdb_v2_operator_create +_duckdb_v2_operator_destroy +_duckdb_v2_operator_execute_get_bind_data +_duckdb_v2_operator_execute_get_global_state +_duckdb_v2_operator_execute_get_input_chunk +_duckdb_v2_operator_execute_get_local_state +_duckdb_v2_operator_execute_get_output_chunk +_duckdb_v2_operator_execute_get_user_data +_duckdb_v2_operator_execute_set_result +_duckdb_v2_operator_finalize_get_bind_data +_duckdb_v2_operator_finalize_get_global_state +_duckdb_v2_operator_finalize_get_local_state +_duckdb_v2_operator_finalize_get_output_chunk +_duckdb_v2_operator_finalize_get_user_data +_duckdb_v2_operator_finalize_set_have_more_output +_duckdb_v2_operator_init_global_get_bind_data +_duckdb_v2_operator_init_global_get_user_data +_duckdb_v2_operator_init_global_set_global_state +_duckdb_v2_operator_init_global_set_max_threads +_duckdb_v2_operator_init_local_get_bind_data +_duckdb_v2_operator_init_local_get_global_state +_duckdb_v2_operator_init_local_get_user_data +_duckdb_v2_operator_init_local_set_local_state +_duckdb_v2_operator_set_execute_callback +_duckdb_v2_operator_set_finalize_callback +_duckdb_v2_operator_set_init_global_callback +_duckdb_v2_operator_set_init_local_callback +_duckdb_v2_operator_set_user_data _duckdb_v2_option_destroy _duckdb_v2_option_get_alias _duckdb_v2_option_get_alias_count @@ -1199,7 +1343,10 @@ _duckdb_v2_result_get_statement_type _duckdb_v2_result_render_box _duckdb_v2_result_step _duckdb_v2_result_wait +_duckdb_v2_scalar_function_bind_replace_call +_duckdb_v2_scalar_function_bind_set_argument_monotonicity _duckdb_v2_scalar_function_bind_set_bind_data +_duckdb_v2_scalar_function_bind_set_property _duckdb_v2_scalar_function_create _duckdb_v2_scalar_function_destroy _duckdb_v2_scalar_function_exec_get_arg @@ -1210,21 +1357,53 @@ _duckdb_v2_scalar_function_exec_get_result _duckdb_v2_scalar_function_exec_get_row_count _duckdb_v2_scalar_function_exec_get_user_data _duckdb_v2_scalar_function_get_docs +_duckdb_v2_scalar_function_get_generic_property _duckdb_v2_scalar_function_get_signature _duckdb_v2_scalar_function_init_get_bind_data _duckdb_v2_scalar_function_init_get_user_data _duckdb_v2_scalar_function_init_set_init_data _duckdb_v2_scalar_function_resolve_types_set_return_type +_duckdb_v2_scalar_function_set_argument_monotonicity _duckdb_v2_scalar_function_set_bind_callback _duckdb_v2_scalar_function_set_exec_callback +_duckdb_v2_scalar_function_set_generic_property _duckdb_v2_scalar_function_set_init_callback _duckdb_v2_scalar_function_set_name _duckdb_v2_scalar_function_set_property _duckdb_v2_scalar_function_set_resolve_types_callback +_duckdb_v2_scalar_function_set_schema +_duckdb_v2_scalar_function_set_stats_callback _duckdb_v2_scalar_function_set_user_data +_duckdb_v2_scalar_function_stats_get_arg_count +_duckdb_v2_scalar_function_stats_get_arg_stats +_duckdb_v2_scalar_function_stats_get_bind_data +_duckdb_v2_scalar_function_stats_get_result_stats +_duckdb_v2_scalar_function_stats_get_user_data _duckdb_v2_schema_destroy _duckdb_v2_schema_get_count _duckdb_v2_schema_get_field +_duckdb_v2_secret_add_redacted_key +_duckdb_v2_secret_add_scope +_duckdb_v2_secret_clear_scope +_duckdb_v2_secret_create +_duckdb_v2_secret_destroy +_duckdb_v2_secret_function_add_named_parameter +_duckdb_v2_secret_function_create +_duckdb_v2_secret_function_destroy +_duckdb_v2_secret_function_set_create_callback +_duckdb_v2_secret_function_set_default +_duckdb_v2_secret_function_set_provider +_duckdb_v2_secret_function_set_type +_duckdb_v2_secret_function_set_user_data +_duckdb_v2_secret_get_key +_duckdb_v2_secret_get_key_count +_duckdb_v2_secret_get_property +_duckdb_v2_secret_get_scope +_duckdb_v2_secret_get_scope_count +_duckdb_v2_secret_get_value +_duckdb_v2_secret_is_key_redacted +_duckdb_v2_secret_set_property +_duckdb_v2_secret_set_value _duckdb_v2_sql_statement_destroy _duckdb_v2_sql_statement_get_parameter_count _duckdb_v2_sql_statement_get_parameter_name @@ -1236,12 +1415,26 @@ _duckdb_v2_statement_execute _duckdb_v2_statement_execute_arrow _duckdb_v2_statement_iterator_destroy _duckdb_v2_statement_iterator_next +_duckdb_v2_stats_assign +_duckdb_v2_stats_can_have_null +_duckdb_v2_stats_can_have_valid +_duckdb_v2_stats_create +_duckdb_v2_stats_destroy +_duckdb_v2_stats_get_value +_duckdb_v2_stats_merge +_duckdb_v2_stats_set_can_have_null +_duckdb_v2_stats_set_can_have_valid +_duckdb_v2_stats_set_value _duckdb_v2_table_description_destroy _duckdb_v2_table_description_get_column _duckdb_v2_table_description_get_column_count _duckdb_v2_table_description_get_qname _duckdb_v2_table_description_is_readonly +_duckdb_v2_table_function_add_virtual_column _duckdb_v2_table_function_bind_add_result_column +_duckdb_v2_table_function_bind_get_input_column_count +_duckdb_v2_table_function_bind_get_input_column_name +_duckdb_v2_table_function_bind_get_input_column_type _duckdb_v2_table_function_bind_set_cardinality _duckdb_v2_table_function_bind_set_order_preservation _duckdb_v2_table_function_create @@ -1265,12 +1458,24 @@ _duckdb_v2_table_function_partitioning_get_partition_column_index _duckdb_v2_table_function_partitioning_get_user_data _duckdb_v2_table_function_partitioning_set_partition_info _duckdb_v2_table_function_set_bind_callback +_duckdb_v2_table_function_set_data_source _duckdb_v2_table_function_set_filter_pushdown_callback _duckdb_v2_table_function_set_get_bind_info_callback _duckdb_v2_table_function_set_name +_duckdb_v2_table_function_set_operator _duckdb_v2_table_function_set_partitioning_callback _duckdb_v2_table_function_set_projection_pushdown +_duckdb_v2_table_function_set_property +_duckdb_v2_table_function_set_stats_callback +_duckdb_v2_table_function_set_to_string_callback _duckdb_v2_table_function_set_user_data +_duckdb_v2_table_function_stats_get_bind_data +_duckdb_v2_table_function_stats_get_column_index +_duckdb_v2_table_function_stats_get_result_stats +_duckdb_v2_table_function_stats_get_user_data +_duckdb_v2_table_function_to_string_get_bind_data +_duckdb_v2_table_function_to_string_get_user_data +_duckdb_v2_table_function_to_string_set _duckdb_v2_token_iterator_destroy _duckdb_v2_token_iterator_ends_unterminated _duckdb_v2_token_iterator_next @@ -1349,6 +1554,7 @@ _duckdb_v2_value_get_uuid _duckdb_v2_value_get_varchar _duckdb_v2_value_is_null _duckdb_v2_value_to_string +_duckdb_v2_value_variant_to_value _duckdb_v2_vector_cast _duckdb_v2_vector_constant_set_valid _duckdb_v2_vector_flat_get_validity_mutable diff --git a/duckdb_java.map b/duckdb_java.map index 24bcb1337..a93460fd3 100644 --- a/duckdb_java.map +++ b/duckdb_java.map @@ -834,6 +834,7 @@ DUCKDB_JAVA { duckdb_v2_aggregate_function_finalize_get_states; duckdb_v2_aggregate_function_finalize_get_user_data; duckdb_v2_aggregate_function_get_docs; + duckdb_v2_aggregate_function_get_generic_property; duckdb_v2_aggregate_function_get_signature; duckdb_v2_aggregate_function_init_get_bind_data; duckdb_v2_aggregate_function_init_get_state_count; @@ -843,15 +844,22 @@ DUCKDB_JAVA { duckdb_v2_aggregate_function_set_combine_callback; duckdb_v2_aggregate_function_set_destroy_callback; duckdb_v2_aggregate_function_set_finalize_callback; + duckdb_v2_aggregate_function_set_generic_property; duckdb_v2_aggregate_function_set_init_callback; duckdb_v2_aggregate_function_set_name; duckdb_v2_aggregate_function_set_property; duckdb_v2_aggregate_function_set_size_callback; + duckdb_v2_aggregate_function_set_stats_callback; duckdb_v2_aggregate_function_set_update_callback; duckdb_v2_aggregate_function_set_user_data; duckdb_v2_aggregate_function_size_get_bind_data; duckdb_v2_aggregate_function_size_get_user_data; duckdb_v2_aggregate_function_size_set_state_size; + duckdb_v2_aggregate_function_stats_get_arg_count; + duckdb_v2_aggregate_function_stats_get_arg_stats; + duckdb_v2_aggregate_function_stats_get_bind_data; + duckdb_v2_aggregate_function_stats_get_result_stats; + duckdb_v2_aggregate_function_stats_get_user_data; duckdb_v2_aggregate_function_update_get_arg; duckdb_v2_aggregate_function_update_get_arg_count; duckdb_v2_aggregate_function_update_get_bind_data; @@ -885,16 +893,11 @@ DUCKDB_JAVA { duckdb_v2_bignum_encode; duckdb_v2_cast_function_create; duckdb_v2_cast_function_destroy; - duckdb_v2_cast_function_exec_get_input; - duckdb_v2_cast_function_exec_get_mode; - duckdb_v2_cast_function_exec_get_output; - duckdb_v2_cast_function_exec_get_row_count; - duckdb_v2_cast_function_exec_get_user_data; - duckdb_v2_cast_function_set_exec_callback; + duckdb_v2_cast_function_set_function; duckdb_v2_cast_function_set_implicit_cast_cost; duckdb_v2_cast_function_set_source_type; duckdb_v2_cast_function_set_target_type; - duckdb_v2_cast_function_set_user_data; + duckdb_v2_cast_function_set_try_function; duckdb_v2_column_data_collection_append; duckdb_v2_column_data_collection_append_state_create; duckdb_v2_column_data_collection_append_state_destroy; @@ -921,15 +924,22 @@ DUCKDB_JAVA { duckdb_v2_config_set_option_text; duckdb_v2_config_set_option_value; duckdb_v2_connection_create; + duckdb_v2_connection_create_in_transaction; + duckdb_v2_connection_create_secret; duckdb_v2_connection_describe_table; duckdb_v2_connection_destroy; duckdb_v2_connection_enable_profiling; duckdb_v2_connection_get_config; duckdb_v2_connection_get_factory; duckdb_v2_connection_get_file_system; + duckdb_v2_connection_get_or_create_state; + duckdb_v2_connection_get_profiling_information; duckdb_v2_connection_get_query_metrics; + duckdb_v2_connection_get_secret_by_name; + duckdb_v2_connection_get_state; duckdb_v2_connection_interrupt; duckdb_v2_connection_log; + duckdb_v2_connection_lookup_secret; duckdb_v2_connection_progress_get; duckdb_v2_connection_register_aggregate_function; duckdb_v2_connection_register_cast_function; @@ -940,11 +950,28 @@ DUCKDB_JAVA { duckdb_v2_connection_register_pragma_function; duckdb_v2_connection_register_replacement_scan; duckdb_v2_connection_register_scalar_function; + duckdb_v2_connection_register_secret_function; duckdb_v2_connection_register_table_function; + duckdb_v2_connection_remove_state; + duckdb_v2_context_create_secret; duckdb_v2_context_get_config; duckdb_v2_context_get_factory; duckdb_v2_context_get_file_system; + duckdb_v2_context_get_object_cache; + duckdb_v2_context_get_or_create_state; + duckdb_v2_context_get_secret_by_name; + duckdb_v2_context_get_state; duckdb_v2_context_log; + duckdb_v2_context_lookup_secret; + duckdb_v2_context_remove_state; + duckdb_v2_context_state_profile_write; + duckdb_v2_context_state_set_profiling_callback; + duckdb_v2_context_state_set_query_begin_callback; + duckdb_v2_context_state_set_query_end_callback; + duckdb_v2_context_state_set_transaction_begin_callback; + duckdb_v2_context_state_set_transaction_commit_callback; + duckdb_v2_context_state_set_transaction_rollback_callback; + duckdb_v2_context_state_set_user_data; duckdb_v2_copy_from_bind_get_column_count; duckdb_v2_copy_from_bind_get_column_name; duckdb_v2_copy_from_bind_get_column_type; @@ -956,6 +983,7 @@ DUCKDB_JAVA { duckdb_v2_copy_from_bind_set_bind_data; duckdb_v2_copy_from_bind_set_cardinality; duckdb_v2_copy_from_set_bind_callback; + duckdb_v2_copy_from_set_data_source; duckdb_v2_copy_function_create; duckdb_v2_copy_function_destroy; duckdb_v2_copy_function_set_file_extension; @@ -1001,6 +1029,28 @@ DUCKDB_JAVA { duckdb_v2_copy_to_statistics_get_user_data; duckdb_v2_copy_to_statistics_set_file_size; duckdb_v2_copy_to_statistics_set_row_count; + duckdb_v2_crypto_cipher_create; + duckdb_v2_crypto_cipher_destroy; + duckdb_v2_crypto_cipher_finalize; + duckdb_v2_crypto_cipher_init; + duckdb_v2_crypto_cipher_update; + duckdb_v2_crypto_hash; + duckdb_v2_crypto_hash_digest_size; + duckdb_v2_crypto_hmac; + duckdb_v2_crypto_provider_create; + duckdb_v2_crypto_provider_destroy; + duckdb_v2_crypto_provider_set_cipher_create_callback; + duckdb_v2_crypto_provider_set_cipher_destroy_callback; + duckdb_v2_crypto_provider_set_cipher_finalize_callback; + duckdb_v2_crypto_provider_set_cipher_init_callback; + duckdb_v2_crypto_provider_set_cipher_update_callback; + duckdb_v2_crypto_provider_set_hash_callback; + duckdb_v2_crypto_provider_set_hmac_callback; + duckdb_v2_crypto_provider_set_random_callback; + duckdb_v2_crypto_provider_set_user_data; + duckdb_v2_crypto_random_bytes; + duckdb_v2_crypto_supports_hash; + duckdb_v2_crypto_supports_hmac; duckdb_v2_custom_option_create; duckdb_v2_custom_option_destroy; duckdb_v2_custom_option_set_default_scope; @@ -1028,6 +1078,60 @@ DUCKDB_JAVA { duckdb_v2_data_chunk_get_size; duckdb_v2_data_chunk_get_vector; duckdb_v2_data_chunk_get_vector_count; + duckdb_v2_data_source_claim_batch_get_bind_data; + duckdb_v2_data_source_claim_batch_get_global_state; + duckdb_v2_data_source_claim_batch_get_local_state; + duckdb_v2_data_source_claim_batch_get_user_data; + duckdb_v2_data_source_claim_batch_set_claimed; + duckdb_v2_data_source_create; + duckdb_v2_data_source_destroy; + duckdb_v2_data_source_exec_add_task; + duckdb_v2_data_source_exec_get_bind_data; + duckdb_v2_data_source_exec_get_column_count; + duckdb_v2_data_source_exec_get_column_index; + duckdb_v2_data_source_exec_get_global_state; + duckdb_v2_data_source_exec_get_local_state; + duckdb_v2_data_source_exec_get_output_chunk; + duckdb_v2_data_source_exec_get_user_data; + duckdb_v2_data_source_exec_set_result; + duckdb_v2_data_source_init_global_get_bind_data; + duckdb_v2_data_source_init_global_get_column_count; + duckdb_v2_data_source_init_global_get_column_index; + duckdb_v2_data_source_init_global_get_user_data; + duckdb_v2_data_source_init_global_set_global_state; + duckdb_v2_data_source_init_global_set_max_threads; + duckdb_v2_data_source_init_local_get_bind_data; + duckdb_v2_data_source_init_local_get_column_count; + duckdb_v2_data_source_init_local_get_column_index; + duckdb_v2_data_source_init_local_get_global_state; + duckdb_v2_data_source_init_local_get_user_data; + duckdb_v2_data_source_init_local_set_local_state; + duckdb_v2_data_source_metrics_get_bind_data; + duckdb_v2_data_source_metrics_get_global_state; + duckdb_v2_data_source_metrics_get_user_data; + duckdb_v2_data_source_metrics_set; + duckdb_v2_data_source_partition_data_get_bind_data; + duckdb_v2_data_source_partition_data_get_global_state; + duckdb_v2_data_source_partition_data_get_local_state; + duckdb_v2_data_source_partition_data_get_partition_column_count; + duckdb_v2_data_source_partition_data_get_partition_column_index; + duckdb_v2_data_source_partition_data_get_user_data; + duckdb_v2_data_source_partition_data_requires_batch_index; + duckdb_v2_data_source_partition_data_requires_partition_columns; + duckdb_v2_data_source_partition_data_set_batch_index; + duckdb_v2_data_source_partition_data_set_partition_value; + duckdb_v2_data_source_progress_get_bind_data; + duckdb_v2_data_source_progress_get_global_state; + duckdb_v2_data_source_progress_get_user_data; + duckdb_v2_data_source_progress_set_progress; + duckdb_v2_data_source_set_claim_batch_callback; + duckdb_v2_data_source_set_exec_callback; + duckdb_v2_data_source_set_init_global_callback; + duckdb_v2_data_source_set_init_local_callback; + duckdb_v2_data_source_set_metrics_callback; + duckdb_v2_data_source_set_partition_data_callback; + duckdb_v2_data_source_set_progress_callback; + duckdb_v2_data_source_set_user_data; duckdb_v2_environment_create; duckdb_v2_environment_destroy; duckdb_v2_environment_get_instance_count; @@ -1038,6 +1142,7 @@ DUCKDB_JAVA { duckdb_v2_error_info_set_code; duckdb_v2_error_info_set_text; duckdb_v2_expression_cast_get_mode; + duckdb_v2_expression_check_statistics; duckdb_v2_expression_column_ref_get_index; duckdb_v2_expression_constant_get_value; duckdb_v2_expression_function_get_name; @@ -1049,6 +1154,7 @@ DUCKDB_JAVA { duckdb_v2_extension_register_aggregate_function; duckdb_v2_extension_register_cast_function; duckdb_v2_extension_register_copy_function; + duckdb_v2_extension_register_crypto_provider; duckdb_v2_extension_register_custom_option; duckdb_v2_extension_register_custom_type; duckdb_v2_extension_register_log_sink; @@ -1057,6 +1163,7 @@ DUCKDB_JAVA { duckdb_v2_extension_register_pragma_function; duckdb_v2_extension_register_replacement_scan; duckdb_v2_extension_register_scalar_function; + duckdb_v2_extension_register_secret_function; duckdb_v2_extension_register_table_function; duckdb_v2_factory_create_common_type; duckdb_v2_factory_create_type_from_id; @@ -1105,7 +1212,10 @@ DUCKDB_JAVA { duckdb_v2_instance_get_config; duckdb_v2_instance_get_factory; duckdb_v2_instance_get_file_system; + duckdb_v2_instance_get_object_cache; duckdb_v2_instance_log; + duckdb_v2_instance_open_shared; + duckdb_v2_instance_register_crypto_provider; duckdb_v2_instance_register_log_sink; duckdb_v2_instance_register_replacement_scan; duckdb_v2_instance_set_default; @@ -1140,6 +1250,40 @@ DUCKDB_JAVA { duckdb_v2_multi_file_function_set_name; duckdb_v2_multi_file_function_set_reader_type; duckdb_v2_multi_file_function_set_single_file_function; + duckdb_v2_object_cache_delete; + duckdb_v2_object_cache_entry_destroy; + duckdb_v2_object_cache_entry_get_data; + duckdb_v2_object_cache_get; + duckdb_v2_object_cache_get_or_create; + duckdb_v2_object_cache_put; + duckdb_v2_operator_create; + duckdb_v2_operator_destroy; + duckdb_v2_operator_execute_get_bind_data; + duckdb_v2_operator_execute_get_global_state; + duckdb_v2_operator_execute_get_input_chunk; + duckdb_v2_operator_execute_get_local_state; + duckdb_v2_operator_execute_get_output_chunk; + duckdb_v2_operator_execute_get_user_data; + duckdb_v2_operator_execute_set_result; + duckdb_v2_operator_finalize_get_bind_data; + duckdb_v2_operator_finalize_get_global_state; + duckdb_v2_operator_finalize_get_local_state; + duckdb_v2_operator_finalize_get_output_chunk; + duckdb_v2_operator_finalize_get_user_data; + duckdb_v2_operator_finalize_set_have_more_output; + duckdb_v2_operator_init_global_get_bind_data; + duckdb_v2_operator_init_global_get_user_data; + duckdb_v2_operator_init_global_set_global_state; + duckdb_v2_operator_init_global_set_max_threads; + duckdb_v2_operator_init_local_get_bind_data; + duckdb_v2_operator_init_local_get_global_state; + duckdb_v2_operator_init_local_get_user_data; + duckdb_v2_operator_init_local_set_local_state; + duckdb_v2_operator_set_execute_callback; + duckdb_v2_operator_set_finalize_callback; + duckdb_v2_operator_set_init_global_callback; + duckdb_v2_operator_set_init_local_callback; + duckdb_v2_operator_set_user_data; duckdb_v2_option_destroy; duckdb_v2_option_get_alias; duckdb_v2_option_get_alias_count; @@ -1201,7 +1345,10 @@ DUCKDB_JAVA { duckdb_v2_result_render_box; duckdb_v2_result_step; duckdb_v2_result_wait; + duckdb_v2_scalar_function_bind_replace_call; + duckdb_v2_scalar_function_bind_set_argument_monotonicity; duckdb_v2_scalar_function_bind_set_bind_data; + duckdb_v2_scalar_function_bind_set_property; duckdb_v2_scalar_function_create; duckdb_v2_scalar_function_destroy; duckdb_v2_scalar_function_exec_get_arg; @@ -1212,21 +1359,53 @@ DUCKDB_JAVA { duckdb_v2_scalar_function_exec_get_row_count; duckdb_v2_scalar_function_exec_get_user_data; duckdb_v2_scalar_function_get_docs; + duckdb_v2_scalar_function_get_generic_property; duckdb_v2_scalar_function_get_signature; duckdb_v2_scalar_function_init_get_bind_data; duckdb_v2_scalar_function_init_get_user_data; duckdb_v2_scalar_function_init_set_init_data; duckdb_v2_scalar_function_resolve_types_set_return_type; + duckdb_v2_scalar_function_set_argument_monotonicity; duckdb_v2_scalar_function_set_bind_callback; duckdb_v2_scalar_function_set_exec_callback; + duckdb_v2_scalar_function_set_generic_property; duckdb_v2_scalar_function_set_init_callback; duckdb_v2_scalar_function_set_name; duckdb_v2_scalar_function_set_property; duckdb_v2_scalar_function_set_resolve_types_callback; + duckdb_v2_scalar_function_set_schema; + duckdb_v2_scalar_function_set_stats_callback; duckdb_v2_scalar_function_set_user_data; + duckdb_v2_scalar_function_stats_get_arg_count; + duckdb_v2_scalar_function_stats_get_arg_stats; + duckdb_v2_scalar_function_stats_get_bind_data; + duckdb_v2_scalar_function_stats_get_result_stats; + duckdb_v2_scalar_function_stats_get_user_data; duckdb_v2_schema_destroy; duckdb_v2_schema_get_count; duckdb_v2_schema_get_field; + duckdb_v2_secret_add_redacted_key; + duckdb_v2_secret_add_scope; + duckdb_v2_secret_clear_scope; + duckdb_v2_secret_create; + duckdb_v2_secret_destroy; + duckdb_v2_secret_function_add_named_parameter; + duckdb_v2_secret_function_create; + duckdb_v2_secret_function_destroy; + duckdb_v2_secret_function_set_create_callback; + duckdb_v2_secret_function_set_default; + duckdb_v2_secret_function_set_provider; + duckdb_v2_secret_function_set_type; + duckdb_v2_secret_function_set_user_data; + duckdb_v2_secret_get_key; + duckdb_v2_secret_get_key_count; + duckdb_v2_secret_get_property; + duckdb_v2_secret_get_scope; + duckdb_v2_secret_get_scope_count; + duckdb_v2_secret_get_value; + duckdb_v2_secret_is_key_redacted; + duckdb_v2_secret_set_property; + duckdb_v2_secret_set_value; duckdb_v2_sql_statement_destroy; duckdb_v2_sql_statement_get_parameter_count; duckdb_v2_sql_statement_get_parameter_name; @@ -1238,12 +1417,26 @@ DUCKDB_JAVA { duckdb_v2_statement_execute_arrow; duckdb_v2_statement_iterator_destroy; duckdb_v2_statement_iterator_next; + duckdb_v2_stats_assign; + duckdb_v2_stats_can_have_null; + duckdb_v2_stats_can_have_valid; + duckdb_v2_stats_create; + duckdb_v2_stats_destroy; + duckdb_v2_stats_get_value; + duckdb_v2_stats_merge; + duckdb_v2_stats_set_can_have_null; + duckdb_v2_stats_set_can_have_valid; + duckdb_v2_stats_set_value; duckdb_v2_table_description_destroy; duckdb_v2_table_description_get_column; duckdb_v2_table_description_get_column_count; duckdb_v2_table_description_get_qname; duckdb_v2_table_description_is_readonly; + duckdb_v2_table_function_add_virtual_column; duckdb_v2_table_function_bind_add_result_column; + duckdb_v2_table_function_bind_get_input_column_count; + duckdb_v2_table_function_bind_get_input_column_name; + duckdb_v2_table_function_bind_get_input_column_type; duckdb_v2_table_function_bind_set_cardinality; duckdb_v2_table_function_bind_set_order_preservation; duckdb_v2_table_function_create; @@ -1267,12 +1460,24 @@ DUCKDB_JAVA { duckdb_v2_table_function_partitioning_get_user_data; duckdb_v2_table_function_partitioning_set_partition_info; duckdb_v2_table_function_set_bind_callback; + duckdb_v2_table_function_set_data_source; duckdb_v2_table_function_set_filter_pushdown_callback; duckdb_v2_table_function_set_get_bind_info_callback; duckdb_v2_table_function_set_name; + duckdb_v2_table_function_set_operator; duckdb_v2_table_function_set_partitioning_callback; duckdb_v2_table_function_set_projection_pushdown; + duckdb_v2_table_function_set_property; + duckdb_v2_table_function_set_stats_callback; + duckdb_v2_table_function_set_to_string_callback; duckdb_v2_table_function_set_user_data; + duckdb_v2_table_function_stats_get_bind_data; + duckdb_v2_table_function_stats_get_column_index; + duckdb_v2_table_function_stats_get_result_stats; + duckdb_v2_table_function_stats_get_user_data; + duckdb_v2_table_function_to_string_get_bind_data; + duckdb_v2_table_function_to_string_get_user_data; + duckdb_v2_table_function_to_string_set; duckdb_v2_token_iterator_destroy; duckdb_v2_token_iterator_ends_unterminated; duckdb_v2_token_iterator_next; @@ -1351,6 +1556,7 @@ DUCKDB_JAVA { duckdb_v2_value_get_varchar; duckdb_v2_value_is_null; duckdb_v2_value_to_string; + duckdb_v2_value_variant_to_value; duckdb_v2_vector_cast; duckdb_v2_vector_constant_set_valid; duckdb_v2_vector_flat_get_validity_mutable; diff --git a/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp b/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp index f39c00408..3dcbc4a56 100644 --- a/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp +++ b/src/duckdb/extension/core_functions/aggregate/algebraic/avg.cpp @@ -604,7 +604,7 @@ void BignumAvgExportState(Vector &state_vector, AggregateFinalizeInputData &, Ve void BignumAvgImportState(AggregateImportInputData &input) { auto entries = input.input_vec.Values>(); - for (idx_t i = 0; i < input.input_vec.size(); i++) { + for (idx_t i = 0; i < entries.size(); i++) { auto &state = *reinterpret_cast(input.dest_buffer + i * input.layout.total_state_size); BignumAvgOperation::Initialize(state); const auto entry = entries[i]; diff --git a/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp b/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp index d513dfa31..a113a5ea8 100644 --- a/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp +++ b/src/duckdb/extension/core_functions/aggregate/distributive/sum.cpp @@ -869,7 +869,7 @@ void BignumSumExportState(Vector &state_vector, AggregateFinalizeInputData &, Ve void BignumSumImportState(AggregateImportInputData &input) { auto entries = input.input_vec.Values(); - for (idx_t i = 0; i < input.input_vec.size(); i++) { + for (idx_t i = 0; i < entries.size(); i++) { auto &state = *reinterpret_cast(input.dest_buffer + i * input.layout.total_state_size); const auto entry = entries[i]; state.is_set = entry.IsValid(); diff --git a/src/duckdb/extension/core_functions/aggregate/holistic/approximate_quantile.cpp b/src/duckdb/extension/core_functions/aggregate/holistic/approximate_quantile.cpp index 3e21637ff..905ec17e9 100644 --- a/src/duckdb/extension/core_functions/aggregate/holistic/approximate_quantile.cpp +++ b/src/duckdb/extension/core_functions/aggregate/holistic/approximate_quantile.cpp @@ -1,5 +1,7 @@ #include "duckdb/common/operator/add.hpp" +#include "duckdb/common/types/bignum_decimal.hpp" #include "duckdb/common/types/decimal.hpp" +#include "duckdb/common/vector/string_vector.hpp" #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/common/vector/vector_iterator.hpp" #include "duckdb/common/vector/list_vector.hpp" @@ -11,6 +13,7 @@ #include "duckdb/common/serializer/serializer.hpp" #include "duckdb/common/serializer/deserializer.hpp" +#include #include namespace duckdb { @@ -23,8 +26,9 @@ struct ApproxQuantileState { }; struct ApproxQuantileCoding { + //! Encodes an input value for the sketch; type is the type of the input, which only the wide decimals read template - static SAVE_TYPE Encode(const INPUT_TYPE &input) { + static SAVE_TYPE Encode(const INPUT_TYPE &input, const LogicalType &type) { return Cast::template Operation(input); } @@ -41,9 +45,11 @@ struct ApproxQuantileCoding { return false; } + //! Decodes a quantile of the sketch into a value of the type of the result vector template - static void Decode(const SAVE_TYPE &source, TARGET_TYPE &target, const LogicalType &type) { + static void Decode(const SAVE_TYPE &source, TARGET_TYPE &target, Vector &result) { Decode(source, target); + const auto &type = result.GetType(); if (type.id() != LogicalTypeId::DECIMAL) { return; } @@ -58,9 +64,58 @@ struct ApproxQuantileCoding { } }; +//! The bignum_t tier of decimals (above 38 digits) sketches the value of the decimal (the unscaled value divided by +//! the power of ten of its scale) as a DOUBLE, so that the magnitude of a value decides whether the sketch holds it, +//! not the number of digits of its width or scale: the unscaled value of 1 as a DECIMAL(310,309) has 310 digits template <> -double ApproxQuantileCoding::Encode(const dtime_t &input) { - return Encode(input.value); +double ApproxQuantileCoding::Encode(const bignum_t &input, const LogicalType &type) { + const auto val = DecimalHelper::ToDouble(input, DecimalType::GetScale(type)); + if (!Value::DoubleIsFinite(val)) { + // skipping the value like an infinite DOUBLE would change the result + throw OutOfRangeException("approx_quantile sketches its input as DOUBLE: a %s value with a magnitude " + "beyond the DOUBLE range (about 1.8e308) cannot be added to the sketch", + type.ToString()); + } + return val; +} + +//! A quantile of the sketch is converted to the nearest value of the DECIMAL type +template <> +void ApproxQuantileCoding::Decode(const double &source, bignum_t &target, Vector &result) { + const auto &type = result.GetType(); + const auto width = DecimalType::GetWidth(type); + const auto scale = DecimalType::GetScale(type); + if (!Value::DoubleIsFinite(source)) { + // the arithmetic of the sketch overflowed (values close to the limits of the DOUBLE range) + throw OutOfRangeException("approx_quantile: the sketch of the %s values overflowed the DOUBLE range, the " + "approximate quantile is not a finite value", + type.ToString()); + } + string unscaled; + if (DecimalHelper::TryFromDouble(source, width, scale, unscaled)) { + target = bignum_t(StringVector::AddStringOrBlob(result, unscaled)); + return; + } + // The DOUBLE nearest to a value at the top of the width can lie just beyond the largest value of the type + // (the DOUBLE of forty nines is 1e40): such a quantile is the largest value. Anything further out is not a + // quantile of values of this type (an imported state can carry any sketch) + string digits = source < 0 ? "-" : ""; + digits.append(width, '9'); + string limit; + if (!DecimalHelper::TryParse(digits.c_str(), digits.size(), width, 0, limit)) { + throw InternalException("approx_quantile: could not construct the DECIMAL limit"); + } + const auto limit_double = DecimalHelper::ToDouble(bignum_t(string_t(limit)), scale); + if (std::fabs(source) > std::fabs(limit_double)) { + throw OutOfRangeException("approx_quantile: the approximate quantile %s is out of the range of %s", + Value::DOUBLE(source).ToString(), type.ToString()); + } + target = bignum_t(StringVector::AddStringOrBlob(result, limit)); +} + +template <> +double ApproxQuantileCoding::Encode(const dtime_t &input, const LogicalType &type) { + return Encode(input.value, type); } template <> @@ -76,8 +131,8 @@ bool ApproxQuantileCoding::Decode(const double &source, dtime_t &target) { } template <> -double ApproxQuantileCoding::Encode(const dtime_tz_t &input) { - return Encode(input.sort_key()); +double ApproxQuantileCoding::Encode(const dtime_tz_t &input, const LogicalType &type) { + return Encode(input.sort_key(), type); } template <> @@ -100,8 +155,8 @@ bool ApproxQuantileCoding::Decode(const double &source, dtime_tz_t &target) { } template <> -double ApproxQuantileCoding::Encode(const timestamp_t &input) { - return Encode(input.value); +double ApproxQuantileCoding::Encode(const timestamp_t &input, const LogicalType &type) { + return Encode(input.value, type); } template <> @@ -169,7 +224,8 @@ struct ApproxQuantileOperation { template static void Operation(STATE &state, const INPUT_TYPE &input, AggregateUnaryInput &unary_input) { - auto val = ApproxQuantileCoding::template Encode(input); + const auto &type = unary_input.input.function.GetArguments()[0]; + const auto val = ApproxQuantileCoding::template Encode(input, type); if (!Value::DoubleIsFinite(val)) { return; } @@ -219,7 +275,7 @@ struct ApproxQuantileScalarOperation : public ApproxQuantileOperation { auto &bind_data = finalize_data.input.bind_data->template Cast(); D_ASSERT(bind_data.quantiles.size() == 1); const auto source = state.h->quantile(bind_data.quantiles[0]); - ApproxQuantileCoding::Decode(source, target, finalize_data.result.GetType()); + ApproxQuantileCoding::Decode(source, target, finalize_data.result); } }; @@ -401,19 +457,23 @@ AggregateFunction GetApproximateQuantileAggregateFunction(const LogicalType &typ case PhysicalType::DOUBLE: return AggregateFunction::UnaryAggregate( type, type); + case PhysicalType::VARCHAR: { + if (type.id() != LogicalTypeId::DECIMAL) { + throw NotImplementedException("Unimplemented quantile aggregate"); + } + // the bignum_t tier of decimals (above 38 digits) + auto function = + AggregateFunction::UnaryAggregate( + type, type); + // a value beyond the DOUBLE range does not fit the sketch + function.SetFallible(); + return function; + } default: throw NotImplementedException("Unimplemented quantile aggregate"); } } -//! Wide decimals have no approximate quantile of their own, they are aggregated as DOUBLE -LogicalType ApproxQuantileInputType(const LogicalType &type) { - if (type.id() == LogicalTypeId::DECIMAL && Decimal::IsWide(DecimalType::GetWidth(type))) { - return LogicalType::DOUBLE; - } - return type; -} - AggregateFunction GetApproximateQuantileDecimalAggregateFunction(const LogicalType &type) { switch (type.InternalType()) { case PhysicalType::INT8: @@ -421,6 +481,8 @@ AggregateFunction GetApproximateQuantileDecimalAggregateFunction(const LogicalTy case PhysicalType::INT32: case PhysicalType::INT64: case PhysicalType::INT128: + case PhysicalType::VARCHAR: + // plans serialized before the bignum_t tier had an approximate quantile aggregated wide decimals as DOUBLE case PhysicalType::DOUBLE: // keep the DECIMAL type as the input and return type so that the width and scale survive the bind return GetApproximateQuantileAggregateFunction(type); @@ -492,7 +554,7 @@ void ReplaceApproxQuantileImplementation(BoundAggregateFunction &function, const unique_ptr BindApproxQuantileDecimal(BindAggregateFunctionInput &input) { auto &function = input.GetBoundFunction(); auto &arguments = input.GetArguments(); - auto decimal_type = ApproxQuantileInputType(arguments[0]->GetReturnType()); + auto decimal_type = arguments[0]->GetReturnType(); auto bind_data = BindApproxQuantile(input); ReplaceApproxQuantileImplementation(function, ApproxQuantileDecimalFunction(decimal_type)); return bind_data; @@ -536,8 +598,7 @@ struct ApproxQuantileListOperation : public ApproxQuantileOperation { for (size_t q = 0; q < entry.length; ++q) { const auto &quantile = bind_data.quantiles[q]; const auto &source = state.h->quantile(quantile); - auto &target = rdata[ridx + q]; - ApproxQuantileCoding::Decode(source, target, result.GetType()); + ApproxQuantileCoding::Decode(source, rdata[ridx + q], result); } ListVector::SetListSize(finalize_data.result, entry.offset + entry.length); @@ -599,6 +660,13 @@ AggregateFunction GetApproxQuantileListAggregateFunction(const LogicalType &type return GetTypedApproxQuantileListAggregateFunction(type); case PhysicalType::INT128: return GetTypedApproxQuantileListAggregateFunction(type); + case PhysicalType::VARCHAR: { + // the bignum_t tier of decimals (above 38 digits) + auto function = GetTypedApproxQuantileListAggregateFunction(type); + // a value beyond the DOUBLE range does not fit the sketch + function.SetFallible(); + return function; + } default: throw NotImplementedException("Unimplemented approximate quantile list decimal aggregate"); } @@ -619,7 +687,7 @@ AggregateFunction ApproxQuantileDecimalListFunction(const LogicalType &type) { unique_ptr BindApproxQuantileDecimalList(BindAggregateFunctionInput &input) { auto &function = input.GetBoundFunction(); auto &arguments = input.GetArguments(); - auto decimal_type = ApproxQuantileInputType(arguments[0]->GetReturnType()); + auto decimal_type = arguments[0]->GetReturnType(); auto bind_data = BindApproxQuantile(input); ReplaceApproxQuantileImplementation(function, ApproxQuantileDecimalListFunction(decimal_type)); return bind_data; diff --git a/src/duckdb/extension/core_functions/aggregate/holistic/mad.cpp b/src/duckdb/extension/core_functions/aggregate/holistic/mad.cpp index 1e9359190..356d226ba 100644 --- a/src/duckdb/extension/core_functions/aggregate/holistic/mad.cpp +++ b/src/duckdb/extension/core_functions/aggregate/holistic/mad.cpp @@ -1,11 +1,13 @@ #include "core_functions/aggregate/holistic_functions.hpp" #include "core_functions/aggregate/quantile_state.hpp" +#include "duckdb/common/bignum.hpp" #include "duckdb/common/helper.hpp" #include "duckdb/common/operator/abs.hpp" #include "duckdb/common/operator/cast_operators.hpp" #include "duckdb/common/operator/subtract.hpp" #include "duckdb/common/smaller_binary.hpp" #include "duckdb/common/typedefs.hpp" +#include "duckdb/common/types/string_heap.hpp" #include "duckdb/planner/expression.hpp" namespace duckdb { @@ -41,6 +43,27 @@ struct MadAccessor { } }; +// bignum_t - bignum_t => bignum_t +template <> +struct MadAccessor { + using INPUT_TYPE = bignum_t; + using RESULT_TYPE = bignum_t; + using MEDIAN_TYPE = bignum_t; + const MEDIAN_TYPE &median; + //! the deviations are BIGNUM blobs, which live in the heap of the accessor + mutable StringHeap heap; + explicit MadAccessor(const MEDIAN_TYPE &median_p) : median(median_p) { + } + inline RESULT_TYPE operator()(const INPUT_TYPE &input) const { + // the blobs order like their values: the absolute deviation is the larger value minus the smaller one + const auto &larger = input < median ? median : input; + const auto &smaller = input < median ? input : median; + const BignumIntermediate lhs(larger); + const BignumIntermediate rhs(smaller); + return bignum_t(BignumIntermediate::Add(heap, lhs, rhs, true)); + } +}; + // hugeint_t - double => undefined template <> struct MadAccessor { @@ -166,7 +189,17 @@ struct MedianAbsoluteDeviationOperation : QuantileOperation { const auto med = interp.template Operation(flattened.Data(), finalize_data.result); MadAccessor accessor(med); - target = interp.template Operation(flattened.Data(), finalize_data.result, accessor); + if constexpr (std::is_same::value) { + // BIGNUM deviations are allocated blobs: compute each one once instead of inside every comparison of the + // selection, replacing the flattened values (scratch space) by their deviations + auto values = flattened.Data(); + for (idx_t i = 0; i < state.linked_list.total_capacity; i++) { + values[i] = accessor(values[i]); + } + target = interp.template Operation(values, finalize_data.result); + } else { + target = interp.template Operation(flattened.Data(), finalize_data.result, accessor); + } } template @@ -306,6 +339,9 @@ AggregateFunction GetMedianAbsoluteDeviationAggregateFunctionInternal(const Logi return GetTypedMedianAbsoluteDeviationAggregateFunction(type, type); case PhysicalType::INT128: return GetTypedMedianAbsoluteDeviationAggregateFunction(type, type); + case PhysicalType::VARCHAR: + // the bignum_t tier (above 38 digits): the BIGNUM blobs of the unscaled values + return GetTypedMedianAbsoluteDeviationAggregateFunction(type, type); default: throw NotImplementedException("Unimplemented Median Absolute Deviation DECIMAL aggregate"); } diff --git a/src/duckdb/extension/core_functions/aggregate/holistic/quantile.cpp b/src/duckdb/extension/core_functions/aggregate/holistic/quantile.cpp index caf2bddcb..3268ebc90 100644 --- a/src/duckdb/extension/core_functions/aggregate/holistic/quantile.cpp +++ b/src/duckdb/extension/core_functions/aggregate/holistic/quantile.cpp @@ -1,5 +1,8 @@ #include "core_functions/aggregate/holistic_functions.hpp" +#include "duckdb/common/bignum.hpp" +#include "duckdb/common/types/bignum_decimal.hpp" #include "duckdb/common/types/decimal.hpp" +#include "duckdb/common/types/string_heap.hpp" #include "core_functions/aggregate/quantile_state.hpp" #include "duckdb/common/enums/quantile_enum.hpp" #include "duckdb/common/operator/abs.hpp" @@ -168,6 +171,68 @@ string_t QuantileCast::Operation(const string_t &src, Vector &result) { return StringVector::AddStringOrBlob(result, src); } +template <> +bignum_t QuantileCast::Operation(const bignum_t &src, Vector &result) { + return bignum_t(StringVector::AddStringOrBlob(result, src.data)); +} + +//===--------------------------------------------------------------------===// +// Quantile Interpolation +//===--------------------------------------------------------------------===// +//! The delta between two wide decimals scaled by the interpolation fraction and truncated towards zero. +//! A delta that a DOUBLE holds exactly is scaled in DOUBLE, as the hugeint tier computes it, so that the same values in +//! a fixed-size and in a wide decimal interpolate to the same result. Any other delta (one that needs more than 53 +//! bits, where the DOUBLE of the hugeint tier is already inexact, or one beyond the DOUBLE range) applies the fraction +//! exactly as mantissa / 2^shift: the median of -0.5 and 0.5 at scale 38 is exactly 0 +static string ScaleWideDecimalDelta(const bignum_t &delta, const double d, StringHeap &heap, + BignumArithmeticState &state) { + const auto delta_double = DecimalHelper::ToDouble(delta, 0); + if (std::isfinite(delta_double) && string_t(DecimalHelper::FromDouble(delta_double)) == delta.data) { + return DecimalHelper::FromDouble(std::trunc(delta_double * d)); + } + int exponent; + const double fraction = std::frexp(d, &exponent); + const auto mantissa = static_cast(std::ldexp(fraction, 53)); + // 0 < d < 1, so the fraction is divided by a power of two + const int shift = 53 - exponent; + D_ASSERT(shift > 0); + const string mantissa_blob = DecimalHelper::FromInteger(hugeint_t(mantissa)); + const bignum_t mantissa_value {string_t(mantissa_blob)}; + const BignumIntermediate mantissa_intermediate(mantissa_value); + const BignumIntermediate delta_intermediate(delta); + const bignum_t product {BignumIntermediate::Multiply(heap, state, delta_intermediate, mantissa_intermediate)}; + const BignumIntermediate product_intermediate(product); + const string power_blob = DecimalHelper::PowerOfTwo(NumericCast(shift)); + const bignum_t power_value {string_t(power_blob)}; + const BignumIntermediate power(power_value); + string_t quotient; + string_t remainder; + if (!BignumIntermediate::TryDivMod(heap, state, product_intermediate, power, quotient, remainder)) { + throw InternalException("QUANTILE: division by a power of two failed"); + } + return quotient.GetString(); +} + +//! The bignum_t tier of decimals interpolates like the hugeint tier: the exact delta between the two values is scaled +//! by the fraction and truncated towards zero - see ScaleWideDecimalDelta for the deltas a DOUBLE does not hold +template <> +bignum_t QuantileInterpolate::Operation(const bignum_t &lo, const double d, const bignum_t &hi, Vector &result) { + D_ASSERT(result.GetType().id() == LogicalTypeId::DECIMAL); + if (d == 0) { + return lo; + } + // an intermediate refers to the bytes of the bignum_t it is built from, which therefore outlives it + StringHeap heap; + BignumArithmeticState state; + const BignumIntermediate start(lo); + const BignumIntermediate end(hi); + const bignum_t delta {BignumIntermediate::Add(heap, end, start, true)}; + const string offset_blob = ScaleWideDecimalDelta(delta, d, heap, state); + const bignum_t offset_value {string_t(offset_blob)}; + const BignumIntermediate offset(offset_value); + return bignum_t(StringVector::AddStringOrBlob(result, BignumIntermediate::Add(heap, start, offset))); +} + //===--------------------------------------------------------------------===// // Scalar Quantile //===--------------------------------------------------------------------===// @@ -547,6 +612,9 @@ AggregateFunction GetContinuousQuantileTemplated(const LogicalType &type) { return OP::template GetFunction(type, type); case PhysicalType::INT128: return OP::template GetFunction(type, type); + case PhysicalType::VARCHAR: + // the bignum_t tier (above 38 digits) buffers and interpolates the BIGNUM blobs of the unscaled values + return OP::template GetFunction(type, type); default: throw NotImplementedException("Unimplemented continuous quantile DECIMAL aggregate"); } @@ -723,14 +791,6 @@ static bool CanInterpolate(const LogicalType &type) { } } -//! Wide decimals have no exact interpolation, they are interpolated as DOUBLE -static LogicalType InterpolationType(const LogicalType &type) { - if (type.id() == LogicalTypeId::DECIMAL && Decimal::IsWide(DecimalType::GetWidth(type))) { - return LogicalType::DOUBLE; - } - return type; -} - struct MedianFunction { static AggregateFunction GetAggregate(const LogicalType &type) { const auto can_interpolate = CanInterpolate(type); @@ -756,7 +816,7 @@ struct MedianFunction { static unique_ptr Bind(BindAggregateFunctionInput &input) { auto &function = input.GetBoundFunction(); auto &arguments = input.GetArguments(); - function.ReplaceImplementation(GetAggregate(InterpolationType(arguments[0]->GetReturnType()))); + function.ReplaceImplementation(GetAggregate(arguments[0]->GetReturnType())); return make_uniq(Value::DECIMAL(int16_t(5), 2, 1)); } }; @@ -865,9 +925,9 @@ struct ContinuousQuantileFunction { static unique_ptr Bind(BindAggregateFunctionInput &input) { auto &function = input.GetBoundFunction(); auto &arguments = input.GetArguments(); - auto impl = GetAggregate(function.GetArguments()[0].id() == LogicalTypeId::DECIMAL - ? InterpolationType(arguments[0]->GetReturnType()) - : function.GetArguments()[0]); + auto impl = + GetAggregate(function.GetArguments()[0].id() == LogicalTypeId::DECIMAL ? arguments[0]->GetReturnType() + : function.GetArguments()[0]); function.ReplaceImplementation(impl); return BindQuantile(input); } @@ -899,9 +959,9 @@ struct ContinuousQuantileListFunction { static unique_ptr Bind(BindAggregateFunctionInput &input) { auto &function = input.GetBoundFunction(); auto &arguments = input.GetArguments(); - auto impl = GetAggregate(function.GetArguments()[0].id() == LogicalTypeId::DECIMAL - ? InterpolationType(arguments[0]->GetReturnType()) - : function.GetArguments()[0]); + auto impl = + GetAggregate(function.GetArguments()[0].id() == LogicalTypeId::DECIMAL ? arguments[0]->GetReturnType() + : function.GetArguments()[0]); function.ReplaceImplementation(impl); return BindQuantile(input); } diff --git a/src/duckdb/extension/core_functions/aggregate/holistic/reservoir_quantile.cpp b/src/duckdb/extension/core_functions/aggregate/holistic/reservoir_quantile.cpp index 7b40dea4a..e8a0a8b0c 100644 --- a/src/duckdb/extension/core_functions/aggregate/holistic/reservoir_quantile.cpp +++ b/src/duckdb/extension/core_functions/aggregate/holistic/reservoir_quantile.cpp @@ -1,7 +1,9 @@ #include "duckdb/common/types.hpp" +#include "duckdb/common/bignum.hpp" #include "duckdb/common/types/decimal.hpp" #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/common/vector/list_vector.hpp" +#include "duckdb/common/vector/string_vector.hpp" #include "duckdb/execution/expression_executor.hpp" #include "duckdb/execution/reservoir_sample.hpp" #include "core_functions/aggregate/holistic_functions.hpp" @@ -43,6 +45,10 @@ struct ReservoirQuantileSampler : public ReservoirSampler 0); @@ -59,6 +65,35 @@ struct ReservoirQuantileSampler : public ReservoirSampler::value, "the sampler lives in an arena"); +//! How the sample keeps a value and how a sampled value becomes a result: the value itself for the fixed-size types +template +struct ReservoirQuantileValue { + static T Own(const T &value, ArenaAllocator &) { + return value; + } + static T Result(const T &value, Vector &) { + return value; + } +}; + +//! The unscaled values of DECIMALs wider than 38 digits are BIGNUM blobs, which order like their values: the sample +//! owns the bytes of its blobs in the aggregate's arena, a result is copied to the result vector +template <> +struct ReservoirQuantileValue { + static bignum_t Own(const bignum_t &value, ArenaAllocator &allocator) { + if (value.data.IsInlined()) { + return value; + } + const auto size = value.data.GetSize(); + auto data = allocator.Allocate(size); + memcpy(data, value.data.GetData(), size); + return bignum_t(string_t(const_char_ptr_cast(data), UnsafeNumericCast(size))); + } + static bignum_t Result(const bignum_t &value, Vector &result) { + return bignum_t(StringVector::AddStringOrBlob(result, value.data)); + } +}; + //! All memory of the state is allocated from the aggregate's arena, so the state needs no destructor template struct ReservoirQuantileState { @@ -68,12 +103,67 @@ struct ReservoirQuantileState { idx_t capacity; ReservoirQuantileSampler *r_samp; - void ReplaceElement(T &input) { - v[r_samp->min_weighted_entry_index] = input; + void ReplaceElement(const T &input, ArenaAllocator &allocator) { + v[r_samp->min_weighted_entry_index] = ReservoirQuantileValue::Own(input, allocator); r_samp->ReplaceElement(); } - void FillReservoir(idx_t sample_size, T element, ArenaAllocator &allocator) { + //! Makes this state a copy of the sampled source in this state's arena, so that Combine leaves the source intact + void CopySampled(const ReservoirQuantileState &source, ArenaAllocator &allocator) { + D_ASSERT(source.r_samp && source.pos == len); + v = reinterpret_cast(allocator.AllocateAligned(len * sizeof(T))); + for (idx_t i = 0; i < len; i++) { + v[i] = ReservoirQuantileValue::Own(source.v[i], allocator); + } + pos = capacity = len; + r_samp = allocator.Make(*source.r_samp); + // the copy continues with Algorithm R, so it needs no keys + r_samp->weights = nullptr; + r_samp->merged = true; + } + + //! Merges two full samples into a uniform sample of all the rows both were drawn from + void MergeSampled(const ReservoirQuantileState &source, ArenaAllocator &allocator) { + D_ASSERT(r_samp && source.r_samp && pos == len && source.pos == len); + auto &sampler = *r_samp; + auto &rng = sampler.random; + // draw how many of the len slots come from this state's rows, without replacement from both row sets + idx_t own_left = sampler.row_count; + idx_t other_left = source.r_samp->row_count; + idx_t keep = 0; + for (idx_t i = 0; i < len; i++) { + if (RandomEngine::NextRandomInteger64Below(rng, own_left + other_left) < own_left) { + keep++; + own_left--; + } else { + other_left--; + } + } + // a uniform subset of this sample in front, then a uniform subset of the source sample + // slot bounds fit in 32 bits, since the sample size is an INTEGER + for (idx_t i = 0; i < keep; i++) { + std::swap(v[i], v[i + rng(NumericCast(len - i))]); + } + idx_t needed = len - keep; + for (idx_t i = 0; i < len && needed > 0; i++) { + if (rng(NumericCast(len - i)) < needed) { + v[len - needed] = ReservoirQuantileValue::Own(source.v[i], allocator); + needed--; + } + } + sampler.merged = true; + sampler.row_count += source.r_samp->row_count; + } + + //! the row replaces a uniform slot with probability len / row_count + void ReplaceUniform(const T &element, ArenaAllocator &allocator) { + const auto slot = RandomEngine::NextRandomInteger64Below(r_samp->random, r_samp->row_count); + if (slot < len) { + v[slot] = ReservoirQuantileValue::Own(element, allocator); + } + } + + void FillReservoir(idx_t sample_size, const T &element, ArenaAllocator &allocator) { if (pos < sample_size) { if (pos == capacity) { // grow lazily, so that small groups do not pay for the full sample size @@ -85,18 +175,24 @@ struct ReservoirQuantileState { : allocator.AllocateAligned(new_size)); capacity = new_capacity; } - v[pos++] = element; + v[pos++] = ReservoirQuantileValue::Own(element, allocator); } else { if (!r_samp) { auto weights = allocator.AllocateAligned(len * sizeof(ReservoirQuantileSampler::Weight)); auto sampler = allocator.Make( reinterpret_cast(weights)); sampler->InitializeReservoirWeights(pos, len); + sampler->row_count = pos; r_samp = sampler; } + r_samp->row_count++; + if (r_samp->merged) { + ReplaceUniform(element, allocator); + return; + } D_ASSERT(r_samp->next_index_to_sample >= r_samp->num_entries_to_skip_b4_next_sample); if (r_samp->next_index_to_sample == r_samp->num_entries_to_skip_b4_next_sample) { - ReplaceElement(element); + ReplaceElement(element, allocator); } else { r_samp->num_entries_to_skip_b4_next_sample++; } @@ -196,9 +292,25 @@ struct ReservoirQuantileOperation { if (target.pos == 0) { target.len = MaxValue(target.len, source.len); } - for (idx_t src_idx = 0; src_idx < source.pos; src_idx++) { - target.FillReservoir(target.len, source.v[src_idx], aggr_input_data.allocator); + auto &allocator = aggr_input_data.allocator; + if (!source.r_samp) { + // the source holds all of its rows + for (idx_t src_idx = 0; src_idx < source.pos; src_idx++) { + target.FillReservoir(target.len, source.v[src_idx], allocator); + } + return; + } + if (!target.r_samp) { + // the target holds all of its rows: continue from a copy of the source with them + const auto rows = target.v; + const auto row_count = target.pos; + target.CopySampled(source, allocator); + for (idx_t row_idx = 0; row_idx < row_count; row_idx++) { + target.FillReservoir(target.len, rows[row_idx], allocator); + } + return; } + target.MergeSampled(source, allocator); } static bool IgnoreNull() { @@ -220,7 +332,7 @@ struct ReservoirQuantileScalarOperation : public ReservoirQuantileOperation { D_ASSERT(bind_data.quantiles.size() == 1); auto offset = (idx_t)((double)(state.pos - 1) * bind_data.quantiles[0]); std::nth_element(v_t, v_t + offset, v_t + state.pos); - target = v_t[offset]; + target = ReservoirQuantileValue::Result(v_t[offset], finalize_data.result); } }; @@ -298,7 +410,7 @@ struct ReservoirQuantileListOperation : public ReservoirQuantileOperation { const auto &quantile = bind_data.quantiles[q]; auto offset = (idx_t)((double)(state.pos - 1) * quantile); std::nth_element(v_t, v_t + offset, v_t + state.pos); - rdata[ridx + q] = v_t[offset]; + rdata[ridx + q] = ReservoirQuantileValue::Result(v_t[offset], result); } ListVector::SetListSize(finalize_data.result, entry.offset + entry.length); @@ -351,6 +463,9 @@ AggregateFunction GetReservoirQuantileListAggregateFunction(const LogicalType &t return GetTypedReservoirQuantileListAggregateFunction(type); case PhysicalType::INT128: return GetTypedReservoirQuantileListAggregateFunction(type); + case PhysicalType::VARCHAR: + // the bignum_t tier (above 38 digits) samples the BIGNUM blobs of the unscaled values + return GetTypedReservoirQuantileListAggregateFunction(type); default: throw NotImplementedException("Unimplemented reservoir quantile list aggregate"); } @@ -426,7 +541,14 @@ static void SetDecimalImplementation(BoundAggregateFunction &function, const Log AggregateFunction::UnaryAggregate, hugeint_t, hugeint_t, ReservoirQuantileScalarOperation>(decimal_type, decimal_type)); break; + case PhysicalType::VARCHAR: + // the bignum_t tier (above 38 digits) samples the BIGNUM blobs of the unscaled values + function.ReplaceImplementation( + AggregateFunction::UnaryAggregate, bignum_t, bignum_t, + ReservoirQuantileScalarOperation>(decimal_type, decimal_type)); + break; case PhysicalType::DOUBLE: + // plans serialized before the bignum_t tier had a reservoir quantile aggregated wide decimals as DOUBLE function.ReplaceImplementation(GetReservoirQuantileAggregateFunction(PhysicalType::DOUBLE)); break; default: @@ -465,11 +587,7 @@ unique_ptr BindReservoirQuantileDecimal(BindAggregateFunctionInput auto &function = input.GetBoundFunction(); auto &arguments = input.GetArguments(); - // wide decimals have no reservoir quantile of their own, they are aggregated as DOUBLE auto decimal_type = arguments[0]->GetReturnType(); - if (Decimal::IsWide(DecimalType::GetWidth(decimal_type))) { - decimal_type = LogicalType::DOUBLE; - } bool is_list = arguments[1]->GetReturnType().id() == LogicalTypeId::LIST; auto bind_data_ptr = BindReservoirQuantile(input); diff --git a/src/duckdb/extension/core_functions/aggregate/nested/binned_histogram.cpp b/src/duckdb/extension/core_functions/aggregate/nested/binned_histogram.cpp index e152fa4f3..a2a4f4818 100644 --- a/src/duckdb/extension/core_functions/aggregate/nested/binned_histogram.cpp +++ b/src/duckdb/extension/core_functions/aggregate/nested/binned_histogram.cpp @@ -357,9 +357,12 @@ AggregateFunction GetHistogramBinFunction(const LogicalType &type) { template AggregateFunction GetHistogramBinFunction(const LogicalType &type) { - if (type.id() == LogicalTypeId::DECIMAL) { - return GetHistogramBinFunction(LogicalType::DOUBLE); + if (type.id() == LogicalTypeId::DECIMAL && type.InternalType() == PhysicalType::VARCHAR) { + // a DECIMAL wider than 38 digits stores its unscaled value as a BIGNUM blob: bin it by its sort key, as text it + // would be compared as a string + return GetHistogramBinFunction(type); } + // the bins of a DECIMAL are DECIMALs of the same type, a value is compared with them exactly switch (type.InternalType()) { #if !DUCKDB_SMALLER_BINARY(binned_histogram_types) case PhysicalType::BOOL: diff --git a/src/duckdb/extension/core_functions/aggregate/nested/list.cpp b/src/duckdb/extension/core_functions/aggregate/nested/list.cpp index 07f00ccb2..ec1f5ba0a 100644 --- a/src/duckdb/extension/core_functions/aggregate/nested/list.cpp +++ b/src/duckdb/extension/core_functions/aggregate/nested/list.cpp @@ -1,4 +1,7 @@ #include "duckdb/function/aggregate/list_aggregate.hpp" +#include "duckdb/planner/expression/bound_aggregate_expression.hpp" +#include "duckdb/storage/statistics/list_stats.hpp" +#include "duckdb/storage/statistics/node_statistics.hpp" #include "core_functions/aggregate/nested_functions.hpp" namespace duckdb { @@ -22,6 +25,35 @@ void ListFinalize(Vector &states_vector, AggregateFinalizeInputData &aggr_input_ functions.BuildLists(linked_lists, result, offset); } +unique_ptr ListStatsFunction(ClientContext &context, BoundAggregateExpression &expr, + AggregateStatisticsInput &input) { + if (expr.StateExportMode() == AggregateStateExportMode::STATE_EXPORT) { + return nullptr; + } + auto stats = ListStats::CreateUnknown(expr.GetReturnType()); + // the elements are exactly the input values. The callback cannot see grouping-set + // replication, so additive child statistics (e.g. string byte totals) are reset. + if (!input.child_stats.empty() && input.child_stats[0].GetType() == ListType::GetChildType(expr.GetReturnType())) { + auto child_stats = input.child_stats[0].ToUnique(); + child_stats->ResetAdditiveStatistics(); + ListStats::SetChildStats(stats, std::move(child_stats)); + } + // a list aggregate folds every input row into one list element, and an empty group yields NULL + auto length_data = ListStats::GetLengthData(stats); + if (input.node_stats && input.node_stats->has_max_cardinality && input.node_stats->max_cardinality >= 1) { + length_data.has_min_list_length = true; + length_data.min_list_length = 1; + length_data.has_max_list_length = true; + length_data.max_list_length = input.node_stats->max_cardinality; + } + if (input.node_stats && input.node_stats->has_estimated_cardinality) { + length_data.has_total_list_length = true; + length_data.total_list_length = input.node_stats->estimated_cardinality; + } + ListStats::SetLengthData(stats, length_data); + return stats.ToUnique(); +} + } // namespace AggregateFunction ListFun::GetFunction() { @@ -31,6 +63,7 @@ AggregateFunction ListFun::GetFunction() { ListCombineFunction, ListFinalize, ListClusterUpdate<>, nullptr, nullptr, nullptr); func.GetSignature().AddParameter("arg", LogicalType::TEMPLATE("T")); AggregateFunction::WireStructStateType(func); + func.SetStatisticsCallback(ListStatsFunction); return func; } diff --git a/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_sort_tree.hpp b/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_sort_tree.hpp index d047d0507..5107c06e6 100644 --- a/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_sort_tree.hpp +++ b/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_sort_tree.hpp @@ -8,6 +8,7 @@ #pragma once +#include "duckdb/common/bignum.hpp" #include "duckdb/common/types/column/column_data_collection.hpp" #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/common/vector/list_vector.hpp" @@ -165,6 +166,20 @@ template <> interval_t QuantileCast::Operation(const dtime_t &src, Vector &result); template <> string_t QuantileCast::Operation(const string_t &src, Vector &result); +template <> +bignum_t QuantileCast::Operation(const bignum_t &src, Vector &result); + +//! Linear interpolation between two quantile values; a value without a fixed size is allocated in the result vector +struct QuantileInterpolate { + template + static inline TARGET_TYPE Operation(const TARGET_TYPE &lo, const double d, const TARGET_TYPE &hi, Vector &result) { + return InterpolateOperator::Operation(lo, d, hi); + } +}; + +//! The unscaled values of DECIMALs wider than 38 digits (BIGNUM blobs) interpolate exactly +template <> +bignum_t QuantileInterpolate::Operation(const bignum_t &lo, const double d, const bignum_t &hi, Vector &result); // Continuous interpolation template @@ -182,7 +197,7 @@ struct QuantileInterpolator { } else { auto lo = QuantileCast::Operation(accessor(lidx), result); auto hi = QuantileCast::Operation(accessor(hidx), result); - return InterpolateOperator::Operation(lo, RN - FRN, hi); + return QuantileInterpolate::Operation(lo, RN - FRN, hi, result); } } @@ -198,7 +213,7 @@ struct QuantileInterpolator { std::nth_element(v_t + FRN, v_t + CRN, v_t + end, comp); auto lo = QuantileCast::Operation(accessor(v_t[FRN]), result); auto hi = QuantileCast::Operation(accessor(v_t[CRN]), result); - return InterpolateOperator::Operation(lo, RN - FRN, hi); + return QuantileInterpolate::Operation(lo, RN - FRN, hi, result); } } @@ -209,7 +224,7 @@ struct QuantileInterpolator { } else { auto lo = QuantileCast::Operation(dest[0], result); auto hi = QuantileCast::Operation(dest[1], result); - return InterpolateOperator::Operation(lo, RN - FRN, hi); + return QuantileInterpolate::Operation(lo, RN - FRN, hi, result); } } diff --git a/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_state.hpp b/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_state.hpp index e6aba7211..77f28595f 100644 --- a/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_state.hpp +++ b/src/duckdb/extension/core_functions/include/core_functions/aggregate/quantile_state.hpp @@ -169,6 +169,19 @@ struct QuantileSkipValue { } }; +//! The BIGNUM blobs of the wide decimals point into the cursor page as well +template <> +struct QuantileSkipValue { + using type = string; + + static inline type Store(const bignum_t &value) { + return value.data.GetString(); + } + static inline bignum_t Load(const type &stored) { + return bignum_t(string_t(stored)); + } +}; + template struct WindowQuantileState { // Windowed Quantile merge sort trees diff --git a/src/duckdb/extension/core_functions/lambda_functions.cpp b/src/duckdb/extension/core_functions/lambda_functions.cpp index 1c964e6e5..b78fa5890 100644 --- a/src/duckdb/extension/core_functions/lambda_functions.cpp +++ b/src/duckdb/extension/core_functions/lambda_functions.cpp @@ -229,7 +229,7 @@ void ListLambdaBindData::Serialize(Serializer &serializer, const optional_ptrCast(); serializer.WriteProperty(100, "return_type", bind_data.return_type); - serializer.WritePropertyWithDefault(101, "lambda_expr", bind_data.lambda_expr, unique_ptr()); + serializer.WritePropertyWithDefault>(101, "lambda_expr", bind_data.lambda_expr); serializer.WriteProperty(102, "has_index", bind_data.has_index); serializer.WritePropertyWithDefault(103, "has_initial", bind_data.has_initial, false); } diff --git a/src/duckdb/extension/core_functions/scalar/date/date_part.cpp b/src/duckdb/extension/core_functions/scalar/date/date_part.cpp index b5df76a40..7af4afb6e 100644 --- a/src/duckdb/extension/core_functions/scalar/date/date_part.cpp +++ b/src/duckdb/extension/core_functions/scalar/date/date_part.cpp @@ -2261,14 +2261,14 @@ date_t LastDayOperator::Operation(timestamp_t input) { struct MonthNameOperator { template static inline TR Operation(TA input) { - return Date::MONTH_NAMES[DatePart::MonthOperator::Operation(input) - 1]; + return Date::MonthNames()[DatePart::MonthOperator::Operation(input) - 1]; } }; struct DayNameOperator { template static inline TR Operation(TA input) { - return Date::DAY_NAMES[DatePart::DayOfWeekOperator::Operation(input)]; + return Date::DayNames()[DatePart::DayOfWeekOperator::Operation(input)]; } }; diff --git a/src/duckdb/extension/core_functions/scalar/list/list_sort.cpp b/src/duckdb/extension/core_functions/scalar/list/list_sort.cpp index 191662f98..2816bf46f 100644 --- a/src/duckdb/extension/core_functions/scalar/list/list_sort.cpp +++ b/src/duckdb/extension/core_functions/scalar/list/list_sort.cpp @@ -1,6 +1,8 @@ #include "duckdb/common/type_visitor.hpp" #include "duckdb/parser/expression/function_expression.hpp" +#include "duckdb/parser/expression/columnref_expression.hpp" #include "duckdb/parser/expression/constant_expression.hpp" +#include "duckdb/parser/expression/lambda_expression.hpp" #include "duckdb/planner/bound_expression_sql_exporter.hpp" #include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/common/vector/list_vector.hpp" @@ -15,6 +17,8 @@ #include "duckdb/planner/expression/bound_cast_expression.hpp" #include "duckdb/execution/expression_executor.hpp" #include "duckdb/planner/expression/bound_reference_expression.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression_iterator.hpp" #include "duckdb/main/config.hpp" #include "duckdb/main/settings.hpp" #include "duckdb/common/sorting/sort.hpp" @@ -416,13 +420,91 @@ static unique_ptr ListReverseSortBind(BindScalarFunctionInput &inp return ListSortBind(context, bound_function, arguments, order, null_order); } +static unique_ptr SystemFunction(const char *name, vector> children) { + return make_uniq(QualifiedName("system", "main", name), std::move(children)); +} + +static void ReplaceElementReference(unique_ptr &expr, const Expression &element) { + if (expr->GetExpressionClass() == ExpressionClass::BOUND_REF) { + expr = element.Copy(); + return; + } + if (expr->GetExpressionClass() == ExpressionClass::BOUND_LAMBDA) { + // the references of a lambda are its own parameters + return; + } + ExpressionIterator::EnumerateChildren( + *expr, [&](unique_ptr &child) { ReplaceElementReference(child, element); }); +} + +//! Exports the sort by its retained key: the list is rearranged by the order of create_sort_key over the key of each +//! element. The key holds the collation functions the sort was bound with, so the generated SQL binds no collation. +static unique_ptr ListSortKeyUnbind(FunctionUnbindInput &input, const ListSortBindData &data) { + auto key = data.sort_key->Copy(); + ReplaceElementReference( + key, BoundColumnRefExpression(data.child_type, ColumnBinding(TableIndex(0), ProjectionIndex(0)))); + BoundExpressionSQLExportContext context; + context.client_context = &data.context; + context.resolve_binding = [&](const ColumnBinding &) { + return optional(ResolvedSQLColumnReference {{Identifier("e")}, data.child_type}); + }; + auto exported_key = BoundExpressionSQLExporter::Export(*key, context); + if (exported_key.HasError()) { + return nullptr; + } + // create_sort_key encodes the order and the position of the NULLs, the keys themselves sort ascending + vector> children; + children.push_back(std::move(exported_key.GetValue())); + children.push_back(ConstantExpression::String( + StringUtil::Format("%s NULLS %s", data.order_type == OrderType::ASCENDING ? "ASC" : "DESC", + data.null_order == OrderByNullType::NULLS_FIRST ? "FIRST" : "LAST"))); + auto element_key = + make_uniq(vector {"e"}, SystemFunction("create_sort_key", std::move(children))); + children.clear(); + if (data.is_grade_up) { + children.push_back(std::move(input.children[0])); + } else { + children.push_back(make_uniq(Identifier("l"))); + } + children.push_back(std::move(element_key)); + auto keys = SystemFunction("list_transform", std::move(children)); + children.clear(); + children.push_back(std::move(keys)); + children.push_back(ConstantExpression::String("ASC")); + children.push_back(ConstantExpression::String("NULLS LAST")); + auto result = SystemFunction("list_grade_up", std::move(children)); + if (!data.is_grade_up) { + // invoke evaluates the list once + children.clear(); + children.push_back(make_uniq(Identifier("l"))); + children.push_back(std::move(result)); + auto sorted = + make_uniq(vector {"l"}, SystemFunction("list_select", std::move(children))); + children.clear(); + children.push_back(std::move(sorted)); + children.push_back(std::move(input.children[0])); + result = SystemFunction("invoke", std::move(children)); + } + auto result_type = BoundExpressionSQLExporter::Export(BoundConstantExpression(Value(data.return_type)), {}); + if (result_type.HasError()) { + return nullptr; + } + children.clear(); + children.push_back(std::move(result)); + children.push_back(std::move(result_type.GetValue())); + return SystemFunction("cast_to_type", std::move(children)); +} + static unique_ptr ListSortUnbind(FunctionUnbindInput &input) { if (input.children.empty() || !input.expression.BindInfo()) { return nullptr; } auto &data = input.expression.BindInfo()->Cast(); - if (!data.default_collation || - TypeVisitor::Contains(data.child_type, [](const LogicalType &type) { return type.HasAlias(); })) { + if (TypeVisitor::Contains(data.child_type, [](const LogicalType &type) { return type.HasAlias(); })) { + // a cast cannot state a collation on an aliased type such as JSON + return ListSortKeyUnbind(input, data); + } + if (!data.default_collation) { return nullptr; } auto type = TypeVisitor::VisitReplace(data.child_type, [&](const LogicalType &child) { diff --git a/src/duckdb/extension/icu/collation/collation_loader.cpp b/src/duckdb/extension/icu/collation/collation_loader.cpp index 51f8c277b..3a7c870da 100644 --- a/src/duckdb/extension/icu/collation/collation_loader.cpp +++ b/src/duckdb/extension/icu/collation/collation_loader.cpp @@ -3,6 +3,7 @@ #include "duckdb/common/exception.hpp" #include "duckdb/common/helper.hpp" #include "duckdb/common/mutex.hpp" +#include "duckdb/common/no_destructor.hpp" #include "duckdb/common/unique_ptr.hpp" #include "duckdb/common/unordered_map.hpp" #include "zstd.h" @@ -69,8 +70,8 @@ class UnitReader { class UnitCache { public: static UnitCache &Get() { - static UnitCache cache; - return cache; + static NoDestructor cache; + return *cache; } //! Decompresses a unit, or returns it when it was decompressed before @@ -169,12 +170,12 @@ const CollationNormalization &GetCollationNormalization() { } const CollationTailoring &GetCollationTailoring(uint32_t unit) { - static mutex lock; - static unordered_map> tailorings; + static NoDestructor lock; + static NoDestructor>> tailorings; - lock_guard guard(lock); - auto entry = tailorings.find(unit); - if (entry != tailorings.end()) { + lock_guard guard(*lock); + auto entry = tailorings->find(unit); + if (entry != tailorings->end()) { return *entry->second; } UnitReader reader(UnitCache::Get().Load(unit), collation_units[unit].size, TAILORING_ARRAY_COUNT); @@ -193,7 +194,7 @@ const CollationTailoring &GetCollationTailoring(uint32_t unit) { tailoring->reorder_table = reorder_count ? reorder : nullptr; auto &result = *tailoring; - tailorings[unit] = std::move(tailoring); + (*tailorings)[unit] = std::move(tailoring); return result; } diff --git a/src/duckdb/extension/icu/datetime/calendar.cpp b/src/duckdb/extension/icu/datetime/calendar.cpp index 322b2a1f2..3c0d92842 100644 --- a/src/duckdb/extension/icu/datetime/calendar.cpp +++ b/src/duckdb/extension/icu/datetime/calendar.cpp @@ -1,6 +1,7 @@ #include "calendar.hpp" #include "duckdb/common/string_util.hpp" +#include "duckdb/common/no_destructor.hpp" #include "grego.hpp" #include "coptic.hpp" #include "gregorian.hpp" @@ -1392,11 +1393,11 @@ unique_ptr Calendar::TryCreate(const string &type, unique_ptr &Calendar::GetAvailableTypes() { - static const vector TYPES = { - "buddhist", "chinese", "coptic", "dangi", "ethiopic", "ethiopic-amete-alem", - "gregorian", "hebrew", "indian", "islamic", "islamic-civil", "islamic-rgsa", - "islamic-tbla", "islamic-umalqura", "iso8601", "japanese", "persian", "roc"}; - return TYPES; + static const NoDestructor> TYPES( + vector {"buddhist", "chinese", "coptic", "dangi", "ethiopic", "ethiopic-amete-alem", "gregorian", + "hebrew", "indian", "islamic", "islamic-civil", "islamic-rgsa", "islamic-tbla", + "islamic-umalqura", "iso8601", "japanese", "persian", "roc"}); + return *TYPES; } } // namespace datetime diff --git a/src/duckdb/extension/icu/datetime/timezone.cpp b/src/duckdb/extension/icu/datetime/timezone.cpp index b2c74db27..1a1e143d0 100644 --- a/src/duckdb/extension/icu/datetime/timezone.cpp +++ b/src/duckdb/extension/icu/datetime/timezone.cpp @@ -1,6 +1,7 @@ #include "timezone.hpp" #include "duckdb/common/string_util.hpp" +#include "duckdb/common/no_destructor.hpp" #include "grego.hpp" #include @@ -409,7 +410,7 @@ unique_ptr TimeZone::TryCreate(const string &id) { } const vector &TimeZone::GetAvailableIds() { - static const auto IDS = []() { + static const NoDestructor> IDS([]() { vector result; const auto &tz = GetTZData(); for (idx_t i = 0; i < tz.zone_count; i++) { @@ -421,8 +422,8 @@ const vector &TimeZone::GetAvailableIds() { result.emplace_back(tz.zones[i].name); } return result; - }(); - return IDS; + }()); + return *IDS; } vector TimeZone::GetEquivalentIds(const string &id) { diff --git a/src/duckdb/extension/icu/datetime/tz_loader.cpp b/src/duckdb/extension/icu/datetime/tz_loader.cpp index 3baeff2f1..a84eefa0b 100644 --- a/src/duckdb/extension/icu/datetime/tz_loader.cpp +++ b/src/duckdb/extension/icu/datetime/tz_loader.cpp @@ -4,6 +4,7 @@ #include "duckdb/common/helper.hpp" #include "duckdb/common/unique_ptr.hpp" #include "duckdb/common/vector.hpp" +#include "duckdb/common/no_destructor.hpp" #include "zstd.h" #include "zstd_errors.h" @@ -184,8 +185,8 @@ static unique_ptr Decompress() { const TZData &GetTZData() { // the initialization of a local static is thread safe, and the block is kept afterwards - static const unique_ptr block = Decompress(); - return block->data; + static const NoDestructor> block(Decompress()); + return (*block)->data; } } // namespace datetime diff --git a/src/duckdb/extension/icu/icu-dateadd.cpp b/src/duckdb/extension/icu/icu-dateadd.cpp index 9a697edab..451666e59 100644 --- a/src/duckdb/extension/icu/icu-dateadd.cpp +++ b/src/duckdb/extension/icu/icu-dateadd.cpp @@ -18,7 +18,7 @@ static duckdb::unique_ptr ICUBindIntervalMonths(BindScalarFunction if (!calendar.SupportsIntervals()) { throw NotImplementedException("INTERVALs do not work with 13 month calendars. Try using DATE_DIFF instead."); } - return std::move(result); + return result; } struct ICUCalendarAdd { @@ -70,19 +70,13 @@ timestamp_tz_t ICUCalendarAdd::Operation(timestamp_tz_t timestamp, interval_t in int64_t millis = timestamp.value / Interval::MICROS_PER_MSEC; int64_t micros = timestamp.value % Interval::MICROS_PER_MSEC; - // Manually move the µs - micros += interval.micros % Interval::MICROS_PER_MSEC; - if (micros >= Interval::MICROS_PER_MSEC) { - micros -= Interval::MICROS_PER_MSEC; - ++millis; - } else if (micros < 0) { - micros += Interval::MICROS_PER_MSEC; - --millis; - } - - // Now use the calendar to add the other parts calendar->SetTime(millis); + // PG applies the interval fields from ragged to non-ragged, with months before days, + // regardless of the sign of each field + calendar->Add(CAL_MONTH, interval.months); + calendar->Add(CAL_DATE, interval.days); + // Break units apart to avoid overflow auto interval_h = interval.micros / Interval::MICROS_PER_MSEC; @@ -95,26 +89,19 @@ timestamp_tz_t ICUCalendarAdd::Operation(timestamp_tz_t timestamp, interval_t in const auto interval_m = static_cast(interval_h % Interval::MINS_PER_HOUR); interval_h /= Interval::MINS_PER_HOUR; - if (interval.months < 0 || interval.days < 0 || interval.micros < 0) { - // Add interval fields from lowest to highest (non-ragged to ragged) - calendar->Add(CAL_MILLISECOND, interval_ms); - calendar->Add(CAL_SECOND, interval_s); - calendar->Add(CAL_MINUTE, interval_m); - CalendarAddHour(calendar, interval_h); + CalendarAddHour(calendar, interval_h); + calendar->Add(CAL_MINUTE, interval_m); + calendar->Add(CAL_SECOND, interval_s); + calendar->Add(CAL_MILLISECOND, interval_ms); - // PG Adds months before days - calendar->Add(CAL_MONTH, interval.months); - calendar->Add(CAL_DATE, interval.days); - } else { - // PG Adds months before days - calendar->Add(CAL_MONTH, interval.months); - calendar->Add(CAL_DATE, interval.days); - - // Add interval fields from highest to lowest (ragged to non-ragged) - CalendarAddHour(calendar, interval_h); - calendar->Add(CAL_MINUTE, interval_m); - calendar->Add(CAL_SECOND, interval_s); - calendar->Add(CAL_MILLISECOND, interval_ms); + // Manually move the µs, carrying any borrowed ms into the calendar + micros += interval.micros % Interval::MICROS_PER_MSEC; + if (micros >= Interval::MICROS_PER_MSEC) { + micros -= Interval::MICROS_PER_MSEC; + calendar->Add(CAL_MILLISECOND, 1); + } else if (micros < 0) { + micros += Interval::MICROS_PER_MSEC; + calendar->Add(CAL_MILLISECOND, -1); } return ICUDateFunc::GetTime(calendar, micros); diff --git a/src/duckdb/extension/icu/icu-datepart.cpp b/src/duckdb/extension/icu/icu-datepart.cpp index fc4ca9a6e..1743550d9 100644 --- a/src/duckdb/extension/icu/icu-datepart.cpp +++ b/src/duckdb/extension/icu/icu-datepart.cpp @@ -262,11 +262,11 @@ struct ICUDatePart : public ICUDateFunc { if (mm == 12) { return "Undecimber"; } - return Date::MONTH_NAMES[mm]; + return Date::MonthNames()[mm]; } static string_t DayName(Calendar *calendar, const uint64_t micros) { - return Date::DAY_NAMES[ExtractDayOfWeek(calendar, micros)]; + return Date::DayNames()[ExtractDayOfWeek(calendar, micros)]; } template @@ -521,7 +521,6 @@ struct ICUDatePart : public ICUDateFunc { static duckdb::unique_ptr BindStruct(BindScalarFunctionInput &input) { auto &bound_function = input.GetBoundFunction(); auto &context = input.GetClientContext(); - auto &arguments = input.GetArguments(); // collect names and deconflict, construct return type auto parts_list = input.GetConstant(0); diff --git a/src/duckdb/extension/icu/icu-strptime.cpp b/src/duckdb/extension/icu/icu-strptime.cpp index 9f71710ea..9cb1b2d37 100644 --- a/src/duckdb/extension/icu/icu-strptime.cpp +++ b/src/duckdb/extension/icu/icu-strptime.cpp @@ -178,7 +178,6 @@ struct ICUStrptime : public ICUDateFunc { static void Parse(DataChunk &args, ExpressionState &state, Vector &result) { D_ASSERT(args.ColumnCount() == 2); const auto &str_arg = args.data[0]; - const auto &fmt_arg = args.data[1]; auto &func_expr = state.expr.Cast(); auto &info = func_expr.BindInfo()->Cast(); @@ -186,7 +185,7 @@ struct ICUStrptime : public ICUDateFunc { CalendarPtr calendar_ptr(info.calendar->Copy()); auto calendar = calendar_ptr.get(); - D_ASSERT(fmt_arg.GetVectorType() == VectorType::CONSTANT_VECTOR); + D_ASSERT(args.data[1].GetVectorType() == VectorType::CONSTANT_VECTOR); UnaryExecutor::Execute(str_arg, result, [&](string_t input) { T parsed; ParseOne(calendar, cache, input, info.formats, parsed); diff --git a/src/duckdb/extension/icu/icu_extension.cpp b/src/duckdb/extension/icu/icu_extension.cpp index 26a656c85..cd08fe75d 100644 --- a/src/duckdb/extension/icu/icu_extension.cpp +++ b/src/duckdb/extension/icu/icu_extension.cpp @@ -84,22 +84,20 @@ struct IcuBindData : public FunctionData { //! The prefix of the collation functions that are kept for backwards compatibility, which return the sort key in //! hexadecimal instead of as a blob. The collation functions themselves are named after the collation. - static const string HEX_FUNCTION_PREFIX; + static constexpr const char HEX_FUNCTION_PREFIX[] = "icu_collate_"; static string EncodeHexFunctionName(const string &collation) { - return HEX_FUNCTION_PREFIX + collation; + return string(HEX_FUNCTION_PREFIX) + collation; } static string DecodeFunctionName(const Identifier &fname) { auto &name = fname.GetIdentifierName(); if (StringUtil::StartsWith(name, HEX_FUNCTION_PREFIX)) { - return name.substr(HEX_FUNCTION_PREFIX.size()); + return name.substr(sizeof(HEX_FUNCTION_PREFIX) - 1); } return name; } }; -const string IcuBindData::HEX_FUNCTION_PREFIX = "icu_collate_"; - //! The two hexadecimal characters of every byte value static const uint16_t &HexDigits(uint8_t byte) { static const auto HEX_PAIRS = []() { diff --git a/src/duckdb/extension/json/include/json_common.hpp b/src/duckdb/extension/json/include/json_common.hpp index 076b5b227..717025efb 100644 --- a/src/duckdb/extension/json/include/json_common.hpp +++ b/src/duckdb/extension/json/include/json_common.hpp @@ -331,13 +331,7 @@ struct JSONCommon { return GetUnsafe(val, ptr, len); } default: { - string path; - if (memchr(ptr, '"', len)) { - path = "/" + string(ptr, len); - } else { - path = "$.\"" + path_str.GetString() + "\""; - } - return GetUnsafe(val, path.c_str(), path.length()); + return yyjson_obj_getn(val, ptr, len); } } } diff --git a/src/duckdb/extension/json/include/json_functions.hpp b/src/duckdb/extension/json/include/json_functions.hpp index 3c4dc3b8b..0caeaa9b1 100644 --- a/src/duckdb/extension/json/include/json_functions.hpp +++ b/src/duckdb/extension/json/include/json_functions.hpp @@ -102,6 +102,7 @@ class JSONFunctions { // Scalar functions static ScalarFunctionSet GetExtractFunction(); static ScalarFunctionSet GetExtractStringFunction(); + static ScalarFunctionSet GetSubscriptFunction(); static ScalarFunctionSet GetArrayFunction(); static ScalarFunctionSet GetObjectFunction(); diff --git a/src/duckdb/extension/json/json_deserializer.cpp b/src/duckdb/extension/json/json_deserializer.cpp index 12c092a23..6b5f72a8e 100644 --- a/src/duckdb/extension/json/json_deserializer.cpp +++ b/src/duckdb/extension/json/json_deserializer.cpp @@ -268,7 +268,7 @@ string JsonDeserializer::ReadString() { if (!yyjson_is_str(val)) { ThrowTypeError(val, "string"); } - return yyjson_get_str(val); + return string(yyjson_get_str(val), yyjson_get_len(val)); } hugeint_t JsonDeserializer::ReadHugeInt() { diff --git a/src/duckdb/extension/json/json_functions.cpp b/src/duckdb/extension/json/json_functions.cpp index 741d02547..fc9c45613 100644 --- a/src/duckdb/extension/json/json_functions.cpp +++ b/src/duckdb/extension/json/json_functions.cpp @@ -35,10 +35,10 @@ JSONPathType JSONReadFunctionData::CheckPath(Context &context, const Value &path path = string(ptr, len); } else if (path_val.type().IsIntegral()) { path = "$[" + string(ptr, len) + "]"; - } else if (memchr(ptr, '"', len)) { - path = "/" + string(ptr, len); } else { - path = "$.\"" + string(ptr, len) + "\""; + auto key = StringUtil::Replace(string(ptr, len), "\\", "\\\\"); + key = StringUtil::Replace(key, "\"", "\\\""); + path = "$.\"" + key + "\""; } len = path.length(); if (*path.c_str() == '$') { @@ -170,10 +170,11 @@ vector JSONFunctions::GetScalarFunctions() { // Extract functions AddAliases({"json_extract", "json_extract_path"}, GetExtractFunction(), functions); AddAliases({"json_extract_string", "json_extract_path_text", "->>"}, GetExtractStringFunction(), functions); + functions.push_back(GetSubscriptFunction()); // Create functions functions.push_back(GetArrayFunction()); - functions.push_back(GetObjectFunction()); + AddAliases({"json_object", "json_build_object"}, GetObjectFunction(), functions); AddAliases({"to_json", "json_quote"}, GetToJSONFunction(), functions); functions.push_back(ScalarFunctionSet(GetJSONCopyToJSONFunction())); functions.push_back(ScalarFunctionSet(GetJSONCopyToGeoJSONFunction())); diff --git a/src/duckdb/extension/json/json_functions/copy_json.cpp b/src/duckdb/extension/json/json_functions/copy_json.cpp index a92a724a4..df6a72c77 100644 --- a/src/duckdb/extension/json/json_functions/copy_json.cpp +++ b/src/duckdb/extension/json/json_functions/copy_json.cpp @@ -1,4 +1,5 @@ #include "duckdb/function/copy_function.hpp" +#include "duckdb/common/static_string_table.hpp" #include "duckdb/common/bind_helpers.hpp" #include "duckdb/parser/expression/columnref_expression.hpp" #include "duckdb/parser/expression/constant_expression.hpp" @@ -192,11 +193,12 @@ static void BindJSONCopyToJSONFunction(Binder &binder, BoundStatement &bound, co } static BoundStatement CopyToJSONPlanInternal(Binder &binder, CopyStatement &stmt, const JSONCopyToFormat format) { - static const identifier_set_t SUPPORTED_BASE_OPTIONS { + static constexpr const char *const SUPPORTED_BASE_OPTIONS_ENTRIES[] = { "compression", "encoding", "use_tmp_file", "overwrite_or_ignore", "overwrite", "append", "filename_pattern", "file_extension", "per_thread_output", "file_size_bytes", "partition_by", "return_files", "preserve_order", "return_stats", "write_partition_columns", "write_empty_file", "hive_file_pattern", "return_column_types"}; + const StaticStringSet SUPPORTED_BASE_OPTIONS(SUPPORTED_BASE_OPTIONS_ENTRIES); auto ©_info = *stmt.info; @@ -282,7 +284,7 @@ static BoundStatement CopyToJSONPlanInternal(Binder &binder, CopyStatement &stmt // Handled below by keeping the partition columns inside the JSON object. We do not forward this to the // CSV writer, as that would write the (separate) partition columns as their own JSON lines. write_partition_columns = GetJSONCopyBoolean(binder, format, option_name, option_values); - } else if (SUPPORTED_BASE_OPTIONS.find(option_name) != SUPPORTED_BASE_OPTIONS.end()) { + } else if (SUPPORTED_BASE_OPTIONS.Contains(option_name)) { if (!option_values.empty() && option_values.back().IsNull()) { ThrowJSONCopyNullException(format, option_name); } diff --git a/src/duckdb/extension/json/json_functions/json_extract.cpp b/src/duckdb/extension/json/json_functions/json_extract.cpp index 2e2a1ec38..c8c3e3698 100644 --- a/src/duckdb/extension/json/json_functions/json_extract.cpp +++ b/src/duckdb/extension/json/json_functions/json_extract.cpp @@ -1,4 +1,5 @@ #include "json_executors.hpp" +#include "duckdb/common/operator/cast_operators.hpp" namespace duckdb { @@ -22,6 +23,32 @@ static void ExtractFunction(DataChunk &args, ExpressionState &state, Vector &res JSONExecutors::BinaryExecute(args, state, result, ExtractFromVal); } +static void SubscriptFunction(DataChunk &args, ExpressionState &state, Vector &result) { + auto &local_state = JSONFunctionLocalState::ResetAndGet(state); + auto alc = local_state.json_allocator->GetYYAlc(); + BinaryExecutor::Execute( + args.data[0], args.data[1], result, args.size(), [&](string_t input, string_t key) -> optional { + auto root = JSONCommon::ReadDocument(input, JSONCommon::READ_FLAG, alc)->root; + optional_ptr value; + uint32_t index; + if (yyjson_is_obj(root)) { + value = yyjson_obj_getn(root, key.GetData(), key.GetSize()); + } else if (yyjson_is_arr(root) && TryCast::Operation(key, index)) { + value = yyjson_arr_get(root, index); + } + return value ? ExtractFromVal(value.get(), alc, result) : nullopt; + }); + JSONAllocator::AddBuffer(result, alc); +} + +ScalarFunctionSet JSONFunctions::GetSubscriptFunction() { + ScalarFunction function("__internal_json_subscript", {}, LogicalType::JSON(), SubscriptFunction, nullptr, nullptr, + JSONFunctionLocalState::Init); + function.GetSignature().AddParameter("json", LogicalType::JSON()).AddParameter("key", LogicalType::VARCHAR); + function.SetFallible(); + return ScalarFunctionSet(std::move(function)); +} + static void ExtractManyFunction(DataChunk &args, ExpressionState &state, Vector &result) { JSONExecutors::ExecuteMany(args, state, result, ExtractFromVal); } diff --git a/src/duckdb/extension/json/json_functions/json_serialize_sql.cpp b/src/duckdb/extension/json/json_functions/json_serialize_sql.cpp index 511a9597a..5db26cdbf 100644 --- a/src/duckdb/extension/json/json_functions/json_serialize_sql.cpp +++ b/src/duckdb/extension/json/json_functions/json_serialize_sql.cpp @@ -108,6 +108,11 @@ static void JsonSerializeFunction(DataChunk &args, ExpressionState &state, Vecto auto options = make_uniq(); options->storage_compatibility = state.GetContext().GetDatabase().config.options.storage_compatibility; + if (options->storage_compatibility.Compare(StorageVersion::V2_0_0) && + !options->storage_compatibility.Compare(StorageVersion::V2_1_0)) { + // v2.1.0 only adds fields to statements, which JSON readers of v2.0.0 ignore + options->storage_compatibility.storage_version = StorageVersion::V2_1_0; + } auto json = JsonSerializer::Serialize(select, doc, info.skip_if_null, info.skip_if_empty, info.skip_if_default, *options); diff --git a/src/duckdb/extension/json/json_scan.cpp b/src/duckdb/extension/json/json_scan.cpp index 217beb911..2368423f1 100644 --- a/src/duckdb/extension/json/json_scan.cpp +++ b/src/duckdb/extension/json/json_scan.cpp @@ -1,4 +1,6 @@ #include "json_scan.hpp" +#include "duckdb/common/static_string_table.hpp" +#include "duckdb/common/virtual_file_system.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/common/enum_util.hpp" @@ -35,22 +37,27 @@ void JSONScanData::InitializeFormats(bool auto_detect_p) { } if (auto_detect_p) { - static const type_id_map_t> FORMAT_TEMPLATES = { - {LogicalTypeId::DATE, {"%m-%d-%Y", "%m-%d-%y", "%d-%m-%Y", "%d-%m-%y", "%Y-%m-%d", "%y-%m-%d"}}, - {LogicalTypeId::TIMESTAMP, - {"%Y-%m-%d %H:%M:%S.%f", "%m-%d-%Y %I:%M:%S %p", "%m-%d-%y %I:%M:%S %p", "%d-%m-%Y %H:%M:%S", - "%d-%m-%y %H:%M:%S", "%Y-%m-%d %H:%M:%S", "%y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%dT%H:%M:%SZ", - "%Y-%m-%dT%H:%M:%S.%fZ", "%Y-%m-%dT%H:%M:%S%z", "%Y-%m-%dT%H:%M:%S.%f%z"}}, + static constexpr const char *const DATE_FORMATS[] = {"%m-%d-%Y", "%m-%d-%y", "%d-%m-%Y", + "%d-%m-%y", "%Y-%m-%d", "%y-%m-%d"}; + static constexpr const char *const TIMESTAMP_FORMATS[] = { + "%Y-%m-%d %H:%M:%S.%f", "%m-%d-%Y %I:%M:%S %p", "%m-%d-%y %I:%M:%S %p", "%d-%m-%Y %H:%M:%S", + "%d-%m-%y %H:%M:%S", "%Y-%m-%d %H:%M:%S", "%y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S", + "%Y-%m-%dT%H:%M:%SZ", "%Y-%m-%dT%H:%M:%S.%fZ", "%Y-%m-%dT%H:%M:%S%z", "%Y-%m-%dT%H:%M:%S.%f%z"}; + struct FormatTemplate { + LogicalTypeId type; + StaticStringSet formats; }; + static constexpr FormatTemplate FORMAT_TEMPLATES[] = { + {LogicalTypeId::DATE, StaticStringSet(DATE_FORMATS)}, + {LogicalTypeId::TIMESTAMP, StaticStringSet(TIMESTAMP_FORMATS)}}; // Populate possible date/timestamp formats, assume this is consistent across columns for (auto &kv : FORMAT_TEMPLATES) { - const auto &logical_type = kv.first; + const auto &logical_type = kv.type; if (DateFormatMap::HasFormats(candidate_formats, logical_type)) { continue; // Already populated } - const auto &format_strings = kv.second; - for (auto &format_string : format_strings) { + for (auto format_string : kv.formats) { DateFormatMap::AddFormat(candidate_formats, logical_type, format_string); } } @@ -178,26 +185,27 @@ bool JSONScan::ParseOption(ClientContext &context, const Identifier &key, const } if (key == "format") { auto arg = StringUtil::Lower(StringValue::Get(value)); - static const auto FORMAT_OPTIONS = - case_insensitive_map_t {{"auto", JSONFormat::AUTO_DETECT}, - {"unstructured", JSONFormat::UNSTRUCTURED}, - {"newline_delimited", JSONFormat::NEWLINE_DELIMITED}, - {"nd", JSONFormat::NEWLINE_DELIMITED}, - {"array", JSONFormat::ARRAY}}; - auto lookup = FORMAT_OPTIONS.find(arg); - if (lookup == FORMAT_OPTIONS.end()) { + static constexpr StaticStringMap::Entry FORMAT_OPTIONS_ENTRIES[] = { + {"auto", JSONFormat::AUTO_DETECT}, + {"unstructured", JSONFormat::UNSTRUCTURED}, + {"newline_delimited", JSONFormat::NEWLINE_DELIMITED}, + {"nd", JSONFormat::NEWLINE_DELIMITED}, + {"array", JSONFormat::ARRAY}}; + const StaticStringMap FORMAT_OPTIONS(FORMAT_OPTIONS_ENTRIES); + auto lookup = FORMAT_OPTIONS.FindCaseInsensitive(arg); + if (!lookup) { vector valid_options; - for (auto &pair : FORMAT_OPTIONS) { - valid_options.push_back(StringUtil::Format("'%s'", pair.first)); + for (auto &option : FORMAT_OPTIONS) { + valid_options.push_back(StringUtil::Format("'%s'", option.key)); } throw BinderException("format must be one of [%s], not '%s'", StringUtil::Join(valid_options, ", "), arg); } - options.format = lookup->second; + options.format = *lookup; options.format_specified = true; return true; } if (key == "compression") { - options.compression = FileCompressionType(StringValue::Get(value)); + options.compression = VirtualFileSystem::Get(context).ParseCompression(StringValue::Get(value)); return true; } if (key == "array") { diff --git a/src/duckdb/extension/json/json_schema_inference.cpp b/src/duckdb/extension/json/json_schema_inference.cpp index 48eeb2865..a17265f8e 100644 --- a/src/duckdb/extension/json/json_schema_inference.cpp +++ b/src/duckdb/extension/json/json_schema_inference.cpp @@ -276,8 +276,8 @@ void JSONStructureNode::RefineCandidateTypesString(yyjson_val *vals[], const idx if (descriptions[0].candidate_types.empty()) { return; } - static JSONTransformOptions OPTIONS; - JSONTransform::GetStringVector(vals, val_count, LogicalType::SQLNULL, string_vector, OPTIONS); + JSONTransformOptions options; + JSONTransform::GetStringVector(vals, val_count, LogicalType::SQLNULL, string_vector, options); EliminateCandidateTypes(val_count, string_vector, date_format_map, user_specified_timestamp_format); } diff --git a/src/duckdb/extension/loader/static_extension_autoregister.cpp b/src/duckdb/extension/loader/static_extension_autoregister.cpp index 463bf2db7..ea74a39b9 100644 --- a/src/duckdb/extension/loader/static_extension_autoregister.cpp +++ b/src/duckdb/extension/loader/static_extension_autoregister.cpp @@ -12,5 +12,14 @@ struct DuckDBStaticExtensionLoader { duckdb_register_static_extensions(); } }; +// registering the statically linked extensions has to happen before main +// raw pragmas: this file is compiled into arbitrary programs without the DuckDB include path +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wglobal-constructors" +#endif const DuckDBStaticExtensionLoader duckdb_static_extension_loader; +#if defined(__clang__) +#pragma clang diagnostic pop +#endif } // namespace diff --git a/src/duckdb/extension/parquet/column_reader.cpp b/src/duckdb/extension/parquet/column_reader.cpp index 7086151b7..a17b05f73 100644 --- a/src/duckdb/extension/parquet/column_reader.cpp +++ b/src/duckdb/extension/parquet/column_reader.cpp @@ -165,15 +165,15 @@ static constexpr idx_t PAGE_INDEX_WHOLE_CHUNK_AFTER_CACHED_BLOCKS = 4; static constexpr idx_t PAGE_INDEX_WHOLE_CHUNK_MAX_MEMORY_SHARE = 4; //! Whether a chunk the cache already holds several small pieces of should be fetched whole instead of the given -//! (offset, size) page ranges: only when a range misses the cache, and only when the chunk fits the memory budget +//! page ranges: only when a range misses the cache, and only when the chunk fits the memory budget static bool ShouldReadChunkWhole(CachingFileHandle &handle, idx_t chunk_start, idx_t chunk_size, - const vector> &ranges) { + const vector &ranges) { if (handle.CountCachedBlocks(chunk_start, chunk_size) < PAGE_INDEX_WHOLE_CHUNK_AFTER_CACHED_BLOCKS) { return false; } bool all_cached = true; for (auto &range : ranges) { - if (!handle.IsCached(range.first, range.second)) { + if (!handle.IsCached(range.offset, range.length)) { all_cached = false; break; } @@ -209,7 +209,7 @@ void ColumnReader::RegisterPrefetch(ThriftFileTransport &transport, bool allow_m const auto chunk_start = FileOffset(); const auto chunk_size = NumericCast(chunk->meta_data.total_compressed_size); const auto first_data_page = NumericCast(locations[0].offset); - vector> ranges; + vector ranges; if (chunk_start < first_data_page) { ranges.emplace_back(chunk_start, first_data_page - chunk_start); } @@ -238,7 +238,7 @@ void ColumnReader::RegisterPrefetch(ThriftFileTransport &transport, bool allow_m } prefetch_offset = first_page_offset; for (auto &range : ranges) { - transport.RegisterPrefetch(range.first, range.second, allow_merge); + transport.RegisterPrefetch(range.offset, range.length, allow_merge); } } @@ -417,6 +417,21 @@ void ColumnReader::PlainSelect(shared_ptr &plain_data, uint8_t throw NotImplementedException("PlainSelect not implemented"); } +void ColumnReader::InitializeCryptoMetadata(const duckdb_parquet::EncryptionAlgorithm &encryption_algorithm, + idx_t row_group_ordinal_p) { + std::string unique_file_identifier; + if (encryption_algorithm.__isset.AES_GCM_V1) { + unique_file_identifier = encryption_algorithm.AES_GCM_V1.aad_file_unique; + } else if (encryption_algorithm.__isset.AES_GCM_CTR_V1) { + throw InvalidInputException("File is encrypted with AES_GCM_CTR_V1, but this is not supported by DuckDB"); + } else { + throw InvalidInputException("File is encrypted but no encryption algorithm is set"); + } + + aad_crypto_metadata.Initialize(unique_file_identifier, NumericCast(row_group_ordinal_p), + NumericCast(ColumnIndex())); +} + void ColumnReader::InitializeRead(idx_t row_group_idx_p, idx_t row_group_num_rows, const duckdb_parquet::ColumnChunkList &columns, TProtocol &protocol_p) { D_ASSERT(ColumnIndex() < columns.size()); @@ -427,6 +442,12 @@ void ColumnReader::InitializeRead(idx_t row_group_idx_p, idx_t row_group_num_row if (chunk->__isset.crypto_metadata && !reader.metadata->crypto_metadata) { throw InvalidInputException("File is encrypted but no file crypto metadata is set"); } + auto &crypto_metadata = reader.metadata->crypto_metadata; + if (crypto_metadata && crypto_metadata->encryption_algorithm.__isset.AES_GCM_V1) { + // track the column and row group ordinal of this leaf reader for the AAD of encrypted files + auto &row_group = reader.GetFileMetadata()->row_groups[row_group_idx_p]; + InitializeCryptoMetadata(crypto_metadata->encryption_algorithm, row_group.ordinal); + } if (!chunk->__isset.meta_data) { throw InvalidInputException("Failed to read file \"%s\": column chunk is missing its metadata", Reader().GetFileName()); diff --git a/src/duckdb/extension/parquet/column_writer.cpp b/src/duckdb/extension/parquet/column_writer.cpp index 643e68799..9f695a551 100644 --- a/src/duckdb/extension/parquet/column_writer.cpp +++ b/src/duckdb/extension/parquet/column_writer.cpp @@ -402,8 +402,9 @@ unique_ptr ColumnWriter::CreateWriterRecursive(ClientContext &cont } // construct the child schemas recursively - // TUPLE children have empty names - NamedChildren synthesizes positional ones for a valid Parquet schema - auto child_types = TupleType::NamedChildren(type); + // only STRUCT members keep their names (an empty name included) - TUPLE and UNION members get positional ones + auto child_types = + type.id() == LogicalTypeId::STRUCT ? StructType::GetChildTypes(type) : TupleType::NamedChildren(type); vector> child_writers; child_writers.reserve(child_types.size()); for (idx_t child_idx = 0; child_idx < child_types.size(); child_idx++) { diff --git a/src/duckdb/extension/parquet/include/column_reader.hpp b/src/duckdb/extension/parquet/include/column_reader.hpp index 8225de5da..de764980d 100644 --- a/src/duckdb/extension/parquet/include/column_reader.hpp +++ b/src/duckdb/extension/parquet/include/column_reader.hpp @@ -154,20 +154,6 @@ class ColumnReader { //! Whether every value in the current row group's column chunk is NULL (according to its statistics) bool AllValuesAreNull() const; - void InitializeCryptoMetadata(const duckdb_parquet::EncryptionAlgorithm &encryption_algorithm, - idx_t row_group_ordinal_p) { - std::string unique_file_identifier; - if (encryption_algorithm.__isset.AES_GCM_V1) { - unique_file_identifier = encryption_algorithm.AES_GCM_V1.aad_file_unique; - } else if (encryption_algorithm.__isset.AES_GCM_CTR_V1) { - throw InvalidInputException("File is encrypted with AES_GCM_CTR_V1, but this is not supported by DuckDB"); - } else { - throw InvalidInputException("File is encrypted but no encryption algorithm is set"); - } - - aad_crypto_metadata.Initialize(unique_file_identifier, row_group_ordinal_p, ColumnIndex()); - } - virtual idx_t FileOffset() const; //! Adds the indexes of the row group's column chunks this reader reads virtual void GatherColumnChunks(unordered_set &column_chunks); @@ -262,6 +248,9 @@ class ColumnReader { void ReadData(const data_ptr_t buffer, const uint32_t buffer_size, PageType::type page_type); private: + //! Initializes the AAD metadata of this (leaf) reader for the row group, called by InitializeRead + void InitializeCryptoMetadata(const duckdb_parquet::EncryptionAlgorithm &encryption_algorithm, + idx_t row_group_ordinal_p); //! this function tries to skip a page in the below conditions: //! 1. a previous table filter has filtered out this page //! 2. page statistics can be used to skip page diff --git a/src/duckdb/extension/parquet/include/parquet_reader.hpp b/src/duckdb/extension/parquet/include/parquet_reader.hpp index acfe69451..8a5eb29a8 100644 --- a/src/duckdb/extension/parquet/include/parquet_reader.hpp +++ b/src/duckdb/extension/parquet/include/parquet_reader.hpp @@ -565,7 +565,8 @@ class ParquetReader : public BaseFileReader { ParquetColumnSchema &element); unique_ptr GenerateAAD(uint8_t module_type, uint16_t row_group_ordinal, uint16_t column_ordinal, uint16_t page_ordinal) const; - optional_ptr GetVariantStats(const ParquetColumnSchema &schema) const; + //! Immutable merged statistics for a column in this reader's physical schema. + optional_ptr GetColumnStatistics(const ParquetColumnSchema &schema) const; //! Open a file handle for scanning, resolving the open flags from the prefetch mode unique_ptr OpenScanHandle(ClientContext &context) const; //! Initialize the shared scan handle, including when pre-opening it for read-ahead @@ -587,8 +588,9 @@ class ParquetReader : public BaseFileReader { unordered_map>> bloom_filter_read_heads; //! Scan handle shared by all scan states of this reader mutable shared_ptr shared_scan_handle; - mutable annotated_mutex variant_stats_lock; - mutable unordered_map> variant_stats_cache; + mutable annotated_mutex column_stats_lock; + //! A null entry records that the column has no usable statistics. + mutable unordered_map> column_stats_cache; }; } // namespace duckdb diff --git a/src/duckdb/extension/parquet/include/thrift_tools.hpp b/src/duckdb/extension/parquet/include/thrift_tools.hpp index 3fc8ffdfc..6acf55002 100644 --- a/src/duckdb/extension/parquet/include/thrift_tools.hpp +++ b/src/duckdb/extension/parquet/include/thrift_tools.hpp @@ -23,24 +23,70 @@ namespace duckdb { // A ReadHead for prefetching data in a specific range struct ReadHead { ReadHead(idx_t location, uint64_t size) : location(location), size(size) {}; + // The caller keeps borrowed bytes alive while the head exists. + ReadHead(idx_t location, uint64_t size, const_data_ptr_t data) : location(location), size(size), buffer_ptr(data) { + D_ASSERT(data); + } // Hint info idx_t location; uint64_t size; - // Current info - FileBufferHandleGroup handle_group; - AllocatedData local_buffer; - const_data_ptr_t buffer_ptr = nullptr; - bool data_isset = false; - mutex fetch_lock; // Sub-ranges whose smaller cached blocks are re-fetched with the gaps around them (see CachingFileHandle::Read) - vector> absorb_ranges; + vector absorb_ranges; idx_t GetEnd() const { return size + location; } - // Materialize [buffer_ptr], should call before access. + // Inspect readiness during preparation or after the head's I/O has settled. + bool HasBacking() const { + return IsMaterialized() || !handle_group.GetHandles().empty(); + } + + bool IsMaterialized() const { + return buffer_ptr != nullptr; + } + + const_data_ptr_t GetData() const { + D_ASSERT(IsMaterialized()); + return buffer_ptr; + } + + void Fetch(CachingFileHandle &file_handle) { + lock_guard guard(fetch_lock); + if (IsMaterialized()) { + return; + } + if (!HasBacking()) { + if (GetEnd() > file_handle.GetFileSize()) { + throw std::runtime_error("Prefetch registered requested for bytes outside file"); + } + handle_group = file_handle.Read(size, location, absorb_ranges); + } + Materialize(file_handle.GetBufferAllocator()); + } + + // Pin resident bytes without fetching or allocating a coalescing buffer. Fetch materializes them on demand. + bool TryPinResident(CachingFileHandle &file_handle) { + unique_lock guard(fetch_lock, std::defer_lock); + if (!guard.try_lock()) { + return false; + } + if (HasBacking()) { + return true; + } + auto resident = file_handle.TryReadResident(size, location); + if (!resident) { + return false; + } + handle_group = std::move(*resident); + if (handle_group.GetHandles().size() == 1) { + buffer_ptr = handle_group.Ptr(); + } + return true; + } + +private: void Materialize(Allocator &allocator) { if (handle_group.GetHandles().size() == 1) { buffer_ptr = handle_group.Ptr(); @@ -52,18 +98,10 @@ struct ReadHead { } } - void Fetch(CachingFileHandle &file_handle) { - lock_guard guard(fetch_lock); - if (data_isset) { - return; - } - if (GetEnd() > file_handle.GetFileSize()) { - throw std::runtime_error("Prefetch registered requested for bytes outside file"); - } - handle_group = file_handle.Read(size, location, absorb_ranges); - Materialize(file_handle.GetBufferAllocator()); - data_isset = true; - } + FileBufferHandleGroup handle_group; + AllocatedData local_buffer; + const_data_ptr_t buffer_ptr = nullptr; + mutex fetch_lock; }; struct ReadHeadComparator { @@ -124,7 +162,7 @@ struct ReadAheadBuffer { existing_head->location = new_start; existing_head->size = new_length; if (absorb_cached_blocks) { - existing_head->absorb_ranges.emplace_back(pos, pos + len); + existing_head->absorb_ranges.emplace_back(pos, len); } return; } @@ -134,7 +172,7 @@ struct ReadAheadBuffer { total_size += len; auto &read_head = *read_heads.front(); if (absorb_cached_blocks) { - read_head.absorb_ranges.emplace_back(pos, pos + len); + read_head.absorb_ranges.emplace_back(pos, len); } if (merge_buffers) { @@ -151,10 +189,7 @@ struct ReadAheadBuffer { // Add a read head whose bytes are already in memory; the caller keeps them alive while the head exists void AddFilledReadHead(idx_t pos, uint64_t len, const_data_ptr_t data) { - read_heads.insert(read_heads.begin(), make_shared_ptr(pos, len)); - auto &read_head = *read_heads.front(); - read_head.buffer_ptr = data; - read_head.data_isset = true; + read_heads.insert(read_heads.begin(), make_shared_ptr(pos, len, data)); } // Returns the relevant read head @@ -163,7 +198,7 @@ struct ReadAheadBuffer { for (auto &read_head : read_heads) { if (pos >= read_head->location && pos < read_head->GetEnd() && len <= read_head->GetEnd() - pos) { // Filter and payload ranges can overlap: reuse fetched bytes before fetching another range. - if (read_head->data_isset) { + if (read_head->HasBacking()) { return read_head.get(); } if (!unfetched_head) { @@ -177,7 +212,7 @@ struct ReadAheadBuffer { // Prefetch all read heads void Prefetch() { for (auto &read_head : read_heads) { - if (!read_head->data_isset) { + if (!read_head->IsMaterialized()) { read_head->Fetch(file_handle); } } @@ -208,10 +243,10 @@ class ThriftFileTransport : public duckdb_apache::thrift::transport::TVirtualTra if (prefetch_buffer != nullptr && location - prefetch_buffer->location + len <= prefetch_buffer->size) { D_ASSERT(location - prefetch_buffer->location + len <= prefetch_buffer->size); - if (!prefetch_buffer->data_isset) { + if (!prefetch_buffer->IsMaterialized()) { prefetch_buffer->Fetch(file_handle); } - memcpy(buf, prefetch_buffer->buffer_ptr + location - prefetch_buffer->location, len); + memcpy(buf, prefetch_buffer->GetData() + location - prefetch_buffer->location, len); } else if (prefetch_mode && len < PREFETCH_FALLBACK_BUFFERSIZE && len > 0) { auto file_size = file_handle.GetFileSize(); if (location >= file_size) { @@ -227,7 +262,7 @@ class ThriftFileTransport : public duckdb_apache::thrift::transport::TVirtualTra location += len; return len; } - memcpy(buf, prefetch_buffer_fallback->buffer_ptr + location - prefetch_buffer_fallback->location, len); + memcpy(buf, prefetch_buffer_fallback->GetData() + location - prefetch_buffer_fallback->location, len); } else { // No prefetch, do a regular (non-caching) read file_handle.GetFileHandle()->Read(context, buf, len, location); @@ -244,7 +279,7 @@ class ThriftFileTransport : public duckdb_apache::thrift::transport::TVirtualTra // Attach an immutable, fetched head without registering it for merging. void AddFetchedReadHead(shared_ptr read_head) { - D_ASSERT(read_head->data_isset); + D_ASSERT(read_head->IsMaterialized()); ra_buffer.read_heads.insert(ra_buffer.read_heads.begin(), std::move(read_head)); } diff --git a/src/duckdb/extension/parquet/parquet_extension.cpp b/src/duckdb/extension/parquet/parquet_extension.cpp index 96dc6223e..470842dbf 100644 --- a/src/duckdb/extension/parquet/parquet_extension.cpp +++ b/src/duckdb/extension/parquet/parquet_extension.cpp @@ -327,12 +327,12 @@ static unique_ptr ParquetWriteBind(ClientContext &context, CopyFun } bind_data->data_page_size_limit = val; } else if (option_name == "write_bloom_filter") { - bind_data->enable_bloom_filters = BooleanValue::Get(option_values[0].CastAs(context, LogicalType::BOOLEAN)); + bind_data->enable_bloom_filters = option_values[0].GetValue(); } else if (option_name == "bloom_filter_fallback_max_bytes") { bind_data->bloom_filter_fallback_max_bytes = ParseBytesArg(context.GetContext(), option_name, option_values[0]); } else if (option_name == "write_page_index") { - bind_data->write_page_index = BooleanValue::Get(option_values[0].CastAs(context, LogicalType::BOOLEAN)); + bind_data->write_page_index = option_values[0].GetValue(); } else if (option_name == "bloom_filter_false_positive_ratio") { auto val = option_values[0].GetValue(); if (!(val > 0 && val <= 1)) { @@ -371,8 +371,7 @@ static unique_ptr ParquetWriteBind(ClientContext &context, CopyFun throw BinderException("Expected geoparquet_version 'NONE', 'V1' or 'BOTH'"); } } else if (option_name == "write_timestamp_as_int96") { - bind_data->write_timestamp_as_int96 = - BooleanValue::Get(option_values[0].CastAs(context, LogicalType::BOOLEAN)); + bind_data->write_timestamp_as_int96 = option_values[0].GetValue(); } else if (option_name == "timestamp_is_adjusted_to_utc") { bind_data->timestamp_is_adjusted_to_utc = EnumUtil::FromString(StringUtil::Upper(option_values[0].ToString())); diff --git a/src/duckdb/extension/parquet/parquet_reader.cpp b/src/duckdb/extension/parquet/parquet_reader.cpp index 232c144e0..4c50317cf 100644 --- a/src/duckdb/extension/parquet/parquet_reader.cpp +++ b/src/duckdb/extension/parquet/parquet_reader.cpp @@ -368,7 +368,7 @@ LoadMetadata(ClientContext &context, Allocator &allocator, CachingFileHandle &fi transport.Prefetch(metadata_pos, total_footer_len); auto read_head = transport.GetReadHead(metadata_pos); - auto data_ptr = read_head->buffer_ptr; + auto data_ptr = read_head->GetData(); idx_t read_footer_len; ParseParquetFooter(data_ptr + footer_len, file_handle.GetPath(), file_size, encryption_config, read_footer_len, @@ -728,7 +728,8 @@ unique_ptr ParquetReader::ReadStatistics(const Identifier &name) return nullptr; } - return ReadStatisticsInternal(*GetFileMetadata(), *root_schema, parquet_options, file_col_idx); + auto stats = GetColumnStatistics(root_schema->children[file_col_idx]); + return stats ? stats->ToUnique() : nullptr; } unique_ptr ParquetReader::ReadStatistics(ClientContext &context, ParquetOptions parquet_options, @@ -785,28 +786,23 @@ static bool IsFullyShredded(const BaseStatistics &variant_stats, const ColumnInd return VariantStats::IsShredded(variant_stats, column_index); } -optional_ptr ParquetReader::GetVariantStats(const ParquetColumnSchema &schema) const { - D_ASSERT(schema.schema_type == ParquetColumnSchemaType::VARIANT); +optional_ptr ParquetReader::GetColumnStatistics(const ParquetColumnSchema &schema) const { D_ASSERT(schema.schema_index.IsValid()); const auto cache_key = schema.schema_index.GetIndex(); { - const annotated_lock_guard guard(variant_stats_lock); - auto entry = variant_stats_cache.find(cache_key); - if (entry != variant_stats_cache.end()) { - D_ASSERT(entry->second); - return *entry->second; + const annotated_lock_guard guard(column_stats_lock); + auto entry = column_stats_cache.find(cache_key); + if (entry != column_stats_cache.end()) { + return entry->second.get(); } } - auto variant_stats = ReadColumnStatistics(*GetFileMetadata(), schema, parquet_options); - if (!variant_stats) { - return nullptr; - } + auto column_stats = ReadColumnStatistics(*GetFileMetadata(), schema, parquet_options); - const annotated_lock_guard guard(variant_stats_lock); - auto res = variant_stats_cache.emplace(cache_key, std::move(variant_stats)); - return *res.first->second; + const annotated_lock_guard guard(column_stats_lock); + auto res = column_stats_cache.emplace(cache_key, std::move(column_stats)); + return res.first->second.get(); } //! Whether the cast of the extracted field can be applied to its 'typed_value' instead of to the VARIANT @@ -998,7 +994,7 @@ unique_ptr ParquetReader::CreateReaderRecursive(ClientContext &con throw InvalidInputException("Variant group can only contain 'value'/'typed_value', found '%s'", typed_value_schema.name); } - auto variant_stats = GetVariantStats(schema); + auto variant_stats = GetColumnStatistics(schema); if (variant_stats && IsFullyShredded(*variant_stats, column_id) && TypedValueCastMatchesVariantCast(typed_value_schema, column_id)) { @@ -2034,12 +2030,6 @@ void ParquetReader::PrepareRowGroupBuffer(ClientContext &context, ParquetReaderS auto col_idx = MultiFileLocalIndex(i); auto &column_reader = state.GetColumnReader(col_idx); - // keep track of column and row group ordinal if data is encrypted - if (metadata->crypto_metadata && metadata->crypto_metadata->encryption_algorithm.__isset.AES_GCM_V1) { - column_reader.InitializeCryptoMetadata(metadata->crypto_metadata->encryption_algorithm, - GetGroup(state).ordinal); - } - if (group.num_rows < 0) { throw InvalidInputException("Failed to read file \"%s\": metadata is corrupt. Row group has invalid " "number of rows (%lld)", @@ -2759,20 +2749,26 @@ void ParquetReader::GetPartitionStats(const duckdb_parquet::FileMetaData &metada } } -// Async I/O tasks for the read heads in the index range [from, to), skipping any that are already fetched. -static vector> -CollectIOTasks(ThriftFileTransport &trans, const shared_ptr &file_handle, idx_t from, idx_t to) { +// Pin resident read heads in [from, to), leaving other reads as async tasks. +static AsyncResult PrepareReadHeads(ThriftFileTransport &trans, const shared_ptr &file_handle, + idx_t from, idx_t to) { auto &read_heads = trans.GetReadHeads(); vector> io_tasks; + idx_t prepared_bytes = 0; for (idx_t i = from; i < to; i++) { auto &read_head = read_heads[i]; - if (!read_head->data_isset) { + if (read_head->HasBacking()) { + continue; + } + if (read_head->TryPinResident(*file_handle)) { + prepared_bytes += read_head->size; + } else { // fetch the read head's bytes on the async pool io_tasks.push_back(make_uniq( [read_head, file_handle] { read_head->Fetch(*file_handle); }, read_head->size)); } } - return io_tasks; + return AsyncResult::FromTasks(std::move(io_tasks), TaskSchedulerType::ASYNC, prepared_bytes); } static void FetchBloomFilterGroups(ClientContext &context, const vector> &read_heads, @@ -3015,23 +3011,19 @@ AsyncResult ParquetReader::ScheduleRowGroupReads(ParquetReaderScanState &state, } auto &trans = reinterpret_cast(*state.thrift_file_proto->getTransport()); auto read_head_count = trans.GetReadHeads().size(); - vector> io_tasks; switch (strategy) { case ParquetPrefetchStrategy::PREFETCH_FILTERS: case ParquetPrefetchStrategy::PREFETCH_FILTERS_PAGES: // schedule only the filter columns' I/O, they are last in our list - io_tasks = CollectIOTasks(trans, state.file_handle, read_head_count - state.filter_head_count, read_head_count); - break; + return PrepareReadHeads(trans, state.file_handle, read_head_count - state.filter_head_count, read_head_count); case ParquetPrefetchStrategy::WHOLE_GROUP: case ParquetPrefetchStrategy::COLUMN_WISE_EAGER: case ParquetPrefetchStrategy::COLUMN_WISE_EAGER_PAGES: // schedule the I/O for all columns up front - io_tasks = CollectIOTasks(trans, state.file_handle, 0, read_head_count); - break; + return PrepareReadHeads(trans, state.file_handle, 0, read_head_count); default: throw InternalException("Unexpected parquet prefetch strategy when scheduling I/O"); } - return AsyncResult::FromTasks(std::move(io_tasks), TaskSchedulerType::ASYNC); } void ParquetReader::FinishRowGroup(ClientContext &context, ParquetReaderScanState &state, bool log_prefetch) { @@ -3128,10 +3120,6 @@ void ParquetReader::DecodeRemainingColumns(ParquetReaderScanState &state, DataCh } auto &result_vector = result.data[i]; auto &child_reader = state.GetColumnReader(col_idx); - if (metadata->crypto_metadata && metadata->crypto_metadata->encryption_algorithm.__isset.AES_GCM_V1) { - child_reader.InitializeCryptoMetadata(metadata->crypto_metadata->encryption_algorithm, - GetGroup(state).ordinal); - } ColumnReaderInput reader_input(result.size(), define_ptr, repeat_ptr); child_reader.Select(reader_input, result_vector, state.sel, filter_count); } @@ -3145,13 +3133,13 @@ vector> ParquetReader::ScheduleRemainingColumns(ParquetRea auto &trans = reinterpret_cast(*state.thrift_file_proto->getTransport()); auto payload_head_count = trans.GetReadHeads().size() - state.filter_head_count; // payload columns are the leading read heads - auto io_tasks = CollectIOTasks(trans, state.file_handle, 0, payload_head_count); - if (io_tasks.empty()) { + auto scheduled = PrepareReadHeads(trans, state.file_handle, 0, payload_head_count); + if (!scheduled.HasTasks()) { // no payload to do return {}; } state.resuming_payload = true; - return io_tasks; + return scheduled.ExtractAsyncTasks(); } AsyncResult ParquetReader::ProcessFilters(ParquetReaderScanState &state, DataChunk &result, idx_t scan_count, @@ -3219,10 +3207,6 @@ AsyncResult ParquetReader::Process(ClientContext &context, ParquetReaderScanStat auto file_col_idx = column_ids[col_idx]; auto &result_vector = result.data[i]; auto &child_reader = state.GetColumnReader(col_idx); - if (metadata->crypto_metadata && metadata->crypto_metadata->encryption_algorithm.__isset.AES_GCM_V1) { - child_reader.InitializeCryptoMetadata(metadata->crypto_metadata->encryption_algorithm, - GetGroup(state).ordinal); - } ColumnReaderInput reader_input(scan_count, define_ptr, repeat_ptr); auto rows_read = child_reader.Read(reader_input, result_vector); if (rows_read != scan_count) { diff --git a/src/duckdb/extension/parquet/parquet_statistics.cpp b/src/duckdb/extension/parquet/parquet_statistics.cpp index 608fbce99..39a963481 100644 --- a/src/duckdb/extension/parquet/parquet_statistics.cpp +++ b/src/duckdb/extension/parquet/parquet_statistics.cpp @@ -785,13 +785,19 @@ ParquetStatisticsUtils::TransformColumnStatistics(const ParquetColumnSchema &sch // Otherwise, its a standard column with stats auto &column_chunk = columns[schema.column_index]; - if (!column_chunk.__isset.meta_data || !column_chunk.meta_data.__isset.statistics) { - // no stats present for row group + if (!column_chunk.__isset.meta_data) { + return nullptr; + } + const auto &metadata = column_chunk.meta_data; + const bool has_statistics = metadata.__isset.statistics || + (type.id() == LogicalTypeId::GEOMETRY && metadata.__isset.geospatial_statistics && + metadata.geospatial_statistics.__isset.bbox); + if (!has_statistics) { return nullptr; } // every column whose chunk statistics become statistics of the scan gets here, whatever it is nested in schema.ValidateNullCount(column_chunk); - auto &parquet_stats = column_chunk.meta_data.statistics; + auto &parquet_stats = metadata.statistics; row_group_stats = TransformParquetStatistics(type, schema, parquet_stats, parquet_options, parquet_options.can_have_nan, &column_chunk); @@ -801,7 +807,7 @@ ParquetStatisticsUtils::TransformColumnStatistics(const ParquetColumnSchema &sch if (parquet_stats.__isset.null_count && parquet_stats.null_count == 0) { row_group_stats->Set(StatsInfo::CANNOT_HAVE_NULL_VALUES); } - if (parquet_stats.__isset.null_count && parquet_stats.null_count == column_chunk.meta_data.num_values) { + if (parquet_stats.__isset.null_count && parquet_stats.null_count == metadata.num_values) { row_group_stats = BaseStatistics::CreateEmpty(type).ToUnique(); if (parquet_stats.null_count > 0) { row_group_stats->Set(StatsInfo::CAN_HAVE_NULL_VALUES); @@ -1327,7 +1333,7 @@ bool ParquetStatisticsUtils::BloomFilterExcludes( transport.SetLocation(bloom_filter_start); if (bloom_filter_length > 0) { auto read_head = transport.GetReadHead(bloom_filter_start, bloom_filter_length); - if (!read_head || !read_head->data_isset) { + if (!read_head || !read_head->IsMaterialized()) { transport.Prefetch(bloom_filter_start, bloom_filter_length); } } diff --git a/src/duckdb/generated_extension_loader_package_build.cpp b/src/duckdb/generated_extension_loader_package_build.cpp index ab8a37a47..36aa6aa8b 100644 --- a/src/duckdb/generated_extension_loader_package_build.cpp +++ b/src/duckdb/generated_extension_loader_package_build.cpp @@ -45,7 +45,7 @@ int32_t duckdb_extension_core_functions_describe(duckdb_extension_descriptor *de descriptor->version = 1; descriptor->name = "core_functions"; descriptor->extension_version = EXT_VERSION_CORE_FUNCTIONS; - descriptor->api_version = "v2.1.0-alpha58374"; + descriptor->api_version = "v2.1.0-alpha59171"; descriptor->entry_cpp = (void (*)(void))core_functions_duckdb_cpp_init; return 0; } @@ -78,7 +78,7 @@ int32_t duckdb_extension_parquet_describe(duckdb_extension_descriptor *descripto descriptor->version = 1; descriptor->name = "parquet"; descriptor->extension_version = EXT_VERSION_PARQUET; - descriptor->api_version = "v2.1.0-alpha58374"; + descriptor->api_version = "v2.1.0-alpha59171"; descriptor->entry_cpp = (void (*)(void))parquet_duckdb_cpp_init; return 0; } @@ -111,7 +111,7 @@ int32_t duckdb_extension_icu_describe(duckdb_extension_descriptor *descriptor) { descriptor->version = 1; descriptor->name = "icu"; descriptor->extension_version = EXT_VERSION_ICU; - descriptor->api_version = "v2.1.0-alpha58374"; + descriptor->api_version = "v2.1.0-alpha59171"; descriptor->entry_cpp = (void (*)(void))icu_duckdb_cpp_init; return 0; } @@ -144,7 +144,7 @@ int32_t duckdb_extension_json_describe(duckdb_extension_descriptor *descriptor) descriptor->version = 1; descriptor->name = "json"; descriptor->extension_version = EXT_VERSION_JSON; - descriptor->api_version = "v2.1.0-alpha58374"; + descriptor->api_version = "v2.1.0-alpha59171"; descriptor->entry_cpp = (void (*)(void))json_duckdb_cpp_init; return 0; } diff --git a/src/duckdb/src/catalog/catalog_entry/duck_table_entry.cpp b/src/duckdb/src/catalog/catalog_entry/duck_table_entry.cpp index 6e3ba1053..319bc2dd5 100644 --- a/src/duckdb/src/catalog/catalog_entry/duck_table_entry.cpp +++ b/src/duckdb/src/catalog/catalog_entry/duck_table_entry.cpp @@ -38,6 +38,7 @@ #include "duckdb/transaction/meta_transaction.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/main/attached_database.hpp" +#include "duckdb/parser/expression/type_expression.hpp" namespace duckdb { @@ -53,6 +54,33 @@ IndexStorageInfo GetIndexInfo(const IndexConstraintType type, const bool v1_0_0_ return index_info; } +//! Throws when an expression an ALTER stores (in the catalog and the WAL) holds an empty member name that the storage +//! version of the database cannot store; a replayed ALTER was checked when it was issued +static void CheckAlterExpressionIsSupported(const AlterInfo &info, const ParsedExpression &expression, + AttachedDatabase &db) { + if (info.bind_mode == AlterBindMode::SKIP_BINDING) { + return; + } + db.GetStorageManager().CheckExpressionEmptyMemberNamesAreSupported(expression); +} + +//! Throws when a field ALTER changes a STRUCT with an empty member name below the storage version that can replay it +static void CheckFieldAlterIsSupported(const AlterInfo &info, const LogicalType &old_type, const LogicalType &new_type, + AttachedDatabase &db) { + if (info.bind_mode == AlterBindMode::SKIP_BINDING) { + return; + } + auto &storage_manager = db.GetStorageManager(); + if (storage_manager.GetStorageVersion() >= StorageManager::EMPTY_MEMBER_NAMES_VERSION_ADDED) { + return; + } + if (TypeExpression::HasEmptyStructMemberName(old_type) || TypeExpression::HasEmptyStructMemberName(new_type)) { + throw InvalidInputException(storage_manager.GetUnsupportedPriorToVersionReason( + "ALTERs that add, drop or rename a field of a STRUCT with an empty member name", + StorageManager::EMPTY_MEMBER_NAMES_VERSION_ADDED)); + } +} + static void CheckTypeIsSupported(const LogicalType &logical_type, AttachedDatabase &db) { if (TypeVisitor::Contains(logical_type, LogicalTypeId::TYPE)) { throw InvalidInputException("A table cannot be created with a 'TYPE' column"); @@ -110,14 +138,19 @@ DuckTableEntry::DuckTableEntry(Catalog &catalog, SchemaCatalogEntry &schema, Bou if (col_def.Generated()) { storage_manager.CheckDecimalWidthIsSupported(col_def.Type()); storage_manager.CheckExpressionDecimalsAreSupported(col_def.GeneratedExpression()); + storage_manager.CheckEmptyMemberNamesAreSupported(col_def.Type(), "columns"); + storage_manager.CheckExpressionEmptyMemberNamesAreSupported(col_def.GeneratedExpression()); } if (col_def.HasDefaultValue()) { storage_manager.CheckExpressionDecimalsAreSupported(col_def.DefaultValue()); + storage_manager.CheckExpressionEmptyMemberNamesAreSupported(col_def.DefaultValue()); } } for (auto &constraint : constraints) { if (constraint->type == ConstraintType::CHECK) { storage_manager.CheckExpressionDecimalsAreSupported(*constraint->Cast().expression); + storage_manager.CheckExpressionEmptyMemberNamesAreSupported( + *constraint->Cast().expression); } } @@ -559,6 +592,12 @@ unique_ptr DuckTableEntry::AddColumn(ClientContext &context, AddCo // Check if type is supported in this database version CheckTypeIsSupported(info.new_column.GetType(), catalog.GetAttached()); + if (info.new_column.HasDefaultValue()) { + CheckAlterExpressionIsSupported(info, info.new_column.DefaultValue(), catalog.GetAttached()); + } + if (info.new_column.Generated()) { + CheckAlterExpressionIsSupported(info, info.new_column.GeneratedExpression(), catalog.GetAttached()); + } info.new_column.SetOid(columns.LogicalColumnCount()); info.new_column.SetStorageOid(columns.PhysicalColumnCount()); @@ -705,6 +744,10 @@ unique_ptr DuckTableEntry::AddField(ClientContext &context, AddFie // follow the path - the parent column must exist regardless of IF NOT EXISTS (which only applies to the new field) auto col_idx = GetColumnIndex(info.column_path[0], false); auto &col = GetColumn(col_idx); + // the new field's default is stored with the ALTER (unlike the remap expression built from it below) + if (info.new_field.HasDefaultValue()) { + CheckAlterExpressionIsSupported(info, info.new_field.DefaultValue(), catalog.GetAttached()); + } auto res = AddFieldToStruct(col.Type(), info.column_path, info.new_field); if (res.error.HasError()) { if (!info.if_field_not_exists) { @@ -712,6 +755,7 @@ unique_ptr DuckTableEntry::AddField(ClientContext &context, AddFie } return nullptr; } + CheckFieldAlterIsSupported(info, col.Type(), res.new_type, catalog.GetAttached()); // construct the struct remapping expression vector> children; @@ -966,6 +1010,7 @@ unique_ptr DuckTableEntry::RemoveField(ClientContext &context, Rem } return nullptr; } + CheckFieldAlterIsSupported(info, col.Type(), res.new_type, catalog.GetAttached()); // construct the struct remapping expression vector> children; @@ -1061,6 +1106,7 @@ unique_ptr DuckTableEntry::RenameField(ClientContext &context, Ren if (res.error.HasError()) { res.error.Throw(); } + CheckFieldAlterIsSupported(info, col.Type(), res.new_type, catalog.GetAttached()); // construct the struct remapping expression vector> children; @@ -1092,6 +1138,9 @@ unique_ptr DuckTableEntry::SetDefault(ClientContext &context, SetD if (col.Generated()) { throw BinderException("Cannot SET DEFAULT for generated column %s", col.Name()); } + if (info.expression) { + CheckAlterExpressionIsSupported(info, *info.expression, catalog.GetAttached()); + } col.SetDefaultValue(info.expression ? info.expression->Copy() : nullptr); auto binder = Binder::CreateBinder(context); @@ -1180,7 +1229,11 @@ unique_ptr DuckTableEntry::ChangeColumnType(ClientContext &context create_info->comment = comment; create_info->tags = tags; - // Bind the USING expression. + // Bind the USING expression. Only a user's USING expression is checked: ADD/REMOVE/RENAME_FIELD build an + // internal remap expression that is not stored. + if (alter_table_type == AlterTableType::ALTER_COLUMN_TYPE) { + CheckAlterExpressionIsSupported(info, *info.expression, catalog.GetAttached()); + } auto binder = Binder::CreateBinder(context); vector bound_columns; AlterBinder expr_binder(*binder, context, *this, bound_columns, info.target_type); diff --git a/src/duckdb/src/catalog/catalog_entry/view_catalog_entry.cpp b/src/duckdb/src/catalog/catalog_entry/view_catalog_entry.cpp index 3acaff029..390e5c64f 100644 --- a/src/duckdb/src/catalog/catalog_entry/view_catalog_entry.cpp +++ b/src/duckdb/src/catalog/catalog_entry/view_catalog_entry.cpp @@ -47,9 +47,9 @@ ViewCatalogEntry::ViewCatalogEntry(Catalog &catalog, SchemaCatalogEntry &schema, Initialize(info); } -//! Whether the column types of a view can be stored in its database. A view with a wide DECIMAL result in a database -//! written before wide decimals is stored without types, like a view that was never bound, so that older engines read -//! it and bind it by their rules. +//! Whether the column types of a view can be stored in its database. A view with a wide DECIMAL result (or a STRUCT +//! with only empty member names) in a database written before those is stored without types, like a view that was +//! never bound, so that older engines read it and bind it by their rules. static bool CanStoreViewTypes(const Catalog &catalog, const vector &types) { auto &db = catalog.GetAttached(); if (!db.HasStorageManager()) { @@ -60,6 +60,10 @@ static bool CanStoreViewTypes(const Catalog &catalog, const vector if (!storage_manager.GetUnsupportedDecimalWidthReason(type).empty()) { return false; } + if (storage_manager.GetStorageVersion() < StorageManager::EMPTY_MEMBER_NAMES_VERSION_ADDED && + StorageManager::ContainsAllEmptyNamesStruct(type)) { + return false; + } } return true; } diff --git a/src/duckdb/src/catalog/catalog_set.cpp b/src/duckdb/src/catalog/catalog_set.cpp index d2a285214..48073f2bf 100644 --- a/src/duckdb/src/catalog/catalog_set.cpp +++ b/src/duckdb/src/catalog/catalog_set.cpp @@ -380,9 +380,13 @@ bool CatalogSet::AlterEntry(CatalogTransaction transaction, const Identifier &na // push the old entry in the undo buffer for this transaction unique_ptr entry_to_destroy; if (transaction.transaction) { - // serialize the AlterInfo into a temporary buffer + // serialize the AlterInfo into a temporary buffer: it is read back in memory and written to the WAL with the + // database's own options, so it must round-trip everything an alter can carry. This copy no longer rejects + // content the database's storage version cannot represent: such feature gates belong in AlterEntry MemoryStream stream(Allocator::Get(transaction.db)); - BinarySerializer serializer(stream); + SerializationOptions options; + options.storage_compatibility = StorageCompatibility::Latest(); + BinarySerializer serializer(stream, options); serializer.Begin(); serializer.WriteProperty(100, "column_name", alter_info.GetColumnName()); serializer.WriteProperty(101, "alter_info", &alter_info); @@ -814,6 +818,22 @@ void CatalogSet::Scan(VisibilityBound bound, const std::function defaults_p) { lock_guard lock(catalog_lock); + if (defaults && !defaults->created_all_entries) { + // Materialize the current generator's entries before replacing it, so that built-in default entries + // (e.g. the default coordinate systems) remain resolvable regardless of extension load order + auto transaction = CatalogTransaction::GetSystemTransaction(catalog.GetDatabase()); + for (auto &default_entry : defaults->GetDefaultEntries()) { + if (map.GetEntry(default_entry)) { + continue; + } + auto entry = defaults->CreateDefaultEntry(transaction, default_entry); + if (!entry) { + // this generator requires a client context to create its entries - we cannot materialize them here + continue; + } + CreateCommittedEntry(std::move(entry)); + } + } defaults = std::move(defaults_p); } diff --git a/src/duckdb/src/catalog/default/default_coordinate_systems.cpp b/src/duckdb/src/catalog/default/default_coordinate_systems.cpp index 6dac4991e..27572167b 100644 --- a/src/duckdb/src/catalog/default/default_coordinate_systems.cpp +++ b/src/duckdb/src/catalog/default/default_coordinate_systems.cpp @@ -1,6 +1,7 @@ #include "duckdb/parser/parsed_data/create_coordinate_system_info.hpp" #include "duckdb/catalog/default/default_coordinate_systems.hpp" #include "duckdb/catalog/catalog_entry/coordinate_system_catalog_entry.hpp" +#include "duckdb/catalog/catalog_transaction.hpp" #include "duckdb/common/array.hpp" namespace duckdb { @@ -43,7 +44,7 @@ DefaultCoordinateSystemGenerator::DefaultCoordinateSystemGenerator(Catalog &cata : DefaultGenerator(catalog), schema(schema) { } -unique_ptr DefaultCoordinateSystemGenerator::CreateDefaultEntry(ClientContext &context, +unique_ptr DefaultCoordinateSystemGenerator::CreateDefaultEntry(CatalogTransaction transaction, const Identifier &entry_name) { if (schema.name != DEFAULT_SCHEMA) { return nullptr; diff --git a/src/duckdb/src/catalog/default/default_views.cpp b/src/duckdb/src/catalog/default/default_views.cpp index 008c01dba..410ab9ffc 100644 --- a/src/duckdb/src/catalog/default/default_views.cpp +++ b/src/duckdb/src/catalog/default/default_views.cpp @@ -85,7 +85,7 @@ static const DefaultView internal_views[] = { "contypid, 0 conindid, 0 conparentid, 0 confrelid, NULL confupdtype, NULL confdeltype, NULL confmatchtype, true " "conislocal, 0 coninhcount, false connoinherit, constraint_column_indexes conkey, NULL confkey, NULL conpfeqop, " "NULL conppeqop, NULL conffeqop, NULL conexclop, expression conbin FROM duckdb_constraints()"}, - {"pg_catalog", "pg_collation", "SELECT NULL::OID oid, NULL::VARCHAR collname WHERE FALSE"}, + {"pg_catalog", "pg_collation", "SELECT NULL::OID oid, NULL::VARCHAR collname, NULL::OID collnamespace WHERE FALSE"}, {"pg_catalog", "pg_database", "SELECT database_oid oid, database_name datname, true::boolean datallowconn, false::boolean AS datistemplate FROM " "duckdb_databases()"}, diff --git a/src/duckdb/src/common/allocator/allocator.cpp b/src/duckdb/src/common/allocator/allocator.cpp index 2d166fb0c..60dfed09f 100644 --- a/src/duckdb/src/common/allocator/allocator.cpp +++ b/src/duckdb/src/common/allocator/allocator.cpp @@ -1,4 +1,5 @@ #include "duckdb/common/allocator.hpp" +#include "duckdb/common/no_destructor.hpp" #include "duckdb/common/assert.hpp" #include "duckdb/common/atomic.hpp" @@ -175,8 +176,8 @@ data_ptr_t Allocator::ReallocateData(data_ptr_t pointer, idx_t old_size, idx_t s return new_pointer; } shared_ptr &Allocator::DefaultAllocatorReference() { - static shared_ptr DEFAULT_ALLOCATOR = make_shared_ptr(); - return DEFAULT_ALLOCATOR; + static NoDestructor> default_allocator(make_shared_ptr()); + return *default_allocator; } Allocator &Allocator::DefaultAllocator() { diff --git a/src/duckdb/src/common/arrow/appender/append_data.cpp b/src/duckdb/src/common/arrow/appender/append_data.cpp index 73595a88d..b3c67ca7d 100644 --- a/src/duckdb/src/common/arrow/appender/append_data.cpp +++ b/src/duckdb/src/common/arrow/appender/append_data.cpp @@ -1,5 +1,9 @@ #include "duckdb/common/arrow/appender/append_data.hpp" +#include "duckdb/common/type_visitor.hpp" +#include "duckdb/common/vector/flat_vector.hpp" +#include "duckdb/common/vector_operations/vector_operations.hpp" + namespace duckdb { void ArrowAppendData::AppendValidity(UnifiedVectorFormat &format, idx_t from, idx_t to) { @@ -40,4 +44,40 @@ void ArrowAppendData::AppendChild(const Vector &input, idx_t from, idx_t to, idx } } +//! Whether appending a value of this type can throw, which must not happen for a value nobody can see. This is the case +//! for a UHUGEINT exported as the decimal128 of format version 1.0, which cannot hold values of 2^127 and above +static bool AppendRejectsValues(const LogicalType &type, const ClientProperties &options) { + if (options.arrow_lossless_conversion || options.arrow_output_version >= ArrowFormatVersion::V1_1) { + return false; + } + return TypeVisitor::Contains(type, LogicalTypeId::UHUGEINT); +} + +void ArrowAppendData::AppendChildOfParent(const Vector &child, const UnifiedVectorFormat &parent_format, idx_t from, + idx_t to, idx_t input_size, idx_t child_count) { + bool has_null_parent = false; + if (!parent_format.validity.CannotHaveNull() && AppendRejectsValues(child.GetType(), options)) { + for (idx_t i = from; i < to && !has_null_parent; i++) { + has_null_parent = !parent_format.validity.RowIsValid(parent_format.sel->get_index(i)); + } + } + if (!has_null_parent) { + AppendChild(child, from * child_count, to * child_count, input_size * child_count); + return; + } + // copy the child values of these rows, so the input stays as it is, and hide the ones under a NULL parent + const auto size = (to - from) * child_count; + Vector hidden(child.GetType(), MaxValue(size, STANDARD_VECTOR_SIZE)); + VectorOperations::Copy(child, hidden, to * child_count, from * child_count, 0); + for (idx_t i = from; i < to; i++) { + if (parent_format.validity.RowIsValid(parent_format.sel->get_index(i))) { + continue; + } + for (idx_t k = 0; k < child_count; k++) { + FlatVector::SetNull(hidden, (i - from) * child_count + k, true); + } + } + AppendChild(hidden, 0, size, size); +} + } // namespace duckdb diff --git a/src/duckdb/src/common/arrow/appender/fixed_size_list_data.cpp b/src/duckdb/src/common/arrow/appender/fixed_size_list_data.cpp index 37dfdea07..c1730e1c2 100644 --- a/src/duckdb/src/common/arrow/appender/fixed_size_list_data.cpp +++ b/src/duckdb/src/common/arrow/appender/fixed_size_list_data.cpp @@ -21,10 +21,12 @@ void ArrowFixedSizeListData::Append(ArrowAppendData &append_data, const Vector & idx_t size = to - from; append_data.AppendValidity(format, from, to); input.Flatten(); + // the vector was flattened, so the validity of the rows has to be looked up again + input.ToUnifiedFormat(format); auto array_size = ArrayType::GetSize(input.GetType()); auto &child_vector = ArrayVector::GetChild(input); auto &child_data = *append_data.child_data[0]; - child_data.AppendChild(child_vector, from * array_size, to * array_size, size * array_size); + child_data.AppendChildOfParent(child_vector, format, from, to, size, array_size); append_data.row_count += size; } diff --git a/src/duckdb/src/common/arrow/appender/struct_data.cpp b/src/duckdb/src/common/arrow/appender/struct_data.cpp index f70940336..bc82efad1 100644 --- a/src/duckdb/src/common/arrow/appender/struct_data.cpp +++ b/src/duckdb/src/common/arrow/appender/struct_data.cpp @@ -27,7 +27,7 @@ void ArrowStructData::Append(ArrowAppendData &append_data, const Vector &input, for (idx_t child_idx = 0; child_idx < children.size(); child_idx++) { auto &child = children[child_idx]; auto &child_data = *append_data.child_data[child_idx]; - child_data.AppendChild(child, from, to, input_size); + child_data.AppendChildOfParent(child, format, from, to, input_size); } append_data.row_count += size; } diff --git a/src/duckdb/src/common/arrow/arrow_appender.cpp b/src/duckdb/src/common/arrow/arrow_appender.cpp index badb0debc..5963835ad 100644 --- a/src/duckdb/src/common/arrow/arrow_appender.cpp +++ b/src/duckdb/src/common/arrow/arrow_appender.cpp @@ -38,6 +38,50 @@ struct ArrowWideDecimalConverter { } }; +//! Zero-extends a UHUGEINT into an Arrow decimal256 +struct ArrowUhugeintDecimal256Converter { + template + static TGT Operation(SRC input) { + TGT result; + result.words[0] = input.lower; + result.words[1] = input.upper; + result.words[2] = 0; + result.words[3] = 0; + return result; + } + + static bool SkipNulls() { + return true; + } + + template + static void SetNull(TGT &value) { + memset(&value, 0, sizeof(TGT)); + } +}; + +//! Appends a UHUGEINT as an Arrow decimal128 (format version 1.0), which only holds values below 2^127 +struct ArrowUhugeintDecimal128Converter { + template + static TGT Operation(SRC input) { + if ((input.upper >> 63) != 0) { + throw InvalidInputException("Cannot convert UHUGEINT value %s to Arrow format version 1.0: it does not fit " + "in a decimal128, SET arrow_output_version to 1.1 or later", + input.ToString()); + } + return input; + } + + static bool SkipNulls() { + return true; + } + + template + static void SetNull(TGT &value) { + value = TGT(0); + } +}; + //===--------------------------------------------------------------------===// // ArrowAppender //===--------------------------------------------------------------------===// @@ -230,7 +274,17 @@ static void InitializeFunctionPointers(ArrowAppendData &append_data, const Logic InitializeAppenderForType>(append_data); break; case LogicalTypeId::UHUGEINT: - InitializeAppenderForType>(append_data); + if (append_data.options.arrow_lossless_conversion) { + InitializeAppenderForType>(append_data); + } else if (append_data.options.arrow_output_version >= ArrowFormatVersion::V1_1) { + // exported as decimal256 with precision 39, see ArrowConverter + InitializeAppenderForType>( + append_data); + } else { + // the decimal128 of format version 1.0 would read values of 2^127 and above as negative + InitializeAppenderForType>( + append_data); + } break; case LogicalTypeId::UTINYINT: InitializeAppenderForType>(append_data); diff --git a/src/duckdb/src/common/arrow/arrow_converter.cpp b/src/duckdb/src/common/arrow/arrow_converter.cpp index c535c2b74..8c1a7ab10 100644 --- a/src/duckdb/src/common/arrow/arrow_converter.cpp +++ b/src/duckdb/src/common/arrow/arrow_converter.cpp @@ -66,7 +66,8 @@ void SetArrowFormat(DuckDBArrowSchemaHolder &root_holder, ArrowSchema &child, co void SetArrowStructFormat(DuckDBArrowSchemaHolder &root_holder, ArrowSchema &child, const LogicalType &type, ClientProperties &options, ClientContext &context, bool map_is_parent = false) { child.format = "+s"; - auto child_types = TupleType::NamedChildren(type); + auto child_types = + type.id() == LogicalTypeId::TUPLE ? TupleType::NamedChildren(type) : StructType::GetChildTypes(type); child.n_children = NumericCast(child_types.size()); root_holder.nested_children.emplace_back(); @@ -166,7 +167,13 @@ void SetArrowFormat(DuckDBArrowSchemaHolder &root_holder, ArrowSchema &child, co case LogicalTypeId::HUGEINT: { if (options.arrow_lossless_conversion) { SetArrowExtension(root_holder, child, type, context); + } else if (type.id() == LogicalTypeId::UHUGEINT && options.arrow_output_version >= ArrowFormatVersion::V1_1) { + // a decimal128 is signed, so it reads a UHUGEINT of 2^127 or more as a negative number. The full range + // needs the 39 digits of a decimal256 (format version 1.1) + child.format = "d:39,0,256"; } else { + // HUGEINT is the raw 16 bytes of a decimal128. For a UHUGEINT at format version 1.0 the appender rejects + // the values that do not fit in one child.format = "d:38,0"; } break; diff --git a/src/duckdb/src/common/base_file_system.cpp b/src/duckdb/src/common/base_file_system.cpp index 5bb60f366..4919f68b2 100644 --- a/src/duckdb/src/common/base_file_system.cpp +++ b/src/duckdb/src/common/base_file_system.cpp @@ -465,7 +465,7 @@ bool BaseFileSystem::ListFilesExtended(Context &context, const string &directory unique_ptr BaseFileSystem::OpenFile(Context &context, const string &path, FileOpenFlags flags) { if (SupportsOpenFileExtended()) { - return OpenFileExtended(context, OpenFileInfo(path), std::move(flags)); + return OpenFileExtended(context, OpenFileInfo(path), flags); } throw NotImplementedException("%s: OpenFile is not implemented!", GetName()); } @@ -775,7 +775,7 @@ bool BaseFileSystem::TryGetNetworkThroughput(FileHandle &handle, NetworkThroughp } FileHandle::FileHandle(BaseFileSystem &file_system, string path_p, FileOpenFlags flags_p) - : file_system(file_system), path(std::move(path_p)), flags(std::move(flags_p)) { + : file_system(file_system), path(std::move(path_p)), flags(flags_p) { } FileHandle::~FileHandle() { diff --git a/src/duckdb/src/common/clustered_aggregate.cpp b/src/duckdb/src/common/clustered_aggregate.cpp index 8225d4acc..e22ed402f 100644 --- a/src/duckdb/src/common/clustered_aggregate.cpp +++ b/src/duckdb/src/common/clustered_aggregate.cpp @@ -47,6 +47,7 @@ constexpr uint64_t GID_MASK = ClusteredAggr::MAX_GID_COUNT - 1; static_assert((1 << SLOT_GRP_BITS) >= STANDARD_VECTOR_SIZE, "Group IDs must be able to address vectorsize"); +//! The default Slot is the sentinel "no slot allocated yet" (all bitfields are 1s) struct Slot { // really just a 64-bits integer union { struct { @@ -66,10 +67,7 @@ struct Slot { // really just a 64-bits integer val.bitfields.idx = i; val.bitfields.gid = g; } - //! Sentinel value meaning "no slot allocated yet" (all bitfields are 1s). - static const Slot UNINITIALIZED; }; -const Slot Slot::UNINITIALIZED {}; // Each cursor uses an independent slice of the shared arena and its own slice of group_runs[]. // Each slice has a hot region first (MAX_HOT_PER_CURSOR lists of HALF_VEC slots) followed by a @@ -202,8 +200,8 @@ bool ClusteredAggr::TryClustered(const uint64_t *group_ids, sel_t count, sel_t * const sel_t sample = SAMPLE_SIZE / 2; // dual cursor: half as many iterations as positions const sel_t half = count / 2; - Slot cur1 = Slot::UNINITIALIZED; - Slot cur2 = Slot::UNINITIALIZED; + Slot cur1; + Slot cur2; sel_t miss1 = 0, miss2 = 0, pos; for (pos = 0; pos < sample && st1.n_runs < MAX_HOT_PER_CURSOR && st2.n_runs < MAX_HOT_PER_CURSOR; pos++) { uint64_t gid1 = group_ids[pos] & GID_MASK; diff --git a/src/duckdb/src/common/csv_writer.cpp b/src/duckdb/src/common/csv_writer.cpp index 4621442cc..629681a7b 100644 --- a/src/duckdb/src/common/csv_writer.cpp +++ b/src/duckdb/src/common/csv_writer.cpp @@ -89,7 +89,7 @@ CSVWriter::CSVWriter(const CSVReaderOptions &options_p, FileSystem &fs, const st options.write_newline, GetWriteCommentChar(options)), file_writer(make_uniq(fs, context, file_path, FileFlags::FILE_FLAGS_WRITE | FileFlags::FILE_FLAGS_FILE_CREATE_NEW | - FileLockType::WRITE_LOCK | std::move(compression))), + FileLockType::WRITE_LOCK | compression)), write_stream(*file_writer), should_initialize(true), shared(shared) { if (!shared) { global_write_state = make_uniq(); diff --git a/src/duckdb/src/common/enum_util.cpp b/src/duckdb/src/common/enum_util.cpp index 9dd3ae415..636b5e351 100644 --- a/src/duckdb/src/common/enum_util.cpp +++ b/src/duckdb/src/common/enum_util.cpp @@ -47,6 +47,7 @@ #include "duckdb/common/enums/function_errors.hpp" #include "duckdb/common/enums/http_status_code.hpp" #include "duckdb/common/enums/identifier_case_mode.hpp" +#include "duckdb/common/enums/implicit_lateral_subqueries.hpp" #include "duckdb/common/enums/index_constraint_type.hpp" #include "duckdb/common/enums/join_type.hpp" #include "duckdb/common/enums/joinref_type.hpp" @@ -80,6 +81,7 @@ #include "duckdb/common/enums/show_behavior.hpp" #include "duckdb/common/enums/statement_type.hpp" #include "duckdb/common/enums/storage_block_prefetch.hpp" +#include "duckdb/common/enums/subquery_lateral_type.hpp" #include "duckdb/common/enums/subquery_type.hpp" #include "duckdb/common/enums/table_function_identifier_conversion.hpp" #include "duckdb/common/enums/tableref_type.hpp" @@ -3434,6 +3436,26 @@ IdentifierCaseMode EnumUtil::FromString(const char *value) { return static_cast(StringUtil::StringToEnum(GetIdentifierCaseModeValues(), 3, "IdentifierCaseMode", value)); } +const StringUtil::EnumStringLiteral *GetImplicitLateralSubqueriesValues() { + static constexpr StringUtil::EnumStringLiteral values[] { + { static_cast(ImplicitLateralSubqueries::DEFAULT), "DEFAULT" }, + { static_cast(ImplicitLateralSubqueries::ALLOW), "ALLOW" }, + { static_cast(ImplicitLateralSubqueries::WARN), "WARN" }, + { static_cast(ImplicitLateralSubqueries::ERROR), "ERROR" } + }; + return values; +} + +template<> +const char* EnumUtil::ToChars(ImplicitLateralSubqueries value) { + return StringUtil::EnumToString(GetImplicitLateralSubqueriesValues(), 4, "ImplicitLateralSubqueries", static_cast(value)); +} + +template<> +ImplicitLateralSubqueries EnumUtil::FromString(const char *value) { + return static_cast(StringUtil::StringToEnum(GetImplicitLateralSubqueriesValues(), 4, "ImplicitLateralSubqueries", value)); +} + const StringUtil::EnumStringLiteral *GetIndexAppendModeValues() { static constexpr StringUtil::EnumStringLiteral values[] { { static_cast(IndexAppendMode::DEFAULT), "DEFAULT" }, @@ -4840,19 +4862,20 @@ const StringUtil::EnumStringLiteral *GetOptimizerTypeValues() { { static_cast(OptimizerType::SET_OPERATION_AGGREGATE), "SET_OPERATION_AGGREGATE" }, { static_cast(OptimizerType::JOIN_TO_SEMI_JOIN), "JOIN_TO_SEMI_JOIN" }, { static_cast(OptimizerType::MARK_JOIN_SIMPLIFIER), "MARK_JOIN_SIMPLIFIER" }, - { static_cast(OptimizerType::GROUP_BY_TOP_KEY), "GROUP_BY_TOP_KEY" } + { static_cast(OptimizerType::GROUP_BY_TOP_KEY), "GROUP_BY_TOP_KEY" }, + { static_cast(OptimizerType::CONSTANT_PROPAGATION), "CONSTANT_PROPAGATION" } }; return values; } template<> const char* EnumUtil::ToChars(OptimizerType value) { - return StringUtil::EnumToString(GetOptimizerTypeValues(), 60, "OptimizerType", static_cast(value)); + return StringUtil::EnumToString(GetOptimizerTypeValues(), 61, "OptimizerType", static_cast(value)); } template<> OptimizerType EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetOptimizerTypeValues(), 60, "OptimizerType", value)); + return static_cast(StringUtil::StringToEnum(GetOptimizerTypeValues(), 61, "OptimizerType", value)); } const StringUtil::EnumStringLiteral *GetOrderByColumnTypeValues() { @@ -7037,6 +7060,27 @@ StrTimeSpecifier EnumUtil::FromString(const char *value) { return static_cast(StringUtil::StringToEnum(GetStrTimeSpecifierValues(), 36, "StrTimeSpecifier", value)); } +const StringUtil::EnumStringLiteral *GetSubqueryLateralTypeValues() { + static constexpr StringUtil::EnumStringLiteral values[] { + { static_cast(SubqueryLateralType::GENERATED), "GENERATED" }, + { static_cast(SubqueryLateralType::IMPLICIT), "IMPLICIT" }, + { static_cast(SubqueryLateralType::EXPLICIT), "EXPLICIT" }, + { static_cast(SubqueryLateralType::FROM_CLAUSE_WRAPPER), "FROM_CLAUSE_WRAPPER" }, + { static_cast(SubqueryLateralType::UNRECORDED), "UNRECORDED" } + }; + return values; +} + +template<> +const char* EnumUtil::ToChars(SubqueryLateralType value) { + return StringUtil::EnumToString(GetSubqueryLateralTypeValues(), 5, "SubqueryLateralType", static_cast(value)); +} + +template<> +SubqueryLateralType EnumUtil::FromString(const char *value) { + return static_cast(StringUtil::StringToEnum(GetSubqueryLateralTypeValues(), 5, "SubqueryLateralType", value)); +} + const StringUtil::EnumStringLiteral *GetSubqueryTypeValues() { static constexpr StringUtil::EnumStringLiteral values[] { { static_cast(SubqueryType::INVALID), "INVALID" }, @@ -7823,19 +7867,20 @@ const StringUtil::EnumStringLiteral *GetVectorBufferTypeValues() { { static_cast(VectorBufferType::DICTIONARY_BUFFER), "DICTIONARY_BUFFER" }, { static_cast(VectorBufferType::FSST_BUFFER), "FSST_BUFFER" }, { static_cast(VectorBufferType::SHREDDED_BUFFER), "SHREDDED_BUFFER" }, - { static_cast(VectorBufferType::SEQUENCE_BUFFER), "SEQUENCE_BUFFER" } + { static_cast(VectorBufferType::SEQUENCE_BUFFER), "SEQUENCE_BUFFER" }, + { static_cast(VectorBufferType::SHARED_DATA_BUFFER), "SHARED_DATA_BUFFER" } }; return values; } template<> const char* EnumUtil::ToChars(VectorBufferType value) { - return StringUtil::EnumToString(GetVectorBufferTypeValues(), 9, "VectorBufferType", static_cast(value)); + return StringUtil::EnumToString(GetVectorBufferTypeValues(), 10, "VectorBufferType", static_cast(value)); } template<> VectorBufferType EnumUtil::FromString(const char *value) { - return static_cast(StringUtil::StringToEnum(GetVectorBufferTypeValues(), 9, "VectorBufferType", value)); + return static_cast(StringUtil::StringToEnum(GetVectorBufferTypeValues(), 10, "VectorBufferType", value)); } const StringUtil::EnumStringLiteral *GetVectorPrepareStateValues() { diff --git a/src/duckdb/src/common/enums/file_compression_type.cpp b/src/duckdb/src/common/enums/file_compression_type.cpp index ea5fdd03d..705e66484 100644 --- a/src/duckdb/src/common/enums/file_compression_type.cpp +++ b/src/duckdb/src/common/enums/file_compression_type.cpp @@ -1,35 +1,57 @@ #include "duckdb/common/enums/file_compression_type.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/common/exception.hpp" +#include "duckdb/common/mutex.hpp" +#include "duckdb/common/no_destructor.hpp" +#include "duckdb/common/unordered_set.hpp" namespace duckdb { -const FileCompressionType FileCompressionType::AUTO_DETECT = FileCompressionType("auto_detect"); -const FileCompressionType FileCompressionType::UNCOMPRESSED = FileCompressionType("uncompressed"); -const FileCompressionType FileCompressionType::GZIP = FileCompressionType("gzip"); -const FileCompressionType FileCompressionType::ZSTD = FileCompressionType("zstd"); +const FileCompressionType FileCompressionType::AUTO_DETECT = FileCompressionType(Kind::AUTO_DETECT); +const FileCompressionType FileCompressionType::UNCOMPRESSED = FileCompressionType(Kind::UNCOMPRESSED); +const FileCompressionType FileCompressionType::GZIP = FileCompressionType(Kind::GZIP); +const FileCompressionType FileCompressionType::ZSTD = FileCompressionType(Kind::ZSTD); -// note: the constructors and predicates below use string literals instead of the constants above, as they can run -// during static initialization of globals in other translation units (e.g. FileFlags), before the constants are -// initialized -FileCompressionType::FileCompressionType() : compression("uncompressed") { +static const string &InternCompressionName(string name) { + static NoDestructor intern_lock; + static NoDestructor> interned; + lock_guard guard(*intern_lock); + return *interned->insert(std::move(name)).first; } -FileCompressionType::FileCompressionType(string compression_p) : compression(std::move(compression_p)) { +bool FileCompressionType::TryGetBuiltIn(const string &lower_compression, Kind &result) { + if (lower_compression == "infer" || lower_compression == "auto" || lower_compression == "auto_detect") { + result = Kind::AUTO_DETECT; + } else if (lower_compression == "none" || lower_compression.empty() || lower_compression == "uncompressed") { + result = Kind::UNCOMPRESSED; + } else if (lower_compression == "gzip") { + result = Kind::GZIP; + } else if (lower_compression == "zstd") { + result = Kind::ZSTD; + } else { + return false; + } + return true; +} + +FileCompressionType::FileCompressionType(string compression) : kind(Kind::CUSTOM), custom(nullptr) { compression = StringUtil::Lower(compression); - if (compression == "infer" || compression == "auto") { - compression = "auto_detect"; - } else if (compression == "none" || compression.empty()) { - compression = "uncompressed"; + if (!TryGetBuiltIn(compression, kind)) { + custom = &InternCompressionName(std::move(compression)); } } +bool FileCompressionType::IsBuiltIn(const string &compression) { + Kind kind; + return TryGetBuiltIn(StringUtil::Lower(compression), kind); +} + bool FileCompressionType::operator==(const FileCompressionType &other) const { - return compression == other.compression; + return kind == other.kind && custom == other.custom; } bool FileCompressionType::operator!=(const FileCompressionType &other) const { - return compression != other.compression; + return !(*this == other); } bool FileCompressionType::IsCompressed() const { @@ -37,15 +59,30 @@ bool FileCompressionType::IsCompressed() const { } bool FileCompressionType::IsUncompressed() const { - return compression == "uncompressed"; + return kind == Kind::UNCOMPRESSED; } bool FileCompressionType::IsAutoDetect() const { - return compression == "auto_detect"; + return kind == Kind::AUTO_DETECT; } const string &FileCompressionType::ToString() const { - return compression; + static const NoDestructor uncompressed("uncompressed"); + static const NoDestructor auto_detect("auto_detect"); + static const NoDestructor gzip("gzip"); + static const NoDestructor zstd("zstd"); + switch (kind) { + case Kind::UNCOMPRESSED: + return *uncompressed; + case Kind::AUTO_DETECT: + return *auto_detect; + case Kind::GZIP: + return *gzip; + case Kind::ZSTD: + return *zstd; + default: + return *custom; + } } string CompressionExtensionFromType(const FileCompressionType &type) { diff --git a/src/duckdb/src/common/enums/optimizer_type.cpp b/src/duckdb/src/common/enums/optimizer_type.cpp index 56d00c6c0..720232468 100644 --- a/src/duckdb/src/common/enums/optimizer_type.cpp +++ b/src/duckdb/src/common/enums/optimizer_type.cpp @@ -72,6 +72,7 @@ static const DefaultOptimizerType internal_optimizer_types[] = { {"set_operation_aggregate", OptimizerType::SET_OPERATION_AGGREGATE}, {"join_to_semi_join", OptimizerType::JOIN_TO_SEMI_JOIN}, {"group_by_top_key", OptimizerType::GROUP_BY_TOP_KEY}, + {"constant_propagation", OptimizerType::CONSTANT_PROPAGATION}, {nullptr, OptimizerType::INVALID}}; string OptimizerTypeToString(OptimizerType type) { diff --git a/src/duckdb/src/common/local_file_system.cpp b/src/duckdb/src/common/local_file_system.cpp index adaa09bd0..c88578ddf 100644 --- a/src/duckdb/src/common/local_file_system.cpp +++ b/src/duckdb/src/common/local_file_system.cpp @@ -230,7 +230,7 @@ struct UnixFileHandle : public FileHandle { public: UnixFileHandle(BaseFileSystem &file_system, string path, int fd, FileOpenFlags flags, optional_ptr db) - : FileHandle(file_system, std::move(path), std::move(flags)), fd(fd), db(db) { + : FileHandle(file_system, std::move(path), flags), fd(fd), db(db) { } ~UnixFileHandle() override { UnixFileHandle::Close(); @@ -952,8 +952,19 @@ bool LocalFileSystem::IsPathAbsolute(const string &path) { } string LocalFileSystem::MakePathAbsolute(const string &path_p, const string &home_directory) { - auto parsed = Path::FromString(FileSystem::ExpandPathWithHome(path_p, home_directory)); - return (parsed.IsAbsolute() ? parsed : Path::FromString(FileSystem::GetWorkingDirectory()).Join(parsed)).ToString(); + auto path = FileSystem::ExpandPathWithHome(path_p, home_directory); + // the '..' are left to the OS, after a symlink 'link/..' is the parent of its target. A URI is absolute as well + if (Path::FromString(path).IsAbsolute()) { + return path; + } + auto working_directory = FileSystem::GetWorkingDirectory(); + if (path.empty()) { + return working_directory; + } + if (StringUtil::EndsWith(working_directory, "/")) { + return working_directory + path; + } + return working_directory + "/" + path; } //===----------------------------------------------------------------------===// @@ -974,7 +985,7 @@ class UnixMemoryMappedFile : public MemoryMappedFile { UnixMemoryMappedFile::UnixMemoryMappedFile(string path_p, FileOpenFlags flags_p, int fd_p, data_ptr_t data_p, idx_t size_p) - : MemoryMappedFile(std::move(path_p), std::move(flags_p), data_p, size_p), fd(fd_p) { + : MemoryMappedFile(std::move(path_p), flags_p, data_p, size_p), fd(fd_p) { } UnixMemoryMappedFile::~UnixMemoryMappedFile() { @@ -1501,12 +1512,13 @@ timestamp_t LocalFileSystem::GetLastModifiedTime(FileHandle &handle) { void LocalFileSystem::Truncate(FileHandle &handle, int64_t new_size) { HANDLE hFile = handle.Cast().fd; - // seek to the location - SetFilePointer(handle, new_size); - // now set the end of file position - if (!SetEndOfFile(hFile)) { + // truncate by explicit size: SetFilePointer + SetEndOfFile would cut at the handle's file pointer, + // which is shared per handle and moved by concurrent reads + FILE_END_OF_FILE_INFO file_size_info; + file_size_info.EndOfFile.QuadPart = new_size; + if (!SetFileInformationByHandle(hFile, FileEndOfFileInfo, &file_size_info, sizeof(file_size_info))) { auto error = LocalFileSystem::GetLastErrorAsString(); - throw IOException("Failure in SetEndOfFile call on file \"%s\": %s", handle.path, error); + throw IOException("Failure in SetFileInformationByHandle call on file \"%s\": %s", handle.path, error); } } diff --git a/src/duckdb/src/common/memory_mapped_file.cpp b/src/duckdb/src/common/memory_mapped_file.cpp index bb67de8be..724cf2058 100644 --- a/src/duckdb/src/common/memory_mapped_file.cpp +++ b/src/duckdb/src/common/memory_mapped_file.cpp @@ -8,7 +8,7 @@ namespace duckdb { // Platform-specific MemoryMappedFile subclasses and the LocalFileSystem::MemoryMapFile // factory live in src/common/local_file_system.cpp. MemoryMappedFile::MemoryMappedFile(string path_p, FileOpenFlags flags_p, data_ptr_t data_p, idx_t size_p) - : path(std::move(path_p)), flags(std::move(flags_p)), data(data_p), size(size_p) { + : path(std::move(path_p)), flags(flags_p), data(data_p), size(size_p) { } MemoryMappedFile::~MemoryMappedFile() { diff --git a/src/duckdb/src/common/partition_selection.cpp b/src/duckdb/src/common/partition_selection.cpp new file mode 100644 index 000000000..615ff36f8 --- /dev/null +++ b/src/duckdb/src/common/partition_selection.cpp @@ -0,0 +1,138 @@ +#include "duckdb/common/partition_selection.hpp" + +#include "duckdb/common/array_ptr.hpp" +#include "duckdb/common/vector/flat_vector.hpp" + +namespace duckdb { + +void PartitionSelectionState::Initialize(idx_t max_partition_idx) { + if (!partition_sel.data()) { + partition_sel.Initialize(); + } + if (max_partition_idx < MAP_THRESHOLD && fixed_partition_entries.GetCapacity() != max_partition_idx + 1) { + fixed_partition_entries.resize(max_partition_idx + 1); + } +} + +template +static void AddPartitionEntry(PartitionSelectionState &state, idx_t partition_index) { + using GETTER = TemplatedMapGetter; + auto &partition_entries = state.GetMap(); + auto partition_entry = partition_entries.find(partition_index); + if (partition_entry == partition_entries.end()) { + partition_entries[partition_index] = list_entry_t(0, 1); + } else { + GETTER::GetValue(partition_entry).length++; + } +} + +template <> +void AddPartitionEntry(PartitionSelectionState &state, idx_t partition_index) { + bool inserted; + auto &partition_entry = state.fixed_partition_entries.GetOrInsert(partition_index, inserted); + if (inserted) { + partition_entry = list_entry_t(0, 1); + } else { + partition_entry.length++; + } +} + +template +static void FillPartitionSelection(PartitionSelectionState &state, const SelectionVector &append_sel, + idx_t append_count, GET_OFFSET get_offset) { + const unsafe_array_ptr partition_indices(FlatVector::GetData(state.partition_indices), + append_count); + for (idx_t i = 0; i < append_count; i++) { + const auto index = HAS_SEL ? append_sel[i] : i; + auto &partition_offset = get_offset(partition_indices[i]); + if (COMPUTE_REVERSE_PARTITION_SEL) { + state.reverse_partition_sel.set_index(index, partition_offset); + } + state.partition_sel[partition_offset++] = UnsafeNumericCast(index); + } +} + +template +static void FillPartitionSelection(PartitionSelectionState &state, const SelectionVector &append_sel, + idx_t append_count, GET_OFFSET get_offset) { + if (append_sel.IsSet()) { + if (state.compute_reverse_partition_sel) { + FillPartitionSelection(state, append_sel, append_count, get_offset); + } else { + FillPartitionSelection(state, append_sel, append_count, get_offset); + } + } else { + if (state.compute_reverse_partition_sel) { + FillPartitionSelection(state, append_sel, append_count, get_offset); + } else { + FillPartitionSelection(state, append_sel, append_count, get_offset); + } + } +} + +template +void PartitionSelectionState::BuildInternal(const SelectionVector &append_sel, idx_t append_count, + idx_t max_partition_idx) { + auto &state = *this; + using GETTER = TemplatedMapGetter; + auto &partition_entries = state.GetMap(); + partition_entries.clear(); + if (append_count == 0) { + return; + } + D_ASSERT(state.partition_indices.GetVectorType() == VectorType::FLAT_VECTOR || + state.partition_indices.GetVectorType() == VectorType::CONSTANT_VECTOR); + const bool is_constant = state.partition_indices.GetVectorType() == VectorType::CONSTANT_VECTOR; + const unsafe_array_ptr partition_indices(FlatVector::GetData(state.partition_indices), + is_constant ? 1 : append_count); + if (max_partition_idx == 0 || is_constant) { + partition_entries[partition_indices[0]] = list_entry_t(0, append_count); + } else { + for (idx_t i = 0; i < append_count; i++) { + AddPartitionEntry(state, partition_indices[i]); + } + } + + if (partition_entries.size() == 1) { + if (state.compute_reverse_partition_sel) { + for (idx_t i = 0; i < append_count; i++) { + state.reverse_partition_sel.set_index(append_sel.get_index(i), i); + } + } + return; + } + + const bool bounded = FIXED || max_partition_idx != DConstants::INVALID_INDEX; + if (bounded && state.partition_offsets.size() <= max_partition_idx) { + state.partition_offsets.resize(max_partition_idx + 1); + } + idx_t offset = 0; + for (auto it = partition_entries.begin(); it != partition_entries.end(); ++it) { + auto &partition_entry = GETTER::GetValue(it); + partition_entry.offset = offset; + if (bounded) { + state.partition_offsets[GETTER::GetKey(it)] = offset; + } + offset += partition_entry.length; + } + + if (bounded) { + FillPartitionSelection(state, append_sel, append_count, [&](idx_t partition_index) -> idx_t & { + return state.partition_offsets[partition_index]; + }); + } else { + // Unbounded partition IDs use the map itself as scratch, avoiding a dense array of all discovered IDs. + FillPartitionSelection(state, append_sel, append_count, [&](idx_t partition_index) -> idx_t & { + return partition_entries[partition_index].offset; + }); + for (auto it = partition_entries.begin(); it != partition_entries.end(); ++it) { + auto &entry = GETTER::GetValue(it); + entry.offset -= entry.length; + } + } +} + +template void PartitionSelectionState::BuildInternal(const SelectionVector &, idx_t, idx_t); +template void PartitionSelectionState::BuildInternal(const SelectionVector &, idx_t, idx_t); + +} // namespace duckdb diff --git a/src/duckdb/src/common/radix_partitioning.cpp b/src/duckdb/src/common/radix_partitioning.cpp index 166e40115..20188d6e7 100644 --- a/src/duckdb/src/common/radix_partitioning.cpp +++ b/src/duckdb/src/common/radix_partitioning.cpp @@ -131,9 +131,6 @@ void RadixPartitionedColumnData::InitializeAppendStateInternal(PartitionedColumn state.partition_append_states.emplace_back(make_uniq()); partitions[i]->InitializeAppend(*state.partition_append_states[i]); } - - // Initialize fixed-size map - state.fixed_partition_entries.resize(RadixPartitioning::NumberOfPartitions(radix_bits)); } void RadixPartitionedColumnData::ComputePartitionIndices(PartitionedColumnDataAppendState &state, DataChunk &input) { diff --git a/src/duckdb/src/common/sort/sorted_run.cpp b/src/duckdb/src/common/sort/sorted_run.cpp index 4c3f9c4bc..4ae521a19 100644 --- a/src/duckdb/src/common/sort/sorted_run.cpp +++ b/src/duckdb/src/common/sort/sorted_run.cpp @@ -17,6 +17,13 @@ namespace duckdb { +void ThrowSortKeyExceedsFixedSize(idx_t key_size, idx_t fixed_size) { + throw DataCorruptionException("Sort key of %llu bytes does not fit the fixed-size sort key of %llu bytes that was " + "selected using the statistics of the sort columns - the statistics do not match " + "the data", + key_size, fixed_size); +} + //===--------------------------------------------------------------------===// // SortedRunScanState //===--------------------------------------------------------------------===// diff --git a/src/duckdb/src/common/sort/topn_heap.cpp b/src/duckdb/src/common/sort/topn_heap.cpp index f1a823336..e7902a239 100644 --- a/src/duckdb/src/common/sort/topn_heap.cpp +++ b/src/duckdb/src/common/sort/topn_heap.cpp @@ -373,7 +373,8 @@ void TopNHeap::AddSmallHeap(DataChunk &input, const Vector &sort_keys_vec) { bool any_added = false; auto sort_key_values = FlatVector::GetData(sort_keys_vec); - for (idx_t r = 0; r < input.size(); r++) { + const auto row_count = input.size(); + for (idx_t r = 0; r < row_count; r++) { auto &sort_key = sort_key_values[r]; if (!EntryShouldBeAdded(sort_key)) { continue; @@ -392,6 +393,7 @@ void TopNHeap::AddSmallHeap(DataChunk &input, const Vector &sort_keys_vec) { // for all matching entries we need to copy over the corresponding payload values idx_t match_count = 0; + const auto base_index = heap_data.size(); for (auto &entry : heap) { if (entry.index < BASE_INDEX) { continue; @@ -401,7 +403,7 @@ void TopNHeap::AddSmallHeap(DataChunk &input, const Vector &sort_keys_vec) { entry.sort_key = sort_key_heap.AddBlob(entry.sort_key); // to finalize the addition of this entry we need to move over the payload data matching_sel.set_index(match_count, entry.index - BASE_INDEX); - entry.index = heap_data.size() + match_count; + entry.index = base_index + match_count; match_count++; } @@ -413,7 +415,8 @@ void TopNHeap::AddLargeHeap(DataChunk &input, const Vector &sort_keys_vec) { auto sort_key_values = FlatVector::GetData(sort_keys_vec); idx_t base_index = heap_data.size(); idx_t match_count = 0; - for (idx_t r = 0; r < input.size(); r++) { + const auto row_count = input.size(); + for (idx_t r = 0; r < row_count; r++) { auto &sort_key = sort_key_values[r]; if (!EntryShouldBeAdded(sort_key)) { continue; diff --git a/src/duckdb/src/common/types.cpp b/src/duckdb/src/common/types.cpp index 4286e7f0f..710b9ae69 100644 --- a/src/duckdb/src/common/types.cpp +++ b/src/duckdb/src/common/types.cpp @@ -238,8 +238,9 @@ const LogicalTypeInfo &LogicalType::GetBuiltinTypeInfo(LogicalTypeId id) { throw InternalException("Invalid LogicalType %d", static_cast(id)); } if (id == LogicalTypeId::VARIANT) { - static const auto variant_type = CreateImmortal(LogicalTypeId::VARIANT, CreateVariantTypeInfo()); - return variant_type.GetTypeInfo(); + static const NoDestructor variant_type( + CreateImmortal(LogicalTypeId::VARIANT, CreateVariantTypeInfo())); + return variant_type->GetTypeInfo(); } return *info; } @@ -255,6 +256,15 @@ const LogicalTypeInfo &LogicalType::AdoptNewTypeInfo(LogicalTypeId id, unique_pt if (!type_info) { return GetBuiltinTypeInfo(id); } + if (type_info->type == LogicalTypeInfoType::INVALID_TYPE_INFO && + (!type_info->alias.empty() || type_info->extension_info)) { + // serialization drops a parameterless info entirely, losing its metadata: adopt the + // serializable representation the stock factories produce instead + auto generic_info = + make_uniq(LogicalTypeInfoType::GENERIC_TYPE_INFO, std::move(type_info->alias)); + generic_info->extension_info = std::move(type_info->extension_info); + type_info = std::move(generic_info); + } if (!TryGetPhysicalType(id, *type_info, type_info->physical_type)) { throw InternalException("Invalid LogicalType %d", static_cast(id)); } @@ -1475,19 +1485,11 @@ void LogicalType::Verify() const { D_ASSERT(Decimal::IsValidWidthScale(DecimalType::GetWidth(*this), DecimalType::GetScale(*this))); break; case LogicalTypeId::STRUCT: { - // verify child types + // verify child types - names (including the empty name) must be unique identifier_set_t child_names; - bool all_empty = true; for (auto &entry : StructType::GetChildTypes(*this)) { - if (entry.first.empty()) { - D_ASSERT(all_empty); - } else { - // check for duplicate struct names - all_empty = false; - auto existing_entry = child_names.find(entry.first); - D_ASSERT(existing_entry == child_names.end()); - child_names.insert(entry.first); - } + D_ASSERT(child_names.find(entry.first) == child_names.end()); + child_names.insert(entry.first); entry.second.Verify(); } break; @@ -1588,6 +1590,13 @@ void LogicalType::Serialize(Serializer &serializer) const { type_info = type_info_.get(); } serializer.WritePropertyWithDefault>(101, "type_info", type_info); + // a STRUCT with only empty member names is read back as a TUPLE (see Deserialize), unless it is marked otherwise; + // readers before v2.1.0 do not skip the marker, such STRUCTs are not stored for them (see StorageManager) + if (serializer.ShouldSerialize(StorageVersion::V2_1_0) && id() == LogicalTypeId::STRUCT && type_info && + type_info->type == LogicalTypeInfoType::STRUCT_TYPE_INFO && + StructType::AllUnnamed(type_info->Cast().child_types)) { + serializer.WriteProperty(102, "is_tuple", false); + } } //! Whether a type cannot be used without its type info (the info holds the child types / members) @@ -1614,9 +1623,10 @@ LogicalType LogicalType::Deserialize(Deserializer &deserializer) { return LogicalType::BLOB; } - // Convert unnamed (non-empty) STRUCTs back to TUPLE + // Convert STRUCTs with only empty member names back to TUPLE (older versions store a TUPLE as such a STRUCT) if (id == LogicalTypeId::STRUCT && type_info && type_info->type == LogicalTypeInfoType::STRUCT_TYPE_INFO && - StructType::AllUnnamed(type_info->Cast().child_types)) { + StructType::AllUnnamed(type_info->Cast().child_types) && + deserializer.ReadPropertyWithExplicitDefault(102, "is_tuple", true)) { id = LogicalTypeId::TUPLE; } @@ -1725,17 +1735,18 @@ static constexpr idx_t DecimalTypeInfoIndex(idx_t width, idx_t scale) { } LogicalType LogicalType::DECIMAL(uint32_t width, uint32_t scale) { + static constexpr uint32_t MAX_CACHED_WIDTH = 64; // width 0 and scale > width stay constructible and are reported by IsComplete D_ASSERT(width >= scale); - // the shared infos cover the fixed-size tiers: wide decimals have too many widths to share, and are rare - if (!Decimal::IsValidWidthScale(width, scale) || Decimal::IsWide(width)) { + // Include common widened intermediates, while bounding the number of immortal infos. + if (!Decimal::IsValidWidthScale(width, scale) || width > MAX_CACHED_WIDTH) { return LogicalType(LogicalTypeId::DECIMAL, make_uniq(width, scale)); } - static constexpr idx_t TYPE_COUNT = DecimalTypeInfoIndex(Decimal::MAX_WIDTH_INT128, Decimal::MAX_WIDTH_INT128) + 1; + static constexpr idx_t TYPE_COUNT = DecimalTypeInfoIndex(MAX_CACHED_WIDTH, MAX_CACHED_WIDTH) + 1; static const auto decimal_types = []() { // Finish allocation before immortalizing any info so failed initialization releases partial allocations. array, TYPE_COUNT> infos; - for (uint32_t width = 1; width <= Decimal::MAX_WIDTH_INT128; width++) { + for (uint32_t width = 1; width <= MAX_CACHED_WIDTH; width++) { for (uint32_t scale = 0; scale <= width; scale++) { infos[DecimalTypeInfoIndex(width, scale)] = make_uniq(width, scale); } @@ -1841,10 +1852,6 @@ bool StructType::AllUnnamed(const child_list_t &children) { } LogicalType LogicalType::STRUCT(child_list_t children) { - if (StructType::AllUnnamed(children)) { - // a struct without any member names is a TUPLE - return LogicalType::TUPLE(std::move(children)); - } auto info = make_uniq(std::move(children)); return LogicalType(LogicalTypeId::STRUCT, std::move(info)); } @@ -2056,9 +2063,9 @@ PhysicalType EnumType::GetPhysicalType(const LogicalType &type) { // JSON Type //===--------------------------------------------------------------------===// LogicalType LogicalType::JSON() { - static const auto json_type = CreateImmortal( - LogicalTypeId::VARCHAR, make_uniq(LogicalTypeInfoType::GENERIC_TYPE_INFO, JSON_TYPE_NAME)); - return json_type; + static const NoDestructor json_type(CreateImmortal( + LogicalTypeId::VARCHAR, make_uniq(LogicalTypeInfoType::GENERIC_TYPE_INFO, JSON_TYPE_NAME))); + return *json_type; } bool LogicalType::IsJSONType() const { diff --git a/src/duckdb/src/common/types/bignum_decimal.cpp b/src/duckdb/src/common/types/bignum_decimal.cpp index 61a61b7da..4facb9ffa 100644 --- a/src/duckdb/src/common/types/bignum_decimal.cpp +++ b/src/duckdb/src/common/types/bignum_decimal.cpp @@ -1,4 +1,5 @@ #include "duckdb/common/limits.hpp" +#include "duckdb/common/no_destructor.hpp" #include "duckdb/common/types/bignum_decimal.hpp" #include "duckdb/main/context.hpp" @@ -232,17 +233,17 @@ string ComputePowerOfTen(idx_t exponent, optional_ptr context) { //! The small constants are built once; their blobs outlive the intermediates that point into them const OwnedBignum &BignumConstant(int32_t value) { - static const OwnedBignum TWO(Bignum::VarcharToBignum(string_t("2"))); - static const OwnedBignum ONE(Bignum::VarcharToBignum(string_t("1"))); - static const OwnedBignum MINUS_ONE(Bignum::VarcharToBignum(string_t("-1"))); + static const NoDestructor TWO(Bignum::VarcharToBignum(string_t("2"))); + static const NoDestructor ONE(Bignum::VarcharToBignum(string_t("1"))); + static const NoDestructor MINUS_ONE(Bignum::VarcharToBignum(string_t("-1"))); switch (value) { case 2: - return TWO; + return *TWO; case 1: - return ONE; + return *ONE; default: D_ASSERT(value == -1); - return MINUS_ONE; + return *MINUS_ONE; } } @@ -256,19 +257,20 @@ bool IsOdd(const BignumIntermediate &value) { string DecimalHelper::PowerOfTen(idx_t exponent, optional_ptr context) { // the powers of everyday widths are computed once and read without locking afterwards static constexpr idx_t CACHED_POWERS = 512; - static array small_powers; + static NoDestructor> small_powers; static array small_flags; if (exponent < CACHED_POWERS) { - CallOnce(small_flags[exponent], [&]() { small_powers[exponent] = ComputePowerOfTen(exponent, context); }); - return small_powers[exponent]; + CallOnce(small_flags[exponent], [&]() { (*small_powers)[exponent] = ComputePowerOfTen(exponent, context); }); + return (*small_powers)[exponent]; } // wider powers are kept in a cache bounded by its total size static constexpr idx_t MAX_CACHED_POWER_BYTES = 16ULL * 1024 * 1024; - static mutex wide_lock; - static unordered_map wide_powers; + static NoDestructor wide_lock; + static NoDestructor> wide_powers_storage; + auto &wide_powers = *wide_powers_storage; static idx_t wide_power_bytes = 0; { - lock_guard guard(wide_lock); + lock_guard guard(*wide_lock); auto entry = wide_powers.find(exponent); if (entry != wide_powers.end()) { return entry->second; @@ -276,7 +278,7 @@ string DecimalHelper::PowerOfTen(idx_t exponent, optional_ptr guard(wide_lock); + lock_guard guard(*wide_lock); if (wide_power_bytes + power.size() > MAX_CACHED_POWER_BYTES) { wide_powers.clear(); wide_power_bytes = 0; @@ -475,8 +477,9 @@ string_t DecimalHelper::DivideAndRound(const BignumIntermediate &sourc if (DecimalHelper::IsZero(bignum_t(remainder))) { return quotient; } - // The remainder has the sign of the value; the quotient is truncated towards zero. - const bool negative = source.is_negative; + // The remainder has the sign of the value; the quotient is truncated towards zero and is negative when the signs + // of the value and the divisor differ. + const bool negative = source.is_negative != divisor.is_negative; int32_t adjustment = 0; switch (rounding) { case DecimalRounding::TRUNCATE: @@ -558,6 +561,32 @@ bool DecimalHelper::TryRescale(const bignum_t &value, uint32_t source_ return true; } +bool DecimalHelper::TryDivide(RescaleState &scratch, const bignum_t ÷nd, const bignum_t &divisor, + int64_t scale_exponent, DecimalRounding rounding, bignum_t &result) { + if (IsZero(divisor)) { + return false; + } + auto numerator = dividend.data; + auto denominator = divisor.data; + if (scale_exponent != 0) { + const auto exponent = NumericCast(scale_exponent < 0 ? -scale_exponent : scale_exponent); + BorrowedBignum factor(scratch.GetPowerOfTen(exponent)); + BorrowedBignum scaled(scale_exponent < 0 ? divisor : dividend); + auto product = + BignumIntermediate::Multiply(scratch.heap, scratch.arithmetic, scaled.intermediate, factor.intermediate); + if (scale_exponent < 0) { + denominator = product; + } else { + numerator = product; + } + } + BorrowedBignum numerator_value {bignum_t(numerator)}; + BorrowedBignum denominator_value {bignum_t(denominator)}; + result = bignum_t(DivideAndRound(numerator_value.intermediate, denominator_value.intermediate, rounding, + scratch.heap, scratch.arithmetic)); + return true; +} + DecimalHelper::RoundState::RoundState(Vector &result, Context &context) : heap(StringVector::GetStringHeap(result)), state(context) { } diff --git a/src/duckdb/src/common/types/column/column_data_collection.cpp b/src/duckdb/src/common/types/column/column_data_collection.cpp index 2e630fc33..a62e2dbeb 100644 --- a/src/duckdb/src/common/types/column/column_data_collection.cpp +++ b/src/duckdb/src/common/types/column/column_data_collection.cpp @@ -3,6 +3,7 @@ #include "duckdb/common/vector/dictionary_vector.hpp" #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/common/vector/list_vector.hpp" +#include "duckdb/common/vector/shared_child_vector.hpp" #include "duckdb/common/vector/struct_vector.hpp" #include "duckdb/common/types/column/column_data_collection.hpp" @@ -148,7 +149,11 @@ void ColumnDataCollection::Initialize(vector types_p) { } void ColumnDataCollection::CreateSegment() { - segments.emplace_back(make_uniq(allocator, types)); + if (share_list_children && !shared_child_accounting) { + shared_child_accounting = make_shared_ptr(); + } + segments.emplace_back(make_uniq( + allocator, types, share_list_children ? shared_child_accounting : nullptr)); } Allocator &ColumnDataCollection::GetAllocator() const { @@ -156,7 +161,7 @@ Allocator &ColumnDataCollection::GetAllocator() const { } idx_t ColumnDataCollection::SizeInBytes() const { - idx_t total_size = 0; + idx_t total_size = shared_child_accounting ? shared_child_accounting->UsedSize() : 0; for (const auto &segment : segments) { total_size += segment->SizeInBytes(); } @@ -164,13 +169,18 @@ idx_t ColumnDataCollection::SizeInBytes() const { } idx_t ColumnDataCollection::AllocationSize() const { - idx_t total_size = 0; + idx_t total_size = shared_child_accounting ? shared_child_accounting->AllocationSize() : 0; for (const auto &segment : segments) { total_size += segment->AllocationSize(); } return total_size; } +void ColumnDataCollection::EnableSharedListChildren() { + D_ASSERT(segments.empty()); + share_list_children = true; +} + void ColumnDataCollection::SetPartitionIndex(const idx_t index) { D_ASSERT(!partition_index.IsValid()); D_ASSERT(Count() == 0); @@ -480,6 +490,14 @@ static void TemplatedColumnDataCopy(ColumnDataMetaData &meta_data, const Unified auto current_index = meta_data.vector_data_index; idx_t remaining = count; while (remaining > 0) { + if (ColumnDataCollectionSegment::IsSharedListChild(segment.GetVectorData(current_index))) { + // shared list children are immutable - continue the append on the next entry + if (!segment.GetVectorData(current_index).next_data.IsValid()) { + segment.AllocateVector(source.GetType(), meta_data.chunk_data, append_state, current_index); + } + current_index = segment.GetVectorData(current_index).next_data; + continue; + } EnsureVectorDataAllocated(meta_data, current_index, OP::TypeSize()); auto ¤t_segment = segment.GetVectorData(current_index); const auto capacity = ColumnDataCollectionSegment::GetVectorCapacity(current_segment); @@ -986,6 +1004,81 @@ static void ForEachSelectedList(const UnifiedVectorFormat &source_data, const li } } +//! The prefix of shared child storage 'child_vector' presents unchanged, cut to the appended child, if the collection +//! should reference it instead of copying. The child must start the storage and cover at least half of it, so a +//! reference retains at most twice the bytes it covers (the bound capacity doubling in list_concat already accepts). +//! Shorter prefixes, e.g. a few elements selected from a large list, are copied rather than pinning the whole storage +static SharedChildPrefix GetReferenceablePrefix(Vector &child_vector, const ConsecutiveChildListInfo &info, + BufferManager &buffer_manager) { + if (info.needs_slicing || info.child_list_info.offset != 0) { + return SharedChildPrefix(); + } + auto prefix = SharedChildVector::GetUnchangedPrefix(child_vector); + const auto length = info.child_list_info.length; + if (!prefix || length > prefix.Count() || 2 * length < prefix.Capacity() || !prefix.IsBackedBy(buffer_manager)) { + return SharedChildPrefix(); + } + return prefix.Prefix(length); +} + +//! In a collection that shares list children (recursive CTE tables), store a NULL-free list child longer than a vector, +//! appended to an empty or full child chain, as a LARGE_FLAT entry referencing shared child storage. Children that +//! arrive as a view of such storage are referenced again without any copy, so large list payloads carried or grown +//! across recursive CTE iterations cost O(1) per append. Returns false if the child must be appended as on main +static bool TryShareLargeListChild(ColumnDataMetaData &meta_data, Vector &source, Vector &child_vector, + const ConsecutiveChildListInfo &info, idx_t offset, idx_t copy_count, + VectorDataIndex last_child_index) { + auto &segment = meta_data.segment; + auto &allocator = *segment.allocator; + D_ASSERT(segment.shared_children.Enabled()); + // shared storage is buffer-managed, and managed result sets must fail cleanly after the database closes + if (allocator.GetType() == ColumnDataAllocatorType::IN_MEMORY_ALLOCATOR || allocator.IsManagedResultSet()) { + return false; + } + if (last_child_index.IsValid()) { + auto &last_vdata = segment.GetVectorData(last_child_index); + if (last_vdata.count != ColumnDataCollectionSegment::GetVectorCapacity(last_vdata)) { + // an entry after a partially filled entry would leave reusable space in the middle of the chain, and + // later appends into that space would break the child offset order + return false; + } + } + const auto internal_type = child_vector.GetType().InternalType(); + if (!TypeIsConstantSize(internal_type)) { + return false; + } + const auto type_size = GetTypeIdSize(internal_type); + const auto length = info.child_list_info.length; + // like every LARGE_FLAT entry, the entry count and block size are 32-bit, also for referenced storage + if (length <= STANDARD_VECTOR_SIZE || + ColumnDataCollectionSegment::GetDataSize(type_size, length) + ValidityMask::ValidityMaskSize(length) > + MAXIMUM_LARGE_LIST_CHILD_SIZE) { + return false; + } + auto &buffer_manager = allocator.GetBufferManager(); + auto prefix = GetReferenceablePrefix(child_vector, info, buffer_manager); + if (!prefix) { + // materialize the child once into fresh shared storage, children with NULLs are not shared + if (info.needs_slicing) { + SelectionVector sel(length); + ListVector::GetConsecutiveChildSelVector(source, sel, offset, copy_count); + prefix = SharedChildVector::Materialize(buffer_manager, child_vector, sel, 0, length); + } else { + prefix = + SharedChildVector::Materialize(buffer_manager, child_vector, *FlatVector::IncrementalSelectionVector(), + info.child_list_info.offset, length); + } + if (!prefix) { + return false; + } + } + auto child_index = segment.AddSharedLargeVector(std::move(prefix), meta_data.chunk_data, last_child_index); + if (!meta_data.GetVectorMetaData().child_index.IsValid()) { + meta_data.GetVectorMetaData().child_index = segment.AddChildIndex(child_index); + } + return true; +} + template <> void ColumnDataCopy(ColumnDataMetaData &meta_data, const UnifiedVectorFormat &source_data, Vector &source, idx_t offset, idx_t copy_count) { @@ -994,13 +1087,15 @@ void ColumnDataCopy(ColumnDataMetaData &meta_data, const UnifiedVe auto &child_vector = ListVector::GetChildMutable(source); auto &child_type = child_vector.GetType(); - // figure out the current list size by traversing the set of child entries + // figure out the current list size and the end of the chain by traversing the set of child entries idx_t current_list_size = 0; + VectorDataIndex last_child_index; if (meta_data.GetVectorMetaData().child_index.IsValid()) { auto current_child_index = segment.GetChildIndex(meta_data.GetVectorMetaData().child_index); while (current_child_index.IsValid()) { auto &child_vdata = segment.GetVectorData(current_child_index); current_list_size += child_vdata.count; + last_child_index = current_child_index; current_child_index = child_vdata.next_data; } } @@ -1055,7 +1150,11 @@ void ColumnDataCopy(ColumnDataMetaData &meta_data, const UnifiedVe return; } auto info = ListVector::GetConsecutiveChildListInfo(source, offset, copy_count); - if (!TryAppendLargeListChild(meta_data, source, child_vector, info, offset, copy_count)) { + // only the consecutive (unselected) path shares: appends through a selection copy as on main + const auto shared = + segment.shared_children.Enabled() && + TryShareLargeListChild(meta_data, source, child_vector, info, offset, copy_count, last_child_index); + if (!shared && !TryAppendLargeListChild(meta_data, source, child_vector, info, offset, copy_count)) { auto &child_function = meta_data.copy_function.child_functions[0]; auto child_index = ListChildChain(meta_data, child_type); @@ -2054,9 +2153,20 @@ void ColumnDataCollection::Combine(ColumnDataCollection &other) { if (types != other.types) { throw InternalException("Attempting to combine ColumnDataCollections with mismatching types"); } + if (share_list_children != other.share_list_children) { + // moved segments would carry shared list children into a collection that does not share them, or the reverse + throw InternalException("Attempting to combine ColumnDataCollections with mismatching list child sharing"); + } this->count += other.count; this->segments.reserve(segments.size() + other.segments.size()); for (auto &other_seg : other.segments) { + if (other_seg->shared_children.Enabled()) { + // segments sharing list children move their storage into the accounting of this collection + if (!shared_child_accounting) { + shared_child_accounting = make_shared_ptr(); + } + other_seg->shared_children.MoveAccounting(shared_child_accounting); + } segments.push_back(std::move(other_seg)); } other.Reset(); @@ -2067,10 +2177,15 @@ void ColumnDataCollection::Swap(ColumnDataCollection &other) { if (types != other.types) { throw InternalException("Attempting to swap ColumnDataCollections with mismatching types"); } + if (share_list_children != other.share_list_children) { + throw InternalException("Attempting to swap ColumnDataCollections with mismatching list child sharing"); + } std::swap(allocator, other.allocator); std::swap(types, other.types); std::swap(count, other.count); std::swap(segments, other.segments); + std::swap(shared_child_accounting, other.shared_child_accounting); + std::swap(share_list_children, other.share_list_children); std::swap(copy_functions, other.copy_functions); std::swap(finished_append, other.finished_append); std::swap(partition_index, other.partition_index); @@ -2109,6 +2224,9 @@ void ColumnDataCollection::Truncate(idx_t new_count) { // If this collection has finished_append true, then calling InitializeAppend is not valid. // So build the tail into a new collection and Combine it back in. auto tail = make_uniq(allocator, types); + if (share_list_children) { + tail->EnableSharedListChildren(); + } ColumnDataAppendState append; tail->InitializeAppend(append); idx_t chunk_index = 0; diff --git a/src/duckdb/src/common/types/column/column_data_collection_segment.cpp b/src/duckdb/src/common/types/column/column_data_collection_segment.cpp index 019e44195..da55da4de 100644 --- a/src/duckdb/src/common/types/column/column_data_collection_segment.cpp +++ b/src/duckdb/src/common/types/column/column_data_collection_segment.cpp @@ -4,18 +4,121 @@ #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/common/vector/list_vector.hpp" #include "duckdb/common/vector/map_vector.hpp" +#include "duckdb/common/vector/shared_child_vector.hpp" #include "duckdb/common/vector/string_vector.hpp" #include "duckdb/common/vector/struct_vector.hpp" #include "duckdb/common/types/column/column_data_collection_segment.hpp" #include "duckdb/common/vector_operations/vector_operations.hpp" +#include "duckdb/storage/buffer_manager.hpp" namespace duckdb { +static idx_t UsedBytes(const map &segments_by_used) { + return segments_by_used.empty() ? 0 : segments_by_used.rbegin()->first; +} + +void ColumnDataSharedChildAccounting::SetUsed(Entry &entry, idx_t previous_used) { + used_size = used_size - previous_used + UsedBytes(entry.segments_by_used); +} + +void ColumnDataSharedChildAccounting::AddReference(idx_t id, idx_t size, idx_t used) { + auto inserted = entries.emplace(id, Entry {size, {}}); + auto &entry = inserted.first->second; + if (inserted.second) { + allocation_size += size; + } + const auto previous_used = UsedBytes(entry.segments_by_used); + entry.segments_by_used[used]++; + SetUsed(entry, previous_used); +} + +void ColumnDataSharedChildAccounting::UpdateUsed(idx_t id, idx_t previous, idx_t used) { + auto &entry = entries.find(id)->second; + const auto previous_used = UsedBytes(entry.segments_by_used); + auto count = entry.segments_by_used.find(previous); + D_ASSERT(count != entry.segments_by_used.end()); + if (--count->second == 0) { + entry.segments_by_used.erase(count); + } + entry.segments_by_used[used]++; + SetUsed(entry, previous_used); +} + +void ColumnDataSharedChildAccounting::RemoveReference(idx_t id, idx_t used) { + auto it = entries.find(id); + D_ASSERT(it != entries.end()); + auto &entry = it->second; + const auto previous_used = UsedBytes(entry.segments_by_used); + auto count = entry.segments_by_used.find(used); + D_ASSERT(count != entry.segments_by_used.end()); + if (--count->second == 0) { + entry.segments_by_used.erase(count); + } + // the used size drops to the longest prefix the remaining segments reference + SetUsed(entry, previous_used); + if (entry.segments_by_used.empty()) { + allocation_size -= entry.size; + entries.erase(it); + } +} + +ColumnDataSegmentSharedChildren::ColumnDataSegmentSharedChildren( + shared_ptr accounting_p) + : accounting(std::move(accounting_p)) { +} + +ColumnDataSegmentSharedChildren::~ColumnDataSegmentSharedChildren() { + ReleaseAccounting(); +} + +void ColumnDataSegmentSharedChildren::ReleaseAccounting() { + for (auto &entry : sizes) { + accounting->RemoveReference(entry.first, entry.second.second); + } +} + +idx_t ColumnDataSegmentSharedChildren::Add(SharedChildPrefix prefix) { + D_ASSERT(Enabled() && prefix); + // the collection accounts each distinct storage once, its used size is the longest prefix still referenced + const auto id = prefix.StorageId(); + const auto allocation = prefix.AllocationSize(); + const auto used = prefix.Count() * prefix.TypeSize(); + auto entry = sizes.emplace(id, make_pair(allocation, used)); + if (entry.second) { + accounting->AddReference(id, allocation, used); + } else if (used > entry.first->second.second) { + accounting->UpdateUsed(id, entry.first->second.second, used); + entry.first->second.second = used; + } + prefixes.push_back(std::move(prefix)); + return prefixes.size() - 1; +} + +void ColumnDataSegmentSharedChildren::Reset() { + ReleaseAccounting(); + sizes.clear(); + prefixes.clear(); +} + +void ColumnDataSegmentSharedChildren::MoveAccounting(shared_ptr target) { + D_ASSERT(Enabled() && target); + if (target == accounting) { + return; + } + for (auto &entry : sizes) { + target->AddReference(entry.first, entry.second.first, entry.second.second); + } + ReleaseAccounting(); + accounting = std::move(target); +} + ColumnDataCollectionSegment::ColumnDataCollectionSegment(shared_ptr allocator_p, - vector types_p) + vector types_p, + shared_ptr accounting) : allocator(std::move(allocator_p)), total_allocated(0), last_chunk_total_allocated(0), constant_metadata_size(0), - types(std::move(types_p)), count(0), heap(make_shared_ptr(allocator->GetAllocator())) { + types(std::move(types_p)), count(0), shared_children(std::move(accounting)), + heap(make_shared_ptr(allocator->GetAllocator())) { } void ColumnDataCollectionSegment::Reset() { @@ -28,9 +131,31 @@ void ColumnDataCollectionSegment::Reset() { child_indices.clear(); dictionaries.clear(); dictionary_map.clear(); + shared_children.Reset(); heap->GetAllocator().Reset(); } +VectorDataIndex ColumnDataCollectionSegment::AddSharedLargeVector(SharedChildPrefix prefix, ChunkMetaData &chunk_meta, + VectorDataIndex prev_index) { + // like every LARGE_FLAT entry it holds more than a vector, a count-0 head would hide the rest of its chain + D_ASSERT(prefix && prefix.Count() > STANDARD_VECTOR_SIZE); + const auto count_p = prefix.Count(); + VectorMetaData meta_data; + // the capacity equals the count, so appends continue on a new entry instead of writing into shared data + meta_data.count = NumericCast(count_p); + meta_data.representation = ColumnDataRepresentation::LARGE_FLAT; + // chunk estimates charge the bytes the reference covers + total_allocated += count_p * prefix.TypeSize(); + meta_data.shared_child_slot = shared_children.Add(std::move(prefix)); + + VectorDataIndex index(vector_data.size()); + vector_data.push_back(std::move(meta_data)); + if (prev_index.IsValid()) { + GetVectorData(prev_index).next_data = index; + } + return index; +} + idx_t ColumnDataCollectionSegment::GetDataSize(idx_t type_size, idx_t capacity) { return AlignValue(type_size * capacity); } @@ -345,9 +470,16 @@ idx_t ColumnDataCollectionSegment::ReadVectorInternal(ChunkManagementState &stat auto internal_type = vector_type.InternalType(); auto type_size = GetTypeIdSize(internal_type); auto &vdata = GetVectorData(vector_index); - D_ASSERT(vdata.is_allocated); + const auto shared_head = IsSharedListChild(vdata); + D_ASSERT(vdata.is_allocated || shared_head); - if (!vdata.next_data.IsValid() && state.properties != ColumnDataScanProperties::DISALLOW_ZERO_COPY) { + const auto zero_copy = state.properties != ColumnDataScanProperties::DISALLOW_ZERO_COPY; + if (!vdata.next_data.IsValid() && zero_copy && shared_head) { + // a complete shared list child: reference the shared storage through a scan-local view + SharedChildVector::SetView(result, GetSharedListChild(vdata)); + return vdata.count; + } + if (!vdata.next_data.IsValid() && zero_copy) { // no next data, we can do a zero-copy read of this vector const auto capacity = GetVectorCapacity(vdata); auto base_ptr = allocator->GetDataPointer(state, vdata.block_id, vdata.offset); @@ -370,6 +502,8 @@ idx_t ColumnDataCollectionSegment::ReadVectorInternal(ChunkManagementState &stat vector_count += current_vdata.count; next_index = current_vdata.next_data; } + // the values are overwritten below, a borrowed buffer is replaced instead of copied + FlatVector::PrepareForOverwrite(result, vector_count); // resize the result vector result.Reserve(vector_count); next_index = vector_index; @@ -379,6 +513,17 @@ idx_t ColumnDataCollectionSegment::ReadVectorInternal(ChunkManagementState &stat idx_t current_offset = 0; while (next_index.IsValid()) { auto ¤t_vdata = GetVectorData(next_index); + if (IsSharedListChild(current_vdata)) { + if (type_size > 0) { + GetSharedListChild(current_vdata).CopyTo(target_data + current_offset * type_size); + } + // shared storage holds no NULLs + target_validity.SliceInPlace(ValidityMask(nullptr, current_vdata.count), current_offset, 0, + current_vdata.count); + current_offset += current_vdata.count; + next_index = current_vdata.next_data; + continue; + } const auto current_capacity = GetVectorCapacity(current_vdata); auto base_ptr = allocator->GetDataPointer(state, current_vdata.block_id, current_vdata.offset); auto validity_data = GetValidityPointer(base_ptr, type_size, current_vdata.count, current_capacity); diff --git a/src/duckdb/src/common/types/column/partitioned_column_data.cpp b/src/duckdb/src/common/types/column/partitioned_column_data.cpp index 3ff3266cb..b41335bfe 100644 --- a/src/duckdb/src/common/types/column/partitioned_column_data.cpp +++ b/src/duckdb/src/common/types/column/partitioned_column_data.cpp @@ -29,12 +29,12 @@ PartitionedColumnData::~PartitionedColumnData() { } void PartitionedColumnData::InitializeAppendState(PartitionedColumnDataAppendState &state) const { - state.partition_sel.Initialize(); + state.Initialize(MaxPartitionIndex()); InitializeAppendStateInternal(state); } bool PartitionedColumnData::UseFixedSizeMap() const { - return MaxPartitionIndex() < PartitionedTupleDataAppendState::MAP_THRESHOLD; + return MaxPartitionIndex() < PartitionSelectionState::MAP_THRESHOLD; } void PartitionedColumnData::Append(PartitionedColumnDataAppendState &state, DataChunk &input) { @@ -42,7 +42,7 @@ void PartitionedColumnData::Append(PartitionedColumnDataAppendState &state, Data ComputePartitionIndices(state, input); // Build the selection vector for the partitions - BuildPartitionSel(state, input.size()); + state.Build(*FlatVector::IncrementalSelectionVector(), input.size(), MaxPartitionIndex()); // Early out: check if everything belongs to a single partition const auto partition_index = state.GetPartitionIndexIfSinglePartition(UseFixedSizeMap()); @@ -60,93 +60,19 @@ void PartitionedColumnData::Append(PartitionedColumnDataAppendState &state, Data } } -void PartitionedColumnData::BuildPartitionSel(PartitionedColumnDataAppendState &state, const idx_t append_count) const { - if (UseFixedSizeMap()) { - BuildPartitionSel(state, append_count); - } else { - BuildPartitionSel(state, append_count); - } -} - -template -MAP_TYPE &PartitionedColumnDataGetMap(PartitionedColumnDataAppendState &) { - throw InternalException("Unknown MAP_TYPE for PartitionedTupleDataGetMap"); -} - -template <> -fixed_size_map_t &PartitionedColumnDataGetMap(PartitionedColumnDataAppendState &state) { - return state.fixed_partition_entries; -} - -template <> -perfect_map_t &PartitionedColumnDataGetMap(PartitionedColumnDataAppendState &state) { - return state.partition_entries; -} - -template -void PartitionedColumnData::BuildPartitionSel(PartitionedColumnDataAppendState &state, const idx_t append_count) { - using GETTER = TemplatedMapGetter; - auto &partition_entries = state.GetMap(); - partition_entries.clear(); - switch (state.partition_indices.GetVectorType()) { - case VectorType::FLAT_VECTOR: { - const auto partition_indices = FlatVector::GetData(state.partition_indices); - for (idx_t i = 0; i < append_count; i++) { - const auto &partition_index = partition_indices[i]; - auto partition_entry = partition_entries.find(partition_index); - if (partition_entry == partition_entries.end()) { - partition_entries[partition_index] = list_entry_t(0, 1); - } else { - GETTER::GetValue(partition_entry).length++; - } - } - break; - } - case VectorType::CONSTANT_VECTOR: - partition_entries[*ConstantVector::GetData(state.partition_indices)] = list_entry_t(0, append_count); - break; - default: - throw InternalException("Unexpected VectorType in PartitionedTupleData::Append"); - } - - // Early out: check if everything belongs to a single partition - if (partition_entries.size() == 1) { - return; - } - - // Compute offsets from the counts - idx_t offset = 0; - for (auto it = partition_entries.begin(); it != partition_entries.end(); ++it) { - auto &partition_entry = GETTER::GetValue(it); - partition_entry.offset = offset; - offset += partition_entry.length; - } - - // Now initialize a single selection vector that acts as a selection vector for every partition - D_ASSERT(state.partition_indices.GetVectorType() == VectorType::FLAT_VECTOR); - const auto partition_indices = FlatVector::GetData(state.partition_indices); - auto &partition_sel = state.partition_sel; - for (idx_t i = 0; i < append_count; i++) { - const auto &partition_index = partition_indices[i]; - auto &partition_offset = partition_entries[partition_index].offset; - partition_sel[partition_offset++] = UnsafeNumericCast(i); - } -} - template void PartitionedColumnData::AppendInternal(PartitionedColumnDataAppendState &state, DataChunk &input) { using GETTER = TemplatedMapGetter; const auto &partition_entries = state.GetMap(); - // Each partition receives its stretch of the partition selection, all in one append. BuildPartitionSel left each - // entry's offset at the end of its stretch. + // Each partition receives its stretch of the partition selection, all in one append. auto &targets = state.partition_targets; targets.clear(); for (auto it = partition_entries.begin(); it != partition_entries.end(); ++it) { const auto partition_index = GETTER::GetKey(it); const auto &entry = GETTER::GetValue(it); - targets.push_back({*partitions[partition_index], *state.partition_append_states[partition_index], - entry.offset - entry.length, entry.offset}); + targets.push_back({*partitions[partition_index], *state.partition_append_states[partition_index], entry.offset, + entry.offset + entry.length}); } ColumnDataCollection::AppendBatch(input, state.partition_sel, input.size(), targets); } diff --git a/src/duckdb/src/common/types/data_chunk.cpp b/src/duckdb/src/common/types/data_chunk.cpp index db0b86454..3994b3e16 100644 --- a/src/duckdb/src/common/types/data_chunk.cpp +++ b/src/duckdb/src/common/types/data_chunk.cpp @@ -34,6 +34,7 @@ DataChunk::~DataChunk() { void DataChunk::InitializeEmpty(const vector &types) { D_ASSERT(data.empty()); + data.reserve(types.size()); for (idx_t i = 0; i < types.size(); i++) { data.emplace_back(types[i], nullptr); } @@ -57,6 +58,8 @@ void DataChunk::Initialize(Allocator &allocator, const vector &type idx_t capacity) { D_ASSERT(types.size() == initialize.size()); D_ASSERT(data.empty()); + data.reserve(types.size()); + vector_caches.reserve(types.size()); for (idx_t i = 0; i < types.size(); i++) { // We copy the type here so we don't create another reference to the same LogicalTypeInfo @@ -209,7 +212,7 @@ void DataChunk::Copy(DataChunk &other, idx_t offset) const { VectorOperations::Copy(data[i], other.data[i], size(), offset, 0); FlatVector::SetSize(other.data[i], target_count); } - other.count = optional_idx(); + other.count = ColumnCount() == 0 ? optional_idx(target_count) : optional_idx(); } void DataChunk::Copy(DataChunk &other, const SelectionVector &sel, const idx_t source_count, const idx_t offset) const { @@ -223,7 +226,7 @@ void DataChunk::Copy(DataChunk &other, const SelectionVector &sel, const idx_t s VectorOperations::Copy(data[i], other.data[i], sel, source_count, offset, 0); FlatVector::SetSize(other.data[i], target_count); } - other.count = optional_idx(); + other.count = ColumnCount() == 0 ? optional_idx(target_count) : optional_idx(); } void DataChunk::Split(DataChunk &other, idx_t split_idx) { diff --git a/src/duckdb/src/common/types/date.cpp b/src/duckdb/src/common/types/date.cpp index eef4f516d..a1c8f72bd 100644 --- a/src/duckdb/src/common/types/date.cpp +++ b/src/duckdb/src/common/types/date.cpp @@ -17,12 +17,27 @@ const DateSpecial Date::PINF = {"infinity", 3}; // NOLINT const DateSpecial Date::NINF = {"-infinity", 4}; // NOLINT const DateSpecial Date::EPOCH = {"epoch", 5}; // NOLINT -const string_t Date::MONTH_NAMES_ABBREVIATED[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; -const string_t Date::MONTH_NAMES[] = {"January", "February", "March", "April", "May", "June", - "July", "August", "September", "October", "November", "December"}; -const string_t Date::DAY_NAMES[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; -const string_t Date::DAY_NAMES_ABBREVIATED[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; +const string_t *Date::MonthNamesAbbreviated() { + static const string_t names[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; + return names; +} + +const string_t *Date::MonthNames() { + static const string_t names[] = {"January", "February", "March", "April", "May", "June", + "July", "August", "September", "October", "November", "December"}; + return names; +} + +const string_t *Date::DayNames() { + static const string_t names[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; + return names; +} + +const string_t *Date::DayNamesAbbreviated() { + static const string_t names[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; + return names; +} const int32_t Date::NORMAL_DAYS[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; const int32_t Date::CUMULATIVE_DAYS[] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}; diff --git a/src/duckdb/src/common/types/row/partitioned_tuple_data.cpp b/src/duckdb/src/common/types/row/partitioned_tuple_data.cpp index 326524b0a..b89f87ce5 100644 --- a/src/duckdb/src/common/types/row/partitioned_tuple_data.cpp +++ b/src/duckdb/src/common/types/row/partitioned_tuple_data.cpp @@ -38,8 +38,7 @@ PartitionedTupleDataType PartitionedTupleData::GetType() const { void PartitionedTupleData::InitializeAppendState(PartitionedTupleDataAppendState &state, TupleDataPinProperties properties) const { - state.partition_sel.Initialize(); - state.reverse_partition_sel.Initialize(); + state.Initialize(MaxPartitionIndex()); InitializeAppendStateInternal(state, properties); } @@ -62,21 +61,11 @@ void PartitionedTupleData::InitializeAppendStateInternal(PartitionedTupleDataApp column_ids.emplace_back(col_idx); } partitions[0]->InitializeChunkState(state.chunk_state, std::move(column_ids)); - - // Initialize fixed-size map - if (UseFixedSizeMap()) { - state.fixed_partition_entries.resize(num_partitions); - } } void PartitionedTupleData::ResetAppendState(PartitionedTupleDataAppendState &state, TupleDataPinProperties properties) const { - if (!state.partition_sel.data()) { - state.partition_sel.Initialize(); - } - if (!state.reverse_partition_sel.data()) { - state.reverse_partition_sel.Initialize(); - } + state.Initialize(MaxPartitionIndex()); const auto num_partitions = partitions.size(); if (state.partition_pin_states.size() != num_partitions) { @@ -105,11 +94,6 @@ void PartitionedTupleData::ResetAppendState(PartitionedTupleDataAppendState &sta state.chunk_state.chunk_lock = nullptr; state.chunk_state.chunk_parts.clear(); state.chunk_state.chunk_part_indices.clear(); - - // the map is cleared before every append, so only its capacity has to match (size() counts occupied entries) - if (UseFixedSizeMap() && state.fixed_partition_entries.GetCapacity() != num_partitions) { - state.fixed_partition_entries.resize(num_partitions); - } } void PartitionedTupleData::Append(PartitionedTupleDataAppendState &state, DataChunk &input, @@ -119,7 +103,7 @@ void PartitionedTupleData::Append(PartitionedTupleDataAppendState &state, DataCh } bool PartitionedTupleData::UseFixedSizeMap() const { - return MaxPartitionIndex() < PartitionedTupleDataAppendState::MAP_THRESHOLD; + return MaxPartitionIndex() < PartitionSelectionState::MAP_THRESHOLD; } void PartitionedTupleData::AppendUnified(PartitionedTupleDataAppendState &state, DataChunk &input, @@ -130,7 +114,7 @@ void PartitionedTupleData::AppendUnified(PartitionedTupleDataAppendState &state, ComputePartitionIndices(state, input, append_sel, actual_append_count); // Build the selection vector for the partitions - BuildPartitionSel(state, append_sel, actual_append_count); + state.Build(append_sel, actual_append_count, MaxPartitionIndex()); // Early out: check if everything belongs to a single partition const auto partition_index = state.GetPartitionIndexIfSinglePartition(UseFixedSizeMap()); @@ -161,14 +145,14 @@ void PartitionedTupleData::AppendUnified(PartitionedTupleDataAppendState &state, void PartitionedTupleData::Append(PartitionedTupleDataAppendState &state, TupleDataChunkState &input, const idx_t append_count, const SelectionVector &append_sel) { const auto max_partition_idx = MaxPartitionIndex(); - const auto use_fixed_size_map = max_partition_idx < PartitionedTupleDataAppendState::MAP_THRESHOLD; + const auto use_fixed_size_map = max_partition_idx < PartitionSelectionState::MAP_THRESHOLD; // Compute partition indices and store them in state.partition_indices ComputePartitionIndices(input.row_locations, append_count, state.partition_indices, state.utility_vector, append_sel); // Build the selection vector for the partitions - BuildPartitionSel(state, append_sel, append_count); + state.Build(append_sel, append_count, max_partition_idx); // Early out: check if everything belongs to a single partition auto partition_index = state.GetPartitionIndexIfSinglePartition(use_fixed_size_map); @@ -202,127 +186,6 @@ void PartitionedTupleData::Append(PartitionedTupleDataAppendState &state, TupleD Verify(); } -void PartitionedTupleData::BuildPartitionSel(PartitionedTupleDataAppendState &state, const SelectionVector &append_sel, - const idx_t append_count) const { - if (UseFixedSizeMap()) { - BuildPartitionSel(state, append_sel, append_count, MaxPartitionIndex()); - } else { - BuildPartitionSel(state, append_sel, append_count, MaxPartitionIndex()); - } -} - -template -static void AddPartitionEntry(PartitionedTupleDataAppendState &state, const idx_t partition_index) { - using GETTER = TemplatedMapGetter; - auto &partition_entries = state.GetMap(); - auto partition_entry = partition_entries.emplace(partition_index, list_entry_t(0, 1)); - if (!partition_entry.second) { - GETTER::GetValue(partition_entry.first).length++; - } -} - -template <> -void AddPartitionEntry(PartitionedTupleDataAppendState &state, const idx_t partition_index) { - bool inserted; - auto &partition_entry = state.fixed_partition_entries.GetOrInsert(partition_index, inserted); - if (inserted) { - partition_entry = list_entry_t(0, 1); - } else { - partition_entry.length++; - } -} - -template -static void TemplatedBuildPartitionSel(PartitionedTupleDataAppendState &state, const SelectionVector &append_sel, - const idx_t append_count) { - D_ASSERT(state.partition_indices.GetVectorType() == VectorType::FLAT_VECTOR); - const auto partition_indices = FlatVector::GetData(state.partition_indices); - auto &partition_sel = state.partition_sel; - auto &reverse_partition_sel = state.reverse_partition_sel; - auto &partition_offsets = state.partition_offsets; - - for (idx_t i = 0; i < append_count; i++) { - const auto index = HAS_SEL ? append_sel[i] : i; - const auto &partition_index = partition_indices[i]; - auto &partition_offset = partition_offsets[partition_index]; - if (COMPUTE_REVERSE_PARTITION_SEL) { - reverse_partition_sel.set_index(index, partition_offset); - } - partition_sel[partition_offset++] = UnsafeNumericCast(index); - } -} - -template -void PartitionedTupleData::BuildPartitionSel(PartitionedTupleDataAppendState &state, const SelectionVector &append_sel, - const idx_t append_count, const idx_t max_partition_idx) { - using GETTER = TemplatedMapGetter; - auto &partition_entries = state.GetMap(); - partition_entries.clear(); - - if (max_partition_idx == 0 || state.partition_indices.GetVectorType() == VectorType::CONSTANT_VECTOR) { - idx_t partition_idx; - if (state.partition_indices.GetVectorType() == VectorType::CONSTANT_VECTOR) { - partition_idx = *ConstantVector::GetData(state.partition_indices); - } else { - partition_idx = FlatVector::GetData(state.partition_indices)[0]; - } - partition_entries[partition_idx] = list_entry_t(0, append_count); - } else { - D_ASSERT(state.partition_indices.GetVectorType() == VectorType::FLAT_VECTOR); - const auto partition_indices = FlatVector::GetData(state.partition_indices); - for (idx_t i = 0; i < append_count; i++) { - AddPartitionEntry(state, partition_indices[i]); - } - } - - // Early out: check if everything belongs to a single partition - if (partition_entries.size() == 1) { - if (!state.compute_reverse_partition_sel) { - return; - } - // This needs to be initialized, even if we go the short path here - if (append_sel.IsSet()) { - for (sel_t i = 0; i < append_count; i++) { - const auto index = append_sel.get_index(i); - state.reverse_partition_sel[index] = i; - } - } else { - for (sel_t i = 0; i < append_count; i++) { - state.reverse_partition_sel[i] = i; - } - } - return; - } - - // Compute offsets from the counts - if (state.partition_offsets.size() <= max_partition_idx) { - state.partition_offsets.resize(max_partition_idx + 1); - } - idx_t offset = 0; - for (auto it = partition_entries.begin(); it != partition_entries.end(); ++it) { - const auto &partition_index = GETTER::GetKey(it); - auto &partition_entry = GETTER::GetValue(it); - partition_entry.offset = offset; - state.partition_offsets[partition_index] = offset; - offset += partition_entry.length; - } - - // Now initialize a single selection vector that acts as a selection vector for every partition - if (append_sel.IsSet()) { - if (state.compute_reverse_partition_sel) { - TemplatedBuildPartitionSel(state, append_sel, append_count); - } else { - TemplatedBuildPartitionSel(state, append_sel, append_count); - } - } else { - if (state.compute_reverse_partition_sel) { - TemplatedBuildPartitionSel(state, append_sel, append_count); - } else { - TemplatedBuildPartitionSel(state, append_sel, append_count); - } - } -} - void PartitionedTupleData::BuildBufferSpace(PartitionedTupleDataAppendState &state) { if (UseFixedSizeMap()) { BuildBufferSpace(state); diff --git a/src/duckdb/src/common/types/row/tuple_data_collection.cpp b/src/duckdb/src/common/types/row/tuple_data_collection.cpp index d71ea031b..cbc605cde 100644 --- a/src/duckdb/src/common/types/row/tuple_data_collection.cpp +++ b/src/duckdb/src/common/types/row/tuple_data_collection.cpp @@ -649,7 +649,10 @@ void TupleDataCollection::Combine(TupleDataCollection &other) { if (this->layout.GetTypes() != other.GetLayout().GetTypes()) { throw InternalException("Attempting to combine TupleDataCollection with mismatching types"); } - this->segments.reserve(this->segments.size() + other.segments.size()); + const auto required_capacity = segments.size() + other.segments.size(); + if (required_capacity > segments.capacity()) { + segments.reserve(MaxValue(required_capacity, 2 * segments.capacity())); + } for (auto &other_seg : other.segments) { AddSegment(std::move(other_seg)); } diff --git a/src/duckdb/src/common/types/uhugeint.cpp b/src/duckdb/src/common/types/uhugeint.cpp index cafdcb6e8..537503f0b 100644 --- a/src/duckdb/src/common/types/uhugeint.cpp +++ b/src/duckdb/src/common/types/uhugeint.cpp @@ -18,46 +18,45 @@ namespace duckdb { //===--------------------------------------------------------------------===// // String Conversion //===--------------------------------------------------------------------===// -const uhugeint_t Uhugeint::POWERS_OF_TEN[] { - uhugeint_t(1), - uhugeint_t(10), - uhugeint_t(100), - uhugeint_t(1000), - uhugeint_t(10000), - uhugeint_t(100000), - uhugeint_t(1000000), - uhugeint_t(10000000), - uhugeint_t(100000000), - uhugeint_t(1000000000), - uhugeint_t(10000000000), - uhugeint_t(100000000000), - uhugeint_t(1000000000000), - uhugeint_t(10000000000000), - uhugeint_t(100000000000000), - uhugeint_t(1000000000000000), - uhugeint_t(10000000000000000), - uhugeint_t(100000000000000000), - uhugeint_t(1000000000000000000), - uhugeint_t(1000000000000000000) * uhugeint_t(10), - uhugeint_t(1000000000000000000) * uhugeint_t(100), - uhugeint_t(1000000000000000000) * uhugeint_t(1000), - uhugeint_t(1000000000000000000) * uhugeint_t(10000), - uhugeint_t(1000000000000000000) * uhugeint_t(100000), - uhugeint_t(1000000000000000000) * uhugeint_t(1000000), - uhugeint_t(1000000000000000000) * uhugeint_t(10000000), - uhugeint_t(1000000000000000000) * uhugeint_t(100000000), - uhugeint_t(1000000000000000000) * uhugeint_t(1000000000), - uhugeint_t(1000000000000000000) * uhugeint_t(10000000000), - uhugeint_t(1000000000000000000) * uhugeint_t(100000000000), - uhugeint_t(1000000000000000000) * uhugeint_t(1000000000000), - uhugeint_t(1000000000000000000) * uhugeint_t(10000000000000), - uhugeint_t(1000000000000000000) * uhugeint_t(100000000000000), - uhugeint_t(1000000000000000000) * uhugeint_t(1000000000000000), - uhugeint_t(1000000000000000000) * uhugeint_t(10000000000000000), - uhugeint_t(1000000000000000000) * uhugeint_t(100000000000000000), - uhugeint_t(1000000000000000000) * uhugeint_t(1000000000000000000), - uhugeint_t(1000000000000000000) * uhugeint_t(1000000000000000000) * uhugeint_t(10), - uhugeint_t(1000000000000000000) * uhugeint_t(1000000000000000000) * uhugeint_t(100)}; +const uhugeint_t Uhugeint::POWERS_OF_TEN[] {uhugeint_t(0ULL, 1ULL), + uhugeint_t(0ULL, 10ULL), + uhugeint_t(0ULL, 100ULL), + uhugeint_t(0ULL, 1000ULL), + uhugeint_t(0ULL, 10000ULL), + uhugeint_t(0ULL, 100000ULL), + uhugeint_t(0ULL, 1000000ULL), + uhugeint_t(0ULL, 10000000ULL), + uhugeint_t(0ULL, 100000000ULL), + uhugeint_t(0ULL, 1000000000ULL), + uhugeint_t(0ULL, 10000000000ULL), + uhugeint_t(0ULL, 100000000000ULL), + uhugeint_t(0ULL, 1000000000000ULL), + uhugeint_t(0ULL, 10000000000000ULL), + uhugeint_t(0ULL, 100000000000000ULL), + uhugeint_t(0ULL, 1000000000000000ULL), + uhugeint_t(0ULL, 10000000000000000ULL), + uhugeint_t(0ULL, 100000000000000000ULL), + uhugeint_t(0ULL, 1000000000000000000ULL), + uhugeint_t(0ULL, 10000000000000000000ULL), + uhugeint_t(5ULL, 7766279631452241920ULL), + uhugeint_t(54ULL, 3875820019684212736ULL), + uhugeint_t(542ULL, 1864712049423024128ULL), + uhugeint_t(5421ULL, 200376420520689664ULL), + uhugeint_t(54210ULL, 2003764205206896640ULL), + uhugeint_t(542101ULL, 1590897978359414784ULL), + uhugeint_t(5421010ULL, 15908979783594147840ULL), + uhugeint_t(54210108ULL, 11515845246265065472ULL), + uhugeint_t(542101086ULL, 4477988020393345024ULL), + uhugeint_t(5421010862ULL, 7886392056514347008ULL), + uhugeint_t(54210108624ULL, 5076944270305263616ULL), + uhugeint_t(542101086242ULL, 13875954555633532928ULL), + uhugeint_t(5421010862427ULL, 9632337040368467968ULL), + uhugeint_t(54210108624275ULL, 4089650035136921600ULL), + uhugeint_t(542101086242752ULL, 4003012203950112768ULL), + uhugeint_t(5421010862427522ULL, 3136633892082024448ULL), + uhugeint_t(54210108624275221ULL, 12919594847110692864ULL), + uhugeint_t(542101086242752217ULL, 68739955140067328ULL), + uhugeint_t(5421010862427522170ULL, 687399551400673280ULL)}; string Uhugeint::ToString(uhugeint_t input) { char buffer[NumericLimits::Digits()]; diff --git a/src/duckdb/src/common/types/validity_mask.cpp b/src/duckdb/src/common/types/validity_mask.cpp index 72ebf13b0..d7b15ba5e 100644 --- a/src/duckdb/src/common/types/validity_mask.cpp +++ b/src/duckdb/src/common/types/validity_mask.cpp @@ -156,17 +156,40 @@ void ValidityMask::CopySel(const ValidityMask &other, const SelectionVector &sel } } +//! Returns the validity of rows [source_idx, source_idx + rows) in the lowest bits, with 0 < rows <= BITS_PER_VALUE +static validity_t ReadValidityEntry(const validity_t *source, idx_t source_idx, idx_t rows) { + D_ASSERT(rows > 0 && rows <= ValidityMask::BITS_PER_VALUE); + const auto shift = source_idx % ValidityMask::BITS_PER_VALUE; + const auto entry = source + source_idx / ValidityMask::BITS_PER_VALUE; + auto result = entry[0] >> shift; + if (shift + rows > ValidityMask::BITS_PER_VALUE) { + result |= entry[1] << (ValidityMask::BITS_PER_VALUE - shift); + } + return result; +} + void ValidityMask::SliceInPlace(const ValidityMask &other, idx_t target_offset, idx_t source_offset, idx_t count) { if (CannotHaveNull() && other.CannotHaveNull()) { // Both validity masks are uninitialized, nothing to do return; } + if (count == 0) { + return; + } + D_ASSERT(target_offset + count <= capacity); + D_ASSERT(other.CannotHaveNull() || source_offset + count <= other.capacity); EnsureWritable(); - const idx_t ragged = count % BITS_PER_VALUE; - const idx_t entire_units = count / BITS_PER_VALUE; + auto target_validity = GetData(); + auto source_validity = other.GetData(); + if (target_validity == source_validity && target_offset == source_offset) { + // slicing a buffer onto itself + return; + } + D_ASSERT(!source_validity || target_validity != source_validity || target_offset + count <= source_offset || + source_offset + count <= target_offset); if (IsAligned(source_offset) && IsAligned(target_offset)) { - auto target_validity = GetData(); - auto source_validity = other.GetData(); + const idx_t ragged = count % BITS_PER_VALUE; + const idx_t entire_units = count / BITS_PER_VALUE; auto source_offset_entries = EntryCount(source_offset); auto target_offset_entries = EntryCount(target_offset); if (!source_validity) { @@ -188,79 +211,19 @@ void ValidityMask::SliceInPlace(const ValidityMask &other, idx_t target_offset, *target_validity = tgt_entry | src_entry; } return; - } else if (IsAligned(target_offset)) { - // Simple common case where we are shifting into an aligned mask (e.g., 0 in Slice above) - const idx_t tail = source_offset % BITS_PER_VALUE; - const idx_t head = BITS_PER_VALUE - tail; - auto source_validity = other.GetData() + (source_offset / BITS_PER_VALUE); - auto target_validity = this->GetData() + (target_offset / BITS_PER_VALUE); - auto src_entry = *source_validity++; - for (idx_t i = 0; i < entire_units; ++i) { - // Start with head of previous src - validity_t tgt_entry = src_entry >> tail; - src_entry = *source_validity++; - // Add in tail of current src - tgt_entry |= (src_entry << head); - *target_validity++ = tgt_entry; - } - // Finish last ragged entry - if (ragged) { - // Start with head of previous src - validity_t tgt_entry = (src_entry >> tail); - // Add in the tail of the next src, if head was too small - if (head < ragged) { - src_entry = *source_validity++; - tgt_entry |= (src_entry << head); - } - // Mask off the bits that go past the ragged end - tgt_entry &= (ValidityBuffer::MAX_ENTRY >> (BITS_PER_VALUE - ragged)); - // Restore the ragged end of the target - tgt_entry |= *target_validity & (ValidityBuffer::MAX_ENTRY << ragged); - *target_validity++ = tgt_entry; - } - return; - } - - // FIXME: use bitwise operations here -#if 1 - for (idx_t i = 0; i < count; i++) { - Set(target_offset + i, other.RowIsValid(source_offset + i)); } -#else - // first shift the "whole" units - idx_t entire_units = offset / BITS_PER_VALUE; - idx_t sub_units = offset - entire_units * BITS_PER_VALUE; - if (entire_units > 0) { - idx_t validity_idx; - for (validity_idx = 0; validity_idx + entire_units < STANDARD_ENTRY_COUNT; validity_idx++) { - new_mask.validity_mask[validity_idx] = other.validity_mask[validity_idx + entire_units]; - } - } - // now we shift the remaining sub units - // this gets a bit more complicated because we have to shift over the borders of the entries - // e.g. suppose we have 2 entries of length 4 and we left-shift by two - // 0101|1010 - // a regular left-shift of both gets us: - // 0100|1000 - // we then OR the overflow (right-shifted by BITS_PER_VALUE - offset) together to get the correct result - // 0100|1000 -> - // 0110|1000 - if (sub_units > 0) { - idx_t validity_idx; - for (validity_idx = 0; validity_idx + 1 < STANDARD_ENTRY_COUNT; validity_idx++) { - new_mask.validity_mask[validity_idx] = - (other.validity_mask[validity_idx] >> sub_units) | - (other.validity_mask[validity_idx + 1] << (BITS_PER_VALUE - sub_units)); - } - new_mask.validity_mask[validity_idx] >>= sub_units; + // shift the source into the target one target entry at a time, only the first and last entries can be partial + for (idx_t copied = 0; copied < count;) { + const idx_t target_idx = target_offset + copied; + const idx_t shift = target_idx % BITS_PER_VALUE; + const idx_t rows = MinValue(count - copied, BITS_PER_VALUE - shift); + const validity_t row_mask = ValidityBuffer::MAX_ENTRY >> (BITS_PER_VALUE - rows); + const validity_t entry = source_validity ? ReadValidityEntry(source_validity, source_offset + copied, rows) + : ValidityBuffer::MAX_ENTRY; + auto &target_entry = target_validity[target_idx / BITS_PER_VALUE]; + target_entry = (target_entry & ~(row_mask << shift)) | ((entry & row_mask) << shift); + copied += rows; } -#ifdef DEBUG - for (idx_t i = offset; i < STANDARD_VECTOR_SIZE; i++) { - D_ASSERT(new_mask.RowIsValid(i - offset) == other.RowIsValid(i)); - } - Initialize(new_mask); -#endif -#endif } enum class ValiditySerialization : uint8_t { BITMASK = 0, VALID_VALUES = 1, INVALID_VALUES = 2 }; diff --git a/src/duckdb/src/common/types/vector_constants.cpp b/src/duckdb/src/common/types/vector_constants.cpp index 3f2f291c4..f654337a4 100644 --- a/src/duckdb/src/common/types/vector_constants.cpp +++ b/src/duckdb/src/common/types/vector_constants.cpp @@ -1,18 +1,19 @@ #include "duckdb/common/vector/constant_vector.hpp" +#include "duckdb/common/no_destructor.hpp" #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/common/types/vector.hpp" namespace duckdb { const SelectionVector *ConstantVector::ZeroSelectionVector() { - static const SelectionVector ZERO_SELECTION_VECTOR = - SelectionVector(const_cast(ConstantVector::ZERO_VECTOR), STANDARD_VECTOR_SIZE); // NOLINT - return &ZERO_SELECTION_VECTOR; + static const NoDestructor zero_selection_vector( + SelectionVector(const_cast(ConstantVector::ZERO_VECTOR), STANDARD_VECTOR_SIZE)); // NOLINT + return zero_selection_vector.Get(); } const SelectionVector *FlatVector::IncrementalSelectionVector() { - static const SelectionVector INCREMENTAL_SELECTION_VECTOR; - return &INCREMENTAL_SELECTION_VECTOR; + static const NoDestructor incremental_selection_vector; + return incremental_selection_vector.Get(); } const sel_t ConstantVector::ZERO_VECTOR[STANDARD_VECTOR_SIZE] = {0}; diff --git a/src/duckdb/src/common/vector/dictionary_vector.cpp b/src/duckdb/src/common/vector/dictionary_vector.cpp index cc16f06ab..33ec60d73 100644 --- a/src/duckdb/src/common/vector/dictionary_vector.cpp +++ b/src/duckdb/src/common/vector/dictionary_vector.cpp @@ -218,15 +218,16 @@ void DictionaryVector::ApplyValidity(Vector &vector, const ValidityMask &mask) { } const auto &child = Child(vector); - idx_t null_index = child.size(); - if (child.GetVectorType() == VectorType::FLAT_VECTOR && child.size() && - !FlatVector::Validity(child).RowIsValid(child.size() - 1)) { + const auto child_count = child.size(); + idx_t null_index = child_count; + if (child.GetVectorType() == VectorType::FLAT_VECTOR && child_count && + !FlatVector::Validity(child).RowIsValid(child_count - 1)) { null_index--; } else { UnifiedVectorFormat format; child.ToUnifiedFormat(format); if (!format.validity.CannotHaveNull()) { - for (idx_t i = 0; i < child.size(); i++) { + for (idx_t i = 0; i < child_count; i++) { if (!format.validity.RowIsValid(format.sel->get_index(i))) { null_index = i; break; diff --git a/src/duckdb/src/common/vector/flat_vector.cpp b/src/duckdb/src/common/vector/flat_vector.cpp index 9202f9d9c..881b7d309 100644 --- a/src/duckdb/src/common/vector/flat_vector.cpp +++ b/src/duckdb/src/common/vector/flat_vector.cpp @@ -583,6 +583,15 @@ void FlatVector::SetNull(Vector &vector, idx_t idx, bool is_null) { } } +void FlatVector::PrepareForOverwrite(Vector &vector, idx_t capacity) { + auto &buffer = vector.GetBufferRef(); + if (!buffer || buffer->GetBufferType() != VectorBufferType::SHARED_DATA_BUFFER) { + return; + } + // writing the view would copy its entries first, a new buffer discards them instead + vector.Initialize(VectorDataInitialization::UNINITIALIZED, capacity); +} + void FlatVector::CopyValidity(Vector &target, const Vector &source, idx_t count) { if (source.GetVectorType() == VectorType::FLAT_VECTOR) { SetValidity(target, Validity(source)); @@ -609,4 +618,29 @@ void FlatVector::CopyValidity(Vector &target, const Vector &source, idx_t count) } } +void FlatVector::DropAllValidMasks(Vector &vector) { + if (!vector.GetBufferRef() || vector.GetVectorType() != VectorType::FLAT_VECTOR) { + return; + } + if (Validity(vector).CanHaveNull()) { + ValidityMutable(vector).ResetIfAllValid(); + } + auto &buffer = vector.BufferMutable(); + switch (buffer.GetBufferType()) { + case VectorBufferType::STRUCT_BUFFER: + for (auto &child : buffer.Cast().GetChildren()) { + DropAllValidMasks(child); + } + break; + case VectorBufferType::LIST_BUFFER: + DropAllValidMasks(buffer.Cast().GetChild()); + break; + case VectorBufferType::ARRAY_BUFFER: + DropAllValidMasks(buffer.Cast().GetChild()); + break; + default: + break; + } +} + } // namespace duckdb diff --git a/src/duckdb/src/common/vector/shared_child_vector.cpp b/src/duckdb/src/common/vector/shared_child_vector.cpp new file mode 100644 index 000000000..e529b819b --- /dev/null +++ b/src/duckdb/src/common/vector/shared_child_vector.cpp @@ -0,0 +1,326 @@ +#include "duckdb/common/vector/shared_child_vector.hpp" + +#include "duckdb/common/vector/unified_vector_format.hpp" +#include "duckdb/common/vector_operations/vector_operations.hpp" +#include "duckdb/storage/buffer_manager.hpp" + +namespace duckdb { + +//! NULL-free fixed-size entries in one buffer-managed block. Only SharedChildVector allocates storage, reserves and +//! writes entries, everything else reads written entries through a SharedChildPrefix. +class SharedChildStorage { +public: + SharedChildStorage(BufferManager &buffer_manager_p, shared_ptr block_p, idx_t type_size_p, + idx_t capacity_p) + : buffer_manager(buffer_manager_p), block(std::move(block_p)), type_size(type_size_p), capacity(capacity_p), + reserved_count(0) { + static atomic next_id {0}; + id = next_id++; + } + + //! Allocate storage for 'capacity' entries of 'type_size' bytes, nothing reserved yet. 'pin' pins it for writing + static shared_ptr Create(BufferManager &buffer_manager, idx_t type_size, idx_t capacity, + BufferHandle &pin) { + D_ASSERT(type_size > 0); + pin = buffer_manager.Allocate(MemoryTag::COLUMN_DATA, AlignValue(type_size * capacity), false); + return make_shared_ptr(buffer_manager, pin.GetBlockHandle(), type_size, capacity); + } + + BufferHandle Pin() { + return buffer_manager.Pin(block); + } + //! Reserve 'extra' entries behind 'current_end' for writing. At most one reservation succeeds for a given end + //! position, so reserved regions never overlap. The entries become readable once the writer publishes a prefix + //! covering them + bool TryReserve(idx_t current_end, idx_t extra) { + if (current_end + extra > capacity) { + return false; + } + auto expected = current_end; + return reserved_count.compare_exchange_strong(expected, current_end + extra); + } + + BufferManager &buffer_manager; + shared_ptr block; + const idx_t type_size; + const idx_t capacity; + //! The end of the reserved entries, published prefixes never exceed it + atomic reserved_count; + idx_t id; +}; + +SharedChildPrefix::SharedChildPrefix(shared_ptr storage_p, idx_t count_p) + : storage(std::move(storage_p)), count(count_p) { + D_ASSERT(storage && count <= storage->reserved_count.load()); +} + +idx_t SharedChildPrefix::Capacity() const { + D_ASSERT(storage); + return storage->capacity; +} + +idx_t SharedChildPrefix::TypeSize() const { + D_ASSERT(storage); + return storage->type_size; +} + +idx_t SharedChildPrefix::AllocationSize() const { + D_ASSERT(storage); + return AlignValue(storage->type_size * storage->capacity); +} + +idx_t SharedChildPrefix::StorageId() const { + D_ASSERT(storage); + return storage->id; +} + +bool SharedChildPrefix::IsBackedBy(const BufferManager &buffer_manager) const { + return storage && &storage->buffer_manager == &buffer_manager; +} + +bool SharedChildPrefix::SharesStorage(const SharedChildPrefix &other) const { + return storage && storage == other.storage; +} + +SharedChildPrefix SharedChildPrefix::Prefix(idx_t new_count) const { + D_ASSERT(storage && new_count <= count); + return SharedChildPrefix(storage, new_count); +} + +void SharedChildPrefix::CopyTo(data_ptr_t target) const { + D_ASSERT(storage); + auto pin = storage->Pin(); + memcpy(target, pin.Ptr(), count * storage->type_size); +} + +SharedChildBuffer::SharedChildBuffer(const SharedChildPrefix &prefix, idx_t offset, idx_t count, bool owns_storage) + : SharedChildBuffer(prefix.storage, prefix.storage->Pin(), offset, count, owns_storage) { + D_ASSERT(offset + count <= prefix.Count()); +} + +SharedChildBuffer::SharedChildBuffer(shared_ptr storage_p, BufferHandle pin_p, idx_t offset, + idx_t count, bool owns_storage_p) + : StandardVectorBuffer(pin_p.GetDataMutable() + offset * storage_p->type_size, count_t(count), + storage_p->type_size), + storage(std::move(storage_p)), pin(std::move(pin_p)), view_offset(offset), owns_storage(owns_storage_p) { + buffer_type = VectorBufferType::SHARED_DATA_BUFFER; +} + +SharedChildBuffer::~SharedChildBuffer() { +} + +SharedChildPrefix SharedChildBuffer::GetUnchangedPrefix() const { + // the storage holds no NULLs, a view presents it as long as no NULL was written to the view + if (!storage || vector_type != VectorType::FLAT_VECTOR || view_offset != 0 || !validity.CannotHaveNull()) { + return SharedChildPrefix(); + } + return SharedChildPrefix(storage, capacity); +} + +void SharedChildBuffer::Release() { + storage.reset(); + pin = BufferHandle(); + owns_storage = false; + buffer_type = VectorBufferType::STANDARD_BUFFER; +} + +void SharedChildBuffer::DetachData(idx_t new_capacity) { + D_ASSERT(storage); + if (new_capacity > DConstants::MAX_VECTOR_SIZE / type_size) { + throw OutOfRangeException("Vector capacity is too large"); + } + auto private_data = Allocator::DefaultAllocator().Allocate(new_capacity * type_size); + memcpy(private_data.get(), data_ptr, MinValue(capacity, new_capacity) * type_size); + allocated_data = std::move(private_data); + data_ptr = allocated_data.get(); + if (new_capacity != capacity) { + validity.Resize(new_capacity); + } + capacity = new_capacity; + Release(); +} + +data_ptr_t SharedChildBuffer::GetDataMutable() { + if (storage) { + DetachData(capacity); + } + return StandardVectorBuffer::GetDataMutable(); +} + +void SharedChildBuffer::ResetCapacity(idx_t capacity_p) { + if (storage) { + // the viewed entries are discarded, the buffer continues as a StandardVectorBuffer that allocates on use + Release(); + data_ptr = nullptr; + allocated_data = AllocatedData(Allocator::DefaultAllocator()); + } + StandardVectorBuffer::ResetCapacity(capacity_p); +} + +void SharedChildBuffer::SetValue(const LogicalType &type, idx_t index, const Value &val) { + if (storage && !val.IsNull()) { + DetachData(capacity); + } + // a NULL only writes the view's own validity + StandardVectorBuffer::SetValue(type, index, val); +} + +idx_t SharedChildBuffer::GetAllocationSize() const { + auto size = StandardVectorBuffer::GetAllocationSize(); + if (storage && owns_storage) { + size += AlignValue(storage->type_size * storage->capacity); + } + return size; +} + +buffer_ptr SharedChildBuffer::SliceInternal(const LogicalType &type, idx_t offset, idx_t end) { + if (!storage) { + return StandardVectorBuffer::SliceInternal(type, offset, end); + } + D_ASSERT(end <= capacity); + const auto count = end - offset; + auto result = + make_buffer(SharedChildPrefix(storage, view_offset + capacity), view_offset + offset, count); + // the slice reads the view's validity, including NULLs written to the view + result->validity.Slice(validity, offset, count); + return std::move(result); +} + +buffer_ptr SharedChildBuffer::ConstantSliceInternal(const LogicalType &type, count_t count) { + if (!storage) { + return StandardVectorBuffer::ConstantSliceInternal(type, count); + } + // a constant aliasing the storage could be written, copy the single entry instead + return ConstantReferenceInternal(type, 0, count); +} + +void SharedChildBuffer::CopyInternal(const Vector &source, const SelectionVector &source_sel, idx_t source_count, + idx_t source_offset, idx_t target_offset, idx_t copy_count) { + if (storage) { + DetachData(capacity); + } + StandardVectorBuffer::CopyInternal(source, source_sel, source_count, source_offset, target_offset, copy_count); +} + +void SharedChildBuffer::ReserveInternal(idx_t new_size) { + if (storage) { + DetachData(new_size); + return; + } + StandardVectorBuffer::ReserveInternal(new_size); +} + +SharedChildPrefix SharedChildVector::GetUnchangedPrefix(const Vector &child) { + if (child.GetVectorType() != VectorType::FLAT_VECTOR) { + return SharedChildPrefix(); + } + auto &buffer = child.GetBufferRef(); + if (!buffer || buffer->GetBufferType() != VectorBufferType::SHARED_DATA_BUFFER) { + return SharedChildPrefix(); + } + return buffer->Cast().GetUnchangedPrefix(); +} + +void SharedChildVector::SetView(Vector &result, const SharedChildPrefix &prefix) { + D_ASSERT(prefix); + result.SetBuffer(make_buffer(prefix, 0, prefix.Count())); +} + +//! Whether any of 'count' entries of 'source' from 'offset' (selected by 'sel') is NULL +static bool HasNull(const Vector &source, const SelectionVector &sel, idx_t offset, idx_t count) { + UnifiedVectorFormat format; + source.ToUnifiedFormat(format); + if (format.validity.CannotHaveNull()) { + return false; + } + for (idx_t i = 0; i < count; i++) { + if (!format.validity.RowIsValid(format.sel->get_index(sel.get_index(offset + i)))) { + return true; + } + } + return false; +} + +//! Copy the values of 'count' NULL-free entries of 'source' into 'pin' from 'target_offset'. The entries are of a +//! constant-size type, so their values hold no references into the temporary target vector +static void WriteEntries(SharedChildStorage &storage, BufferHandle &pin, const Vector &source, + const SelectionVector &sel, idx_t source_offset, idx_t target_offset, idx_t count) { + D_ASSERT(TypeIsConstantSize(source.GetType().InternalType())); + Vector target(source.GetType(), pin.GetDataMutable() + target_offset * storage.type_size, count); + VectorOperations::Copy(source, target, sel, source_offset + count, source_offset, 0, count); +} + +SharedChildPrefix SharedChildVector::Materialize(BufferManager &buffer_manager, const Vector &source, + const SelectionVector &sel, idx_t source_offset, idx_t count) { + const auto internal_type = source.GetType().InternalType(); + // variable-size and nested values reference memory the storage does not own + if (!TypeIsConstantSize(internal_type) || HasNull(source, sel, source_offset, count)) { + return SharedChildPrefix(); + } + BufferHandle pin; + auto storage = SharedChildStorage::Create(buffer_manager, GetTypeIdSize(internal_type), count, pin); + auto reserved = storage->TryReserve(0, count); + D_ASSERT(reserved); + (void)reserved; + WriteEntries(*storage, pin, source, sel, source_offset, 0, count); + return SharedChildPrefix(std::move(storage), count); +} + +bool SharedChildVector::TryExtend(BufferManager &buffer_manager, const Vector &prefix_child, const list_entry_t &prefix, + const vector &extras, Vector &result_child, idx_t &result_offset) { + auto source = GetUnchangedPrefix(prefix_child); + if (!source || !source.IsBackedBy(buffer_manager)) { + return false; + } + D_ASSERT(TypeIsConstantSize(prefix_child.GetType().InternalType())); + D_ASSERT(prefix.offset + prefix.length <= source.Count()); + auto &incremental = *FlatVector::IncrementalSelectionVector(); + idx_t extra_count = 0; + for (auto &extra : extras) { + if (extra.child.GetType().InternalType() != prefix_child.GetType().InternalType() || + HasNull(extra.child, incremental, extra.entry.offset, extra.entry.length)) { + return false; + } + extra_count += extra.entry.length; + } + const auto prefix_end = prefix.offset + prefix.length; + const auto required = prefix.length + extra_count; + + shared_ptr target; + BufferHandle pin; + idx_t write_offset; + bool owns_storage; + if (source.storage->TryReserve(prefix_end, extra_count)) { + // the entries behind the prefix are reserved for this extension, no published prefix covers them + target = source.storage; + pin = target->Pin(); + write_offset = prefix_end; + result_offset = prefix.offset; + owns_storage = false; + } else { + if (required <= STANDARD_VECTOR_SIZE) { + // a list that fits a vector is cheaper to concatenate the regular way + return false; + } + // copy the prefix once into storage with room to grow, so appends stay amortized constant + target = SharedChildStorage::Create(buffer_manager, source.TypeSize(), NextPowerOfTwo(required + 1), pin); + auto reserved = target->TryReserve(0, required); + D_ASSERT(reserved); + (void)reserved; + WriteEntries(*target, pin, prefix_child, incremental, prefix.offset, 0, prefix.length); + write_offset = prefix.length; + result_offset = 0; + owns_storage = true; + } + for (auto &extra : extras) { + WriteEntries(*target, pin, extra.child, incremental, extra.entry.offset, write_offset, extra.entry.length); + write_offset += extra.entry.length; + } + // publish the written prefix + const auto published = result_offset + required; + result_child.SetBuffer( + make_buffer(SharedChildPrefix(std::move(target), published), 0, published, owns_storage)); + return true; +} + +} // namespace duckdb diff --git a/src/duckdb/src/common/vector_operations/vector_hash.cpp b/src/duckdb/src/common/vector_operations/vector_hash.cpp index 82326e07f..86c6920e8 100644 --- a/src/duckdb/src/common/vector_operations/vector_hash.cpp +++ b/src/duckdb/src/common/vector_operations/vector_hash.cpp @@ -160,21 +160,14 @@ void ListLoopHash(const Vector &input, Vector &hashes, const SelectionVector *rs input.ToUnifiedFormat(idata); const auto ldata = UnifiedVectorFormat::GetData(idata); - // Hash the children into a temporary const auto &child = ListVector::GetChild(input); const auto child_count = ListVector::GetListSize(input); - Vector child_hashes(LogicalType::HASH, child_count); - if (child_count > 0) { - VectorOperations::Hash(child, child_hashes, child_count); - child_hashes.Flatten(); - } - auto chdata = FlatVector::GetDataMutable(child_hashes); - // Reduce the number of entries to check to the non-empty ones SelectionVector unprocessed(count); SelectionVector cursor(HAS_RSEL ? STANDARD_VECTOR_SIZE : count); idx_t remaining = 0; + idx_t referenced = 0; for (idx_t i = 0; i < count; ++i) { const idx_t ridx = HAS_RSEL ? rsel->get_index(i) : i; const auto lidx = idata.sel->get_index(ridx); @@ -182,6 +175,7 @@ void ListLoopHash(const Vector &input, Vector &hashes, const SelectionVector *rs if (idata.validity.RowIsValid(lidx) && entry.length > 0) { unprocessed.set_index(remaining++, ridx); cursor.set_index(ridx, entry.offset); + referenced += entry.length; } else if (FIRST_HASH) { hdata[ridx] = HashOp::NULL_HASH; } @@ -193,6 +187,28 @@ void ListLoopHash(const Vector &input, Vector &hashes, const SelectionVector *rs return; } + // Hash only the referenced child entries when they are under half of the child + const bool compact = child_count >= STANDARD_VECTOR_SIZE && referenced < child_count / 2; + Vector child_hashes(LogicalType::HASH, compact ? referenced : child_count); + if (compact) { + SelectionVector child_sel(referenced); + idx_t next = 0; + for (idx_t i = 0; i < count; ++i) { + const auto ridx = unprocessed.get_index(i); + const auto &entry = ldata[idata.sel->get_index(ridx)]; + cursor.set_index(ridx, next); + for (idx_t j = 0; j < entry.length; ++j) { + child_sel.set_index(next++, entry.offset + j); + } + } + const Vector referenced_child(child, child_sel, referenced); + VectorOperations::Hash(referenced_child, child_hashes, referenced); + } else { + VectorOperations::Hash(child, child_hashes, child_count); + } + child_hashes.Flatten(); + auto chdata = FlatVector::GetDataMutable(child_hashes); + // Merge the first position hash into the main hash idx_t position = 1; if (FIRST_HASH) { diff --git a/src/duckdb/src/common/virtual_file_system.cpp b/src/duckdb/src/common/virtual_file_system.cpp index 635eb253f..0151feec3 100644 --- a/src/duckdb/src/common/virtual_file_system.cpp +++ b/src/duckdb/src/common/virtual_file_system.cpp @@ -155,6 +155,12 @@ static FileCompressionType CompressionFromExtension(const string &lower_path) { return FileCompressionType::UNCOMPRESSED; } +static NotImplementedException UnsupportedCompression(const string &compression, const string &hint) { + return NotImplementedException( + "Attempting to open a compressed file, but the compression type is not supported (compression type \"%s\")%s", + compression, hint); +} + optional_ptr VirtualFileSystem::FindCompressionFileSystem(FileSystemRegistry ®istry, const FileCompressionType &compression, const string &filepath, bool for_writing) { @@ -203,9 +209,20 @@ optional_ptr VirtualFileSystem::FindCompressionFileSystem(FileSy "treat it as uncompressed", filepath); } - throw NotImplementedException( - "Attempting to open a compressed file, but the compression type is not supported (compression type \"%s\")%s", - resolved.ToString(), hint); + throw UnsupportedCompression(resolved.ToString(), hint); +} + +FileCompressionType VirtualFileSystem::ParseCompression(const string &compression) { + if (FileCompressionType::IsBuiltIn(compression)) { + return FileCompressionType(compression); + } + // an unsupported name is not interned, as interned names are never freed + auto lower_compression = StringUtil::Lower(compression); + auto registry = file_system_registry.atomic_load(); + if (registry->compressed_fs.find(lower_compression) == registry->compressed_fs.end()) { + throw UnsupportedCompression(lower_compression, string()); + } + return FileCompressionType(lower_compression); } unique_ptr VirtualFileSystem::OpenFile(Context &context, const OpenFileInfo &file, FileOpenFlags flags) { diff --git a/src/duckdb/src/execution/adaptive_filter.cpp b/src/duckdb/src/execution/adaptive_filter.cpp index 188fbfd89..9cd7a2968 100644 --- a/src/duckdb/src/execution/adaptive_filter.cpp +++ b/src/duckdb/src/execution/adaptive_filter.cpp @@ -119,8 +119,9 @@ void AdaptiveFilter::AdaptRuntimeStatistics(double duration) { D_ASSERT(!disable_permutations); if (!warmup) { - // the last swap was observed - if (observe && iteration_count == observe_interval) { + // Stop once the trial cannot beat the previous mean, even if its remaining chunks were free. + if (observe && + (iteration_count == observe_interval || runtime_sum >= prev_mean * static_cast(observe_interval))) { // keep swap if runtime decreased, else reverse swap auto trial_mean = runtime_sum / static_cast(iteration_count); const char *action; diff --git a/src/duckdb/src/execution/aggregate_hashtable.cpp b/src/duckdb/src/execution/aggregate_hashtable.cpp index b46a8edc0..c63152520 100644 --- a/src/duckdb/src/execution/aggregate_hashtable.cpp +++ b/src/duckdb/src/execution/aggregate_hashtable.cpp @@ -559,11 +559,12 @@ optional_idx GroupedAggregateHashTable::TryAddDictionaryGroups(DataChunk &groups auto &found_entry = dict_state.found_entry; auto &unique_entries = dict_state.unique_entries; idx_t unique_count = 0; + const auto row_count = groups.size(); // for each of the dictionary entries - check if we have already done a look-up into the hash table // if we have, we can just use the cached group pointers // once every dict slot has been seen the walk would produce no new entries - skip it if (dict_state.resolved_count < dict_size) { - for (idx_t i = 0; i < groups.size(); i++) { + for (idx_t i = 0; i < row_count; i++) { auto dict_idx = offsets.get_index(i); unique_entries.set_index(unique_count, dict_idx); unique_count += !found_entry[dict_idx]; @@ -614,15 +615,15 @@ optional_idx GroupedAggregateHashTable::TryAddDictionaryGroups(DataChunk &groups dict_addresses[dict_idx] = addr; } // now set up the addresses for the aggregates - auto result_addresses = FlatVector::Writer(state.addresses, groups.size()); - for (idx_t i = 0; i < groups.size(); i++) { + auto result_addresses = FlatVector::Writer(state.addresses, row_count); + for (idx_t i = 0; i < row_count; i++) { auto dict_idx = offsets.get_index(i); result_addresses.WriteValue(dict_addresses[dict_idx]); } - FlatVector::SetSize(state.addresses, groups.size()); + FlatVector::SetSize(state.addresses, row_count); // finally process the aggregates (ht_offsets are only valid for unique entries, not the full payload) - UpdateAggregates(payload, filter, groups.size(), false); + UpdateAggregates(payload, filter, row_count, false); return new_group_count; } @@ -841,12 +842,14 @@ void GroupedAggregateHashTable::FetchAggregates(DataChunk &groups, DataChunk &re } template -static void GroupedAggregateHashTableInnerLoop(ht_entry_t *const entries, const idx_t capacity, const hash_t bitmask, - const hash_t *const hash_salts, uint64_t *const ht_offsets, - const SelectionVector *const sel_vector, const idx_t remaining_entries, - SelectionVector &empty_vector, SelectionVector &compare_vector, - idx_t &empty_count, idx_t &compare_count) { - // For each remaining entry, figure out whether or not it belongs to a full or empty group +static idx_t GroupedAggregateHashTableProbeRound(ht_entry_t *const entries, const hash_t bitmask, + const hash_t *const hash_salts, uint64_t *const ht_offsets, + const SelectionVector *const sel_vector, const idx_t remaining_entries, + SelectionVector &empty_vector, SelectionVector &compare_vector, + SelectionVector &retry_vector, idx_t &empty_count, + idx_t &compare_count) { + // Resolve one slot per row before retrying collisions, so independent probes can overlap. + idx_t retry_count = 0; for (idx_t i = 0; i < remaining_entries; i++) { PrefetchHashTableEntry(i, remaining_entries, [&](idx_t next_idx) { const auto next_index = HAS_SEL ? sel_vector->get_index_unsafe(next_idx) : next_idx; @@ -855,29 +858,39 @@ static void GroupedAggregateHashTableInnerLoop(ht_entry_t *const entries, const const auto index = HAS_SEL ? sel_vector->get_index_unsafe(i) : i; const auto salt = hash_salts[index]; auto &ht_offset = ht_offsets[index]; - - idx_t inner_iteration_count; - for (inner_iteration_count = 0; inner_iteration_count < capacity; inner_iteration_count++) { - auto &entry = entries[ht_offset]; - if (!entry.IsOccupied()) { - if (CREATE_MISSING) { - entry.SetSalt(salt); - } - empty_vector.set_index(empty_count++, index); - break; - } - - if (DUCKDB_LIKELY(entry.GetSalt() == salt)) { // Matching salt: compare groups - compare_vector.set_index(compare_count++, index); - break; + auto &entry = entries[ht_offset]; + if (!entry.IsOccupied()) { + if (CREATE_MISSING) { + entry.SetSalt(salt); } - - // Linear probing + empty_vector.set_index(empty_count++, index); + } else if (DUCKDB_LIKELY(entry.GetSalt() == salt)) { + compare_vector.set_index(compare_count++, index); + } else { SaltIncrementAndWrap(ht_offset, salt, bitmask); + retry_vector.set_index(retry_count++, index); } - if (DUCKDB_UNLIKELY(inner_iteration_count == capacity)) { - throw InternalException("Maximum inner iteration count reached in GroupedAggregateHashTable"); - } + } + return retry_count; +} + +template +static void GroupedAggregateHashTableInnerLoop(ht_entry_t *const entries, const idx_t capacity, const hash_t bitmask, + const hash_t *const hash_salts, uint64_t *const ht_offsets, + const SelectionVector *const sel_vector, idx_t remaining_entries, + SelectionVector &empty_vector, SelectionVector &compare_vector, + SelectionVector &retry_vector, idx_t &empty_count, + idx_t &compare_count) { + remaining_entries = GroupedAggregateHashTableProbeRound( + entries, bitmask, hash_salts, ht_offsets, sel_vector, remaining_entries, empty_vector, compare_vector, + retry_vector, empty_count, compare_count); + for (idx_t iteration = 1; remaining_entries > 0 && iteration < capacity; iteration++) { + remaining_entries = GroupedAggregateHashTableProbeRound( + entries, bitmask, hash_salts, ht_offsets, &retry_vector, remaining_entries, empty_vector, compare_vector, + retry_vector, empty_count, compare_count); + } + if (remaining_entries > 0) { + throw InternalException("Maximum inner iteration count reached in GroupedAggregateHashTable"); } } @@ -980,11 +993,11 @@ idx_t GroupedAggregateHashTable::FindOrCreateGroupsInternal(DataChunk &groups, V if (sel_vector->IsSet()) { GroupedAggregateHashTableInnerLoop( entries, capacity, bitmask, hash_salts, ht_offsets, sel_vector, remaining_entries, empty_vector, - state.group_compare_vector, new_entry_count, need_compare_count); + state.group_compare_vector, state.no_match_vector, new_entry_count, need_compare_count); } else { GroupedAggregateHashTableInnerLoop( entries, capacity, bitmask, hash_salts, ht_offsets, sel_vector, remaining_entries, empty_vector, - state.group_compare_vector, new_entry_count, need_compare_count); + state.group_compare_vector, state.no_match_vector, new_entry_count, need_compare_count); } new_group_count += new_entry_count; @@ -1141,13 +1154,15 @@ idx_t GroupedAggregateHashTable::LookupGroups(DataChunk &groups, AggregateHTLook idx_t missing_count = 0; idx_t compare_count = 0; if (remaining_sel->IsSet()) { - GroupedAggregateHashTableInnerLoop( - entries, capacity, bitmask, hash_salts, ht_offsets, remaining_sel, remaining_count, - lookup_state.missing_vector, lookup_state.group_compare_vector, missing_count, compare_count); + GroupedAggregateHashTableInnerLoop(entries, capacity, bitmask, hash_salts, ht_offsets, + remaining_sel, remaining_count, lookup_state.missing_vector, + lookup_state.group_compare_vector, + lookup_state.no_match_vector, missing_count, compare_count); } else { GroupedAggregateHashTableInnerLoop( entries, capacity, bitmask, hash_salts, ht_offsets, remaining_sel, remaining_count, - lookup_state.missing_vector, lookup_state.group_compare_vector, missing_count, compare_count); + lookup_state.missing_vector, lookup_state.group_compare_vector, lookup_state.no_match_vector, + missing_count, compare_count); } for (idx_t compare_idx = 0; compare_idx < compare_count; compare_idx++) { diff --git a/src/duckdb/src/execution/aggregate_state_spilling.cpp b/src/duckdb/src/execution/aggregate_state_spilling.cpp index 63616fb42..97468f956 100644 --- a/src/duckdb/src/execution/aggregate_state_spilling.cpp +++ b/src/duckdb/src/execution/aggregate_state_spilling.cpp @@ -109,6 +109,7 @@ void AggregateStateSpilling::ExportStates(ClientContext &context, const TupleDat TupleDataScanState scan_state; source.InitializeScan(scan_state, TupleDataPinProperties::DESTROY_AFTER_DONE); while (source.Scan(scan_state, group_chunk)) { + context.FastInterruptCheck(); const auto count = group_chunk.size(); exported_chunk.Reset(); for (idx_t col_idx = 0; col_idx < column_count; col_idx++) { diff --git a/src/duckdb/src/execution/index/art/art.cpp b/src/duckdb/src/execution/index/art/art.cpp index 8a6807b81..c0e212b74 100644 --- a/src/duckdb/src/execution/index/art/art.cpp +++ b/src/duckdb/src/execution/index/art/art.cpp @@ -17,7 +17,7 @@ #include "duckdb/execution/index/art/node256.hpp" #include "duckdb/execution/index/art/node256_leaf.hpp" #include "duckdb/execution/index/art/node48.hpp" -#include "duckdb/execution/index/art/prefix.hpp" +#include "duckdb/execution/index/art/prefix_handle.hpp" #include "duckdb/optimizer/matcher/expression_matcher.hpp" #include "duckdb/planner/expression/bound_between_expression.hpp" #include "duckdb/planner/expression/bound_comparison_expression.hpp" @@ -124,7 +124,7 @@ ART::ART(const Identifier &name, const IndexConstraintType index_constraint_type SetPrefixCount(info); if (!allocators) { owns_data = true; - auto prefix_size = NumericCast(prefix_count) + NumericCast(Prefix::METADATA_SIZE); + auto prefix_size = NumericCast(prefix_count) + NumericCast(PrefixHandle::METADATA_SIZE); auto &block_manager = table_io_manager.GetIndexBlockManager(); const auto leaf256_size = GetNode256LeafSegmentSize(info, db.GetStorageManager().GetStorageVersion()); @@ -1131,8 +1131,9 @@ void ART::TransformToDeprecated() { auto idx = NodePtr::GetAllocatorIdx(NType::PREFIX); auto &block_manager = (*allocators)[idx]->block_manager; unsafe_unique_ptr deprecated_allocator = nullptr; - if (prefix_count != Prefix::DEPRECATED_COUNT) { - auto prefix_size = NumericCast(Prefix::DEPRECATED_COUNT) + NumericCast(Prefix::METADATA_SIZE); + if (prefix_count != PrefixHandle::DEPRECATED_COUNT) { + auto prefix_size = + NumericCast(PrefixHandle::DEPRECATED_COUNT) + NumericCast(PrefixHandle::METADATA_SIZE); deprecated_allocator = make_unsafe_uniq(prefix_size, block_manager); } @@ -1147,7 +1148,7 @@ void ART::TransformToDeprecated() { // Replace the prefix allocator with the deprecated allocator. if (state->HasAllocator()) { deprecated_allocator = state->TakeAllocator(); - prefix_count = Prefix::DEPRECATED_COUNT; + prefix_count = PrefixHandle::DEPRECATED_COUNT; D_ASSERT((*allocators)[idx]->Empty()); (*allocators)[idx]->Reset(); @@ -1185,7 +1186,7 @@ IndexStorageInfo ART::PrepareSerialize(const ARTSerializationFormat target_forma D_ASSERT((*allocators)[NodePtr::GetAllocatorIdx(NType::NODE_15_LEAF)]->Empty()); D_ASSERT((*allocators)[NodePtr::GetAllocatorIdx(NType::NODE_256_LEAF)]->Empty()); D_ASSERT((*allocators)[NodePtr::GetAllocatorIdx(NType::PREFIX)]->GetSegmentSize() == - Prefix::DEPRECATED_COUNT + Prefix::METADATA_SIZE); + PrefixHandle::DEPRECATED_COUNT + PrefixHandle::METADATA_SIZE); } #endif @@ -1263,12 +1264,12 @@ void ART::Deserialize(const BlockPointer &pointer) { void ART::SetPrefixCount(const IndexStorageInfo &info) { if (info.IsValid() && info.root_block_ptr.IsValid()) { - prefix_count = Prefix::DEPRECATED_COUNT; + prefix_count = PrefixHandle::DEPRECATED_COUNT; return; } if (info.IsValid()) { - auto serialized_count = info.allocator_infos[0].segment_size - Prefix::METADATA_SIZE; + auto serialized_count = info.allocator_infos[0].segment_size - PrefixHandle::METADATA_SIZE; prefix_count = NumericCast(serialized_count); return; } @@ -1281,7 +1282,7 @@ void ART::SetPrefixCount(const IndexStorageInfo &info) { // Get the maximum possible prefix size. // Minus one to index the prefix count (last byte). auto numeric_max = NumericLimits().Maximum(); - uint8_t max_aligned = AlignValueFloor(numeric_max - Prefix::METADATA_SIZE) - 1; + uint8_t max_aligned = AlignValueFloor(numeric_max - PrefixHandle::METADATA_SIZE) - 1; // Ceiling of compound size, // minus one to index the prefix count (last byte). diff --git a/src/duckdb/src/execution/index/art/art_merger.cpp b/src/duckdb/src/execution/index/art/art_merger.cpp index 0d4b15669..ee36724bf 100644 --- a/src/duckdb/src/execution/index/art/art_merger.cpp +++ b/src/duckdb/src/execution/index/art/art_merger.cpp @@ -1,9 +1,10 @@ #include "duckdb/execution/index/art/art_merger.hpp" +#include "duckdb/common/array.hpp" #include "duckdb/common/swap.hpp" #include "duckdb/execution/index/art/base_leaf.hpp" #include "duckdb/execution/index/art/node256_leaf.hpp" -#include "duckdb/execution/index/art/prefix.hpp" +#include "duckdb/execution/index/art/const_prefix_handle.hpp" #include "duckdb/execution/index/art/prefix_handle.hpp" #include "duckdb/execution/index/art/base_node.hpp" #include "duckdb/execution/index/art/node48.hpp" @@ -133,20 +134,6 @@ ARTConflictType ARTMerger::MergeNodeAndInlined(NodePtr &left_ptr, NodeEntry &ent DeleteIndexInfo(), IndexAppendMode::DEFAULT); } -array_ptr ARTMerger::GetBytes(NodePtr &leaf_ptr) { - const auto type = leaf_ptr.GetType(); - switch (type) { - case NType::NODE_7_LEAF: - return NodePtr::Ref(art, leaf_ptr, type).GetBytes(); - case NType::NODE_15_LEAF: - return NodePtr::Ref(art, leaf_ptr, type).GetBytes(); - case NType::NODE_256_LEAF: - return NodePtr::Ref(art, leaf_ptr, type).GetBytes(arena); - default: - throw InternalException("invalid node type for ARTMerger::GetBytes: %s", EnumUtil::ToString(type)); - } -} - void ARTMerger::MergeLeaves(NodePtr &left_ptr, NodeEntry &entry) { D_ASSERT(left_ptr.IsNestedLeaf()); D_ASSERT(entry.right_ptr.IsNestedLeaf()); @@ -160,11 +147,12 @@ void ARTMerger::MergeLeaves(NodePtr &left_ptr, NodeEntry &entry) { // Get the bytes of the right node. // Then, copy them into left. - auto bytes = GetBytes(entry.right_ptr); + array bytes; + auto byte_count = entry.right_ptr.GetBytes(art, array_ptr(bytes.data(), bytes.size())); // FIXME: Obtain a reference to left once and // FIXME: handle the different node type combinations. - for (idx_t i = 0; i < bytes.size(); i++) { + for (idx_t i = 0; i < byte_count; i++) { NodePtr::InsertChild(art, left_ptr, bytes[i]); } NodePtr::FreeNode(art, entry.right_ptr); @@ -172,15 +160,16 @@ void ARTMerger::MergeLeaves(NodePtr &left_ptr, NodeEntry &entry) { NodeChildren ARTMerger::ExtractChildren(NodePtr &node_ptr) { const auto type = node_ptr.GetType(); + ConstNodeHandle handle(art, node_ptr); switch (type) { case NType::NODE_4: - return NodePtr::Ref(art, node_ptr, type).ExtractChildren(arena); + return handle.Get().ExtractChildren(arena); case NType::NODE_16: - return NodePtr::Ref(art, node_ptr, type).ExtractChildren(arena); + return handle.Get().ExtractChildren(arena); case NType::NODE_48: - return NodePtr::Ref(art, node_ptr, type).ExtractChildren(arena); + return handle.Get().ExtractChildren(arena); case NType::NODE_256: - return NodePtr::Ref(art, node_ptr, type).ExtractChildren(arena); + return handle.Get().ExtractChildren(arena); default: throw InternalException("invalid node type for ARTMerger::GetChildren: %s", EnumUtil::ToString(type)); } @@ -236,9 +225,9 @@ void ARTMerger::MergeNodeAndPrefix(NodePtr &node_ptr, NodePtr &prefix_ptr, const D_ASSERT(node_ptr.IsInternalNode()); D_ASSERT(prefix_ptr.GetType() == NType::PREFIX); - const auto byte = Prefix::GetByte(art, prefix_ptr, pos); + const auto byte = ConstPrefixHandle(art, prefix_ptr).GetByte(pos); // Reduce the prefix to the bytes after pos. - Prefix::Reduce(art, prefix_ptr, pos); + PrefixHandle::Reduce(art, prefix_ptr, pos); { // Get the child at the prefix byte, or nullptr, if there is no child. @@ -281,18 +270,31 @@ void ARTMerger::MergePrefixes(NodePtr &left_ptr, NodeEntry &entry) { // the prefixes are the same. That means, we only need to keep // one of them around. - Prefix l_prefix(art, left_ptr, true); - Prefix r_prefix(art, entry.right_ptr, true); - const auto count = art.PrefixCount(); - - // Find a byte at pos where the prefixes differ. - // If they match up to max_count, then pos stays invalid. - const auto max_count = MinValue(l_prefix.data[count], r_prefix.data[count]); + uint8_t l_count; + uint8_t r_count; + uint8_t max_count; optional_idx pos; - for (idx_t i = 0; i < max_count; i++) { - if (l_prefix.data[i] != r_prefix.data[i]) { - pos = i; - break; + uint8_t l_byte = 0; + uint8_t r_byte = 0; + NodePtr r_child_ptr; + { + // Release the pins before Split, Reduce, or FreeNode change the prefixes. + ConstPrefixHandle l_prefix(art, left_ptr); + ConstPrefixHandle r_prefix(art, entry.right_ptr); + l_count = l_prefix.GetCount(art); + r_count = r_prefix.GetCount(art); + r_child_ptr = r_prefix.Child(art); + + // Find a byte at pos where the prefixes differ. + // If they match up to max_count, then pos stays invalid. + max_count = MinValue(l_count, r_count); + for (idx_t i = 0; i < max_count; i++) { + if (l_prefix.GetByte(i) != r_prefix.GetByte(i)) { + pos = i; + l_byte = l_prefix.GetByte(i); + r_byte = r_prefix.GetByte(i); + break; + } } } @@ -302,14 +304,12 @@ void ARTMerger::MergePrefixes(NodePtr &left_ptr, NodeEntry &entry) { // Then, we insert both remainders into a new Node4. // Then, we are done. const auto split_pos = UnsafeNumericCast(pos.GetIndex()); - const auto l_byte = Prefix::GetByte(art, left_ptr, split_pos); - const auto r_byte = Prefix::GetByte(art, entry.right_ptr, split_pos); // Split and reduce. NodePtr branching_node4_ptr; Node4::New(art, branching_node4_ptr); auto l_child_ptr = PrefixHandle::Split(art, left_ptr, branching_node4_ptr, split_pos); - Prefix::Reduce(art, entry.right_ptr, split_pos); + PrefixHandle::Reduce(art, entry.right_ptr, split_pos); Node4::InsertChild(art, branching_node4_ptr, l_byte, l_child_ptr); Node4::InsertChild(art, branching_node4_ptr, r_byte, entry.right_ptr); @@ -317,22 +317,21 @@ void ARTMerger::MergePrefixes(NodePtr &left_ptr, NodeEntry &entry) { return; } - if (l_prefix.data[count] == r_prefix.data[count]) { + if (l_count == r_count) { // The prefixes match. // Free the right prefix, but keep the reference to its child alive. // Then, iterate on the left and right (reduced) child. - auto r_child_ptr = *r_prefix.child_slot; NodePtr::FreeNode(art, entry.right_ptr); entry.right_ptr = r_child_ptr; - auto depth = entry.depth + l_prefix.data[count]; + auto depth = entry.depth + l_count; auto l_child_ptr_handle = NodePtrHandle::PrefixChild(art, NodeHandle(art, left_ptr)); Emplace(l_child_ptr_handle.Get(), left_ptr, 0, entry.right_ptr, entry.status, depth); return; } // max_count indexes the byte after the exhausted prefix in a child node. - if (r_prefix.data[count] == max_count) { + if (r_count == max_count) { // We exhausted the right prefix. // Ensure that we continue merging into left. swap(left_ptr, entry.right_ptr); diff --git a/src/duckdb/src/execution/index/art/base_leaf.cpp b/src/duckdb/src/execution/index/art/base_leaf.cpp index e10a61bc9..7c124b392 100644 --- a/src/duckdb/src/execution/index/art/base_leaf.cpp +++ b/src/duckdb/src/execution/index/art/base_leaf.cpp @@ -3,7 +3,7 @@ #include "duckdb/execution/index/art/art_key.hpp" #include "duckdb/execution/index/art/base_node.hpp" #include "duckdb/execution/index/art/leaf.hpp" -#include "duckdb/execution/index/art/prefix.hpp" +#include "duckdb/execution/index/art/prefix_handle.hpp" #include "duckdb/execution/index/art/node256_leaf.hpp" namespace duckdb { diff --git a/src/duckdb/src/execution/index/art/iterator.cpp b/src/duckdb/src/execution/index/art/iterator.cpp index a05340a7d..d56667bd1 100644 --- a/src/duckdb/src/execution/index/art/iterator.cpp +++ b/src/duckdb/src/execution/index/art/iterator.cpp @@ -1,13 +1,15 @@ #include "duckdb/execution/index/art/iterator.hpp" #include "duckdb/common/algorithm.hpp" +#include "duckdb/common/array.hpp" #include "duckdb/common/limits.hpp" #include "duckdb/common/vector_size.hpp" #include "duckdb/execution/index/art/art.hpp" #include "duckdb/execution/index/art/const_prefix_handle.hpp" #include "duckdb/execution/index/art/node.hpp" +#include "duckdb/execution/index/art/node256_leaf.hpp" #include "duckdb/execution/index/art/node_handle.hpp" -#include "duckdb/execution/index/art/prefix.hpp" +#include "duckdb/execution/index/art/prefix_handle.hpp" namespace duckdb { @@ -131,18 +133,19 @@ ARTScanProgress Iterator::Scan(const ARTKey &upper_bound, Output &output, bool e resume_state.nested_started = true; } // Try to output the next inlined leaf. - while (last_leaf_ptr.GetNextByte(art, resume_state.nested_byte)) { + array bytes; + auto byte_count = last_leaf_ptr.GetBytes(art, array_ptr(bytes.data(), bytes.size())); + for (idx_t i = 0; i < byte_count; i++) { + if (bytes[i] < resume_state.nested_byte) { + continue; + } + resume_state.nested_byte = bytes[i]; row_id[ROW_ID_SIZE - 1] = resume_state.nested_byte; ARTKey rid_key(&row_id[0], ROW_ID_SIZE); if (!output.TryAdd(rid_key.GetRowId())) { // If we pause here, then scanning will resume at nested_byte in the current leaf. return ARTScanProgress::PAUSED; } - - if (resume_state.nested_byte == NumericLimits::Maximum()) { - break; - } - resume_state.nested_byte++; } resume_state.nested_started = false; break; @@ -191,7 +194,7 @@ void Iterator::FindMinimum(NodePtr current_ptr) { if (status == GateStatus::GATE_SET) { row_id[nested_depth] = data[i]; nested_depth++; - D_ASSERT(nested_depth < Prefix::ROW_ID_SIZE); + D_ASSERT(nested_depth < PrefixHandle::ROW_ID_SIZE); } } // Copy the child locator before releasing the prefix handle. @@ -212,7 +215,7 @@ void Iterator::FindMinimum(NodePtr current_ptr) { if (status == GateStatus::GATE_SET) { row_id[nested_depth] = byte; nested_depth++; - D_ASSERT(nested_depth < Prefix::ROW_ID_SIZE); + D_ASSERT(nested_depth < PrefixHandle::ROW_ID_SIZE); } nodes.emplace(current_ptr, byte); current_ptr = child_ptr.Get(); @@ -355,7 +358,7 @@ void Iterator::PopNode() { current_key.Pop(1); if (status == GateStatus::GATE_SET) { nested_depth--; - D_ASSERT(nested_depth < Prefix::ROW_ID_SIZE); + D_ASSERT(nested_depth < PrefixHandle::ROW_ID_SIZE); } } else { @@ -367,7 +370,7 @@ void Iterator::PopNode() { if (status == GateStatus::GATE_SET) { nested_depth -= prefix_byte_count; - D_ASSERT(nested_depth < Prefix::ROW_ID_SIZE); + D_ASSERT(nested_depth < PrefixHandle::ROW_ID_SIZE); } } nodes.pop(); diff --git a/src/duckdb/src/execution/index/art/leaf.cpp b/src/duckdb/src/execution/index/art/leaf.cpp index d2901c546..f3e9c4a3c 100644 --- a/src/duckdb/src/execution/index/art/leaf.cpp +++ b/src/duckdb/src/execution/index/art/leaf.cpp @@ -7,7 +7,6 @@ #include "duckdb/execution/index/art/base_node.hpp" #include "duckdb/execution/index/art/iterator.hpp" #include "duckdb/execution/index/art/node.hpp" -#include "duckdb/execution/index/art/prefix.hpp" #include "duckdb/execution/index/art/prefix_handle.hpp" #include "duckdb/execution/index/art/art_operator.hpp" @@ -47,7 +46,7 @@ void Leaf::MergeInlined(ArenaAllocator &arena, ART &art, NodePtr &left_ptr, Node auto right_byte = right_key.data[pos]; NodePtr merged_root_ptr; - if (pos == Prefix::ROW_ID_COUNT) { + if (pos == PrefixHandle::ROW_ID_COUNT) { // The row IDs differ on the last byte. Node7Leaf::New(art, merged_root_ptr); Node7Leaf::InsertByte(art, merged_root_ptr, left_byte); @@ -100,7 +99,10 @@ void Leaf::TransformToNested(ART &art, NodePtr &node_ptr) { current_ptr = leaf.next_leaf_ptr; } - root_ptr.SetGateStatus(GateStatus::GATE_SET); + // v1.1 could write deprecated leaves with a single row ID, which become an inlined leaf without a gate. + if (root_ptr.GetType() != NType::LEAF_INLINED) { + root_ptr.SetGateStatus(GateStatus::GATE_SET); + } DeprecatedFree(art, node_ptr); node_ptr = root_ptr; } @@ -112,6 +114,11 @@ void Leaf::TransformToDeprecated(ART &art, NodePtr &node_ptr) { if (node_ptr.GetGateStatus() == GateStatus::GATE_NOT_SET) { return; } + // An inlined leaf with a v1.1 gate: clear the gate. + if (!node_ptr.IsGate(art)) { + node_ptr.SetGateStatus(GateStatus::GATE_NOT_SET); + return; + } // Collect all row IDs and free the nested leaf. set row_ids; @@ -206,16 +213,16 @@ string Leaf::DeprecatedToString(ART &art, const NodePtr &node_ptr, const ToStrin return str; } - reference leaf_ptr_ref(node_ptr); - - while (leaf_ptr_ref.get().HasMetadata()) { - auto &leaf = NodePtr::Ref(art, leaf_ptr_ref, LEAF); + NodePtr current_ptr = node_ptr; + while (current_ptr.HasMetadata()) { + ConstNodeHandle handle(art, current_ptr); + auto &leaf = handle.Get(); str += options.tree_prefix + "Leaf [count: " + to_string(leaf.count) + ", row IDs: "; for (uint8_t i = 0; i < leaf.count; i++) { str += to_string(leaf.row_ids[i]) + "-"; } str += "]\n"; - leaf_ptr_ref = leaf.next_leaf_ptr; + current_ptr = leaf.next_leaf_ptr; } return str; diff --git a/src/duckdb/src/execution/index/art/node.cpp b/src/duckdb/src/execution/index/art/node.cpp index 5c815de70..7d0952be6 100644 --- a/src/duckdb/src/execution/index/art/node.cpp +++ b/src/duckdb/src/execution/index/art/node.cpp @@ -1,5 +1,6 @@ #include "duckdb/execution/index/art/node.hpp" +#include "duckdb/common/array.hpp" #include "duckdb/common/limits.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/common/swap.hpp" @@ -13,7 +14,6 @@ #include "duckdb/execution/index/art/node256_leaf.hpp" #include "duckdb/execution/index/art/node48.hpp" #include "duckdb/execution/index/art/const_prefix_handle.hpp" -#include "duckdb/execution/index/art/prefix.hpp" #include "duckdb/execution/index/art/prefix_handle.hpp" #include "duckdb/storage/table_io_manager.hpp" @@ -287,29 +287,6 @@ OptionalNodePtr NodePtr::GetNextChildNode(const ART &art, uint8_t &byte) const { } } -template -unsafe_optional_ptr GetNextChildInternal(ART &art, NODE &node_ptr, uint8_t &byte) { - D_ASSERT(node_ptr.HasMetadata()); - - auto type = node_ptr.GetType(); - switch (type) { - case NType::NODE_4: - return Node4::GetNextChild(NodePtr::Ref(art, node_ptr, type), byte); - case NType::NODE_16: - return Node16::GetNextChild(NodePtr::Ref(art, node_ptr, type), byte); - case NType::NODE_48: - return Node48::GetNextChild(NodePtr::Ref(art, node_ptr, type), byte); - case NType::NODE_256: - return Node256::GetNextChild(NodePtr::Ref(art, node_ptr, type), byte); - default: - throw InternalException("Invalid node type for GetNextChildInternal: %d.", type); - } -} - -const unsafe_optional_ptr NodePtr::GetNextChild(ART &art, uint8_t &byte) const { - return GetNextChildInternal(art, *this, byte); -} - bool NodePtr::HasByte(const ART &art, const uint8_t byte) const { D_ASSERT(HasMetadata()); @@ -327,19 +304,21 @@ bool NodePtr::HasByte(const ART &art, const uint8_t byte) const { } } -bool NodePtr::GetNextByte(const ART &art, uint8_t &byte) const { +idx_t NodePtr::GetBytes(const ART &art, array_ptr bytes) const { D_ASSERT(HasMetadata()); + D_ASSERT(bytes.size() >= Node256Leaf::CAPACITY); auto type = GetType(); + ConstNodeHandle handle(art, *this); switch (type) { case NType::NODE_7_LEAF: - return Ref(art, *this, NType::NODE_7_LEAF).GetNextByte(byte); + return handle.Get().GetBytes(bytes); case NType::NODE_15_LEAF: - return Ref(art, *this, NType::NODE_15_LEAF).GetNextByte(byte); + return handle.Get().GetBytes(bytes); case NType::NODE_256_LEAF: - return Ref(art, *this, NType::NODE_256_LEAF).GetNextByte(byte); + return handle.Get().GetBytes(bytes); default: - throw InternalException("Invalid node type for GetNextByte: %d.", type); + throw InternalException("Invalid node type for GetBytes: %d.", type); } } @@ -416,6 +395,10 @@ bool NodePtr::IsAnyLeaf() const { } } +bool NodePtr::HasNoStorageVersion(const ART &art) { + return art.storage_version == StorageVersion::INVALID; +} + //===--------------------------------------------------------------------===// // TransformToDeprecated //===--------------------------------------------------------------------===// @@ -486,14 +469,14 @@ void NodePtr::Verify(ART &art) const { if (!IsNestedLeaf()) { uint8_t byte = 0; - auto child_ptr = GetNextChild(art, byte); + auto child_ptr = GetNextChildNode(art, byte); while (child_ptr) { - child_ptr->Verify(art); + child_ptr.Get().Verify(art); if (byte == NumericLimits::Maximum()) { break; } byte++; - child_ptr = GetNextChild(art, byte); + child_ptr = GetNextChildNode(art, byte); } } } @@ -568,29 +551,24 @@ string NodePtr::ToStringChildren(ART &art, const ToStringOptions &options) const if (IsNestedLeaf()) { str += StringUtil::Format("%s%sLeaf |", options.tree_prefix, NODE_BRANCH_END); - uint8_t byte = 0; - auto has_byte = GetNextByte(art, byte); - while (has_byte) { - str += StringUtil::Format("%s|", format_byte(byte)); - if (byte == NumericLimits::Maximum()) { - break; - } - byte++; - has_byte = GetNextByte(art, byte); + array bytes; + auto byte_count = GetBytes(art, array_ptr(bytes.data(), bytes.size())); + for (idx_t i = 0; i < byte_count; i++) { + str += StringUtil::Format("%s|", format_byte(bytes[i])); } str += "\n"; } else if (IsInternalNode()) { // Collect all children first to know which is last - vector> children; + vector> children; uint8_t byte = 0; - auto child_ptr = GetNextChild(art, byte); + auto child_ptr = GetNextChildNode(art, byte); while (child_ptr) { - children.emplace_back(byte, child_ptr.get()); + children.emplace_back(byte, child_ptr.Get()); if (byte == NumericLimits::Maximum()) { break; } byte++; - child_ptr = GetNextChild(art, byte); + child_ptr = GetNextChildNode(art, byte); } uint8_t expected_byte = 0; @@ -603,7 +581,7 @@ string NodePtr::ToStringChildren(ART &art, const ToStringOptions &options) const for (idx_t child_idx = 0; child_idx < children.size(); child_idx++) { auto &child_entry = children[child_idx]; auto child_byte = child_entry.first; - auto &child_slot = child_entry.second; + auto child_node_ptr = child_entry.second; auto is_last = (child_idx == children.size() - 1); auto on_path = !has_expected_byte || (has_expected_byte && child_byte == expected_byte); @@ -623,17 +601,17 @@ string NodePtr::ToStringChildren(ART &art, const ToStringOptions &options) const child_options.expand_after_n_levels = (options.expand_after_n_levels > 0) ? options.expand_after_n_levels - 1 : 0; - auto child_type = child_slot->GetType(); + auto child_type = child_node_ptr.GetType(); auto is_internal = (child_type == NType::NODE_4 || child_type == NType::NODE_16 || child_type == NType::NODE_48 || child_type == NType::NODE_256); if (is_internal) { str += StringUtil::Format("%s%sNode%s\n", child_prefix, NODE_BRANCH_END, to_string(GetCapacity(child_type))); child_options.tree_prefix = StringUtil::Format("%s%s", child_prefix, NODE_SPACE); - str += child_slot->ToStringChildren(art, child_options); + str += child_node_ptr.ToStringChildren(art, child_options); } else { child_options.tree_prefix = child_prefix; - str += child_slot->ToString(art, child_options); + str += child_node_ptr.ToString(art, child_options); } } else { if (!options.structure_only) { diff --git a/src/duckdb/src/execution/index/art/node256_leaf.cpp b/src/duckdb/src/execution/index/art/node256_leaf.cpp index 143499905..da45daac9 100644 --- a/src/duckdb/src/execution/index/art/node256_leaf.cpp +++ b/src/duckdb/src/execution/index/art/node256_leaf.cpp @@ -53,33 +53,14 @@ bool Node256Leaf::HasByte(const uint8_t byte) const { return ValidityMask::RowIsValid(mask[entry_idx], idx_in_entry); } -array_ptr Node256Leaf::GetBytes(ArenaAllocator &arena) { - auto mem = arena.AllocateAligned(sizeof(uint8_t) * count); - array_ptr bytes(mem, count); - - ValidityMask v_mask(&mask[0], Node256::CAPACITY); - uint16_t ptr_idx = 0; +idx_t Node256Leaf::GetBytes(array_ptr bytes) const { + idx_t ptr_idx = 0; for (uint16_t i = 0; i < CAPACITY; i++) { - if (v_mask.RowIsValid(i)) { + if (HasByte(UnsafeNumericCast(i))) { bytes[ptr_idx++] = UnsafeNumericCast(i); } } - - return bytes; -} - -bool Node256Leaf::GetNextByte(uint8_t &byte) const { - for (uint16_t i = byte; i < CAPACITY; i++) { - idx_t entry_idx = 0; - idx_t idx_in_entry = 0; - ValidityMask::GetEntryIndex(i, entry_idx, idx_in_entry); - if (ValidityMask::RowIsValid(mask[entry_idx], idx_in_entry)) { - byte = UnsafeNumericCast(i); - return true; - } - } - - return false; + return ptr_idx; } void Node256Leaf::GrowNode15Leaf(ART &art, NodePtr &node256_leaf_ptr, NodePtr &node15_leaf_ptr) { diff --git a/src/duckdb/src/execution/index/art/prefix.cpp b/src/duckdb/src/execution/index/art/prefix.cpp deleted file mode 100644 index 44e51f417..000000000 --- a/src/duckdb/src/execution/index/art/prefix.cpp +++ /dev/null @@ -1,126 +0,0 @@ -#include "duckdb/execution/index/art/prefix.hpp" - -#include "duckdb/common/swap.hpp" -#include "duckdb/execution/index/art/art.hpp" -#include "duckdb/execution/index/art/base_leaf.hpp" -#include "duckdb/execution/index/art/base_node.hpp" -#include "duckdb/execution/index/art/const_prefix_handle.hpp" -#include "duckdb/execution/index/art/leaf.hpp" -#include "duckdb/execution/index/art/node.hpp" -#include "duckdb/execution/index/art/prefix_handle.hpp" - -namespace duckdb { - -Prefix::Prefix(const ART &art, const NodePtr node_ptr, const bool is_mutable, const bool set_in_memory) { - if (!set_in_memory) { - data = NodePtr::GetAllocator(art, PREFIX).Get(node_ptr, is_mutable); - } else { - data = NodePtr::GetAllocator(art, PREFIX).GetIfLoaded(node_ptr); - if (!data) { - child_slot = nullptr; - in_memory = false; - return; - } - } - child_slot = &PrefixHandle::ChildRefWithCount(data, art.PrefixCount()); - in_memory = true; -} - -Prefix::Prefix(FixedSizeAllocator &allocator, const NodePtr node_ptr, const idx_t count) { - data = allocator.Get(node_ptr, true); - child_slot = &PrefixHandle::ChildRefWithCount(data, count); - in_memory = true; -} - -uint8_t Prefix::GetByte(const ART &art, const NodePtr &node_ptr, const uint8_t pos) { - D_ASSERT(node_ptr.GetType() == PREFIX); - ConstPrefixHandle prefix(art, node_ptr); - return prefix.GetByte(pos); -} - -Prefix Prefix::NewInternal(ART &art, NodePtr &node_ptr, const data_ptr_t data, const uint8_t count, - const idx_t offset) { - node_ptr = NodePtr::GetAllocator(art, PREFIX).New(); - node_ptr.SetMetadata(static_cast(PREFIX)); - - Prefix prefix(art, node_ptr, true); - prefix.data[art.PrefixCount()] = count; - if (data) { - D_ASSERT(count); - memcpy(prefix.data, data + offset, count); - } - prefix.child_slot->Clear(); - return prefix; -} - -void Prefix::Reduce(ART &art, NodePtr &node_ptr, const idx_t pos) { - D_ASSERT(node_ptr.HasMetadata()); - D_ASSERT(pos < art.PrefixCount()); - - // We always reduce by at least one byte, - // thus, if the prefix was a gate, it no longer is. - node_ptr.SetGateStatus(GateStatus::GATE_NOT_SET); - - Prefix prefix(art, node_ptr); - if (pos == idx_t(prefix.data[art.PrefixCount()] - 1)) { - auto next_ptr = *prefix.child_slot; - NodePtr::FreeNode(art, node_ptr); - node_ptr = next_ptr; - return; - } - - // FIXME: Copy into new prefix (chain) instead of shifting. - for (idx_t i = 0; i < art.PrefixCount() - pos - 1; i++) { - prefix.data[i] = prefix.data[pos + i + 1]; - } - - prefix.data[art.PrefixCount()] -= pos + 1; - prefix.Append(art, *prefix.child_slot); -} - -Prefix Prefix::Append(ART &art, const uint8_t byte) { - if (data[art.PrefixCount()] != art.PrefixCount()) { - data[data[art.PrefixCount()]] = byte; - data[art.PrefixCount()]++; - return *this; - } - - auto prefix = NewInternal(art, *child_slot, nullptr, 0, 0); - return prefix.Append(art, byte); -} - -void Prefix::Append(ART &art, NodePtr other_ptr) { - D_ASSERT(other_ptr.HasMetadata()); - - Prefix prefix = *this; - while (other_ptr.GetType() == PREFIX) { - if (other_ptr.GetGateStatus() == GateStatus::GATE_SET) { - *prefix.child_slot = other_ptr; - return; - } - - Prefix other_prefix(art, other_ptr, true); - for (idx_t i = 0; i < other_prefix.data[art.PrefixCount()]; i++) { - prefix = prefix.Append(art, other_prefix.data[i]); - } - - *prefix.child_slot = *other_prefix.child_slot; - NodePtr::FreeNode(art, other_ptr); - other_ptr = *prefix.child_slot; - } -} - -Prefix Prefix::TransformToDeprecatedAppend(ART &art, FixedSizeAllocator &allocator, uint8_t byte) { - if (data[DEPRECATED_COUNT] != DEPRECATED_COUNT) { - data[data[DEPRECATED_COUNT]] = byte; - data[DEPRECATED_COUNT]++; - return *this; - } - - *child_slot = allocator.New(); - child_slot->SetMetadata(static_cast(PREFIX)); - Prefix prefix(allocator, *child_slot, DEPRECATED_COUNT); - return prefix.TransformToDeprecatedAppend(art, allocator, byte); -} - -} // namespace duckdb diff --git a/src/duckdb/src/execution/index/art/prefix_handle.cpp b/src/duckdb/src/execution/index/art/prefix_handle.cpp index 0874e19ca..56a2ea31b 100644 --- a/src/duckdb/src/execution/index/art/prefix_handle.cpp +++ b/src/duckdb/src/execution/index/art/prefix_handle.cpp @@ -192,6 +192,39 @@ NodePtr PrefixHandle::Split(ART &art, NodePtr &prefix_ptr, NodePtr &branching_no return child_ptr; } +void PrefixHandle::Reduce(ART &art, NodePtr &node_ptr, const idx_t pos) { + D_ASSERT(node_ptr.HasMetadata()); + D_ASSERT(pos < art.PrefixCount()); + + // We always reduce by at least one byte, + // thus, if the prefix was a gate, it no longer is. + node_ptr.SetGateStatus(GateStatus::GATE_NOT_SET); + + NodePtr child_ptr; + { + PrefixHandle prefix(NodeHandle(art, node_ptr)); + const idx_t count = prefix.GetCount(art); + D_ASSERT(pos < count); + if (pos + 1 != count) { + for (idx_t i = 0; i < art.PrefixCount() - pos - 1; i++) { + prefix.SetByte(i, prefix.GetByte(pos + i + 1)); + } + prefix.SetCount(art, UnsafeNumericCast(count - pos - 1)); + + // Merge any subsequent prefix nodes into this prefix. + auto next_ptr = prefix.Child(art); + Append(art, std::move(prefix), next_ptr); + return; + } + child_ptr = prefix.Child(art); + } + + // All bytes of this prefix are removed. + // Release the handle before freeing the node, which may destroy the allocator buffer. + NodePtr::FreeNode(art, node_ptr); + node_ptr = child_ptr; +} + NodeHandle PrefixHandle::NewDeprecated(FixedSizeAllocator &allocator, NodePtr &node_ptr) { node_ptr = allocator.New(); node_ptr.SetMetadata(static_cast(PREFIX)); diff --git a/src/duckdb/src/execution/index/index_type_set.cpp b/src/duckdb/src/execution/index/index_type_set.cpp index 1ae6ebeb2..db6e846f7 100644 --- a/src/duckdb/src/execution/index/index_type_set.cpp +++ b/src/duckdb/src/execution/index/index_type_set.cpp @@ -7,7 +7,9 @@ namespace duckdb { IndexTypeSet::IndexTypeSet() { // Register the ART index type by default - RegisterIndexType(ART::GetARTIndexType()); + auto art = ART::GetARTIndexType(); + art.internal = true; + RegisterIndexType(art); } optional_ptr IndexTypeSet::FindByName(const string &name) { @@ -27,4 +29,13 @@ void IndexTypeSet::RegisterIndexType(const IndexType &index_type) { functions[Identifier(index_type.name)] = index_type; } +vector IndexTypeSet::GetIndexTypes() { + lock_guard g(lock); + vector result; + for (auto &entry : functions) { + result.push_back(RegisteredIndexType {entry.second.name, entry.second.registered_by, entry.second.internal}); + } + return result; +} + } // namespace duckdb diff --git a/src/duckdb/src/execution/join_hashtable.cpp b/src/duckdb/src/execution/join_hashtable.cpp index 04951a029..5087d6106 100644 --- a/src/duckdb/src/execution/join_hashtable.cpp +++ b/src/duckdb/src/execution/join_hashtable.cpp @@ -13,6 +13,7 @@ #include "duckdb/logging/log_manager.hpp" #include "duckdb/execution/expression_executor.hpp" #include "duckdb/execution/mark_join_row_comparison.hpp" +#include "duckdb/execution/operator/join/join_filter_pushdown.hpp" #include "duckdb/execution/operator/join/physical_hash_join.hpp" #include "duckdb/execution/perfect_hash_join_table.hpp" #include "duckdb/main/client_context.hpp" @@ -98,6 +99,11 @@ JoinHashTable::ProbeState::ProbeState() is_match_v(LogicalType::BOOLEAN), needs_next_v(LogicalType::BOOLEAN) { } +void JoinHashTable::ProbeState::Reset() { + probe_filter_stats.reset(); + dict_state.reset(); +} + JoinHashTable::ProbeDictionaryState::ProbeDictionaryState() : unique_entries(STANDARD_VECTOR_SIZE) { } @@ -570,6 +576,49 @@ static void GetRowPointersInternal(DataChunk &keys, TupleDataChunkState &key_sta count = match_count; } +idx_t JoinHashTable::SelectProbeCandidates(ProbeState &state, Vector &first_key, const Vector &hashes, + optional_ptr sel, idx_t count) const { + D_ASSERT(probe_filter_type != ProbeFilterType::NONE); + if (!state.probe_filter_stats) { + float threshold; + idx_t vectors_to_check; + GetThresholdAndVectorsToCheck(probe_filter_type == ProbeFilterType::PRF ? SelectivityOptionalFilterType::PRF + : SelectivityOptionalFilterType::BF, + threshold, vectors_to_check); + state.probe_filter_stats = + make_uniq(vectors_to_check, threshold); + if (!state.probe_filter_sel.IsSet()) { + state.probe_filter_sel.Initialize(STANDARD_VECTOR_SIZE); + } + } + auto &stats = *state.probe_filter_stats; + if (!stats.IsActive()) { + stats.Update(0, 0); + return count; + } + + auto &filter_sel = state.probe_filter_sel; + D_ASSERT(!sel || sel.get() != &filter_sel); + idx_t approved; + if (probe_filter_type == ProbeFilterType::PRF) { + auto &filter = *prefix_range_filters[0]; + approved = sel ? filter.LookupKeys(first_key, *sel, filter_sel, count) + : filter.LookupKeys(first_key, filter_sel, count); + } else if (hashes.GetVectorType() == VectorType::CONSTANT_VECTOR) { + approved = probe_bloom_filter->LookupOne(*ConstantVector::GetData(hashes)) ? count : 0; + } else { + approved = sel ? probe_bloom_filter->LookupHashes(hashes, *sel, filter_sel, count) + : probe_bloom_filter->LookupHashes(hashes, filter_sel, count); + } + stats.Update(approved, count); + if (approved < count && sel) { + for (idx_t i = 0; i < approved; i++) { + filter_sel.set_index(i, sel->get_index(filter_sel.get_index(i))); + } + } + return approved; +} + inline bool JoinHashTable::UseSalt() const { // only use salt for large hash tables return this->capacity > USE_SALT_THRESHOLD; @@ -577,16 +626,37 @@ inline bool JoinHashTable::UseSalt() const { void JoinHashTable::GetRowPointers(DataChunk &keys, TupleDataChunkState &key_state, ProbeState &state, optional_ptr precomputed_hashes, optional_ptr sel, - idx_t &count, Vector &pointers_result_v, SelectionVector &match_sel, - const bool has_sel) { + idx_t &count, Vector &pointers_result_v, SelectionVector &match_sel, bool has_sel) { if (perfect_hash_table) { perfect_hash_table->GetRowPointers(keys.data[0], sel, count, pointers_result_v, match_sel); return; } auto &hashes = precomputed_hashes ? *precomputed_hashes : state.hashes; - if (!precomputed_hashes) { + const auto filter_before_hash = !precomputed_hashes && probe_filter_type == ProbeFilterType::PRF; + if (!precomputed_hashes && !filter_before_hash) { Hash(keys, state.hash_executor, hashes); } + if (probe_filter_type != ProbeFilterType::NONE && count > 0) { + const auto approved = SelectProbeCandidates(state, keys.data[0], hashes, has_sel ? sel : nullptr, count); + if (approved < count) { + sel = state.probe_filter_sel; + has_sel = true; + count = approved; + if (count == 0) { + return; + } + } + } + if (filter_before_hash) { + if (has_sel && count < keys.size()) { + D_ASSERT(HasSingleEqualityKey()); + VectorOperations::Hash(keys.data[0], hashes, *sel, count); + // Selected hashing writes at original row indices; preserve that logical index domain. + FlatVector::SetSize(hashes, count_t(keys.size())); + } else { + Hash(keys, state.hash_executor, hashes); + } + } auto entries = GetEntries(); if (UseSalt()) { GetRowPointersInternal(keys, key_state, state, hashes, sel, count, *this, entries, pointers_result_v, @@ -1246,6 +1316,10 @@ static void InsertHashesLoop(unsafe_optional_ptr> entries, Ve void JoinHashTable::InsertHashes(Vector &hashes_v, TupleDataChunkState &chunk_state, InsertState &insert_state, bool parallel) { + // Consume the combined hashes before insertion replaces them with bucket offsets. + if (probe_bloom_filter) { + probe_bloom_filter->InsertHashes(hashes_v); + } // a sealed filter was accumulated during Sink and is already complete; only a finalize-built one fills here if (!bloom_filters.empty() && HasSingleEqualityKey()) { auto &filter = bloom_filters[0]; @@ -1290,6 +1364,32 @@ void JoinHashTable::SetBuildBloomFilter(idx_t key_idx) { should_build_bloom_filters[key_idx] = true; } +void JoinHashTable::InitializeProbeFilter(idx_t estimated_probe_count, const Value &min, const Value &max) { + D_ASSERT(!perfect_hash_table); + if (!JoinFilterPushdownUtil::CanBuildProbeFilter(Count(), estimated_probe_count)) { + return; + } + const auto &condition = conditions[0]; + uhugeint_t span; + static constexpr idx_t MAX_PROBE_PRF_SPAN = 1ULL << 26; + // Keep the bitmap small, even if prefixes introduce false positives. + static constexpr idx_t MAX_PROBE_PRF_BITS = 1ULL << 20; + if (!min.IsNull() && !max.IsNull() && HasSingleEqualityKey() && + condition.GetComparisonType() == ExpressionType::COMPARE_EQUAL && + PrefixRangeFilter::SupportedType(condition.GetRHS().GetReturnType()) && + PrefixRangeFilter::TryComputeSpan(min, max, span) && span < MAX_PROBE_PRF_SPAN) { + auto filter = PrefixRangeFilter::CreatePrefixRangeFilter(condition.GetRHS().GetReturnType()); + filter->Initialize(context, Count(), min, max, MAX_PROBE_PRF_BITS); + SetPrefixRangeFilter(0, std::move(filter)); + should_build_prefix_range_filter = true; + probe_filter_type = ProbeFilterType::PRF; + } else { + probe_bloom_filter = make_uniq(); + probe_bloom_filter->Initialize(context, Count(), JoinFilterPushdownInfo::GetMemoryBudget(context)); + probe_filter_type = ProbeFilterType::BF; + } +} + void JoinHashTable::InitializeBloomFilters(const vector &key_idxs, idx_t build_estimate, idx_t memory_budget) { bloom_filters.clear(); if (key_idxs.empty()) { @@ -1315,6 +1415,9 @@ void JoinHashTable::SealBloomFilters() { filter->Seal(context); } } + if (probe_bloom_filter && !probe_bloom_filter->IsSealed()) { + probe_bloom_filter->Seal(context); + } } bool JoinHashTable::HasPublishableBloomFilter(idx_t key_idx) const { @@ -1725,7 +1828,8 @@ bool JoinHashTable::TryProbeDictionary(ScanStructure &scan_structure, DataChunk auto &unique_entries = dict_state.unique_entries; idx_t unique_count = 0; if (dict_state.resolved_count < dict_size) { - for (idx_t i = 0; i < keys.size(); i++) { + const auto row_count = keys.size(); + for (idx_t i = 0; i < row_count; i++) { const auto dict_idx = offsets.get_index(i); unique_entries.set_index(unique_count, dict_idx); unique_count += !found_entry[dict_idx]; @@ -2522,13 +2626,15 @@ void ScanStructure::NextRightSemiOrAntiJoin(DataChunk &keys, DataChunk &probe_da static bool MarkJoinChunkHasUnknown(DataChunk &left, idx_t left_row, DataChunk &right) { D_ASSERT(left.ColumnCount() == right.ColumnCount()); + const auto left_count = left.size(); + const auto right_count = right.size(); bool row_is_false[STANDARD_VECTOR_SIZE] = {false}; bool row_is_unknown[STANDARD_VECTOR_SIZE] = {false}; for (idx_t col_idx = 0; col_idx < left.ColumnCount(); col_idx++) { - MarkJoinRowComparison::CompareEquality(left.data[col_idx], left_row, left.size(), right.data[col_idx], - right.size(), row_is_false, row_is_unknown); + MarkJoinRowComparison::CompareEquality(left.data[col_idx], left_row, left_count, right.data[col_idx], + right_count, row_is_false, row_is_unknown); } - for (idx_t right_row = 0; right_row < right.size(); right_row++) { + for (idx_t right_row = 0; right_row < right_count; right_row++) { if (!row_is_false[right_row] && row_is_unknown[right_row]) { return true; } @@ -2554,9 +2660,10 @@ void JoinHashTable::ConstructMarkJoinResult(DataChunk &join_keys, DataChunk &pro // first we set the NULL values from the join keys // if there is any NULL in the keys, the result is NULL + const auto row_count = probe_data.size(); auto bool_result = FlatVector::GetDataMutable(mark_vector); auto &mask = FlatVector::ValidityMutable(mark_vector); - mask.SetAllValid(probe_data.size()); + mask.SetAllValid(row_count); if (!HasUncorrelatedMarkJoin()) { for (idx_t col_idx = 0; col_idx < join_keys.ColumnCount(); col_idx++) { if (null_values_are_equal[col_idx]) { @@ -2565,7 +2672,8 @@ void JoinHashTable::ConstructMarkJoinResult(DataChunk &join_keys, DataChunk &pro UnifiedVectorFormat jdata; join_keys.data[col_idx].ToUnifiedFormat(jdata); if (jdata.validity.CanHaveNull()) { - for (idx_t i = 0; i < join_keys.size(); i++) { + const auto key_count = join_keys.size(); + for (idx_t i = 0; i < key_count; i++) { auto jidx = jdata.sel->get_index(i); if (!jdata.validity.RowIsValidUnsafe(jidx)) { mask.SetInvalid(i); @@ -2576,13 +2684,13 @@ void JoinHashTable::ConstructMarkJoinResult(DataChunk &join_keys, DataChunk &pro } // now set the remaining entries to either true or false based on whether a match was found - for (idx_t i = 0; i < probe_data.size(); i++) { + for (idx_t i = 0; i < row_count; i++) { bool_result[i] = found_match && found_match.get()[i]; } // if the right side contains NULL values, the result of any FALSE becomes NULL if (!HasUncorrelatedMarkJoin() && has_null) { - for (idx_t i = 0; i < probe_data.size(); i++) { + for (idx_t i = 0; i < row_count; i++) { if (!bool_result[i]) { mask.SetInvalid(i); } @@ -2599,7 +2707,8 @@ void JoinHashTable::ConstructMarkJoinResult(DataChunk &join_keys, DataChunk &pro SelectionVector refinement_sel(STANDARD_VECTOR_SIZE); idx_t refinement_count = 0; - for (idx_t probe_idx = 0; probe_idx < join_keys.size(); probe_idx++) { + const auto key_count = join_keys.size(); + for (idx_t probe_idx = 0; probe_idx < key_count; probe_idx++) { if ((mark_join_info.uncorrelated_has_null || requires_refinement[probe_idx]) && !bool_result[probe_idx] && mask.RowIsValid(probe_idx)) { refinement_sel.set_index(refinement_count++, probe_idx); @@ -3075,6 +3184,8 @@ void JoinHashTable::Repartition(JoinHashTable &global_ht) { } void JoinHashTable::Reset() { + probe_filter_type = ProbeFilterType::NONE; + probe_bloom_filter.reset(); materialized_dictionary.reset(); bucket_shift = 0; data_collection->Reset(); @@ -3111,6 +3222,8 @@ static void ResetMarkJoinInfo(JoinHashTable &ht) { } void JoinHashTable::ResetForNewIterationSinglePartition() { + probe_filter_type = ProbeFilterType::NONE; + probe_bloom_filter.reset(); // Always use a single partition (radix_bits=0) to avoid per-iteration overhead of resetting // and re-creating many radix partitions when only one thread builds the hash table. This also // keeps an unpublished shell consistent with the global radix bits when it is recycled. diff --git a/src/duckdb/src/execution/operator/aggregate/physical_streaming_window.cpp b/src/duckdb/src/execution/operator/aggregate/physical_streaming_window.cpp index abdc50a3b..51441d8bc 100644 --- a/src/duckdb/src/execution/operator/aggregate/physical_streaming_window.cpp +++ b/src/duckdb/src/execution/operator/aggregate/physical_streaming_window.cpp @@ -369,6 +369,9 @@ void PhysicalStreamingWindow::ExecuteInput(ExecutionContext &context, DataChunk output.data[col_idx].Reference(input.data[col_idx]); FlatVector::SetSize(output.data[col_idx], count_t(count)); } + if (input.ColumnCount() == 0) { + output.SetChildCardinality(count); + } ExecuteFunctions(context, output, state.delayed, gstate_p); } @@ -399,6 +402,9 @@ void PhysicalStreamingWindow::ExecuteShifted(ExecutionContext &context, DataChun VectorOperations::Copy(input.data[col_idx], delayed.data[col_idx], in, 0, delay - out); FlatVector::SetSize(delayed.data[col_idx], count_t(new_delayed_count)); } + if (delayed.ColumnCount() == 0) { + delayed.SetChildCardinality(new_delayed_count); + } ExecuteFunctions(context, output, delayed, gstate_p); } @@ -411,6 +417,9 @@ void PhysicalStreamingWindow::ExecuteDelayed(ExecutionContext &context, DataChun output.data[col_idx].Reference(delayed.data[col_idx]); FlatVector::SetSize(output.data[col_idx], count_t(count)); } + if (delayed.ColumnCount() == 0) { + output.SetChildCardinality(count); + } ExecuteFunctions(context, output, input, gstate_p); } diff --git a/src/duckdb/src/execution/operator/aggregate/physical_window.cpp b/src/duckdb/src/execution/operator/aggregate/physical_window.cpp index 6ddd4b061..ee6fefb66 100644 --- a/src/duckdb/src/execution/operator/aggregate/physical_window.cpp +++ b/src/duckdb/src/execution/operator/aggregate/physical_window.cpp @@ -690,10 +690,10 @@ void WindowHashGroup::ComputeMasks(const idx_t block_begin, const idx_t block_en [&](const idx_t row_idx, DataChunk &prev, DataChunk &curr, const idx_t ndistinct, SelectionVector &distinct, const SelectionVector &matching) { // Process the partition boundaries + partition_count += ndistinct; for (idx_t i = 0; i < ndistinct; ++i) { const idx_t curr_index = row_idx + distinct.get_index(i); partition_mask.SetValidUnsafe(curr_index); - ++partition_count; for (auto &order_mask : order_masks) { order_mask.second.SetValidUnsafe(curr_index); } @@ -1188,8 +1188,8 @@ bool WindowHashGroup::ShouldCoEvaluate(idx_t size) const { const auto active_rows = npartitions * k; const auto prob_i_active = active_rows / dcount; const auto prob_i_inactive = 1 - prob_i_active; - const auto avg_inactive = (partition_avg - partition_limit) / 2; const auto dsize = LossyNumericCast(size); + const auto avg_inactive = MinValue(dsize, partition_avg - k) / 2; double expected = 0; // Case 1: begin is active diff --git a/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_file_handle.cpp b/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_file_handle.cpp index 29e29017e..b0e4ae11f 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_file_handle.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/buffer_manager/csv_file_handle.cpp @@ -20,7 +20,7 @@ CSVFileHandle::CSVFileHandle(ClientContext &context_p, unique_ptr fi unique_ptr CSVFileHandle::OpenFileHandle(FileSystem &fs, Allocator &allocator, const OpenFileInfo &file, FileCompressionType compression) { - FileOpenFlags flags = FileFlags::FILE_FLAGS_READ | FileFlags::FILE_FLAGS_PARALLEL_ACCESS | std::move(compression); + FileOpenFlags flags = FileFlags::FILE_FLAGS_READ | FileFlags::FILE_FLAGS_PARALLEL_ACCESS | compression; flags.SetCachingMode(CachingMode::CACHE_REMOTE_ONLY); auto file_handle = fs.OpenFile(file, flags); if (file_handle->CanSeek()) { diff --git a/src/duckdb/src/execution/operator/csv_scanner/util/csv_reader_options.cpp b/src/duckdb/src/execution/operator/csv_scanner/util/csv_reader_options.cpp index 4595bec66..8fa50c3b6 100644 --- a/src/duckdb/src/execution/operator/csv_scanner/util/csv_reader_options.cpp +++ b/src/duckdb/src/execution/operator/csv_scanner/util/csv_reader_options.cpp @@ -6,6 +6,7 @@ #include "duckdb/common/operator/multiply.hpp" #include "duckdb/common/multi_file/multi_file_reader.hpp" #include "duckdb/common/set.hpp" +#include "duckdb/common/virtual_file_system.hpp" #include "duckdb/parser/keyword_helper.hpp" namespace duckdb { @@ -111,8 +112,8 @@ void CSVReaderOptions::SetHeader(bool input) { this->dialect_options.header.Set(input); } -void CSVReaderOptions::SetCompression(const string &compression_p) { - this->compression = FileCompressionType(compression_p); +void CSVReaderOptions::SetCompression(Context &context, const string &compression_p) { + this->compression = VirtualFileSystem::Get(context.GetDatabase()).ParseCompression(compression_p); } void CSVReaderOptions::SetEscape(const string &input) { @@ -447,7 +448,7 @@ bool CSVReaderOptions::SetBaseOption(Context &context, const Identifier &loption } } else if (loption == "compression") { - SetCompression(ParseString(value, loption)); + SetCompression(context, ParseString(value, loption)); } else if (loption == "strict_mode") { SetRFC4180(ParseBoolean(context, value, loption)); } else { diff --git a/src/duckdb/src/execution/operator/helper/physical_streaming_sample.cpp b/src/duckdb/src/execution/operator/helper/physical_streaming_sample.cpp index 23452f8a5..c9e6040ec 100644 --- a/src/duckdb/src/execution/operator/helper/physical_streaming_sample.cpp +++ b/src/duckdb/src/execution/operator/helper/physical_streaming_sample.cpp @@ -74,8 +74,9 @@ void PhysicalStreamingSample::SystemSampleRows(DataChunk &input, DataChunk &resu // where the systematic sample starts. auto &state = state_p.Cast(); idx_t result_count = 0; - SelectionVector sel(input.size()); - for (idx_t i = 0; i < input.size(); i++) { + const auto row_count = input.size(); + SelectionVector sel(row_count); + for (idx_t i = 0; i < row_count; i++) { auto before = std::floor(LossyNumericCast(state.system_rows_seen) * rate + system_sample_phase); state.system_rows_seen++; auto after = std::floor(LossyNumericCast(state.system_rows_seen) * rate + system_sample_phase); @@ -94,7 +95,8 @@ void PhysicalStreamingSample::BernoulliSample(DataChunk &input, DataChunk &resul auto &state = state_p.Cast(); idx_t result_count = 0; SelectionVector sel(STANDARD_VECTOR_SIZE); - for (idx_t i = 0; i < input.size(); i++) { + const auto row_count = input.size(); + for (idx_t i = 0; i < row_count; i++) { double rand = state.random.NextRandom(); if (rand <= percentage) { sel.set_index(result_count++, i); diff --git a/src/duckdb/src/execution/operator/join/join_filter_pushdown.cpp b/src/duckdb/src/execution/operator/join/join_filter_pushdown.cpp index 338f9f104..f311b45be 100644 --- a/src/duckdb/src/execution/operator/join/join_filter_pushdown.cpp +++ b/src/duckdb/src/execution/operator/join/join_filter_pushdown.cpp @@ -1,5 +1,6 @@ #include "duckdb/execution/operator/join/join_filter_pushdown.hpp" +#include "duckdb/common/allocator.hpp" #include "duckdb/common/vector_operations/vector_operations.hpp" #include "duckdb/function/cast/cast_function_set.hpp" #include "duckdb/execution/join_hashtable.hpp" @@ -875,15 +876,17 @@ class HashJoinFilterCopyTask : public ExecutorTask { if (phase == HashJoinFilterCopyPhase::PRIMARY || ((force || group == copy.replica_group.GetIndex()) && !copy.claimed.exchange(true, std::memory_order_relaxed))) { try { - auto buffer = copy.filter->CopyBuffer(context); + auto buffer = BufferAllocator::Get(context).AllocateHuge(copy.filter->GetBitmapSize()); const auto home = buffer.GetAllocationShard(); if (force || home.IsValid()) { const auto buffer_group = force ? group : BlockAllocator::GetShardGroup(home.GetIndex(), shard_count); - if (phase == HashJoinFilterCopyPhase::PRIMARY) { - copy.replica_group = optional_idx(force ? group : 1 - buffer_group); - copy.buffer = std::move(buffer); - } else if (force || buffer_group == copy.replica_group.GetIndex()) { + if (phase == HashJoinFilterCopyPhase::PRIMARY || force || + buffer_group == copy.replica_group.GetIndex()) { + copy.filter->CopyBuffer(context, buffer); + if (phase == HashJoinFilterCopyPhase::PRIMARY) { + copy.replica_group = optional_idx(force ? group : 1 - buffer_group); + } copy.buffer = std::move(buffer); } } @@ -968,8 +971,8 @@ void JoinFilterPushdownInfo::FinalizeRuntimeFilters(Pipeline &pipeline, Event &e JoinHashTable &ht, optional_ptr filter_state, idx_t num_threads) { auto &context = pipeline.GetClientContext(); + ht.SealBloomFilters(); if (filter_state) { - ht.SealBloomFilters(); auto &gstate = *filter_state; const auto shard_count = BlockAllocator::Get(*context.db).GetFallbackShardCount(); const auto force = Settings::Get(context); diff --git a/src/duckdb/src/execution/operator/join/outer_join_marker.cpp b/src/duckdb/src/execution/operator/join/outer_join_marker.cpp index 065b96792..3d3ed10aa 100644 --- a/src/duckdb/src/execution/operator/join/outer_join_marker.cpp +++ b/src/duckdb/src/execution/operator/join/outer_join_marker.cpp @@ -99,7 +99,8 @@ void OuterJoinMarker::Scan(OuterJoinGlobalScanState &gstate, OuterJoinLocalScanS while (gstate.data->Scan(gstate.global_scan, lstate.local_scan, lstate.scan_chunk)) { idx_t result_count = 0; // figure out which tuples did (not) find a match in the RHS - for (idx_t i = 0; i < lstate.scan_chunk.size(); i++) { + const auto row_count = lstate.scan_chunk.size(); + for (idx_t i = 0; i < row_count; i++) { if (found_match[lstate.local_scan.current_row_index + i] == matched) { lstate.match_sel.set_index(result_count++, i); } diff --git a/src/duckdb/src/execution/operator/join/physical_hash_join.cpp b/src/duckdb/src/execution/operator/join/physical_hash_join.cpp index 9b1474b05..c1bdfa928 100644 --- a/src/duckdb/src/execution/operator/join/physical_hash_join.cpp +++ b/src/duckdb/src/execution/operator/join/physical_hash_join.cpp @@ -1,4 +1,5 @@ #include "duckdb/execution/operator/join/physical_hash_join.hpp" +#include "duckdb/parallel/parallel_destroy_task.hpp" #include "duckdb/function/builtin_function_lookup.hpp" #include "duckdb/logging/log_manager.hpp" @@ -375,7 +376,7 @@ class HashJoinGlobalSinkState : public GlobalSinkState { void InitializePerExecutionState(ClientContext &context, shared_ptr recycled_filter = nullptr) { external = Settings::Get(context); global_filter_state.reset(); - if (op.filter_pushdown && !op.filter_pushdown->probe_info.empty()) { + if (op.filter_pushdown) { global_filter_state = op.filter_pushdown->GetGlobalState(context, op); } JoinFilterPushdownInfo::InitializeBloomFilters(context, op, *hash_table, std::move(recycled_filter)); @@ -920,11 +921,17 @@ static void ExecuteHashJoinTableInitTask(HashJoinGlobalSinkState &sink, idx_t en } struct PrefixRangeBuildLane { - explicit PrefixRangeBuildLane(JoinHashTable::PrefixRangeBuildStates states_p) : states(std::move(states_p)) { + JoinHashTable::PrefixRangeBuildStates &GetStates(JoinHashTable &ht) { + // Allow build workers to initialize different lanes concurrently. + CallOnce(initialize_once, [&] { states = ht.InitializePrefixRangeBuildState(); }); + return states; } JoinHashTable::PrefixRangeBuildStates states; idx_t task_count = 0; + +private: + OnceFlag initialize_once; }; struct JoinBuildRange { @@ -937,7 +944,7 @@ static void ExecuteHashJoinFinalizeTask(HashJoinGlobalSinkState &sink, const Joi optional_ptr prefix_range_states; bool prefix_range_parallel = false; if (prefix_range_lane) { - prefix_range_states = prefix_range_lane->states; + prefix_range_states = prefix_range_lane->GetStates(*sink.hash_table); prefix_range_parallel = prefix_range_lane->task_count > 1; } sink.hash_table->Finalize(chunk_range.begin, chunk_range.end, parallel, prefix_range_states, prefix_range_parallel); @@ -1179,7 +1186,9 @@ class HashJoinFinalizeEvent : public BasePipelineEvent { private: void FinishTasks(Event &event) { for (auto &lane : prefix_range_lanes) { - sink.hash_table->MergePrefixRangeBuildState(lane->states); + if (!lane->states.empty()) { + sink.hash_table->MergePrefixRangeBuildState(lane->states); + } } sink.hash_table->GetDataCollection().VerifyEverythingPinned(); @@ -1217,7 +1226,11 @@ class HashJoinFinalizeEvent : public BasePipelineEvent { const auto lane_count = MinValue(task_count, lanes_within_budget); prefix_range_lanes.reserve(lane_count); for (idx_t lane_idx = 0; lane_idx < lane_count; lane_idx++) { - prefix_range_lanes.push_back(make_uniq(ht.InitializePrefixRangeBuildState())); + prefix_range_lanes.push_back(make_uniq()); + } + if (lane_count == 1) { + // With one lane there is no initialization to parallelize. + prefix_range_lanes[0]->GetStates(ht); } } @@ -1452,16 +1465,31 @@ SinkFinalizeType PhysicalHashJoin::Finalize(Pipeline &pipeline, Event &event, Cl ht.Merge(local_ht.get()); } sink.local_hash_tables.clear(); + if (sink.owned_local_hash_tables.size() >= 64) { + auto &scheduler = TaskScheduler::GetScheduler(context); + const auto task_count = MinValue(4, scheduler.NumberOfThreads()); + if (task_count > 1) { + ParallelDestroyTask::Schedule( + scheduler, sink.owned_local_hash_tables.begin(), sink.owned_local_hash_tables.end(), task_count); + } + } sink.owned_local_hash_tables.clear(); ht.Unpartition(); const auto use_perfect_hash = ht.TryInitializePerfectHashTable(); + Value min; + Value max; if (sink.global_filter_state && ht.Count() > 0) { auto filter_min_max = filter_pushdown->FinalizeMinMax(*sink.global_filter_state); + min = filter_min_max->data[0].GetValue(0); + max = filter_min_max->data[1].GetValue(0); filter_pushdown->FinalizeFilters(context, *this, std::move(filter_min_max), &ht, !use_perfect_hash, true, sink.global_filter_state.get()); } + if (!use_perfect_hash && (!filter_pushdown || filter_pushdown->probe_info.empty())) { + ht.InitializeProbeFilter(children[0].get().estimated_cardinality, min, max); + } sink.ScheduleFinalize(pipeline, event); sink.finalized = true; if (ht.Count() == 0 && EmptyResultIfRHSIsEmpty()) { @@ -1538,7 +1566,7 @@ class HashJoinOperatorState : public CachingOperatorState { if (spill_chunk.ColumnCount() != 0) { spill_chunk.Reset(); } - probe_state.dict_state.reset(); + probe_state.Reset(); if (CanUseCompressedProbe(op.sink_state->Cast(), op.conditions)) { probe_state.dict_state = make_uniq(); } diff --git a/src/duckdb/src/execution/operator/join/physical_nested_loop_join.cpp b/src/duckdb/src/execution/operator/join/physical_nested_loop_join.cpp index c2ad983d7..97d7edd21 100644 --- a/src/duckdb/src/execution/operator/join/physical_nested_loop_join.cpp +++ b/src/duckdb/src/execution/operator/join/physical_nested_loop_join.cpp @@ -50,7 +50,8 @@ bool PhysicalJoin::HasNullValues(DataChunk &chunk) { if (!entries.CanHaveNull()) { continue; } - for (idx_t i = 0; i < chunk.size(); i++) { + const auto row_count = chunk.size(); + for (idx_t i = 0; i < row_count; i++) { if (!entries.IsValid(i)) { return true; } @@ -100,35 +101,37 @@ void PhysicalJoin::ConstructMarkJoinResult(DataChunk &join_keys, DataChunk &left mark_vector.SetVectorType(VectorType::FLAT_VECTOR); // first we set the NULL values from the join keys // if there is any NULL in the keys, the result is NULL + const auto row_count = left.size(); auto bool_result = FlatVector::GetDataMutable(mark_vector); auto &mask = FlatVector::ValidityMutable(mark_vector); - mask.SetAllValid(left.size()); + mask.SetAllValid(row_count); for (idx_t col_idx = 0; !found_unknown && col_idx < join_keys.ColumnCount(); col_idx++) { auto entries = join_keys.data[col_idx].Validity(); if (!entries.CanHaveNull()) { continue; } - for (idx_t i = 0; i < join_keys.size(); i++) { + const auto key_count = join_keys.size(); + for (idx_t i = 0; i < key_count; i++) { mask.Set(i, entries.IsValid(i)); } } // now set the remaining entries to either true or false based on whether a match was found if (found_match) { - for (idx_t i = 0; i < left.size(); i++) { + for (idx_t i = 0; i < row_count; i++) { bool_result[i] = found_match[i]; } } else { - memset(bool_result, 0, sizeof(bool) * left.size()); + memset(bool_result, 0, sizeof(bool) * row_count); } // if the right side contains NULL values, the result of any FALSE becomes NULL if (found_unknown) { - for (idx_t i = 0; i < left.size(); i++) { + for (idx_t i = 0; i < row_count; i++) { if (!bool_result[i] && found_unknown.get()[i]) { mask.SetInvalid(i); } } } else if (has_null) { - for (idx_t i = 0; i < left.size(); i++) { + for (idx_t i = 0; i < row_count; i++) { if (!bool_result[i]) { mask.SetInvalid(i); } @@ -396,6 +399,8 @@ class PhysicalNestedLoopJoinState : public CachingOperatorState { idx_t left_tuple; idx_t right_tuple; + SelectionVector left_matches; + SelectionVector right_matches; OuterJoinMarker left_outer; @@ -609,18 +614,24 @@ void PhysicalNestedLoopJoin::ResolveRightSemiJoin(ExecutionContext &context, Dat OperatorResultType PhysicalNestedLoopJoin::ResolveComplexJoin(ExecutionContext &context, DataChunk &input, DataChunk &chunk, OperatorState &state_p) const { + enum class RHSScanMode : uint8_t { SCAN, REUSE }; auto &state = state_p.Cast(); auto &gstate = sink_state->Cast(); idx_t match_count; do { + // Keep a complete single-chunk RHS pinned instead of rescanning it for every input chunk. + const auto rhs_scan_mode = state.right_condition.size() == gstate.right_condition_data.Count() + ? RHSScanMode::REUSE + : RHSScanMode::SCAN; if (state.fetch_next_right) { // we exhausted the chunk on the right: move to the next chunk on the right state.left_tuple = 0; state.right_tuple = 0; state.fetch_next_right = false; // check if we exhausted all chunks on the RHS - if (gstate.right_condition_data.Scan(state.condition_scan_state, state.right_condition)) { + if (rhs_scan_mode == RHSScanMode::SCAN && + gstate.right_condition_data.Scan(state.condition_scan_state, state.right_condition)) { if (!gstate.right_payload_data.Scan(state.payload_scan_state, state.right_payload)) { throw InternalException("Nested loop join: payload and conditions are unaligned!?"); } @@ -646,11 +657,13 @@ OperatorResultType PhysicalNestedLoopJoin::ResolveComplexJoin(ExecutionContext & state.left_tuple = 0; state.right_tuple = 0; - gstate.right_condition_data.InitializeScan(state.condition_scan_state); - gstate.right_condition_data.Scan(state.condition_scan_state, state.right_condition); + if (rhs_scan_mode == RHSScanMode::SCAN) { + gstate.right_condition_data.InitializeScan(state.condition_scan_state); + gstate.right_condition_data.Scan(state.condition_scan_state, state.right_condition); - gstate.right_payload_data.InitializeScan(state.payload_scan_state); - gstate.right_payload_data.Scan(state.payload_scan_state, state.right_payload); + gstate.right_payload_data.InitializeScan(state.payload_scan_state); + gstate.right_payload_data.Scan(state.payload_scan_state, state.right_payload); + } state.fetch_next_left = false; } // now we have a left and a right chunk that we can join together @@ -665,11 +678,17 @@ OperatorResultType PhysicalNestedLoopJoin::ResolveComplexJoin(ExecutionContext & right_payload.Verify(context.client.db); // now perform the join - SelectionVector lvector(STANDARD_VECTOR_SIZE), rvector(STANDARD_VECTOR_SIZE); - match_count = NestedLoopJoinInner::Perform(state.left_tuple, state.right_tuple, state.left_condition, - right_condition, lvector, rvector, conditions); + if (!state.left_matches.IsSet()) { + state.left_matches.Initialize(STANDARD_VECTOR_SIZE); + state.right_matches.Initialize(STANDARD_VECTOR_SIZE); + } + match_count = + NestedLoopJoinInner::Perform(state.left_tuple, state.right_tuple, state.left_condition, right_condition, + state.left_matches, state.right_matches, conditions); // we have finished resolving the join conditions if (match_count > 0) { + auto &lvector = state.left_matches; + auto &rvector = state.right_matches; // we have matching tuples! // construct the result chunk.Slice(input, lvector, match_count); diff --git a/src/duckdb/src/execution/operator/persistent/copy_batch_slicer.cpp b/src/duckdb/src/execution/operator/persistent/copy_batch_slicer.cpp index aad699c9e..68324bf82 100644 --- a/src/duckdb/src/execution/operator/persistent/copy_batch_slicer.cpp +++ b/src/duckdb/src/execution/operator/persistent/copy_batch_slicer.cpp @@ -42,8 +42,9 @@ const Vector &CopyBatchSlicer::ComputeRowSizes(DataChunk &chunk) { D_ASSERT(row_bytes_state); auto &row_sizes = row_bytes_state->heap_sizes; if (layout.AllConstant()) { - auto writer = FlatVector::Writer(row_sizes, chunk.size()); - for (idx_t i = 0; i < chunk.size(); i++) { + const auto row_count = chunk.size(); + auto writer = FlatVector::Writer(row_sizes, row_count); + for (idx_t i = 0; i < row_count; i++) { writer.WriteValue(fixed_row_bytes); } } else { diff --git a/src/duckdb/src/execution/operator/persistent/physical_batch_copy_to_file.cpp b/src/duckdb/src/execution/operator/persistent/physical_batch_copy_to_file.cpp index 1237645c2..053e7e9b9 100644 --- a/src/duckdb/src/execution/operator/persistent/physical_batch_copy_to_file.cpp +++ b/src/duckdb/src/execution/operator/persistent/physical_batch_copy_to_file.cpp @@ -6,12 +6,10 @@ #include "duckdb/common/types/batched_data_collection.hpp" #include "duckdb/common/vector_operations/vector_operations.hpp" #include "duckdb/execution/operator/persistent/batch_memory_manager.hpp" -#include "duckdb/execution/operator/persistent/batch_task_manager.hpp" #include "duckdb/execution/operator/persistent/copy_batch_slicer.hpp" #include "duckdb/execution/operator/persistent/copy_output_lifecycle.hpp" #include "duckdb/execution/operator/persistent/physical_copy_to_file.hpp" -#include "duckdb/parallel/base_pipeline_event.hpp" -#include "duckdb/parallel/executor_task.hpp" +#include "duckdb/parallel/task_executor.hpp" #include "duckdb/storage/buffer_manager.hpp" #include "duckdb/storage/storage_info.hpp" #include "duckdb/logging/logger.hpp" @@ -57,14 +55,6 @@ OperatorPartitionInfo PhysicalBatchCopyToFile::RequiredPartitionInfo() const { //===--------------------------------------------------------------------===// // States //===--------------------------------------------------------------------===// -class BatchCopyTask { -public: - virtual ~BatchCopyTask() { - } - - virtual void Execute(const PhysicalBatchCopyToFile &op, ClientContext &context, GlobalSinkState &gstate_p) = 0; -}; - struct FixedRawBatchData { FixedRawBatchData(idx_t memory_usage_p, unique_ptr collection_p) : memory_usage(memory_usage_p), collection(std::move(collection_p)) { @@ -88,16 +78,17 @@ class FixedBatchCopyGlobalState : public GlobalSinkState { public: explicit FixedBatchCopyGlobalState(ClientContext &context_p, idx_t minimum_memory_per_thread) : output_lifecycle(context_p), memory_manager(context_p, minimum_memory_per_thread), rows_copied(0), - scheduled_batch_index(0), flushed_batch_index(0), any_flushing(false), any_finished(false), + scheduled_batch_index(0), flushed_batch_index(0), any_flushing(false), minimum_memory_per_thread(minimum_memory_per_thread) { } //! Destroy after global_state so its handle closes before cleanup. CopyOutputLifecycle output_lifecycle; BatchMemoryManager memory_manager; - BatchTaskManager task_manager; - mutex lock; - mutex flush_lock; + annotated_mutex lock; + //! Serializes batch assembly without holding the state lock while copying or preparing. + annotated_mutex repartition_lock; + annotated_mutex flush_lock; atomic initialized {false}; //! The total number of rows copied to the file atomic rows_copied; @@ -116,17 +107,15 @@ class FixedBatchCopyGlobalState : public GlobalSinkState { //! Files a rotating copy has written, in order (for RETURN_FILES and RETURN_STATS) vector> rotated_files; //! Unpartitioned batches - map> raw_batches; + map> raw_batches DUCKDB_GUARDED_BY(lock); //! The prepared batch data by batch index - ready to flush - map> batch_data; + map> batch_data DUCKDB_GUARDED_BY(lock); //! The index of the latest batch index that has been scheduled atomic scheduled_batch_index; //! The index of the latest batch index that has been flushed atomic flushed_batch_index; //! Whether or not any thread is flushing atomic any_flushing; - //! Whether or not any threads are finished - atomic any_finished; //! Minimum memory per thread idx_t minimum_memory_per_thread; //! Written file info (for RETURN_STATS) @@ -136,7 +125,7 @@ class FixedBatchCopyGlobalState : public GlobalSinkState { if (initialized.load(std::memory_order_acquire)) { return; } - lock_guard guard(lock); + annotated_lock_guard guard(lock); if (initialized.load(std::memory_order_relaxed)) { return; } @@ -181,7 +170,7 @@ class FixedBatchCopyGlobalState : public GlobalSinkState { void AddBatchData(idx_t batch_index, unique_ptr new_batch, idx_t memory_usage, const CopyFunctionBatchAnalyzer &batch_analyzer) { // move the batch data to the set of prepared batch data - lock_guard l(lock); + annotated_lock_guard l(lock); auto prepared_data = unique_ptr( new FixedPreparedBatchData {memory_usage, std::move(new_batch), batch_analyzer}); auto entry = batch_data.insert(make_pair(batch_index, std::move(prepared_data))); @@ -198,8 +187,6 @@ class FixedBatchCopyGlobalState : public GlobalSinkState { } }; -enum class FixedBatchCopyState : uint8_t { SINKING_DATA = 1, PROCESSING_TASKS = 2 }; - class FixedBatchCopyLocalState : public LocalSinkState { public: explicit FixedBatchCopyLocalState(unique_ptr local_state_p) @@ -218,8 +205,6 @@ class FixedBatchCopyLocalState : public LocalSinkState { idx_t local_memory_usage; //! The current batch index optional_idx batch_index; - //! Current task - FixedBatchCopyState current_task = FixedBatchCopyState::SINKING_DATA; void InitializeCollection(ClientContext &context, const PhysicalOperator &op) { collection = make_uniq(context, op.children[0].get().GetTypes()); @@ -238,29 +223,18 @@ SinkResultType PhysicalBatchCopyToFile::Sink(ExecutionContext &context, DataChun auto &gstate = input.global_state.Cast(); auto &memory_manager = gstate.memory_manager; auto batch_index = state.partition_info.batch_index.GetIndex(); - if (state.current_task == FixedBatchCopyState::PROCESSING_TASKS) { - ExecuteTasks(context.client, gstate); - FlushBatchData(context.client, gstate); - - if (!memory_manager.IsMinimumBatchIndex(batch_index) && memory_manager.OutOfMemory(batch_index)) { - annotated_lock_guard guard(memory_manager.lock); - if (!memory_manager.IsMinimumBatchIndex(batch_index)) { - // no tasks to process, we are not the minimum batch index and we have no memory available to buffer - // block the task for now - return memory_manager.BlockSink(input.interrupt_state); - } - } - state.current_task = FixedBatchCopyState::SINKING_DATA; + memory_manager.UpdateMinBatchIndex(state.partition_info.min_batch_index.GetIndex()); + if (memory_manager.IsMinimumBatchIndex(batch_index) && + memory_manager.GetUnflushedMemory() >= memory_manager.AvailableMemory()) { + // Let an active assembler free memory before the minimum producer buffers more. + annotated_lock_guard guard(gstate.repartition_lock); } - if (!memory_manager.IsMinimumBatchIndex(batch_index)) { - memory_manager.UpdateMinBatchIndex(state.partition_info.min_batch_index.GetIndex()); - - // we are not processing the current min batch index - // check if we have exceeded the maximum number of unflushed rows - if (memory_manager.OutOfMemory(batch_index)) { - // out-of-memory - stop sinking chunks and instead assist in processing tasks for the minimum batch index - state.current_task = FixedBatchCopyState::PROCESSING_TASKS; - return Sink(context, chunk, input); + if (!memory_manager.IsMinimumBatchIndex(batch_index) && memory_manager.OutOfMemory(batch_index)) { + RepartitionBatches(context.client, gstate); + annotated_lock_guard guard(memory_manager.lock); + if (!memory_manager.IsMinimumBatchIndex(batch_index) && + memory_manager.GetUnflushedMemory() >= memory_manager.AvailableMemory()) { + return memory_manager.BlockSink(input.interrupt_state); } } if (!write_empty_file) { @@ -294,81 +268,17 @@ SinkCombineResultType PhysicalBatchCopyToFile::Combine(ExecutionContext &context // add any final remaining local batches AddLocalBatch(context.client, gstate, state); - if (!gstate.any_finished) { - // signal that this thread is finished processing batches and that we should move on to Finalize - lock_guard l(gstate.lock); - gstate.any_finished = true; - } memory_manager.UpdateMinBatchIndex(state.partition_info.min_batch_index.GetIndex()); - ExecuteTasks(context.client, gstate); + RepartitionBatches(context.client, gstate); return SinkCombineResultType::FINISHED; } -//===--------------------------------------------------------------------===// -// ProcessRemainingBatchesEvent -//===--------------------------------------------------------------------===// -class ProcessRemainingBatchesTask : public ExecutorTask { -public: - ProcessRemainingBatchesTask(Executor &executor, shared_ptr event_p, FixedBatchCopyGlobalState &state_p, - ClientContext &context, const PhysicalBatchCopyToFile &op) - : ExecutorTask(executor, std::move(event_p)), op(op), gstate(state_p), context(context) { - } - - TaskExecutionResult ExecuteTask(TaskExecutionMode mode) override { - while (op.ExecuteTask(context, gstate)) { - op.FlushBatchData(context, gstate); - } - event->FinishTask(); - return TaskExecutionResult::TASK_FINISHED; - } - - string TaskType() const override { - return "ProcessRemainingBatchesTask"; - } - -private: - const PhysicalBatchCopyToFile &op; - FixedBatchCopyGlobalState &gstate; - ClientContext &context; -}; - -class ProcessRemainingBatchesEvent : public BasePipelineEvent { -public: - ProcessRemainingBatchesEvent(const PhysicalBatchCopyToFile &op_p, FixedBatchCopyGlobalState &gstate_p, - Pipeline &pipeline_p, ClientContext &context) - : BasePipelineEvent(pipeline_p), op(op_p), gstate(gstate_p), context(context) { - } - const PhysicalBatchCopyToFile &op; - FixedBatchCopyGlobalState &gstate; - ClientContext &context; - -public: - void Schedule() override { - vector> tasks; - for (idx_t i = 0; i < TaskScheduler::GetScheduler(context).NumberOfThreads(); i++) { - auto process_task = - make_uniq(pipeline->executor, shared_from_this(), gstate, context, op); - tasks.push_back(std::move(process_task)); - } - D_ASSERT(!tasks.empty()); - SetTasks(std::move(tasks)); - } - - void FinishEvent() override { - //! Now that all batches are processed we finish flushing the file to disk - op.FinalFlush(context, gstate); - } -}; //===--------------------------------------------------------------------===// // Finalize //===--------------------------------------------------------------------===// SinkFinalizeType PhysicalBatchCopyToFile::FinalFlush(ClientContext &context, GlobalSinkState &gstate_p) const { auto &gstate = gstate_p.Cast(); - if (gstate.task_manager.TaskCount() != 0) { - throw InternalException("Unexecuted tasks are remaining in PhysicalFixedBatchCopy::FinalFlush!?"); - } - FlushBatchData(context, gstate_p); if (gstate.scheduled_batch_index != gstate.flushed_batch_index) { throw InternalException("Not all batches were flushed to disk - incomplete file?"); @@ -394,57 +304,41 @@ SinkFinalizeType PhysicalBatchCopyToFile::FinalFlush(ClientContext &context, Glo SinkFinalizeType PhysicalBatchCopyToFile::Finalize(Pipeline &pipeline, Event &event, ClientContext &context, OperatorSinkFinalizeInput &input) const { - auto &gstate = input.global_state.Cast(); - auto min_batch_index = idx_t(NumericLimits::Maximum()); - // repartition any remaining batches - RepartitionBatches(context, input.global_state, min_batch_index, true); - // check if we have multiple tasks to execute - if (gstate.task_manager.TaskCount() <= 1) { - // we don't - just execute the remaining task and finish flushing to disk - ExecuteTasks(context, input.global_state); - FinalFlush(context, input.global_state); - } else { - // we have multiple tasks remaining - launch an event to execute the tasks in parallel - auto new_event = make_shared_ptr(*this, gstate, pipeline, context); - event.InsertEvent(std::move(new_event)); - } - return SinkFinalizeType::READY; + RepartitionBatches(context, input.global_state, true); + return FinalFlush(context, input.global_state); } //===--------------------------------------------------------------------===// // Tasks //===--------------------------------------------------------------------===// -class RepartitionedFlushTask : public BatchCopyTask { -public: - RepartitionedFlushTask() { - } - - void Execute(const PhysicalBatchCopyToFile &op, ClientContext &context, GlobalSinkState &gstate_p) override { - op.FlushBatchData(context, gstate_p); - } -}; - -class PrepareBatchTask : public BatchCopyTask { +class PrepareBatchTask : public BaseExecutorTask { public: - PrepareBatchTask(idx_t batch_index, unique_ptr batch_data_p) - : batch_index(batch_index), batch_data(std::move(batch_data_p)) { + PrepareBatchTask(TaskExecutor &executor, const PhysicalBatchCopyToFile &op, ClientContext &context, + FixedBatchCopyGlobalState &gstate, idx_t batch_index, unique_ptr batch_data) + : BaseExecutorTask(executor), op(op), context(context), gstate(gstate), batch_index(batch_index), + batch_data(std::move(batch_data)) { } - idx_t batch_index; - unique_ptr batch_data; - - void Execute(const PhysicalBatchCopyToFile &op, ClientContext &context, GlobalSinkState &gstate_p) override { - auto &gstate = gstate_p.Cast(); + void ExecuteTask() override { auto memory_usage = batch_data->memory_usage; const CopyFunctionBatchAnalyzer batch_analyzer(*batch_data->collection, op.batch_size, op.batch_size_bytes); auto prepared_batch = op.function.prepare_batch(context, *op.bind_data, *gstate.prepare_state.load(std::memory_order_acquire), std::move(batch_data->collection)); gstate.AddBatchData(batch_index, std::move(prepared_batch), memory_usage, batch_analyzer); - if (batch_index == gstate.flushed_batch_index) { - gstate.task_manager.AddTask(make_uniq()); - } + op.FlushBatchData(context, gstate); + } + + string TaskType() const override { + return "PrepareBatchTask"; } + +private: + const PhysicalBatchCopyToFile &op; + ClientContext &context; + FixedBatchCopyGlobalState &gstate; + idx_t batch_index; + unique_ptr batch_data; }; //===--------------------------------------------------------------------===// @@ -455,156 +349,136 @@ void PhysicalBatchCopyToFile::AddRawBatchData(ClientContext &context, GlobalSink auto &gstate = gstate_p.Cast(); // add the batch index to the set of raw batches - lock_guard l(gstate.lock); + annotated_lock_guard l(gstate.lock); auto entry = gstate.raw_batches.insert(make_pair(batch_index, std::move(raw_batch))); if (!entry.second) { throw InternalException("Duplicate batch index %llu encountered in PhysicalFixedBatchCopy", batch_index); } } -static bool CorrectSizeForBatch(const ColumnDataCollection &batch, const optional_idx &batch_size, - const optional_idx &batch_size_bytes) { - if (!batch_size.IsValid()) { - // no row target (only ROW_GROUP_SIZE_BYTES): the byte target alone decides - return CopyFunctionBatchAnalyzer(batch, batch_size, batch_size_bytes).IsAcceptable(); - } - if (batch_size.GetIndex() == 0) { - // a batch size of 0 indicates we are happy with any batch size - return true; - } - - const auto size_vector_diff = - NumericCast(batch.Count()) - NumericCast(batch_size.GetIndex()) / STANDARD_VECTOR_SIZE; - - int64_t size_bytes_vector_diff = 0; - if (batch_size_bytes.IsValid()) { - const auto size_bytes_overshoot = - NumericCast(batch.SizeInBytes()) - NumericCast(batch_size_bytes.GetIndex()); - const auto bytes_per_tuple = NumericCast(batch.SizeInBytes() / batch.Count()) + 1; - size_bytes_vector_diff = size_bytes_overshoot / bytes_per_tuple / STANDARD_VECTOR_SIZE; - } - - if (size_vector_diff == 0) { - // The row count diff is within one vector, OK if byte size overshot 2 vectors or less - return size_bytes_vector_diff <= 2; - } - - if (size_bytes_vector_diff == 0) { - // The byte size diff is within two vectors, OK if row count is low - return size_vector_diff <= 0; - } - - return false; -} - -void PhysicalBatchCopyToFile::RepartitionBatches(ClientContext &context, GlobalSinkState &gstate_p, idx_t min_index, - bool final) const { +void PhysicalBatchCopyToFile::RepartitionBatches(ClientContext &context, GlobalSinkState &gstate_p, bool final) const { auto &gstate = gstate_p.Cast(); - auto &task_manager = gstate.task_manager; - - // repartition batches until the min index is reached - lock_guard l(gstate.lock); - if (gstate.raw_batches.empty()) { + annotated_unique_lock guard(gstate.lock); + annotated_unique_lock repartition_guard(gstate.repartition_lock, std::try_to_lock); + if (!repartition_guard.owns_lock()) { + // The current assembler will pick up newly ready batches before releasing the state lock. + D_ASSERT(!final); return; } - if (!final) { - if (gstate.any_finished) { - // we only repartition in ::NextBatch if all threads are still busy processing batches - // otherwise we might end up repartitioning a lot of data with only a few threads remaining - // which causes erratic performance + TaskExecutor executor(context); + const auto max_tasks = + MinValue(TaskScheduler::GetScheduler(context).NumberOfThreads(), + gstate.memory_manager.AvailableMemory() / gstate.minimum_memory_per_thread + 1); + idx_t pending_tasks = 0; + auto schedule_batch = [&](unique_ptr batch) { + executor.ScheduleTask(make_uniq(executor, *this, context, gstate, + gstate.scheduled_batch_index++, std::move(batch))); + if (++pending_tasks >= max_tasks) { + executor.WorkOnTasks(); + FlushBatchData(context, gstate); + pending_tasks = 0; + } + }; + while (true) { + auto min_index = + final ? idx_t(NumericLimits::Maximum()) : gstate.memory_manager.GetMinimumBatchIndex(); + if (gstate.raw_batches.empty() || gstate.raw_batches.begin()->first >= min_index) { return; } - // if this is not the final flush we first check if we have enough data to merge past the batch threshold - idx_t candidate_rows = 0; - idx_t candidate_size_bytes = 0; - for (auto entry = gstate.raw_batches.begin(); entry != gstate.raw_batches.end(); entry++) { + if (!final) { + idx_t candidate_rows = 0; + idx_t candidate_size_bytes = 0; + for (auto &entry : gstate.raw_batches) { + if (entry.first >= min_index) { + break; + } + candidate_rows += entry.second->collection->Count(); + candidate_size_bytes += entry.second->collection->SizeInBytes(); + } + if (!CopyFunctionBatchAnalyzer(candidate_rows, candidate_size_bytes, batch_size, batch_size_bytes) + .MeetsFlushCriteria()) { + return; + } + } + // gather all collections we can repartition + idx_t max_batch_index = 0; + vector> raw_batches; + for (auto entry = gstate.raw_batches.begin(); entry != gstate.raw_batches.end();) { if (entry->first >= min_index) { - // we have exceeded the minimum batch break; } - candidate_rows += entry->second->collection->Count(); - candidate_size_bytes += entry->second->collection->SizeInBytes(); - } - const CopyFunctionBatchAnalyzer batch_analyzer(candidate_rows, candidate_size_bytes, batch_size, - batch_size_bytes); - if (!batch_analyzer.MeetsFlushCriteria()) { - // not enough rows/bytes - cancel! - return; - } - } - // gather all collections we can repartition - idx_t max_batch_index = 0; - vector> raw_batches; - for (auto entry = gstate.raw_batches.begin(); entry != gstate.raw_batches.end();) { - if (entry->first >= min_index) { - break; + max_batch_index = entry->first; + raw_batches.push_back(std::move(entry->second)); + entry = gstate.raw_batches.erase(entry); } - max_batch_index = entry->first; - raw_batches.push_back(std::move(entry->second)); - entry = gstate.raw_batches.erase(entry); - } - unique_ptr append_batch; - ColumnDataAppendState append_state; - CopyBatchSlicer batch_slicer(children[0].get().GetTypes(), batch_size_bytes); - // now perform the actual repartitioning - for (auto ¤t_batch : raw_batches) { - if (!append_batch) { - const CopyFunctionBatchAnalyzer batch_analyzer(*current_batch->collection, batch_size, batch_size_bytes); - if (batch_analyzer.IsAcceptable()) { - // the collection is ~approximately equal to the batch size (off by at most one vector) - // use it directly - task_manager.AddTask( - make_uniq(gstate.scheduled_batch_index++, std::move(current_batch))); - current_batch.reset(); - } else if (!batch_analyzer.MeetsFlushCriteria()) { - // the collection is smaller than the batch size - use it as a starting point - append_batch = std::move(current_batch); - current_batch.reset(); - } else { - // the collection is too large for a batch - we need to repartition - // create an empty collection - auto new_collection = make_uniq(context, children[0].get().GetTypes()); - new_collection->SetPartitionIndex(0); // Makes the buffer manager less likely to spill this data - append_batch = make_uniq(0U, std::move(new_collection)); + unique_ptr append_batch; + ColumnDataAppendState append_state; + CopyBatchSlicer batch_slicer(children[0].get().GetTypes(), batch_size_bytes); + guard.unlock(); + // now perform the actual repartitioning + for (auto ¤t_batch : raw_batches) { + if (!append_batch) { + const CopyFunctionBatchAnalyzer batch_analyzer(*current_batch->collection, batch_size, + batch_size_bytes); + if (batch_analyzer.MeetsFlushCriteria() && batch_analyzer.IsAcceptable()) { + // the collection is ~approximately equal to the batch size (off by at most one vector) + // use it directly + schedule_batch(std::move(current_batch)); + current_batch.reset(); + } else if (!batch_analyzer.MeetsFlushCriteria()) { + // the collection is smaller than the batch size - use it as a starting point + append_batch = std::move(current_batch); + current_batch.reset(); + } + if (append_batch) { + append_batch->collection->InitializeAppend(append_state); + } } - if (append_batch) { - append_batch->collection->InitializeAppend(append_state); + if (!current_batch) { + // we have consumed the collection already - no need to append + continue; } - } - if (!current_batch) { - // we have consumed the collection already - no need to append - continue; - } - auto ¤t_collection = *current_batch->collection; - append_batch->memory_usage += current_batch->memory_usage; - // iterate the collection while appending - for (auto &chunk : current_collection.Chunks()) { - idx_t offset = 0; - while (offset < chunk.size()) { - auto &slice = batch_slicer.Slice(chunk, offset, *append_batch->collection); - append_batch->collection->Append(append_state, slice); - const CopyFunctionBatchAnalyzer batch_analyzer(*append_batch->collection, batch_size, batch_size_bytes); - if (!batch_analyzer.MeetsFlushCriteria()) { - continue; // the collection is still under the desired batch size + auto ¤t_collection = *current_batch->collection; + // iterate the collection while appending + for (auto &chunk : current_collection.Chunks()) { + idx_t offset = 0; + while (offset < chunk.size()) { + if (!append_batch) { + auto new_collection = make_uniq(context, children[0].get().GetTypes()); + new_collection->SetPartitionIndex(0); // Makes the buffer manager less likely to spill this data + append_batch = make_uniq(0U, std::move(new_collection)); + append_batch->collection->InitializeAppend(append_state); + } + auto &slice = batch_slicer.Slice(chunk, offset, *append_batch->collection); + append_batch->collection->Append(append_state, slice); + auto allocation_size = append_batch->collection->AllocationSize(); + gstate.memory_manager.IncreaseUnflushedMemory(allocation_size - append_batch->memory_usage); + append_batch->memory_usage = allocation_size; + const CopyFunctionBatchAnalyzer batch_analyzer(*append_batch->collection, batch_size, + batch_size_bytes); + if (!batch_analyzer.MeetsFlushCriteria()) { + continue; // the collection is still under the desired batch size + } + // the collection is full - move it to the result + append_state.current_chunk_state.handles.clear(); + schedule_batch(std::move(append_batch)); + append_batch.reset(); } - // the collection is full - move it to the result and create a new one - task_manager.AddTask( - make_uniq(gstate.scheduled_batch_index++, std::move(append_batch))); - - auto new_collection = make_uniq(context, children[0].get().GetTypes()); - new_collection->SetPartitionIndex(0); // Makes the buffer manager less likely to spill this data - append_batch = make_uniq(0U, std::move(new_collection)); - append_batch->collection->InitializeAppend(append_state); } + auto memory_usage = current_batch->memory_usage; + current_batch.reset(); + gstate.memory_manager.ReduceUnflushedMemory(memory_usage); } - } - if (append_batch && append_batch->collection->Count() > 0) { - // if there are any remaining batches that are not filled up to the batch size - // AND this is not the final collection - // re-add it to the set of raw (to-be-merged) batches - if (final || CorrectSizeForBatch(*append_batch->collection, batch_size, batch_size_bytes)) { - task_manager.AddTask(make_uniq(gstate.scheduled_batch_index++, std::move(append_batch))); - } else { + if (final && append_batch && append_batch->collection->Count() > 0) { + append_state.current_chunk_state.handles.clear(); + schedule_batch(std::move(append_batch)); + append_batch.reset(); + } + executor.WorkOnTasks(); + FlushBatchData(context, gstate); + pending_tasks = 0; + guard.lock(); + if (append_batch && append_batch->collection->Count() > 0) { gstate.raw_batches[max_batch_index] = std::move(append_batch); } } @@ -618,7 +492,7 @@ void PhysicalBatchCopyToFile::FlushBatchData(ClientContext &context, GlobalSinkS // grab the flush lock - we can only call flush_batch with this lock // otherwise the data might end up in the wrong order { - lock_guard l(gstate.flush_lock); + annotated_lock_guard l(gstate.flush_lock); if (gstate.any_flushing) { return; } @@ -628,7 +502,7 @@ void PhysicalBatchCopyToFile::FlushBatchData(ClientContext &context, GlobalSinkS while (true) { unique_ptr batch_data; { - lock_guard l(gstate.lock); + annotated_lock_guard l(gstate.lock); if (gstate.batch_data.empty()) { // no batch data left to flush break; @@ -655,6 +529,8 @@ void PhysicalBatchCopyToFile::FlushBatchData(ClientContext &context, GlobalSinkS batch_data->prepared_data.reset(); memory_manager.ReduceUnflushedMemory(batch_data->memory_usage); gstate.flushed_batch_index++; + annotated_lock_guard guard(memory_manager.lock); + memory_manager.UnblockTasks(); } } @@ -684,24 +560,6 @@ void PhysicalBatchCopyToFile::RotateFile(ClientContext &context, GlobalSinkState gstate.OpenFile(context, *this); } -//===--------------------------------------------------------------------===// -// Tasks -//===--------------------------------------------------------------------===// -bool PhysicalBatchCopyToFile::ExecuteTask(ClientContext &context, GlobalSinkState &gstate_p) const { - auto &gstate = gstate_p.Cast(); - auto task = gstate.task_manager.GetTask(); - if (!task) { - return false; - } - task->Execute(*this, context, gstate_p); - return true; -} - -void PhysicalBatchCopyToFile::ExecuteTasks(ClientContext &context, GlobalSinkState &gstate_p) const { - while (ExecuteTask(context, gstate_p)) { - } -} - //===--------------------------------------------------------------------===// // Next Batch //===--------------------------------------------------------------------===// @@ -715,26 +573,13 @@ void PhysicalBatchCopyToFile::AddLocalBatch(ClientContext &context, GlobalSinkSt } // we finished processing this batch // start flushing data - auto min_batch_index = state.partition_info.min_batch_index.GetIndex(); // push the raw batch data into the set of unprocessed batches auto raw_batch = make_uniq(state.local_memory_usage, std::move(state.collection)); + state.append_state.current_chunk_state.handles.clear(); AddRawBatchData(context, gstate, state.batch_index.GetIndex(), std::move(raw_batch)); // attempt to repartition to our desired batch size - RepartitionBatches(context, gstate, min_batch_index); - // unblock tasks so they can help process batches (if any are blocked) - bool any_unblocked; - { - annotated_lock_guard guard(memory_manager.lock); - any_unblocked = memory_manager.UnblockTasks(); - } - // if any threads were unblocked they can pick up execution of the tasks - // otherwise we will execute a task and flush here - if (!any_unblocked) { - //! Execute a single repartition task - ExecuteTask(context, gstate); - //! Flush batch data to disk (if any is ready) - FlushBatchData(context, gstate); - } + memory_manager.UpdateMinBatchIndex(state.partition_info.min_batch_index.GetIndex()); + RepartitionBatches(context, gstate); } SinkNextBatchType PhysicalBatchCopyToFile::NextBatch(ExecutionContext &context, @@ -755,10 +600,11 @@ SinkNextBatchType PhysicalBatchCopyToFile::NextBatch(ExecutionContext &context, return SinkNextBatchType::READY; } -SinkNextBatchType PhysicalBatchCopyToFile::UpdateMinBatchIndex(ExecutionContext &, +SinkNextBatchType PhysicalBatchCopyToFile::UpdateMinBatchIndex(ExecutionContext &context, OperatorSinkNextBatchInput &input) const { auto &gstate = input.global_state.Cast(); gstate.memory_manager.UpdateMinBatchIndex(input.local_state.partition_info.min_batch_index.GetIndex()); + RepartitionBatches(context.client, gstate); return SinkNextBatchType::READY; } diff --git a/src/duckdb/src/execution/operator/persistent/physical_copy_to_file.cpp b/src/duckdb/src/execution/operator/persistent/physical_copy_to_file.cpp index 06359ade2..206d05939 100644 --- a/src/duckdb/src/execution/operator/persistent/physical_copy_to_file.cpp +++ b/src/duckdb/src/execution/operator/persistent/physical_copy_to_file.cpp @@ -5035,7 +5035,15 @@ SinkResultType PhysicalCopyToFile::Sink(ExecutionContext &context, DataChunk &ch idx_t offset = 0; while (offset < chunk.size()) { if (!lstate.batch) { - lstate.batch = make_uniq(context.client, expected_types); + if (!parallel && !per_thread_output) { + // a sequential copy sinks its pipelines (e.g. the children of a UNION ALL) one after another: + // continue the leftover of the previous pipeline, so that its rows are written before this one's + annotated_lock_guard guard(gstate.last_batch_lock); + lstate.batch = std::move(gstate.last_batch); + } + if (!lstate.batch) { + lstate.batch = make_uniq(context.client, expected_types); + } lstate.batch->InitializeAppend(lstate.batch_append_state); } auto &slice = lstate.batch_slicer->Slice(chunk, offset, *lstate.batch); diff --git a/src/duckdb/src/execution/operator/persistent/physical_export.cpp b/src/duckdb/src/execution/operator/persistent/physical_export.cpp index c211b317b..5e7523fff 100644 --- a/src/duckdb/src/execution/operator/persistent/physical_export.cpp +++ b/src/duckdb/src/execution/operator/persistent/physical_export.cpp @@ -52,6 +52,8 @@ static void WriteStringStreamToFile(FileSystem &fs, stringstream &ss, const stri auto handle = fs.OpenFile(path, FileFlags::FILE_FLAGS_WRITE | FileFlags::FILE_FLAGS_FILE_CREATE_NEW | FileLockType::WRITE_LOCK); fs.Write(*handle, (void *)ss_string.c_str(), NumericCast(ss_string.size())); + // Close explicitly: destroying the handle does not finalize a remote (e.g. S3 multipart) upload + handle->Close(); handle.reset(); } diff --git a/src/duckdb/src/execution/operator/persistent/physical_update.cpp b/src/duckdb/src/execution/operator/persistent/physical_update.cpp index bca524334..ac1872cc0 100644 --- a/src/duckdb/src/execution/operator/persistent/physical_update.cpp +++ b/src/duckdb/src/execution/operator/persistent/physical_update.cpp @@ -277,6 +277,9 @@ SinkResultType PhysicalUpdate::Sink(ExecutionContext &context, DataChunk &chunk, // The update chunk now contains exactly those rows that we are deleting. Vector del_row_ids(Vector::Ref(row_ids)); if (update_count != update_chunk.size()) { + // like an in-place update, check every match, also those that are not written + ConstraintState constraint_state(tableref, bound_constraints); + table.VerifyUpdateConstraints(constraint_state, context.client, update_chunk, columns); update_chunk.Slice(sel, update_count); del_row_ids.Slice(row_ids, sel, update_count); } diff --git a/src/duckdb/src/execution/operator/projection/physical_pivot.cpp b/src/duckdb/src/execution/operator/projection/physical_pivot.cpp index 86dc1bf44..c3fb71918 100644 --- a/src/duckdb/src/execution/operator/projection/physical_pivot.cpp +++ b/src/duckdb/src/execution/operator/projection/physical_pivot.cpp @@ -60,7 +60,8 @@ OperatorResultType PhysicalPivot::Execute(ExecutionContext &context, DataChunk & } // move the pivots to the given columns - for (idx_t r = 0; r < input.size(); r++) { + const auto row_count = input.size(); + for (idx_t r = 0; r < row_count; r++) { auto list = pivot_column_lists[r]; for (idx_t l = 0; l < list.length; l++) { // figure out the column value number of this list diff --git a/src/duckdb/src/execution/operator/projection/physical_tableinout_function.cpp b/src/duckdb/src/execution/operator/projection/physical_tableinout_function.cpp index bd24bb842..da76ca7ef 100644 --- a/src/duckdb/src/execution/operator/projection/physical_tableinout_function.cpp +++ b/src/duckdb/src/execution/operator/projection/physical_tableinout_function.cpp @@ -2,6 +2,8 @@ #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/execution/operator/projection/physical_tableinout_function.hpp" +#include + namespace duckdb { class TableInOutLocalState : public OperatorState { @@ -74,6 +76,22 @@ unique_ptr PhysicalTableInOutFunction::GetGlobalOperatorSta return std::move(result); } +ProgressData PhysicalTableInOutFunction::GetOperatorProgress(ClientContext &context, GlobalOperatorState &gstate_p, + const ProgressData upstream_progress) const { + if (!function.table_in_out_progress || !upstream_progress.IsValid()) { + return upstream_progress; + } + auto &gstate = gstate_p.Cast(); + auto percentage = function.table_in_out_progress(context, bind_data.get(), gstate.global_state.get()); + auto result = upstream_progress; + if (!std::isfinite(percentage) || percentage < 0.0 || percentage > 100.0) { + result.SetInvalid(); + return result; + } + result.done = MinValue(result.done, percentage / 100.0 * result.total); + return result; +} + void PhysicalTableInOutFunction::SetOrdinality(DataChunk &chunk, const optional_idx &ordinality_column_idx, const idx_t &ordinality_idx, const idx_t &ordinality) { D_ASSERT(ordinality_column_idx.IsValid()); diff --git a/src/duckdb/src/execution/operator/projection/physical_unnest.cpp b/src/duckdb/src/execution/operator/projection/physical_unnest.cpp index 63d860a1d..031bd1076 100644 --- a/src/duckdb/src/execution/operator/projection/physical_unnest.cpp +++ b/src/duckdb/src/execution/operator/projection/physical_unnest.cpp @@ -103,15 +103,16 @@ void UnnestOperatorState::PrepareInput(DataChunk &input, const vector unnest_lengths.size()) { - unnest_lengths.resize(list_data.size()); + const auto row_count = list_data.size(); + if (row_count > unnest_lengths.size()) { + unnest_lengths.resize(row_count); } - for (idx_t r = 0; r < list_data.size(); r++) { + for (idx_t r = 0; r < row_count; r++) { unnest_lengths[r] = 0; } for (idx_t col_idx = 0; col_idx < list_data.ColumnCount(); col_idx++) { auto &vector_data = list_vector_data[col_idx]; - for (idx_t r = 0; r < list_data.size(); r++) { + for (idx_t r = 0; r < row_count; r++) { auto current_idx = vector_data.sel->get_index(r); if (!vector_data.validity.RowIsValid(current_idx)) { continue; @@ -151,7 +152,8 @@ OperatorResultType PhysicalUnnest::ExecuteInternal(ExecutionContext &context, Da } // finished with all rows of this input chunk, reset - if (state.current_row >= input.size()) { + const auto row_count = input.size(); + if (state.current_row >= row_count) { state.ResetState(); return OperatorResultType::NEED_MORE_INPUT; } @@ -166,7 +168,7 @@ OperatorResultType PhysicalUnnest::ExecuteInternal(ExecutionContext &context, Da for (idx_t col_idx = 0; col_idx < state.list_data.ColumnCount(); col_idx++) { state.null_counts[col_idx] = 0; } - while (result_length < STANDARD_VECTOR_SIZE && state.current_row < input.size()) { + while (result_length < STANDARD_VECTOR_SIZE && state.current_row < row_count) { auto current_row_length = MinValue(STANDARD_VECTOR_SIZE - result_length, state.unnest_lengths[state.current_row] - state.list_position); diff --git a/src/duckdb/src/execution/operator/scan/physical_positional_scan.cpp b/src/duckdb/src/execution/operator/scan/physical_positional_scan.cpp index c799be588..2dc240966 100644 --- a/src/duckdb/src/execution/operator/scan/physical_positional_scan.cpp +++ b/src/duckdb/src/execution/operator/scan/physical_positional_scan.cpp @@ -1,48 +1,57 @@ #include "duckdb/execution/operator/scan/physical_positional_scan.hpp" -#include "duckdb/catalog/catalog_entry/table_catalog_entry.hpp" -#include "duckdb/common/string_util.hpp" -#include "duckdb/common/vector/flat_vector.hpp" -#include "duckdb/parallel/interrupt.hpp" -#include "duckdb/planner/expression/bound_conjunction_expression.hpp" -#include "duckdb/transaction/transaction.hpp" - -#include +#include "duckdb/common/vector/constant_vector.hpp" #include "duckdb/common/vector_operations/vector_operations.hpp" +#include "duckdb/execution/expression_executor.hpp" +#include "duckdb/execution/operator/projection/physical_projection.hpp" +#include "duckdb/parallel/interrupt.hpp" namespace duckdb { +static bool IsPositionalSource(const PhysicalOperator &op) { + return op.type == PhysicalOperatorType::TABLE_SCAN || op.type == PhysicalOperatorType::POSITIONAL_SCAN; +} + +bool PhysicalPositionalScan::IsSupportedInput(const PhysicalOperator &input) { + if (input.type == PhysicalOperatorType::PROJECTION) { + return input.children.size() == 1 && IsPositionalSource(input.children[0].get()) && input.ParallelOperator(); + } + return IsPositionalSource(input); +} + +static PhysicalOperator &GetPositionalSource(PhysicalOperator &input) { + return input.type == PhysicalOperatorType::PROJECTION ? input.children[0].get() : input; +} + PhysicalPositionalScan::PhysicalPositionalScan(PhysicalPlan &physical_plan, vector types, PhysicalOperator &left, PhysicalOperator &right) : PhysicalOperator(physical_plan, PhysicalOperatorType::POSITIONAL_SCAN, std::move(types), MaxValue(left.estimated_cardinality, right.estimated_cardinality)) { - // Manage the children ourselves - if (left.type == PhysicalOperatorType::TABLE_SCAN) { - child_tables.emplace_back(left); - } else if (left.type == PhysicalOperatorType::POSITIONAL_SCAN) { - auto &left_scan = left.Cast(); - child_tables = std::move(left_scan.child_tables); - } else { - throw InternalException("Invalid left input for PhysicalPositionalScan"); - } - - if (right.type == PhysicalOperatorType::TABLE_SCAN) { - child_tables.emplace_back(right); - } else if (right.type == PhysicalOperatorType::POSITIONAL_SCAN) { - auto &right_scan = right.Cast(); - auto &right_tables = right_scan.child_tables; - child_tables.reserve(child_tables.size() + right_tables.size()); - std::move(right_tables.begin(), right_tables.end(), std::back_inserter(child_tables)); - } else { - throw InternalException("Invalid right input for PhysicalPositionalScan"); - } + D_ASSERT(IsSupportedInput(left)); + D_ASSERT(IsSupportedInput(right)); + auto append_input = [&](PhysicalOperator &input) { + // A projection consumes the nested scan's rows before the outer scan pads its output. + if (input.type != PhysicalOperatorType::POSITIONAL_SCAN) { + inputs.emplace_back(input); + return; + } + auto &nested = input.Cast(); + if (inputs.empty()) { + inputs = std::move(nested.inputs); + return; + } + inputs.reserve(inputs.size() + nested.inputs.size()); + std::move(nested.inputs.begin(), nested.inputs.end(), std::back_inserter(inputs)); + }; + append_input(left); + append_input(right); } class PositionalScanGlobalSourceState : public GlobalSourceState { public: PositionalScanGlobalSourceState(ClientContext &context, const PhysicalPositionalScan &op) { - for (const auto &table : op.child_tables) { - global_states.emplace_back(table.get().GetGlobalSourceState(context)); + for (const auto &input : op.inputs) { + global_states.emplace_back(GetPositionalSource(input.get()).GetGlobalSourceState(context)); } } @@ -53,61 +62,67 @@ class PositionalScanGlobalSourceState : public GlobalSourceState { } }; -class PositionalTableScanner { +class PositionalInputScanner { public: - PositionalTableScanner(ExecutionContext &context, PhysicalOperator &table_p, GlobalSourceState &gstate_p) - : table(table_p), global_state(gstate_p), source_count(0), source_offset(0), exhausted(false) { - local_state = table.GetLocalSourceState(context, gstate_p); - source.Initialize(Allocator::Get(context.client), table.types); + PositionalInputScanner(ExecutionContext &context, PhysicalOperator &input, GlobalSourceState &global_state) + : scan(GetPositionalSource(input)), global_state(global_state), source_count(0), source_offset(0), + exhausted(false) { + local_state = scan.GetLocalSourceState(context, global_state); + auto &allocator = Allocator::Get(context.client); + if (input.type == PhysicalOperatorType::PROJECTION) { + auto &projection = input.Cast(); + projection_executor = make_uniq(context.client, projection.select_list); + unprojected.Initialize(allocator, scan.types); + projection.InitializeOutputChunk(allocator, source); + } else { + source.Initialize(allocator, scan.types); + } } idx_t Refill(ExecutionContext &context) { - if (source_offset >= source_count) { - if (!exhausted) { - source.Reset(); - source_count = 0; - - InterruptState interrupt_state; - OperatorSourceInput source_input {global_state, *local_state, interrupt_state}; - auto source_result = SourceResultType::HAVE_MORE_OUTPUT; - while (source_result == SourceResultType::HAVE_MORE_OUTPUT && source_count == 0) { - // TODO: this could as well just be propagated further, but for now iterating it is - source_result = table.GetData(context, source, source_input); - source_count = source.size(); - if (source_result == SourceResultType::BLOCKED) { - throw NotImplementedException( - "Unexpected interrupt from table Source in PositionalTableScanner refill"); - } - } - } - source_offset = 0; + if (source_offset < source_count) { + return source_count - source_offset; + } + source_offset = 0; + if (exhausted) { + return 0; } + auto &scan_chunk = projection_executor ? unprojected : source; + InterruptState interrupt_state; + OperatorSourceInput source_input {global_state, *local_state, interrupt_state}; + SourceResultType source_result; + do { + scan_chunk.Reset(); + source_result = scan.GetData(context, scan_chunk, source_input); + if (source_result == SourceResultType::BLOCKED) { + throw NotImplementedException("Unexpected interrupt from source in positional scan"); + } + source_count = scan_chunk.size(); + } while (!source_count && source_result == SourceResultType::HAVE_MORE_OUTPUT); - const auto available = source_count - source_offset; - if (!available) { - if (!exhausted) { - source.Reset(); - source_count = 0; - for (idx_t i = 0; i < source.ColumnCount(); ++i) { - auto &vec = source.data[i]; - ConstantVector::SetNull(vec, count_t(STANDARD_VECTOR_SIZE)); - } - exhausted = true; + if (!source_count) { + source.Reset(); + for (auto &vec : source.data) { + ConstantVector::SetNull(vec, count_t(STANDARD_VECTOR_SIZE)); } + exhausted = true; + } else if (projection_executor) { + // Only evaluate expressions on real input rows. CopyData pads the resulting columns. + source.Reset(); + projection_executor->Execute(unprojected, source); } - return available; + return source_count; } - idx_t CopyData(ExecutionContext &context, DataChunk &output, const idx_t count, const idx_t col_offset) { + idx_t CopyData(ExecutionContext &context, DataChunk &output, idx_t count, idx_t col_offset) { if (!source_offset && (source_count >= count || exhausted)) { - // Fast track: aligned and has enough data + // Reference an aligned chunk. for (idx_t i = 0; i < source.ColumnCount(); ++i) { output.data[col_offset + i].Reference(source.data[i]); } source_offset += count; } else { - // Copy data for (idx_t target_offset = 0; target_offset < count;) { const auto needed = count - target_offset; const auto available = exhausted ? needed : (source_count - source_offset); @@ -119,20 +134,20 @@ class PositionalTableScanner { } target_offset += copy_count; source_offset += copy_count; - Refill(context); + if (target_offset < count) { + Refill(context); + } } } - return source.ColumnCount(); } - ProgressData GetProgress(ClientContext &context) { - return table.GetProgress(context, global_state); - } - - PhysicalOperator &table; +private: + PhysicalOperator &scan; GlobalSourceState &global_state; unique_ptr local_state; + unique_ptr projection_executor; + DataChunk unprojected; DataChunk source; idx_t source_count; idx_t source_offset; @@ -143,14 +158,12 @@ class PositionalScanLocalSourceState : public LocalSourceState { public: PositionalScanLocalSourceState(ExecutionContext &context, PositionalScanGlobalSourceState &gstate, const PhysicalPositionalScan &op) { - for (size_t i = 0; i < op.child_tables.size(); ++i) { - auto &child = op.child_tables[i]; - auto &global_state = *gstate.global_states[i]; - scanners.emplace_back(make_uniq(context, child, global_state)); + for (idx_t i = 0; i < op.inputs.size(); ++i) { + scanners.emplace_back(make_uniq(context, op.inputs[i], *gstate.global_states[i])); } } - vector> scanners; + vector> scanners; }; unique_ptr PhysicalPositionalScan::GetLocalSourceState(ExecutionContext &context, @@ -166,36 +179,29 @@ SourceResultType PhysicalPositionalScan::GetDataInternal(ExecutionContext &conte OperatorSourceInput &input) const { auto &lstate = input.local_state.Cast(); - // Find the longest source block idx_t count = 0; for (auto &scanner : lstate.scanners) { count = MaxValue(count, scanner->Refill(context)); } - // All done? if (!count) { return SourceResultType::FINISHED; } - // Copy or reference the source columns idx_t col_offset = 0; for (auto &scanner : lstate.scanners) { col_offset += scanner->CopyData(context, output, count, col_offset); } - output.SetChildCardinality(count); return SourceResultType::HAVE_MORE_OUTPUT; } ProgressData PhysicalPositionalScan::GetProgress(ClientContext &context, GlobalSourceState &gstate_p) const { auto &gstate = gstate_p.Cast(); - ProgressData res; - - for (size_t t = 0; t < child_tables.size(); ++t) { - res.Add(child_tables[t].get().GetProgress(context, *gstate.global_states[t])); + for (idx_t i = 0; i < inputs.size(); ++i) { + res.Add(GetPositionalSource(inputs[i].get()).GetProgress(context, *gstate.global_states[i])); } - return res; } @@ -205,22 +211,21 @@ bool PhysicalPositionalScan::Equals(const PhysicalOperator &other_p) const { } auto &other = other_p.Cast(); - if (child_tables.size() != other.child_tables.size()) { + if (inputs.size() != other.inputs.size()) { return false; } - for (size_t i = 0; i < child_tables.size(); ++i) { - if (!child_tables[i].get().Equals(other.child_tables[i])) { + for (idx_t i = 0; i < inputs.size(); ++i) { + if (!inputs[i].get().Equals(other.inputs[i])) { return false; } } - return true; } vector> PhysicalPositionalScan::GetChildren() const { auto result = PhysicalOperator::GetChildren(); - for (auto &entry : child_tables) { - result.push_back(entry.get()); + for (const auto &input : inputs) { + result.emplace_back(input.get()); } return result; } diff --git a/src/duckdb/src/execution/operator/set/physical_recursive_cte_union.cpp b/src/duckdb/src/execution/operator/set/physical_recursive_cte_union.cpp index 184f09b95..f5d800528 100644 --- a/src/duckdb/src/execution/operator/set/physical_recursive_cte_union.cpp +++ b/src/duckdb/src/execution/operator/set/physical_recursive_cte_union.cpp @@ -22,6 +22,8 @@ struct RecursiveCTEDistinctPartition { //===--------------------------------------------------------------------===// RecursiveCTEUnionState::RecursiveCTEUnionState(ClientContext &context, const PhysicalRecursiveCTE &op) : RecursiveCTEState(context, op), intermediate_table(context, op.GetTypes()) { + // like the working table, so the iterations alternating between them never copy shared large list children + intermediate_table.EnableSharedListChildren(); if (!op.UnionAll()) { ht = make_uniq(context, BufferAllocator::Get(context), op.distinct_types); } @@ -43,6 +45,8 @@ class RecursiveCTEUnionLocalState : public LocalSinkState { : op(op), hashes(LogicalType::HASH), partition_hashes(LogicalType::HASH), dummy_addresses(LogicalType::POINTER), new_groups(STANDARD_VECTOR_SIZE) { output = make_uniq(context, op.GetTypes()); + // combined into the working or intermediate table, which share large list children + output->EnableSharedListChildren(); output->InitializeAppend(append_state); if (!op.UnionAll()) { partition_chunk.Initialize(Allocator::Get(context), op.GetTypes()); diff --git a/src/duckdb/src/execution/physical_operator.cpp b/src/duckdb/src/execution/physical_operator.cpp index 702e97fad..c739ad859 100644 --- a/src/duckdb/src/execution/physical_operator.cpp +++ b/src/duckdb/src/execution/physical_operator.cpp @@ -160,6 +160,11 @@ TableFunctionParallelism PhysicalOperator::SourceParallelism() const { return TableFunctionParallelism::SELF_MANAGED_PARALLELISM; } +ProgressData PhysicalOperator::GetOperatorProgress(ClientContext &context, GlobalOperatorState &gstate, + const ProgressData upstream_progress) const { + return upstream_progress; +} + ProgressData PhysicalOperator::GetProgress(ClientContext &context, GlobalSourceState &gstate) const { ProgressData res; res.SetInvalid(); diff --git a/src/duckdb/src/execution/physical_plan/plan_filter.cpp b/src/duckdb/src/execution/physical_plan/plan_filter.cpp index 62a3d5d7c..ed8475332 100644 --- a/src/duckdb/src/execution/physical_plan/plan_filter.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_filter.cpp @@ -5,6 +5,7 @@ #include "duckdb/planner/expression/bound_comparison_expression.hpp" #include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/planner/expression/bound_reference_expression.hpp" +#include "duckdb/planner/filter/expression_filter.hpp" #include "duckdb/planner/operator/logical_filter.hpp" #include "duckdb/planner/operator/logical_get.hpp" @@ -13,6 +14,11 @@ namespace duckdb { PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalFilter &op) { D_ASSERT(op.children.size() == 1); reference plan = CreatePlanRecursive(*op.children[0]); + for (idx_t i = 0; i < op.expressions.size(); i++) { + if (ExpressionFilter::IsOptionalExpression(*op.expressions[i])) { + op.expressions.erase_at(i--); + } + } if (!op.expressions.empty()) { // create a filter if there is anything to filter auto &filter = Make(plan.get().GetTypes(), std::move(op.expressions), op.estimated_cardinality); diff --git a/src/duckdb/src/execution/physical_plan/plan_get.cpp b/src/duckdb/src/execution/physical_plan/plan_get.cpp index 97464698d..5bd4dc6e0 100644 --- a/src/duckdb/src/execution/physical_plan/plan_get.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_get.cpp @@ -8,6 +8,7 @@ #include "duckdb/planner/expression/bound_cast_expression.hpp" #include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/planner/expression/bound_reference_expression.hpp" +#include "duckdb/planner/expression_iterator.hpp" #include "duckdb/planner/filter/expression_filter.hpp" #include "duckdb/planner/operator/logical_get.hpp" #include "duckdb/planner/expression/bound_conjunction_expression.hpp" @@ -15,7 +16,8 @@ namespace duckdb { -unique_ptr MoveTableFilters(TableFilterSet &table_filters) { +static unique_ptr MoveTableFilters(LogicalGet &get) { + auto &table_filters = get.table_filters; // create the table filter map auto table_filter_set = make_uniq(); for (auto &entry : table_filters) { @@ -23,6 +25,20 @@ unique_ptr MoveTableFilters(TableFilterSet &table_filters) { } for (const auto &filter : table_filters.GetMultiColumnFilters()) { const auto &expression_filter = ExpressionFilter::GetExpressionFilter(*filter, "MoveTableFilters"); + for (auto column : expression_filter.column_indexes) { + if (!column.IsValid() || column >= get.GetColumnIds().size()) { + throw InternalException("Multi-column filter column is out of range"); + } + } + // Validate the visible scan inputs; the private predicate references optional-function arguments. + ExpressionIterator::VisitExpression( + *expression_filter.expr, [&](const BoundReferenceExpression &ref) { + if (ref.Index() >= expression_filter.column_indexes.size() || + ref.GetReturnType() != + get.GetColumnType(get.GetColumnIndex(expression_filter.column_indexes[ref.Index()]))) { + throw InternalException("Multi-column filter input type does not match its scan column"); + } + }); table_filter_set->PushMultiColumnFilter(expression_filter.Copy()); } return table_filter_set; @@ -68,8 +84,8 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalGet &op) { } unique_ptr table_filters; - if (op.table_filters.HasFilters() || op.table_filters.HasMultiColumnFilters()) { - table_filters = MoveTableFilters(op.table_filters); + if (op.table_filters.HasAnyFilters()) { + table_filters = MoveTableFilters(op); } vector projection_indices; for (auto &projection_id : op.projection_ids) { @@ -117,8 +133,8 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalGet &op) { } unique_ptr table_filters; - if (op.table_filters.HasFilters() || op.table_filters.HasMultiColumnFilters()) { - table_filters = MoveTableFilters(op.table_filters); + if (op.table_filters.HasAnyFilters()) { + table_filters = MoveTableFilters(op); } if (op.function.dependency) { diff --git a/src/duckdb/src/execution/physical_plan/plan_positional_join.cpp b/src/duckdb/src/execution/physical_plan/plan_positional_join.cpp index 2bde1e3e7..02326eb08 100644 --- a/src/duckdb/src/execution/physical_plan/plan_positional_join.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_positional_join.cpp @@ -10,19 +10,8 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalPositionalJoin &op) { auto &left = CreatePlanRecursive(*op.children[0]); auto &right = CreatePlanRecursive(*op.children[1]); - switch (left.type) { - case PhysicalOperatorType::TABLE_SCAN: - case PhysicalOperatorType::POSITIONAL_SCAN: - switch (right.type) { - case PhysicalOperatorType::TABLE_SCAN: - case PhysicalOperatorType::POSITIONAL_SCAN: - return Make(op.types, left, right); - default: - break; - } - break; - default: - break; + if (PhysicalPositionalScan::IsSupportedInput(left) && PhysicalPositionalScan::IsSupportedInput(right)) { + return Make(op.types, left, right); } return Make(op.types, left, right, op.estimated_cardinality); } diff --git a/src/duckdb/src/execution/physical_plan/plan_recursive_cte.cpp b/src/duckdb/src/execution/physical_plan/plan_recursive_cte.cpp index 281e45ddf..05bd4079d 100644 --- a/src/duckdb/src/execution/physical_plan/plan_recursive_cte.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_recursive_cte.cpp @@ -25,6 +25,10 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalRecursiveCTE &op) { // Create the working_table that the PhysicalRecursiveCTE will use for evaluation. const auto &working_types = !op.key_targets.empty() && !op.union_all ? op.types : op.internal_types; auto working_table = make_shared_ptr(context, working_types); + if (op.key_targets.empty()) { + // rows carried or grown across iterations reference their large list children instead of copying them + working_table->EnableSharedListChildren(); + } // Add the ColumnDataCollection to the context of this PhysicalPlanGenerator recursive_cte_tables[op.table_index] = working_table; diff --git a/src/duckdb/src/execution/physical_plan/plan_window.cpp b/src/duckdb/src/execution/physical_plan/plan_window.cpp index cd48c63ad..c855e2274 100644 --- a/src/duckdb/src/execution/physical_plan/plan_window.cpp +++ b/src/duckdb/src/execution/physical_plan/plan_window.cpp @@ -8,6 +8,7 @@ #include "duckdb/optimizer/apply_functional_dependencies.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/expression_binder/base_select_binder.hpp" +#include "duckdb/planner/expression_iterator.hpp" #include "duckdb/planner/expression/bound_reference_expression.hpp" #include "duckdb/planner/expression/bound_window_expression.hpp" #include "duckdb/planner/operator/logical_window.hpp" @@ -92,8 +93,14 @@ ColumnBinding GetColumnBinding(const Expression &expr, const bindings_t &binding switch (expr.GetExpressionType()) { case ExpressionType::BOUND_COLUMN_REF: return expr.Cast().Binding(); - case ExpressionType::BOUND_REF: - return bindings.at(expr.Cast().Index()); + case ExpressionType::BOUND_REF: { + // Hoisted keys are not child columns + const auto index = expr.Cast().Index(); + if (index < bindings.size()) { + return bindings.at(index); + } + break; + } default: break; } @@ -193,6 +200,42 @@ bool HasDegenerateFrame(ClientContext &client, BoundWindowExpression &wexpr, con return case_i_iv; } +bool HoistVolatileKey(unique_ptr &key, const idx_t input_width, vector> &hoisted) { + if (!key->IsVolatile()) { + return false; + } + auto ref = make_uniq(key->GetReturnType(), input_width + hoisted.size()); + hoisted.emplace_back(std::move(key)); + key = std::move(ref); + return true; +} + +bool ReplaceKey(unique_ptr &expr, const Expression &key, const Expression &ref) { + if (expr->Equals(key)) { + expr = ref.Copy(); + return true; + } + bool replaced = false; + ExpressionIterator::EnumerateChildren( + *expr, [&](unique_ptr &child) { replaced = ReplaceKey(child, key, ref) || replaced; }); + return replaced; +} + +// RANGE boundaries are bound as offsets from a copy of the ordering key +void ReplaceRangeKey(const WindowBoundary boundary, unique_ptr &expr, const Expression &key, + const Expression &ref) { + switch (boundary) { + case WindowBoundary::EXPR_PRECEDING_RANGE: + case WindowBoundary::EXPR_FOLLOWING_RANGE: + break; + default: + return; + } + if (!ReplaceKey(expr, key, ref)) { + throw InternalException("Window RANGE boundary does not reference its volatile ordering key"); + } +} + }; // namespace PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalWindow &op) { @@ -218,6 +261,40 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalWindow &op) { const auto input_width = types.size() - op.expressions.size(); types.resize(input_width); + // Evaluate volatile keys exactly once per row by projecting them below the window operators + vector> hoisted; + for (auto &expr : op.expressions) { + auto &wexpr = expr->Cast(); + for (auto &partition : wexpr.PartitionsMutable()) { + HoistVolatileKey(partition, input_width, hoisted); + } + for (auto &order : wexpr.OrderByMutable()) { + if (!HoistVolatileKey(order.expression, input_width, hoisted)) { + continue; + } + const auto &key = *hoisted.back(); + ReplaceRangeKey(wexpr.WindowStart(), wexpr.StartExprMutable(), key, *order.expression); + ReplaceRangeKey(wexpr.WindowEnd(), wexpr.EndExprMutable(), key, *order.expression); + } + for (auto &order : wexpr.ArgOrdersMutable()) { + HoistVolatileKey(order.expression, input_width, hoisted); + } + } + if (!hoisted.empty()) { + vector> select_list; + for (idx_t i = 0; i < input_width; ++i) { + select_list.emplace_back(make_uniq(types[i], i)); + } + for (auto &key : hoisted) { + types.emplace_back(key->GetReturnType()); + select_list.emplace_back(std::move(key)); + } + auto &proj = Make(types, std::move(select_list), op.estimated_cardinality); + proj.children.push_back(plan); + plan = proj; + } + const auto input_types = types; + // Identify streaming windows, partitioned windows and degenerate frames (0,1) using Columns = vector; const bool enable_optimizer = Settings::Get(context); @@ -277,7 +354,7 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalWindow &op) { unordered_map projection_map; vector> window_expressions; idx_t special_count = 0; - auto output_pos = input_width; + auto output_pos = input_types.size(); auto &special_windows = streaming_windows.empty() ? partitioned_windows : streaming_windows; while (!blocking_windows.empty() || !special_windows.empty()) { const bool process_blocking = special_windows.empty(); @@ -389,7 +466,6 @@ PhysicalOperator &PhysicalPlanGenerator::CreatePlan(LogicalWindow &op) { } // Evaluate the degenerate functions as scalar window functions FunctionBinder binder(context); - const vector input_types(op.types.begin(), op.types.begin() + NumericCast(input_width)); for (const auto &expr_idx : degenerate_frames) { auto &wexpr = op.expressions[expr_idx]->Cast(); select_list[input_width + expr_idx] = binder.BindScalarWindowFunction(wexpr, input_types); diff --git a/src/duckdb/src/execution/radix_ht_adaptivity.cpp b/src/duckdb/src/execution/radix_ht_adaptivity.cpp index b5ff89e45..0e1ff96b6 100644 --- a/src/duckdb/src/execution/radix_ht_adaptivity.cpp +++ b/src/duckdb/src/execution/radix_ht_adaptivity.cpp @@ -37,7 +37,7 @@ bool RadixHTAdaptivity::TryGrow(RadixHTGlobalSinkState &gstate, RadixHTLocalSink const auto &adaptivity = ht.GetAdaptivityState(); const auto materialized_count = ht.GetMaterializedCount(); if (!adaptivity.HLLEnabled() || ht.Count() == materialized_count || - (gstate.spill_plan && gstate.StatePressureExceeded(ht))) { + (gstate.spill_plan && gstate.StatePressureExceeded(lstate))) { return false; } diff --git a/src/duckdb/src/execution/radix_partitioned_hashtable.cpp b/src/duckdb/src/execution/radix_partitioned_hashtable.cpp index a844cbfd4..82b03643e 100644 --- a/src/duckdb/src/execution/radix_partitioned_hashtable.cpp +++ b/src/duckdb/src/execution/radix_partitioned_hashtable.cpp @@ -18,6 +18,9 @@ #include "duckdb/storage/temporary_memory_manager.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/main/settings.hpp" +#include "duckdb/parallel/pipeline.hpp" + +#include namespace duckdb { @@ -210,7 +213,8 @@ void RadixHTGlobalSinkState::Destroy() { RadixHTConfig::RadixHTConfig(RadixHTGlobalSinkState &sink_p) : sink(sink_p), row_width(sink.radix_ht.GetLayout().GetRowWidth()), sink_capacity(SinkCapacity()), - sink_radix_bits(InitialSinkRadixBits(sink.number_of_threads)), maximum_sink_radix_bits(MaximumSinkRadixBits()) { + initial_sink_radix_bits(InitialSinkRadixBits(sink.number_of_threads)), sink_radix_bits(initial_sink_radix_bits), + maximum_sink_radix_bits(MaximumSinkRadixBits()) { static_assert(MAXIMUM_INITIAL_SINK_RADIX_BITS <= MAXIMUM_FINAL_SINK_RADIX_BITS, "Initial sink radix bits exceed the final limit"); static_assert(MAXIMUM_FINAL_SINK_RADIX_BITS <= RadixPartitioning::MAX_RADIX_BITS, @@ -222,11 +226,13 @@ void RadixHTConfig::ResetForNewIteration(const idx_t scheduled_workers) { // workers the scheduler actually assigns instead of the thread-count-sized default, down to a // single partition for serial iterations. SetRadixBits grows the configuration again when an // iteration carries enough data. - sink_radix_bits = InitialSinkRadixBits(MaxValue(scheduled_workers, 1)); + initial_sink_radix_bits = InitialSinkRadixBits(MaxValue(scheduled_workers, 1)); + sink_radix_bits = initial_sink_radix_bits; + materialized_rows = 0; } // Budget row blocks and optional heap or exported-state blocks across workers, with headroom for repartitioning. -static idx_t PartitioningBytesPerPartition(const RadixHTGlobalSinkState &sink) { +idx_t RadixHTConfig::PartitioningBytesPerPartition() const { const idx_t blocks_per_partition = sink.radix_ht.GetLayout().AllConstant() && !sink.spill_plan ? 2 : 4; return sink.number_of_threads * sink.block_alloc_size * blocks_per_partition; } @@ -236,7 +242,7 @@ void RadixHTConfig::SetRadixBits(const idx_t &radix_bits_p) { // Reserve extra partitions only for workers that have started sinking. const auto workers = MaxValue(MinValue(sink.number_of_threads, sink.active_threads.load()), 1); const auto reserve_bits = MinValue(requested_bits, RadixPartitioning::RadixBits(workers) - 1); - const auto required = RadixPartitioning::NumberOfPartitions(reserve_bits) * PartitioningBytesPerPartition(sink); + const auto required = RadixPartitioning::NumberOfPartitions(reserve_bits) * PartitioningBytesPerPartition(); auto &memory = *sink.temporary_memory_state; const auto should_reserve = [&](const idx_t bits) { return reserve_bits > bits && !sink.any_combined && !sink.external && required > memory.GetRemainingSize(); @@ -254,6 +260,89 @@ void RadixHTConfig::SetRadixBits(const idx_t &radix_bits_p) { SetRadixBitsInternal(MinValue(requested_bits, available_bits), false); } +void RadixHTConfig::ObserveMaterializedRows(LocalState &state, const GroupedAggregateHashTable &ht) { + if (sink.external || sink.any_combined) { + return; + } + const auto rows = ht.GetMaterializedCount(); + D_ASSERT(rows >= state.reported_materialized_rows); + materialized_rows.fetch_add(rows - state.reported_materialized_rows, std::memory_order_relaxed); + state.reported_materialized_rows = rows; +} + +void RadixHTConfig::AdaptToData(const GroupedAggregateHashTable &ht, optional_ptr pipeline) { + const auto &layout = ht.GetPartitionedData().GetLayout(); + auto data_size = ht.GetMaterializedCount() * layout.GetRowWidth(); + if (!layout.AllConstant() && ht.GetPartitionedData().PartitionCount() < sink.number_of_threads) { + // Include heap bytes when additional partitions can expose more parallelism. + data_size = ht.GetMaterializedSize(); + } + GrowForSize(data_size); + if (!sink.external && !sink.any_combined) { + GrowForParallelism(ht.GetRadixBits(), pipeline); + } +} + +void RadixHTConfig::GrowForSize(const idx_t data_size) { + // Earlier parallelism-driven growth must not lower the size-driven minimum. + auto bits = initial_sink_radix_bits; + const auto threshold = LossyNumericCast(BLOCK_FILL_FACTOR * static_cast(sink.block_alloc_size)); + while (bits < maximum_sink_radix_bits && (data_size >> bits) > threshold) { + bits += REPARTITION_RADIX_BITS; + } + const auto current_bits = GetRadixBits(); + if (bits > current_bits) { + SetRadixBits(MinValue(bits, current_bits + REPARTITION_RADIX_BITS)); + } +} + +void RadixHTConfig::GrowForParallelism(const idx_t local_radix_bits, optional_ptr pipeline) { + const auto rows = materialized_rows.load(std::memory_order_relaxed); + const auto workers = MaxValue(MinValue(sink.number_of_threads, sink.active_threads.load()), 1); + const auto bytes = static_cast(rows) * static_cast(row_width); + auto target = RadixBitsForWork(bytes, GetRadixBits(), workers); + if (pipeline && target > local_radix_bits && + RadixBitsForWork(bytes * MAXIMUM_WORK_ESTIMATE_MULTIPLIER, target, workers) > target) { + // Forecast only before a pending repartition, when it can avoid another copy later. + // Source progress can lead or lag this sink, so bound the extrapolation. + PipelineProgress progress; + pipeline->GetDetailedProgress(progress); + const auto &source = progress.source; + if (source.IsValid() && source.total > 0 && source.done > 0 && std::isfinite(source.total)) { + const auto estimated_bytes = bytes * MinValue(source.total / source.done, MAXIMUM_WORK_ESTIMATE_MULTIPLIER); + target = RadixBitsForWork(estimated_bytes, target, workers); + } + } + if (target > GetRadixBits()) { + SetRadixBits(target); + } +} + +idx_t RadixHTConfig::RadixBitsForWork(const double bytes, idx_t target, const idx_t workers) const { + const auto limit = MinValue(GetMaximumSinkRadixBits(), RadixPartitioning::RadixBits(workers) - 1); + const auto source_workers = + MinValue(static_cast(workers), MaxValue(bytes / MINIMUM_SOURCE_BYTES_PER_THREAD, 1)); + while (target < limit) { + const idx_t partitions = idx_t(1) << target; + const idx_t next = 2 * partitions; + if (static_cast(next) > source_workers) { + break; + } + // Compare shorter parallel combining with row copies and additional output buffers. + const auto saved = + FINALIZE_TO_COPY_COST_RATIO * (bytes / static_cast(partitions) - bytes / static_cast(next)); + const auto copy = bytes / static_cast(workers); + const auto buffers = static_cast(next - partitions) * + static_cast(PartitioningBytesPerPartition()) / + static_cast(2 * sink.number_of_threads); + if (saved <= copy + buffers) { + break; + } + target++; + } + return target; +} + bool RadixHTConfig::SetRadixBitsToExternal() { SetRadixBitsInternal(ExternalRadixBits(true), true); return sink.external; @@ -315,7 +404,7 @@ idx_t RadixHTConfig::ExternalRadixBits(const bool dynamic) const { // An unspillable arena cannot fund a larger partitioning working set. const auto use_reservation = dynamic && (sink.spill_plan || reservation <= sink.memory_limit); const auto memory_limit = use_reservation ? reservation : sink.memory_limit / 2; - const auto max_partitions = memory_limit / PartitioningBytesPerPartition(sink); + const auto max_partitions = memory_limit / PartitioningBytesPerPartition(); // Compute number of bits, rounded down, at least as much as initial bits const auto bits = @@ -392,6 +481,7 @@ void RadixHTLocalSinkState::ResetForReuse(const RadixPartitionedHashTable &radix } registered = false; spilling = false; + partitioning = RadixHTConfig::LocalState(); size_after_abandon = 0; adaptivity.Reset(); abandoned_data.reset(); @@ -521,6 +611,7 @@ void GrowExportedData(ClientContext &context, RadixHTGlobalSinkState &gstate, source.InitializeScan(scan_state, ColumnDataScanProperties::DISALLOW_ZERO_COPY); SelectionVector sel(STANDARD_VECTOR_SIZE); while (source.Scan(scan_state, chunk)) { + context.FastInterruptCheck(); const auto count = chunk.size(); const auto hashes = FlatVector::GetData(chunk.data[hash_col_idx]); for (idx_t target = 0; target < fan_out; target++) { @@ -605,9 +696,23 @@ void ExportAbandonedData(ClientContext &context, RadixHTGlobalSinkState &gstate, MemoryTag::HASH_TABLE, radix_bits, hash_col_idx, context); } -bool RadixHTGlobalSinkState::StatePressureExceeded(GroupedAggregateHashTable &ht) const { - return ht.GetAggregateAllocator()->AllocationSize() > - GetThreadLimit() / RadixHTConfig::AGGREGATE_STATE_PRESSURE_DIVISOR; +// The arena at the next check. Until this thread spills, the next chunk can start one more arena block. Once it spills, +// the arena gets a share of the thread limit, leaving the rest to the spilled data. +static idx_t ArenaDemand(const RadixHTLocalSinkState &lstate) { + auto &ht = *lstate.ht; + const auto arena_size = ht.GetAggregateAllocator()->AllocationSize(); + if (lstate.spilling) { + return arena_size * RadixHTConfig::AGGREGATE_STATE_PRESSURE_DIVISOR; + } + if (ht.GetMaterializedCount() == 0) { + // Combine moved the rows out, no more chunks follow + return arena_size; + } + return arena_size + MinValue(arena_size, ArenaAllocator::ARENA_ALLOCATOR_MAX_CAPACITY); +} + +bool RadixHTGlobalSinkState::StatePressureExceeded(const RadixHTLocalSinkState &lstate) const { + return ArenaDemand(lstate) > GetThreadLimit(); } idx_t RadixHTGlobalSinkState::SpillableSize(GroupedAggregateHashTable &ht) const { @@ -625,7 +730,7 @@ bool ShouldExportStates(RadixHTGlobalSinkState &gstate, RadixHTLocalSinkState &l // every current state is inline, and exporting would only cost return false; } - if (gstate.force_external || gstate.StatePressureExceeded(ht) || !lstate.abandoned_exported_data.empty()) { + if (gstate.force_external || gstate.StatePressureExceeded(lstate) || !lstate.abandoned_exported_data.empty()) { return true; } if (!gstate.external) { @@ -649,7 +754,7 @@ bool MemoryPressure(RadixHTGlobalSinkState &gstate, RadixHTLocalSinkState &lstat idx_t total_size) { const auto thread_limit = gstate.GetThreadLimit(); if (gstate.spill_plan) { - return total_size > thread_limit || gstate.StatePressureExceeded(ht); + return total_size > thread_limit || gstate.StatePressureExceeded(lstate); } if (total_size <= thread_limit) { return false; @@ -666,13 +771,11 @@ bool MemoryPressure(RadixHTGlobalSinkState &gstate, RadixHTLocalSinkState &lstat return spillable_size > lstate.size_after_abandon + growth_limit / RadixHTConfig::AGGREGATE_STATE_SPILL_DIVISOR; } -void UpdateSinkReservation(ClientContext &context, RadixHTGlobalSinkState &gstate, GroupedAggregateHashTable &ht, +void UpdateSinkReservation(ClientContext &context, RadixHTGlobalSinkState &gstate, RadixHTLocalSinkState &lstate, idx_t total_size) { + auto &ht = *lstate.ht; // Include the headroom required by the arena's export threshold. - const auto required_size = gstate.spill_plan - ? MaxValue(total_size, ht.GetAggregateAllocator()->AllocationSize() * - RadixHTConfig::AGGREGATE_STATE_PRESSURE_DIVISOR) - : total_size; + const auto required_size = gstate.spill_plan ? MaxValue(total_size, ArenaDemand(lstate)) : total_size; if (required_size <= gstate.GetThreadLimit() || gstate.external) { return; } @@ -694,11 +797,12 @@ void UpdateSinkReservation(ClientContext &context, RadixHTGlobalSinkState &gstat } void MaybeRepartition(ClientContext &context, RadixHTGlobalSinkState &gstate, RadixHTLocalSinkState &lstate, - const bool combine) { + const bool combine, optional_ptr pipeline = nullptr) { auto &config = gstate.config; auto &ht = *lstate.ht; const auto total_size = ht.GetSizeInBytes(); - UpdateSinkReservation(context, gstate, ht, total_size); + UpdateSinkReservation(context, gstate, lstate, total_size); + config.ObserveMaterializedRows(lstate.partitioning, ht); if (gstate.SpillableSize(ht) > SpillableLimit(gstate, ht)) { if (gstate.config.SetRadixBitsToExternal()) { @@ -726,19 +830,7 @@ void MaybeRepartition(ClientContext &context, RadixHTGlobalSinkState &gstate, Ra const auto current_radix_bits = RadixPartitioning::RadixBitsOfPowerOfTwo(partition_count); D_ASSERT(current_radix_bits <= config.GetRadixBits()); - const auto &layout = ht.GetPartitionedData().GetLayout(); - auto data_size = ht.GetMaterializedCount() * layout.GetRowWidth(); - if (!layout.AllConstant() && partition_count < gstate.number_of_threads) { - // Include heap bytes when additional partitions can expose more parallelism. - data_size = ht.GetMaterializedSize(); - } - const auto size_per_partition = data_size / partition_count; - if (size_per_partition > - LossyNumericCast(config.BLOCK_FILL_FACTOR * static_cast(gstate.block_alloc_size))) { - // We crossed our block filling threshold, try to increment radix bits - config.SetRadixBits(current_radix_bits + config.REPARTITION_RADIX_BITS); - } - + config.AdaptToData(ht, pipeline); const auto global_radix_bits = config.GetRadixBits(); if (current_radix_bits == global_radix_bits) { return; // We're already on the right number of radix bits @@ -776,7 +868,7 @@ void RadixPartitionedHashTable::Sink(ExecutionContext &context, DataChunk &chunk // Row width and aggregate state size can increase without filling the pointer table. const auto total_size = ht.GetSizeInBytes(); - UpdateSinkReservation(context.client, gstate, ht, total_size); + UpdateSinkReservation(context.client, gstate, lstate, total_size); const auto memory_pressure = MemoryPressure(gstate, lstate, ht, total_size); if (!memory_pressure && ht.Count() + STANDARD_VECTOR_SIZE < GroupedAggregateHashTable::ResizeThreshold(lstate.local_sink_capacity)) { @@ -791,7 +883,7 @@ void RadixPartitionedHashTable::Sink(ExecutionContext &context, DataChunk &chunk // Check if we need to repartition const auto radix_bits_before = ht.GetRadixBits(); - MaybeRepartition(context.client, gstate, lstate, false); + MaybeRepartition(context.client, gstate, lstate, false, context.pipeline); const auto repartitioned = radix_bits_before != ht.GetRadixBits(); if (repartitioned && ht.Count() != 0) { @@ -884,15 +976,25 @@ void RadixPartitionedHashTable::Combine(ExecutionContext &context, GlobalSinkSta ht.GetAggregateAllocator()->FreeAll(); } + while (lstate.abandoned_data) { + unique_ptr previous; + { + const annotated_lock_guard guard {gstate.lock}; + if (!gstate.uncombined_data) { + gstate.uncombined_data = std::move(lstate.abandoned_data); + break; + } + previous = std::move(gstate.uncombined_data); + } + // Append the smaller input while both collections are exclusively owned. + if (previous->Count() > lstate.abandoned_data->Count()) { + previous.swap(lstate.abandoned_data); + } + lstate.abandoned_data->Combine(*previous); + } auto aggregate_allocator = ht.GetAggregateAllocator(); - const annotated_lock_guard guard {gstate.lock}; D_ASSERT(!gstate.finalized); - if (gstate.uncombined_data) { - gstate.uncombined_data->Combine(*lstate.abandoned_data); - } else { - gstate.uncombined_data = std::move(lstate.abandoned_data); - } if (!lstate.abandoned_exported_data.empty()) { if (gstate.uncombined_exported_data.empty()) { gstate.uncombined_exported_data = std::move(lstate.abandoned_exported_data); @@ -1307,7 +1409,10 @@ void RadixHTLocalSourceState::Scan(RadixHTGlobalSinkState &sink, RadixHTGlobalSo if (!data_collection.Scan(scan_state, scan_chunk)) { if (sink.scan_pin_properties == TupleDataPinProperties::DESTROY_AFTER_DONE) { - data_collection.Reset(); + // This partition will not be scanned again. Release its metadata here instead of + // retaining reusable capacity until the global state is destroyed. + scan_state.Reset(); + partition.data.reset(); partition.allocator.reset(); partition.import_allocator.reset(); } @@ -1346,6 +1451,10 @@ void RadixHTLocalSourceState::Scan(RadixHTGlobalSinkState &sink, RadixHTGlobalSo chunk.data[radix_ht.op.GroupCount() + radix_ht.op.aggregates.size() + i].Reference(radix_ht.grouping_values[i], count_t(scan_chunk.size())); } + if (chunk.ColumnCount() == 0) { + // Empty grouping sets can produce rows without any output vectors to carry their cardinality. + chunk.SetChildCardinality(scan_chunk.size()); + } D_ASSERT(chunk.size() != 0); } diff --git a/src/duckdb/src/execution/sample/reservoir_sample.cpp b/src/duckdb/src/execution/sample/reservoir_sample.cpp index da5bf2da7..941ed048c 100644 --- a/src/duckdb/src/execution/sample/reservoir_sample.cpp +++ b/src/duckdb/src/execution/sample/reservoir_sample.cpp @@ -607,7 +607,12 @@ SelectionVectorHelper ReservoirSample::GetReplacementIndexes(idx_t sample_chunk_ SelectionVectorHelper ReservoirSample::GetReplacementIndexesFast(idx_t sample_chunk_offset, idx_t chunk_length) { // how much weight to the other tuples have compared to the ones in this chunk? auto weight_tuples_other = static_cast(chunk_length) / static_cast(GetTuplesSeen() + chunk_length); - auto num_to_pop = static_cast(round(weight_tuples_other * static_cast(sample_count))); + auto expected_to_pop = weight_tuples_other * static_cast(sample_count); + // round stochastically so the expected number of replacements stays exact + auto num_to_pop = static_cast(expected_to_pop); + if (base_reservoir_sample->random.NextRandom() < expected_to_pop - static_cast(num_to_pop)) { + num_to_pop++; + } D_ASSERT(num_to_pop <= sample_count); D_ASSERT(num_to_pop <= sel_size); SelectionVectorHelper ret; @@ -640,7 +645,8 @@ SelectionVectorHelper ReservoirSample::GetReplacementIndexesFast(idx_t sample_ch SelectionVectorHelper ReservoirSample::GetReplacementIndexesSlow(const idx_t sample_chunk_offset, const idx_t chunk_length) { idx_t remaining = chunk_length; - std::unordered_map ret_map; + // allocated on the first replacement, with room for every input row + SelectionVector ret_sel; idx_t sample_chunk_index = 0; idx_t base_offset = 0; @@ -654,9 +660,10 @@ SelectionVectorHelper ReservoirSample::GetReplacementIndexesSlow(const idx_t sam break; } // in this chunk! replace the element - // ret[index_in_new_chunk] = index_in_sample_chunk (the sample chunk offset will be applied later) - // D_ASSERT(sample_chunk_index == ret.size()); - ret_map[base_offset + offset] = sample_chunk_index; + if (!ret_sel.IsSet()) { + ret_sel.Initialize(chunk_length); + } + ret_sel.set_index(sample_chunk_index, base_offset + offset); double r2 = base_reservoir_sample->random.NextRandom32(base_reservoir_sample->min_weight_threshold, 1); // replace element in our max_heap // first get the top most pair @@ -667,20 +674,15 @@ SelectionVectorHelper ReservoirSample::GetReplacementIndexesSlow(const idx_t sam base_reservoir_sample->ReplaceElementWithIndex(index, r2, false); sample_chunk_index += 1; - // shift the chunk forward - remaining -= offset; - base_offset += offset; + // resume after the replaced element, so the next gap starts at the following row + remaining -= offset + 1; + base_offset += offset + 1; } - // create selection vector to return - SelectionVector ret_sel(ret_map.size()); D_ASSERT(sel_size == sample_count); - for (auto &kv : ret_map) { - ret_sel.set_index(kv.second, kv.first); - } SelectionVectorHelper ret; ret.sel = SelectionVector(ret_sel); - ret.size = static_cast(ret_map.size()); + ret.size = static_cast(sample_chunk_index); return ret; } diff --git a/src/duckdb/src/function/aggregate/distributive/decimal_avg.cpp b/src/duckdb/src/function/aggregate/distributive/decimal_avg.cpp index 4fc90abd8..3780370ed 100644 --- a/src/duckdb/src/function/aggregate/distributive/decimal_avg.cpp +++ b/src/duckdb/src/function/aggregate/distributive/decimal_avg.cpp @@ -172,7 +172,7 @@ static void WideDecimalAvgExportState(Vector &state_vector, AggregateFinalizeInp static void WideDecimalAvgImportState(AggregateImportInputData &input) { auto entries = input.input_vec.Values>(); - for (idx_t i = 0; i < input.input_vec.size(); i++) { + for (idx_t i = 0; i < entries.size(); i++) { auto &state = *reinterpret_cast(input.dest_buffer + i * input.layout.total_state_size); BignumAvgOperation::Initialize(state); const auto entry = entries[i]; diff --git a/src/duckdb/src/function/cast/cast_function_set.cpp b/src/duckdb/src/function/cast/cast_function_set.cpp index d852f8fb2..d1ea1571a 100644 --- a/src/duckdb/src/function/cast/cast_function_set.cpp +++ b/src/duckdb/src/function/cast/cast_function_set.cpp @@ -67,6 +67,7 @@ BoundCastInfo BindCastInput::GetCastFunction(const LogicalType &source, const Lo input.query_location = query_location; auto result = function_set.GetCastFunction(source, target, input); stability = LeastStable(stability, result.GetStability()); + fallible = fallible || result.IsFallible(); return result; } @@ -74,8 +75,16 @@ BindCastFunction::BindCastFunction(bind_cast_function_t function_p, unique_ptr CopyDefaultCombineTypesRules() { + vector rules; + for (auto &rule : DefaultCombineTypesRules()) { + rules.push_back(rule); + } + return rules; +} + CastFunctionSet::CastFunctionSet() - : default_bind_function(DefaultCasts::GetDefaultCastFunction), combine_rules(DefaultCombineTypesRules()), + : default_bind_function(DefaultCasts::GetDefaultCastFunction), combine_rules(CopyDefaultCombineTypesRules()), map_info(nullptr) { } @@ -124,6 +133,10 @@ BoundCastInfo CastFunctionSet::GetCastFunction(const LogicalType &source, const input.query_location = get_input.query_location; auto result = bind_function.function(input, source, target); result.SetStability(LeastStable(result.GetStability(), input.stability)); + // a cast from VARIANT selects the cast of each value when it runs, which can be a registered one + if (input.fallible || (source.id() == LogicalTypeId::VARIANT && !registered_bind_functions.empty())) { + result.SetFallible(); + } return result; }; @@ -155,9 +168,15 @@ struct MapCastNode { MapCastNode(bind_cast_function_t func, int64_t implicit_cast_cost) : cast_info(nullptr), bind_function(func), implicit_cast_cost(implicit_cast_cost) { } + MapCastNode(bind_cast_function_t func, shared_ptr bind_info, int64_t implicit_cast_cost) + : cast_info(nullptr), bind_function(func), bind_info(std::move(bind_info)), + implicit_cast_cost(implicit_cast_cost) { + } BoundCastInfo cast_info; bind_cast_function_t bind_function; + //! Per-cast info, visible as input.info while bind_function runs + shared_ptr bind_info; int64_t implicit_cast_cost; }; @@ -342,7 +361,20 @@ static BoundCastInfo MapCastFunction(BindCastInput &input, const LogicalType &so auto entry = map_info.GetEntry(source, target); if (entry) { if (entry->bind_function) { - return entry->bind_function(input, source, target); + if (!entry->bind_info) { + return entry->bind_function(input, source, target); + } + // the outer info is restored afterwards, also when the bind function throws + auto outer_info = input.info; + input.info = entry->bind_info.get(); + try { + auto result = entry->bind_function(input, source, target); + input.info = outer_info; + return result; + } catch (...) { + input.info = outer_info; + throw; + } } return entry->cast_info.Copy(); } @@ -359,6 +391,12 @@ void CastFunctionSet::RegisterCastFunction(const LogicalType &source, const Logi RegisterCastFunction(source, target, MapCastNode(bind_function, implicit_cast_cost)); } +void CastFunctionSet::RegisterCastFunction(const LogicalType &source, const LogicalType &target, + bind_cast_function_t bind_function, shared_ptr bind_info, + int64_t implicit_cast_cost) { + RegisterCastFunction(source, target, MapCastNode(bind_function, std::move(bind_info), implicit_cast_cost)); +} + void CastFunctionSet::RegisterCastFunction(const LogicalType &source, const LogicalType &target, MapCastNode node) { if (!map_info) { // create the cast map and the cast map function @@ -373,7 +411,7 @@ void CastFunctionSet::RegisterCombineTypesRule(CombineTypesRule rule) { combine_rules.insert(combine_rules.begin(), rule); // newest extension first, ahead of built-ins } -bool CastFunctionSet::TryCombineTypes(const vector &rules, LogicalTypeResolver &resolver, +bool CastFunctionSet::TryCombineTypes(array_ptr rules, LogicalTypeResolver &resolver, const LogicalType &left, const LogicalType &right, LogicalType &result, bool &success) { // first matching rule wins @@ -388,7 +426,8 @@ bool CastFunctionSet::TryCombineTypes(const vector &rules, Log bool CastFunctionSet::TryCombineTypes(LogicalTypeResolver &resolver, const LogicalType &left, const LogicalType &right, LogicalType &result, bool &success) { - return TryCombineTypes(combine_rules, resolver, left, right, result, success); + return TryCombineTypes(array_ptr(combine_rules.data(), combine_rules.size()), resolver, + left, right, result, success); } } // namespace duckdb diff --git a/src/duckdb/src/function/cast/default_casts.cpp b/src/duckdb/src/function/cast/default_casts.cpp index 85fbd4dde..cca9a8ac7 100644 --- a/src/duckdb/src/function/cast/default_casts.cpp +++ b/src/duckdb/src/function/cast/default_casts.cpp @@ -44,6 +44,7 @@ BoundCastInfo BoundCastInfo::Copy() const { auto result = BoundCastInfo(function, cast_data ? cast_data->Copy() : nullptr, init_local_state); result.statistics = statistics; result.stability = stability; + result.fallible = fallible; return result; } diff --git a/src/duckdb/src/function/cast/nested_to_varchar_cast.cpp b/src/duckdb/src/function/cast/nested_to_varchar_cast.cpp index 97923ecfe..9569ed805 100644 --- a/src/duckdb/src/function/cast/nested_to_varchar_cast.cpp +++ b/src/duckdb/src/function/cast/nested_to_varchar_cast.cpp @@ -144,9 +144,13 @@ void NestedToVarcharCast::WrapChildCast(BoundCastInfo &child_cast, const Logical return; } auto stability = child_cast.GetStability(); + auto fallible = child_cast.IsFallible(); child_cast = BoundCastInfo(QuotedChildCast, make_uniq(std::move(child_cast), child_type), InitQuotedChildLocalState); child_cast.SetStability(stability); + if (fallible) { + child_cast.SetFallible(); + } } } // namespace duckdb diff --git a/src/duckdb/src/function/cast/union_casts.cpp b/src/duckdb/src/function/cast/union_casts.cpp index ea82ac601..b65316876 100644 --- a/src/duckdb/src/function/cast/union_casts.cpp +++ b/src/duckdb/src/function/cast/union_casts.cpp @@ -118,6 +118,7 @@ static unique_ptr BindToUnionMemberCast(BindCastInput &input, con // otherwise, return the selected cast, which is the only member cast that is applied input.stability = candidates[0].member_casts[0].GetStability(); + input.fallible = candidates[0].member_casts[0].IsFallible(); return make_uniq(std::move(candidates[0])); } diff --git a/src/duckdb/src/function/cast/variant/from_variant.cpp b/src/duckdb/src/function/cast/variant/from_variant.cpp index ecdecd919..9374a04a4 100644 --- a/src/duckdb/src/function/cast/variant/from_variant.cpp +++ b/src/duckdb/src/function/cast/variant/from_variant.cpp @@ -12,6 +12,8 @@ #include "duckdb/common/types/variant.hpp" #include "duckdb/common/type_visitor.hpp" #include "duckdb/common/types/variant_visitor.hpp" +#include "duckdb/common/types/variant_iterator.hpp" +#include "duckdb/common/types/variant_writer.hpp" #include "duckdb/function/cast/cast_function_set.hpp" #include "duckdb/function/scalar/variant_utils.hpp" #include "duckdb/common/serializer/varint.hpp" @@ -557,6 +559,11 @@ static void VerifyVarcharSerialization(FromVariantConversionData &conversion_dat } #endif +//! Whether the type holds an alias, which VARIANT does not preserve (including JSON in nested types) +static bool ContainsAlias(const LogicalType &type) { + return TypeVisitor::Contains(type, [](const LogicalType &child) { return child.HasAlias(); }); +} + static bool HasVarcharCastOverride(FromVariantConversionData &conversion_data) { if (conversion_data.varchar_cast_override) { return *conversion_data.varchar_cast_override; @@ -567,8 +574,7 @@ static bool HasVarcharCastOverride(FromVariantConversionData &conversion_data) { } auto &casts = CastFunctionSet::Get(*conversion_data.client); for (auto &type : casts.GetRegisteredCastSourceTypes(LogicalType::VARCHAR)) { - // VARIANT does not preserve aliases, including JSON in nested types. - if (TypeVisitor::Contains(type, [](const LogicalType &child) { return child.HasAlias(); })) { + if (ContainsAlias(type)) { continue; } switch (type.id()) { @@ -1307,18 +1313,124 @@ static bool TryFromShreddedCast(Vector &variant_vec, Vector &result) { return false; } +//! Whether the row is a SQL NULL or a VARIANT null +static bool IsNullVariant(const VectorIterator &variants, idx_t row) { + return variants[row].GetTypeId() == LogicalTypeId::SQLNULL; +} + +//! Writes the element, a VARIANT null as a SQL NULL +static void WriteVariantElement(VectorWriter &writer, const VariantNode &element) { + if (element.GetTypeId() == LogicalTypeId::SQLNULL) { + writer.WriteNull(); + } else { + writer.WriteValue(element); + } +} + +static void CopyToVariantList(const VectorIterator &variants, Vector &result, idx_t count) { + auto writer = FlatVector::Writer>(result, count); + for (idx_t row = 0; row < count; row++) { + if (IsNullVariant(variants, row)) { + writer.WriteNull(); + continue; + } + auto elements = variants[row].GetArrayChildren(); + idx_t element_idx = 0; + for (auto &element_writer : writer.WriteList(elements.size())) { + WriteVariantElement(element_writer, elements[element_idx++]); + } + } +} + +static void CopyToVariantArray(const VectorIterator &variants, Vector &result, idx_t count) { + auto array_size = ArrayType::GetSize(result.GetType()); + auto writer = FlatVector::Writer(ArrayVector::GetChildMutable(result), count * array_size); + auto &validity = FlatVector::ValidityMutable(result); + for (idx_t row = 0; row < count; row++) { + if (IsNullVariant(variants, row)) { + validity.SetInvalid(row); + for (idx_t i = 0; i < array_size; i++) { + writer.WriteNull(); + } + continue; + } + for (auto element : variants[row].GetArrayChildren()) { + WriteVariantElement(writer, element); + } + } +} + +//! Whether a cast registered on the connection may convert the elements to the target, which a copy would skip +static bool HasElementCastOverride(optional_ptr client, const LogicalType &target_type, + const LogicalType &element_type) { + if (!client) { + return false; + } + auto &casts = CastFunctionSet::Get(*client); + auto has_cast_to = [&](const LogicalType &type) { + for (auto &source : casts.GetRegisteredCastSourceTypes(type)) { + if (!ContainsAlias(source)) { + return true; + } + } + return false; + }; + return has_cast_to(target_type) || has_cast_to(element_type); +} + +//! Casts to VARIANT[] or VARIANT[N] by copying each element, when every row is NULL or an ARRAY that fits +static bool TryCopyVariantElements(Vector &variant_vec, Vector &result, idx_t count, + optional_ptr client) { + auto &target_type = result.GetType(); + optional_idx array_size; + optional_ptr element_type; + if (target_type.id() == LogicalTypeId::ARRAY) { + array_size = ArrayType::GetSize(target_type); + element_type = &ArrayType::GetChildType(target_type); + } else if (target_type.id() == LogicalTypeId::LIST) { + element_type = &ListType::GetChildType(target_type); + } + if (!element_type || element_type->id() != LogicalTypeId::VARIANT || + HasElementCastOverride(client, target_type, *element_type)) { + return false; + } + VectorIterator variants(variant_vec); + for (idx_t row = 0; row < count; row++) { + if (IsNullVariant(variants, row)) { + continue; + } + auto root = variants[row]; + if (root.GetTypeId() != LogicalTypeId::LIST || + (array_size.IsValid() && root.GetArrayChildren().size() != array_size.GetIndex())) { + return false; + } + } + if (array_size.IsValid()) { + CopyToVariantArray(variants, result, count); + } else { + CopyToVariantList(variants, result, count); + } + if (variant_vec.GetVectorType() == VectorType::CONSTANT_VECTOR) { + result.SetVectorType(VectorType::CONSTANT_VECTOR); + } + return true; +} + static bool CastFromVARIANT(Vector &variant_vec, Vector &result, idx_t count, CastParameters ¶meters) { if (TryFromShreddedCast(variant_vec, result)) { return true; } - // fallback to conversion - D_ASSERT(variant_vec.GetType().id() == LogicalTypeId::VARIANT); - RecursiveUnifiedVectorFormat variant_format; - Vector::RecursiveToUnifiedFormat(variant_vec, variant_format); optional_ptr client; if (parameters.cast_data) { client = parameters.cast_data->Cast().client; } + if (TryCopyVariantElements(variant_vec, result, count, client)) { + return true; + } + // fallback to conversion + D_ASSERT(variant_vec.GetType().id() == LogicalTypeId::VARIANT); + RecursiveUnifiedVectorFormat variant_format; + Vector::RecursiveToUnifiedFormat(variant_vec, variant_format); FromVariantConversionData conversion_data(variant_format, client); reference sel(*ConstantVector::ZeroSelectionVector()); diff --git a/src/duckdb/src/function/combine_types_rules.cpp b/src/duckdb/src/function/combine_types_rules.cpp index b44008fee..fb5155137 100644 --- a/src/duckdb/src/function/combine_types_rules.cpp +++ b/src/duckdb/src/function/combine_types_rules.cpp @@ -413,8 +413,8 @@ static bool UnequalMatchesStringLiteral(const LogicalType &left, const LogicalTy } // Rules are matched in order, so the first matching rule wins -const vector &DefaultCombineTypesRules() { - static const vector rules = { +array_ptr DefaultCombineTypesRules() { + static constexpr CombineTypesRule RULES[] = { {MatchesNoAlias, CombineNoAliasTypes}, {UnequalMatchesVariant, CombineVariant}, {UnequalMatchesNullOrUnknown, CombineNullOrUnknown}, @@ -433,7 +433,7 @@ const vector &DefaultCombineTypesRules() { {EqualMatchesStruct, CombineStructTypes}, {EqualMatchesUnion, CombineEqualUnion}, }; - return rules; + return array_ptr(RULES, sizeof(RULES) / sizeof(RULES[0])); } } // namespace duckdb diff --git a/src/duckdb/src/function/copy_blob.cpp b/src/duckdb/src/function/copy_blob.cpp index 362d28a08..da5b7d2a2 100644 --- a/src/duckdb/src/function/copy_blob.cpp +++ b/src/duckdb/src/function/copy_blob.cpp @@ -1,4 +1,5 @@ #include "duckdb/common/file_system.hpp" +#include "duckdb/common/virtual_file_system.hpp" #include "duckdb/common/types/column/column_data_collection.hpp" #include "duckdb/common/vector_operations/unary_executor.hpp" #include "duckdb/function/built_in_functions.hpp" @@ -47,7 +48,7 @@ unique_ptr WriteBlobBind(ClientContext &context, CopyFunctionBindI throw BinderException("COPY (FORMAT BLOB) option %s requires a value", SQLIdentifier(option_name)); } auto compression_str = ParseStringOption(option_values[0], option_name); - result->compression_type = FileCompressionType(compression_str); + result->compression_type = VirtualFileSystem::Get(context).ParseCompression(compression_str); } else { throw BinderException("Unrecognized option for COPY (FORMAT BLOB): %s", SQLIdentifier(option_name)); } diff --git a/src/duckdb/src/function/function.cpp b/src/duckdb/src/function/function.cpp index 3fea985a0..c8ab0c22e 100644 --- a/src/duckdb/src/function/function.cpp +++ b/src/duckdb/src/function/function.cpp @@ -1,4 +1,5 @@ #include "duckdb/function/function.hpp" +#include "duckdb/common/no_destructor.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/common/types/hash.hpp" @@ -185,6 +186,10 @@ bool FunctionData::SupportStatementCache() const { return true; } +bool FunctionData::IsIdentifiedByCall() const { + return false; +} + Function::Function(Identifier name_p) : name(std::move(name_p)) { } Function::~Function() { @@ -760,7 +765,7 @@ optional BindFunctionInput::TryGetConstant(const Identifier &name) const } const Identifier &BindFunctionInput::GetArgumentName(idx_t arg_idx) const { - static const Identifier UNNAMED; + static const NoDestructor UNNAMED; // The binder lays the arguments out in the order of the signature: the positional ones fill the standard // parameters, then "*args" - the named ones are keyword-only parameters or "**kwargs" const auto positional_count = function.GetPositionalArgumentCount(); @@ -774,7 +779,7 @@ const Identifier &BindFunctionInput::GetArgumentName(idx_t arg_idx) const { if (arg_idx < signature.GetPositionalParameterCount()) { return signature.GetParameter(arg_idx).GetName(); } - return UNNAMED; + return *UNNAMED; } optional_idx BindFunctionInput::GetArgumentIndex(const Identifier &name) const { diff --git a/src/duckdb/src/function/function_binder.cpp b/src/duckdb/src/function/function_binder.cpp index 7ebdce0b4..2a611404b 100644 --- a/src/duckdb/src/function/function_binder.cpp +++ b/src/duckdb/src/function/function_binder.cpp @@ -42,11 +42,11 @@ static bool TrySplitArguments(vector>> & vector> &positional, vector>> &named) { idx_t positional_count = 0; - while (positional_count < arguments.size() && arguments[positional_count].first.empty()) { + while (positional_count < arguments.size() && !arguments[positional_count].first.IsSet()) { positional_count++; } for (idx_t i = positional_count; i < arguments.size(); i++) { - if (arguments[i].first.empty()) { + if (!arguments[i].first.IsSet()) { return false; } } @@ -62,7 +62,7 @@ static bool TrySplitArguments(vector>> & } void FunctionCallArguments::AddArgument(FunctionCallArgument argument) { - if (argument.name.empty()) { + if (!argument.name.IsSet()) { if (positional_count != arguments.size()) { throw InternalException("FunctionCallArguments: a positional argument cannot follow a named one"); } @@ -609,7 +609,7 @@ static bool AnyOverloadSupportsImplicitArgumentNames(const BaseFunctionSet &func static ErrorData PositionalAfterNamedArgumentError(const vector>> &arguments) { bool seen_named = false; for (const auto &[name, expr] : arguments) { - if (!name.empty()) { + if (name.IsSet()) { seen_named = true; continue; } @@ -658,7 +658,7 @@ FunctionBinder::SelectFunctionFromArguments(const BaseFunctionSet &functions, if (implicit_names) { // Attempt to salvage the call by implicitly naming the positional arguments and retrying again for (auto &[name, expr] : arguments) { - if (name.empty()) { + if (!name.IsSet() && expr->GetAlias().IsSet()) { name = expr->GetAlias(); } } @@ -1094,7 +1094,7 @@ unique_ptr FunctionBinder::BindScalarFunction(const ScalarFunctionCa vector>> arguments; arguments.reserve(children.size()); for (auto &child : children) { - arguments.emplace_back(string(), std::move(child)); + arguments.emplace_back(Identifier(), std::move(child)); } return BindScalarFunction(func, std::move(arguments), error, is_operator, binder, std::move(alias), query_location); } diff --git a/src/duckdb/src/function/scalar/generic/invoke.cpp b/src/duckdb/src/function/scalar/generic/invoke.cpp index 37a952f9e..c6d606ec7 100644 --- a/src/duckdb/src/function/scalar/generic/invoke.cpp +++ b/src/duckdb/src/function/scalar/generic/invoke.cpp @@ -20,26 +20,26 @@ static void PropagateLambdaProperties(BoundScalarFunction &function, const Expre } struct LambdaInvokeData final : public LambdaFunctionData { - unique_ptr lambda_expr; + cow_ptr lambda_expr; explicit LambdaInvokeData(unique_ptr lambda_expr_p) : lambda_expr(std::move(lambda_expr_p)) { } unique_ptr Copy() const override { - auto lambda_expr_copy = lambda_expr ? lambda_expr->Copy() : nullptr; - return make_uniq(std::move(lambda_expr_copy)); + return make_uniq(*this); } bool Equals(const FunctionData &other_p) const override { auto &other = other_p.Cast(); - return Expression::Equals(lambda_expr, other.lambda_expr); + return lambda_expr.shares_with(other.lambda_expr) || + (lambda_expr && other.lambda_expr && lambda_expr->Equals(*other.lambda_expr)); } //! Serializes a lambda function's bind data static void Serialize(Serializer &serializer, const optional_ptr bind_data_p, const BoundScalarFunction &function) { auto &bind_data = bind_data_p->Cast(); - serializer.WritePropertyWithDefault(101, "lambda_expr", bind_data.lambda_expr, unique_ptr()); + serializer.WritePropertyWithDefault>(101, "lambda_expr", bind_data.lambda_expr); } //! Deserializes a lambda function's bind data diff --git a/src/duckdb/src/function/scalar/operator/arithmetic.cpp b/src/duckdb/src/function/scalar/operator/arithmetic.cpp index 06d93cc6f..d9d99bbd5 100644 --- a/src/duckdb/src/function/scalar/operator/arithmetic.cpp +++ b/src/duckdb/src/function/scalar/operator/arithmetic.cpp @@ -648,7 +648,6 @@ ScalarFunction AddFunction::GetFunction(const LogicalType &left_type, const Logi } else if (left_type.IsFloating()) { ScalarFunction function("+", {left_type, right_type}, left_type, GetScalarBinaryFunction(left_type.InternalType())); - function.SetFallible(); function.SetArgProperties({inc, inc}); function.SetStatisticsCallback(PropagateFloatingStats); return function; @@ -1046,7 +1045,6 @@ ScalarFunction SubtractFunction::GetFunction(const LogicalType &left_type, const } else if (left_type.IsFloating()) { ScalarFunction function("-", {left_type, right_type}, left_type, GetScalarBinaryFunction(left_type.InternalType())); - function.SetFallible(); function.SetArgProperties({ArgProperties().StrictlyIncreasing(), ArgProperties().StrictlyDecreasing()}); function.SetStatisticsCallback(PropagateFloatingStats); return function; diff --git a/src/duckdb/src/function/scalar/operator/cast.cpp b/src/duckdb/src/function/scalar/operator/cast.cpp index e4bc72046..0e382c145 100644 --- a/src/duckdb/src/function/scalar/operator/cast.cpp +++ b/src/duckdb/src/function/scalar/operator/cast.cpp @@ -41,6 +41,9 @@ static bool BoundCastCanThrow(const BoundCastInfo &bound_cast, const LogicalType // No cast exists between these types - it throws for every non-NULL value, unless this is a try_cast return !try_cast; } + if (bound_cast.IsFallible()) { + return true; + } return BoundCastExpression::CastCanThrow(source_type, target_type, try_cast); } diff --git a/src/duckdb/src/function/scalar/operator/decimal_division.cpp b/src/duckdb/src/function/scalar/operator/decimal_division.cpp index ef57f834b..a8f300e3a 100644 --- a/src/duckdb/src/function/scalar/operator/decimal_division.cpp +++ b/src/duckdb/src/function/scalar/operator/decimal_division.cpp @@ -1,6 +1,8 @@ #include "duckdb/common/exception.hpp" #include "duckdb/common/hugeint.hpp" #include "duckdb/common/operator/cast_operators.hpp" +#include "duckdb/common/types/bignum.hpp" +#include "duckdb/common/types/bignum_decimal.hpp" #include "duckdb/common/types/cast_helpers.hpp" #include "duckdb/common/types/decimal.hpp" #include "duckdb/execution/expression_executor.hpp" @@ -18,9 +20,9 @@ struct DecimalDivBindData : public FunctionData { // scale_exp = s2 + result_scale - s1 // >= 0: scale numerator up: result_int = (a_int * 10^scale_exp) / b_int // < 0: scale divisor up: result_int = a_int / (b_int * 10^|scale_exp|) - int32_t scale_exp; + int64_t scale_exp; - explicit DecimalDivBindData(int32_t scale_exp_p) : scale_exp(scale_exp_p) { + explicit DecimalDivBindData(int64_t scale_exp_p) : scale_exp(scale_exp_p) { } unique_ptr Copy() const override { @@ -38,6 +40,7 @@ struct DecimalDivBindData : public FunctionData { // COMPUTE_TYPE controls intermediate arithmetic: // int64_t -- when input_max_width + |scale_exp| < CACHED_POWERS_OF_TEN (product fits in int64_t) // hugeint_t -- otherwise +// A division with an argument or a result wider than 38 digits runs in the bignum_t tier instead (see below) //===--------------------------------------------------------------------===// template @@ -100,6 +103,8 @@ static void DecimalDivExecute(DataChunk &args, ExpressionState &state, Vector &r bool scale_divisor = bind_data.scale_exp < 0; uint32_t abs_exp = UnsafeNumericCast(AbsValue(bind_data.scale_exp)); + // the fixed-size tiers are only selected when the scaled operands fit a hugeint_t + D_ASSERT(abs_exp <= Decimal::MAX_WIDTH_INT128); COMPUTE_TYPE scale_factor; if constexpr (std::is_same_v) { @@ -210,6 +215,102 @@ static scalar_function_t GetDecimalDivExecuteFunction(PhysicalType result_physic } } +//===--------------------------------------------------------------------===// +// The bignum_t tier: an argument or the result is wider than 38 digits +// +// The arguments are brought to BIGNUM blobs of their unscaled values and divided with the rounding of the fixed-size +// tiers (half to even); the quotient is a BIGNUM blob, or an integer when the result is a fixed-size decimal +//===--------------------------------------------------------------------===// + +template +static void WidenDecimalToBignum(Vector &input, Vector &widened, idx_t count) { + auto &heap = StringVector::GetStringHeap(widened); + UnaryExecutor::Execute(input, widened, count, [&](SOURCE_TYPE value) { + return HugeintCastToBignum::Operation(hugeint_t(value), heap).data; + }); +} + +//! Bring an argument to the bignum_t tier; a decimal keeps its unscaled value at the same scale +static Vector &GetWideDecimalInput(Vector &input, idx_t count, unique_ptr &widened) { + auto source_physical = input.GetType().InternalType(); + if (source_physical == PhysicalType::VARCHAR) { + return input; + } + auto scale = DecimalType::GetScale(input.GetType()); + widened = make_uniq(LogicalType::DECIMAL(Decimal::MAX_WIDTH_INT128 + 1, scale), count); + switch (source_physical) { + case PhysicalType::INT16: + WidenDecimalToBignum(input, *widened, count); + break; + case PhysicalType::INT32: + WidenDecimalToBignum(input, *widened, count); + break; + case PhysicalType::INT64: + WidenDecimalToBignum(input, *widened, count); + break; + case PhysicalType::INT128: + WidenDecimalToBignum(input, *widened, count); + break; + default: + throw InternalException("decimal_division: unexpected argument physical type"); + } + return *widened; +} + +//! RESULT_TYPE is string_t for a result wider than 38 digits, the integer of the result tier otherwise +template +static void WideDecimalDivExecute(DataChunk &args, ExpressionState &state, Vector &result) { + auto &bind_data = state.expr.Cast().BindInfo()->Cast(); + unique_ptr lhs_widened; + unique_ptr rhs_widened; + auto &lhs = GetWideDecimalInput(args.data[0], args.size(), lhs_widened); + auto &rhs = GetWideDecimalInput(args.data[1], args.size(), rhs_widened); + + const auto scale_exp = bind_data.scale_exp; + const auto result_width = DecimalType::GetWidth(result.GetType()); + DecimalHelper::RescaleState scratch(state.GetContext().TryGetClientContext()); + + BinaryExecutor::Execute( + lhs, rhs, result, args.size(), [&](bignum_t a, bignum_t b) -> RESULT_TYPE { + // the quotient of the previous row has been consumed + scratch.Reset(); + bignum_t quotient; + if (!DecimalHelper::TryDivide(scratch, a, b, scale_exp, DecimalRounding::HALF_TO_EVEN, + quotient)) { + throw InvalidInputException("decimal_division: division by zero"); + } + // rounding can carry into a digit the result type does not have + if (!DecimalHelper::FitsWidth(quotient, result_width)) { + throw OutOfRangeException("decimal_division: result out of range for result type"); + } + if constexpr (std::is_same_v) { + return StringVector::AddStringOrBlob(result, quotient.data); + } else { + hugeint_t value; + RESULT_TYPE out; + if (!DecimalHelper::TryToHugeint(quotient, value) || !Hugeint::TryCast(value, out)) { + throw OutOfRangeException("decimal_division: result out of range for result type"); + } + return out; + } + }); +} + +static scalar_function_t GetWideDecimalDivExecuteFunction(PhysicalType result_physical) { + switch (result_physical) { + case PhysicalType::INT16: + return WideDecimalDivExecute; + case PhysicalType::INT32: + return WideDecimalDivExecute; + case PhysicalType::INT64: + return WideDecimalDivExecute; + case PhysicalType::INT128: + return WideDecimalDivExecute; + default: + return WideDecimalDivExecute; + } +} + //===--------------------------------------------------------------------===// // Bind function //===--------------------------------------------------------------------===// @@ -219,7 +320,9 @@ static void SelectDecimalDivFunction(BoundScalarFunction &bound_function); // Result width and scale for e1 / e2 (SQL Server semantics): // result_scale = max(6, s1 + p2 + 1) // result_width = p1 - s1 + s2 + result_scale -// Both are capped at Decimal::MAX_WIDTH_INT128 (38). +// Both are bounded by the widest DECIMAL the session binds (the max_decimal_width setting, or an argument that is +// wider), like the results of the other decimal operators: a session bound to the fixed-size decimals +// (max_decimal_width = 38) raises the errors of the fixed-size division. static void DecimalDivisionResolveTypes(ResolveScalarFunctionTypesInput &input) { auto &bound_function = input.GetBoundFunction(); auto &lhs_type = input.GetArgumentType(0); @@ -229,50 +332,66 @@ static void DecimalDivisionResolveTypes(ResolveScalarFunctionTypesInput &input) if (!lhs_type.GetDecimalProperties(p1, s1) || !rhs_type.GetDecimalProperties(p2, s2)) { throw InvalidInputException("decimal_division: both arguments must be DECIMAL"); } - if (Decimal::IsWide(p1) || Decimal::IsWide(p2)) { - throw NotImplementedException("decimal_division is not supported for DECIMAL types wider than %d digits", - Decimal::MAX_WIDTH_INT128); + // the widest DECIMAL the division constructs: the limit of the session, or a DECIMAL argument that is wider + const auto decimal_width_limit = input.GetDecimalWidthLimit(); + uint32_t max_decimal_width = 0; + if (lhs_type.id() == LogicalTypeId::DECIMAL) { + max_decimal_width = MaxValue(max_decimal_width, p1); + } + if (rhs_type.id() == LogicalTypeId::DECIMAL) { + max_decimal_width = MaxValue(max_decimal_width, p2); + } + const idx_t width_limit = decimal_width_limit.ResultWidth(max_decimal_width); + // an integer argument is an implicit DECIMAL(p, 0), bound on its canonical DECIMAL type within that width: in a + // session bound to the fixed-size decimals an integer type with more digits is a DECIMAL(38,0) + if (lhs_type.id() != LogicalTypeId::DECIMAL) { + p1 = NumericCast(MinValue(p1, width_limit)); + } + if (rhs_type.id() != LogicalTypeId::DECIMAL) { + p2 = NumericCast(MinValue(p2, width_limit)); } - // an integer argument is an implicit DECIMAL(p, 0): bind on its canonical DECIMAL type auto lhs_decimal_type = lhs_type.id() == LogicalTypeId::DECIMAL ? lhs_type : LogicalType::DECIMAL(p1, s1); auto rhs_decimal_type = rhs_type.id() == LogicalTypeId::DECIMAL ? rhs_type : LogicalType::DECIMAL(p2, s2); - uint32_t result_scale; + idx_t result_scale; if (input.GetArgumentCount() == 3) { auto scale_val = input.GetNonNullConstant(2); auto scale_i = scale_val.GetValue(); - if (scale_i < 0 || scale_i > Decimal::MAX_WIDTH_INT128) { - throw InvalidInputException("decimal_division: scale must be between 0 and %d, got %d", - Decimal::MAX_WIDTH_INT128, scale_i); + if (scale_i < 0 || idx_t(scale_i) > width_limit) { + throw InvalidInputException("decimal_division: scale must be between 0 and %llu, got %d", width_limit, + scale_i); } - result_scale = UnsafeNumericCast(scale_i); + result_scale = UnsafeNumericCast(scale_i); } else { - result_scale = MaxValue(6, s1 + p2 + 1); + result_scale = MaxValue(6, idx_t(s1) + idx_t(p2) + 1); } // result_width uses signed arithmetic to catch underflow before casting. auto result_width_i = int64_t(p1) - int64_t(s1) + int64_t(s2) + int64_t(result_scale); if (result_width_i < 1) { - throw InvalidInputException("decimal_division: scale %d produces a zero-width result for these input types", + throw InvalidInputException("decimal_division: scale %llu produces a zero-width result for these input types", result_scale); } - uint32_t result_width = UnsafeNumericCast(result_width_i); + idx_t result_width = UnsafeNumericCast(result_width_i); - if (result_scale > Decimal::MAX_WIDTH_INT128) { + if (result_scale > width_limit) { throw OutOfRangeException( - "Needed scale %d to accurately represent the division result, but this is out of range of the " - "DECIMAL type. Max scale is %d; could not perform an accurate division. Either add a cast to DOUBLE, " + "Needed scale %llu to accurately represent the division result, but this is out of range of the " + "DECIMAL type. Max scale is %llu; could not perform an accurate division. Either add a cast to DOUBLE, " "or add an explicit cast to a decimal with a lower scale.", - result_scale, Decimal::MAX_WIDTH_INT128); + result_scale, width_limit); } - if (result_width > Decimal::MAX_WIDTH_INT128) { + if (result_width > width_limit && !Decimal::IsWide(width_limit)) { + // the session is bound to the fixed-size decimals: the division does not narrow its result throw OutOfRangeException( - "Needed width %d to accurately represent the division result, but this is out of range of the " - "DECIMAL type. Max width is %d; could not perform an accurate division. Either add a cast to DOUBLE, " + "Needed width %llu to accurately represent the division result, but this is out of range of the " + "DECIMAL type. Max width is %llu; could not perform an accurate division. Either add a cast to DOUBLE, " "or add an explicit cast to a decimal with a lower scale.", - result_width, Decimal::MAX_WIDTH_INT128); + result_width, width_limit); } - bound_function.SetReturnType(LogicalType::DECIMAL(result_width, result_scale)); + bound_function.SetReturnType( + LogicalType::DECIMAL(decimal_width_limit.CheckedWidth(result_width, max_decimal_width, "Division"), + NumericCast(result_scale))); // keep the argument types: a narrower argument is widened at execution, so binding again yields the same types bound_function.GetArguments()[0] = lhs_decimal_type; bound_function.GetArguments()[1] = rhs_decimal_type; @@ -283,11 +402,17 @@ static void DecimalDivisionResolveTypes(ResolveScalarFunctionTypesInput &input) static void SelectDecimalDivFunction(BoundScalarFunction &bound_function) { auto &arguments = bound_function.GetArguments(); const auto result_physical = bound_function.GetReturnType().InternalType(); + if (result_physical == PhysicalType::VARCHAR || arguments[0].InternalType() == PhysicalType::VARCHAR || + arguments[1].InternalType() == PhysicalType::VARCHAR) { + // an argument or the result is wider than 38 digits + bound_function.SetFunctionCallback(GetWideDecimalDivExecuteFunction(result_physical)); + return; + } const auto wider = MaxValue(arguments[0].InternalType(), arguments[1].InternalType()); - const int32_t scale_exp = int32_t(DecimalType::GetScale(arguments[1])) + - int32_t(DecimalType::GetScale(bound_function.GetReturnType())) - - int32_t(DecimalType::GetScale(arguments[0])); - const int32_t abs_scale_exp = scale_exp < 0 ? -scale_exp : scale_exp; + const int64_t scale_exp = int64_t(DecimalType::GetScale(arguments[1])) + + int64_t(DecimalType::GetScale(bound_function.GetReturnType())) - + int64_t(DecimalType::GetScale(arguments[0])); + const int64_t abs_scale_exp = scale_exp < 0 ? -scale_exp : scale_exp; switch (wider) { case PhysicalType::INT16: @@ -322,7 +447,7 @@ static unique_ptr DecimalDivisionBind(BindScalarFunctionInput &inp auto lhs_scale = DecimalType::GetScale(bound_function.GetArguments()[0]); auto rhs_scale = DecimalType::GetScale(bound_function.GetArguments()[1]); auto result_scale = DecimalType::GetScale(bound_function.GetReturnType()); - return make_uniq(int32_t(rhs_scale) + int32_t(result_scale) - int32_t(lhs_scale)); + return make_uniq(int64_t(rhs_scale) + int64_t(result_scale) - int64_t(lhs_scale)); } //===--------------------------------------------------------------------===// diff --git a/src/duckdb/src/function/scalar/strftime_format.cpp b/src/duckdb/src/function/scalar/strftime_format.cpp index 04e6755b7..3dc738a22 100644 --- a/src/duckdb/src/function/scalar/strftime_format.cpp +++ b/src/duckdb/src/function/scalar/strftime_format.cpp @@ -89,9 +89,9 @@ idx_t StrfTimeFormat::GetSpecifierLength(StrTimeSpecifier specifier, date_t date const char *tz_name) { switch (specifier) { case StrTimeSpecifier::FULL_WEEKDAY_NAME: - return Date::DAY_NAMES[Date::ExtractISODayOfTheWeek(date) % 7].GetSize(); + return Date::DayNames()[Date::ExtractISODayOfTheWeek(date) % 7].GetSize(); case StrTimeSpecifier::FULL_MONTH_NAME: - return Date::MONTH_NAMES[data[1] - 1].GetSize(); + return Date::MonthNames()[data[1] - 1].GetSize(); case StrTimeSpecifier::YEAR_DECIMAL: return StrfTimeYearLength(data[0]); case StrTimeSpecifier::YEAR_ISO: @@ -274,12 +274,12 @@ char *StrfTimeFormat::WriteDateSpecifier(StrTimeSpecifier specifier, date_t date switch (specifier) { case StrTimeSpecifier::ABBREVIATED_WEEKDAY_NAME: { auto dow = Date::ExtractISODayOfTheWeek(date); - target = WriteString(target, Date::DAY_NAMES_ABBREVIATED[dow % 7]); + target = WriteString(target, Date::DayNamesAbbreviated()[dow % 7]); break; } case StrTimeSpecifier::FULL_WEEKDAY_NAME: { auto dow = Date::ExtractISODayOfTheWeek(date); - target = WriteString(target, Date::DAY_NAMES[dow % 7]); + target = WriteString(target, Date::DayNames()[dow % 7]); break; } case StrTimeSpecifier::WEEKDAY_DECIMAL: { @@ -329,11 +329,11 @@ char *StrfTimeFormat::WriteStandardSpecifier(StrTimeSpecifier specifier, int32_t target = WritePadded2(target, UnsafeNumericCast(data[2])); break; case StrTimeSpecifier::ABBREVIATED_MONTH_NAME: { - auto &month_name = Date::MONTH_NAMES_ABBREVIATED[data[1] - 1]; + auto &month_name = Date::MonthNamesAbbreviated()[data[1] - 1]; return WriteString(target, month_name); } case StrTimeSpecifier::FULL_MONTH_NAME: { - auto &month_name = Date::MONTH_NAMES[data[1] - 1]; + auto &month_name = Date::MonthNames()[data[1] - 1]; return WriteString(target, month_name); } case StrTimeSpecifier::MONTH_DECIMAL_PADDED: @@ -1271,21 +1271,21 @@ bool StrpTimeFormat::Parse(const char *data, size_t size, ParseResult &result, b } // we parse weekday names, but we don't use them as information case StrTimeSpecifier::ABBREVIATED_WEEKDAY_NAME: - if (TryParseCollection(data, pos, size, Date::DAY_NAMES_ABBREVIATED, 7) < 0) { + if (TryParseCollection(data, pos, size, Date::DayNamesAbbreviated(), 7) < 0) { error_message = "Expected an abbreviated day name (Mon, Tue, Wed, Thu, Fri, Sat, Sun)"; error_position = pos; return false; } break; case StrTimeSpecifier::FULL_WEEKDAY_NAME: - if (TryParseCollection(data, pos, size, Date::DAY_NAMES, 7) < 0) { + if (TryParseCollection(data, pos, size, Date::DayNames(), 7) < 0) { error_message = "Expected a full day name (Monday, Tuesday, etc...)"; error_position = pos; return false; } break; case StrTimeSpecifier::ABBREVIATED_MONTH_NAME: { - int32_t month = TryParseCollection(data, pos, size, Date::MONTH_NAMES_ABBREVIATED, 12); + int32_t month = TryParseCollection(data, pos, size, Date::MonthNamesAbbreviated(), 12); if (month < 0) { error_message = "Expected an abbreviated month name (Jan, Feb, Mar, etc..)"; error_position = pos; @@ -1295,7 +1295,7 @@ bool StrpTimeFormat::Parse(const char *data, size_t size, ParseResult &result, b break; } case StrTimeSpecifier::FULL_MONTH_NAME: { - int32_t month = TryParseCollection(data, pos, size, Date::MONTH_NAMES, 12); + int32_t month = TryParseCollection(data, pos, size, Date::MonthNames(), 12); if (month < 0) { error_message = "Expected a full month name (January, February, etc...)"; error_position = pos; diff --git a/src/duckdb/src/function/scalar/string/concat.cpp b/src/duckdb/src/function/scalar/string/concat.cpp index f0e3d562d..f91049045 100644 --- a/src/duckdb/src/function/scalar/string/concat.cpp +++ b/src/duckdb/src/function/scalar/string/concat.cpp @@ -2,6 +2,7 @@ #include "duckdb/common/vector/constant_vector.hpp" #include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/common/vector/list_vector.hpp" +#include "duckdb/common/vector/shared_child_vector.hpp" #include "duckdb/common/vector/string_vector.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/types/vector.hpp" @@ -150,6 +151,43 @@ struct ListConcatInputData { VectorIterator list_data; }; +//! Extend a single-row concat result in the shared storage its first input views instead of copying the prefix. +//! Returns false if the inputs do not fit that shape. +bool TryExtendSharedListChild(Context &context, const vector &input_data, Vector &result, + idx_t count) { + if (count != 1 || input_data.size() < 2) { + return false; + } + auto &prefix = input_data[0]; + auto prefix_val = prefix.list_data[0]; + if (!prefix_val.IsValid()) { + return false; + } + vector extras; + for (idx_t input_idx = 1; input_idx < input_data.size(); input_idx++) { + auto &input = input_data[input_idx]; + auto entry_val = input.list_data[0]; + if (!entry_val.IsValid()) { + return false; + } + extras.push_back(SharedChildExtra {input.child_vec, entry_val.GetValue()}); + } + const auto prefix_entry = prefix_val.GetValue(); + idx_t result_offset; + auto &result_child = ListVector::GetChildMutable(result); + if (!SharedChildVector::TryExtend(context.GetBufferManager(), prefix.child_vec, prefix_entry, extras, result_child, + result_offset)) { + return false; + } + idx_t result_length = prefix_entry.length; + for (auto &extra : extras) { + result_length += extra.entry.length; + } + auto writer = FlatVector::Writer(result, count); + writer.WriteValue(list_entry_t {result_offset, result_length}); + return true; +} + void ListConcatFunction(DataChunk &args, ExpressionState &state, Vector &result, bool is_operator) { auto count = args.size(); @@ -162,6 +200,13 @@ void ListConcatFunction(DataChunk &args, ExpressionState &state, Vector &result, input_data.emplace_back(input, count); } + if (TryExtendSharedListChild(state.GetContext(), input_data, result, count)) { + return; + } + + // a previous fast-path result may have left a view in the reused result vector, its values are discarded + FlatVector::PrepareForOverwrite(ListVector::GetChildMutable(result), STANDARD_VECTOR_SIZE); + // the || operator yields NULL whenever any input is NULL, while list_concat skips NULLs vector row_invalid(count, false); if (is_operator) { diff --git a/src/duckdb/src/function/scalar/struct/struct_concat.cpp b/src/duckdb/src/function/scalar/struct/struct_concat.cpp index 5c8b717ea..3494e3943 100644 --- a/src/duckdb/src/function/scalar/struct/struct_concat.cpp +++ b/src/duckdb/src/function/scalar/struct/struct_concat.cpp @@ -32,18 +32,27 @@ static unique_ptr StructConcatBind(BindScalarFunctionInput &input) child_list_t combined_children; identifier_set_t name_set; - bool has_unnamed = false; + bool has_tuple = false; + bool has_struct = false; for (idx_t arg_idx = 0; arg_idx < arguments.size(); arg_idx++) { const auto &arg = arguments[arg_idx]; - if (!StructType::IsStruct(arg->GetReturnType())) { + auto &arg_type = arg->GetReturnType(); + if (!StructType::IsStruct(arg_type)) { throw InvalidInputException("struct_concat: Argument at position \"%d\" is not a STRUCT", arg_idx + 1); } - const auto &child_types = StructType::GetChildTypes(arg->GetReturnType()); - for (const auto &child : child_types) { - if (!child.first.empty()) { + const auto &child_types = StructType::GetChildTypes(arg_type); + if (child_types.empty()) { + // an empty STRUCT or TUPLE contributes no fields + continue; + } + if (arg_type.id() == LogicalTypeId::TUPLE) { + has_tuple = true; + } else { + has_struct = true; + for (const auto &child : child_types) { auto it = name_set.find(child.first); if (it != name_set.end()) { if (it->GetIdentifierName() == child.first.GetIdentifierName()) { @@ -55,19 +64,19 @@ static unique_ptr StructConcatBind(BindScalarFunctionInput &input) child.first, *it); } name_set.insert(child.first); - } else { - has_unnamed = true; } + } + for (const auto &child : child_types) { combined_children.push_back(child); } } - if (has_unnamed && !name_set.empty()) { + if (has_tuple && has_struct) { throw InvalidInputException("struct_concat: Cannot mix named and unnamed STRUCTs"); } - // all-unnamed inputs produce an unnamed TUPLE, otherwise a named STRUCT - if (has_unnamed) { + // TUPLE inputs produce a TUPLE, otherwise a named STRUCT + if (has_tuple) { bound_function.SetReturnType(LogicalType::TUPLE(combined_children)); } else { bound_function.SetReturnType(LogicalType::STRUCT(combined_children)); diff --git a/src/duckdb/src/function/scalar/struct/struct_extract.cpp b/src/duckdb/src/function/scalar/struct/struct_extract.cpp index 670376017..b52bb6b5a 100644 --- a/src/duckdb/src/function/scalar/struct/struct_extract.cpp +++ b/src/duckdb/src/function/scalar/struct/struct_extract.cpp @@ -31,9 +31,6 @@ enum class StructExtractKey : uint8_t { NAME, INDEX, INDEX_AT }; //! Looks up the entry with the given name, returns its index and sets the type of the entry static idx_t ResolveStructEntryByName(const LogicalType &struct_type, const string &key_str, LogicalType &entry_type) { auto &struct_children = StructType::GetChildTypes(struct_type); - if (key_str.empty()) { - throw BinderException("Key name for struct_extract must not be empty"); - } auto key = Identifier(key_str); for (idx_t i = 0; i < struct_children.size(); i++) { if (struct_children[i].first == key) { diff --git a/src/duckdb/src/function/scalar/struct/struct_pack.cpp b/src/duckdb/src/function/scalar/struct/struct_pack.cpp index 70a324497..65037e79b 100644 --- a/src/duckdb/src/function/scalar/struct/struct_pack.cpp +++ b/src/duckdb/src/function/scalar/struct/struct_pack.cpp @@ -81,7 +81,8 @@ static unique_ptr StructPackUnbind(FunctionUnbindInput &input) auto &expression = input.expression; vector arguments; for (idx_t i = 0; i < input.children.size(); i++) { - auto name = IS_STRUCT_PACK ? StructType::GetChildName(expression.GetReturnType(), i) : Identifier(); + // a member is always passed as a named argument, also when its name is empty + auto name = IS_STRUCT_PACK ? StructType::GetChildName(expression.GetReturnType(), i).AsSet() : Identifier(); arguments.emplace_back(std::move(name), std::move(input.children[i])); } return make_uniq(expression.Function().GetDefinition()->GetQualifiedName(), diff --git a/src/duckdb/src/function/table/copy_csv.cpp b/src/duckdb/src/function/table/copy_csv.cpp index e3587d10c..a2739b6c0 100644 --- a/src/duckdb/src/function/table/copy_csv.cpp +++ b/src/duckdb/src/function/table/copy_csv.cpp @@ -246,7 +246,7 @@ struct LocalWriteCSVData : public LocalFunctionData { static unique_ptr OpenCSVFileWriter(ClientContext &context, const string &file_path, FileCompressionType compression) { auto &fs = FileSystem::GetFileSystem(context); - auto flags = FileFlags::FILE_FLAGS_WRITE | FileFlags::FILE_FLAGS_FILE_CREATE_NEW | std::move(compression); + auto flags = FileFlags::FILE_FLAGS_WRITE | FileFlags::FILE_FLAGS_FILE_CREATE_NEW | compression; // checking a remote path costs a request, so a remote output is opened like one that may exist if (!fs.IsRemoteFile(file_path) && !fs.FileExists(file_path) && !fs.IsPipe(file_path)) { flags |= FileFlags::FILE_FLAGS_EXCLUSIVE_CREATE; @@ -257,7 +257,7 @@ static unique_ptr OpenCSVFileWriter(ClientContext &context, con struct GlobalWriteCSVData : public GlobalFunctionData { GlobalWriteCSVData(const CSVReaderOptions &options, ClientContext &context, const string &file_path, FileCompressionType compression_p) - : file_writer(OpenCSVFileWriter(context, file_path, std::move(compression_p))), writer(options, *file_writer), + : file_writer(OpenCSVFileWriter(context, file_path, compression_p)), writer(options, *file_writer), compression(file_writer->GetFileCompressionType()) { } diff --git a/src/duckdb/src/function/table/read_duckdb.cpp b/src/duckdb/src/function/table/read_duckdb.cpp index 6374cc492..c2b818b42 100644 --- a/src/duckdb/src/function/table/read_duckdb.cpp +++ b/src/duckdb/src/function/table/read_duckdb.cpp @@ -129,8 +129,6 @@ class DuckDBReader : public BaseFileReader { unique_ptr bind_data; unique_ptr global_state; atomic finished; - //! The column indexes to scan - the row id is scanned if no columns are projected - vector scan_column_indexes; //! The subset of the filters that is pushed into the table scan - only set when some columns are converted unique_ptr scan_filters; idx_t column_count; @@ -153,8 +151,6 @@ struct DuckDBConvertedColumn { struct DuckDBReadLocalState : LocalTableFunctionState { unique_ptr local_state; shared_ptr attached_database; - //! The chunk to scan into when no columns are projected (we then scan the row ids) - DataChunk row_id_chunk; //! The columns of the current file that are converted after the table scan vector converted_columns; //! For each scan column, whether it is one of the converted columns @@ -339,11 +335,6 @@ bool DuckDBReader::TryInitializeScan(ClientContext &context, GlobalTableFunction } } - scan_column_indexes = column_indexes; - if (scan_column_indexes.empty()) { - // the table scan requires at least one column - scan the row id if no columns are projected - scan_column_indexes.emplace_back(COLUMN_IDENTIFIER_ROW_ID); - } if (filters && !expression_map.empty()) { // a filter on a converted column is written against the converted values, not against those of the file - // it is applied after the conversion, the table scan only evaluates the filters on the other columns @@ -355,19 +346,16 @@ bool DuckDBReader::TryInitializeScan(ClientContext &context, GlobalTableFunction } } // initialize the scan over this table - TableFunctionInitInput input(bind_data.get(), scan_column_indexes, vector(), GetScanFilters()); + TableFunctionInitInput input(bind_data.get(), column_indexes, vector(), GetScanFilters()); global_state = scan_function.init_global(context, input); } AssignSharedPointer(lstate.attached_database, db_wrapper); // initialize the local scan ThreadContext thread(context); ExecutionContext exec_context(context, thread, nullptr); - TableFunctionInitInput input(bind_data.get(), scan_column_indexes, vector(), GetScanFilters()); + TableFunctionInitInput input(bind_data.get(), column_indexes, vector(), GetScanFilters()); lstate.local_state = scan_function.init_local(exec_context, input, global_state.get()); InitializeConvertedColumns(context, lstate); - if (column_indexes.empty() && lstate.row_id_chunk.ColumnCount() == 0) { - lstate.row_id_chunk.Initialize(context, {LogicalType::ROW_TYPE}); - } return true; } @@ -394,12 +382,12 @@ void DuckDBReader::InitializeConvertedColumns(ClientContext &context, DuckDBRead ExpressionIterator::VisitExpression( *converted.expression, [&](const BoundReferenceExpression &ref) { input_types[ref.Index()] = ref.GetReturnType(); }); - if (converted.position + input_types.size() > scan_column_indexes.size()) { + if (converted.position + input_types.size() > column_indexes.size()) { throw InternalException("Converted column %llu of read_duckdb is out of range", converted.position); } converted.input = make_uniq(); converted.input->InitializeEmpty(input_types); - lstate.converted_position.resize(scan_column_indexes.size(), false); + lstate.converted_position.resize(column_indexes.size(), false); lstate.converted_position[converted.position] = true; lstate.converted_columns.push_back(std::move(converted)); } @@ -479,12 +467,7 @@ AsyncResult DuckDBReader::Scan(ClientContext &context, GlobalTableFunctionState } else { input.async_result = AsyncResultType::IMPLICIT; input.results_execution_mode = AsyncResultsExecutionMode::TASK_EXECUTOR; - if (column_indexes.empty()) { - // no columns are projected - scan the row ids and only emit the count - lstate.row_id_chunk.Reset(); - scan_function.function(context, input, lstate.row_id_chunk); - chunk.SetChildCardinality(lstate.row_id_chunk.size()); - } else if (!lstate.converted_columns.empty()) { + if (!lstate.converted_columns.empty()) { ScanConvertedColumns(context, input, lstate, chunk); } else { scan_function.function(context, input, chunk); diff --git a/src/duckdb/src/function/table/simple_table_function.cpp b/src/duckdb/src/function/table/simple_table_function.cpp new file mode 100644 index 000000000..302c0ca6e --- /dev/null +++ b/src/duckdb/src/function/table/simple_table_function.cpp @@ -0,0 +1,185 @@ +#include "duckdb/function/table/simple_table_function.hpp" + +#include "duckdb/common/types/column/column_data_collection.hpp" +#include "duckdb/main/client_context.hpp" + +namespace duckdb { + +//===--------------------------------------------------------------------===// +// RowAppender +//===--------------------------------------------------------------------===// +RowAppender::RowAppender(ClientContext &context, ColumnDataCollection &collection_p) : collection(collection_p) { + chunk.Initialize(Allocator::Get(context), collection.Types()); +} + +RowAppender::~RowAppender() { + Flush(); +} + +void RowAppender::Append(vector values) { + auto &types = collection.Types(); + if (values.size() != types.size()) { + throw InternalException("RowAppender::Append: %llu values for %llu columns", values.size(), types.size()); + } + auto row = chunk.size(); + for (idx_t col = 0; col < values.size(); col++) { + // Append grows the child vector by one, so chunk.size() follows the children + chunk.data[col].Append(values[col].DefaultCastAs(types[col])); + } + chunk.CheckCardinality(row + 1); + if (chunk.size() == STANDARD_VECTOR_SIZE) { + Flush(); + } +} + +void RowAppender::Flush() { + if (chunk.size() == 0) { + return; + } + collection.Append(chunk); + chunk.Reset(); +} + +//===--------------------------------------------------------------------===// +// SimpleBindData +//===--------------------------------------------------------------------===// +SimpleBindData::~SimpleBindData() { +} + +unique_ptr SimpleBindData::Copy() const { + return make_uniq(); +} + +bool SimpleBindData::Equals(const FunctionData &other) const { + return false; +} + +//===--------------------------------------------------------------------===// +// SimpleTableFunction +//===--------------------------------------------------------------------===// +namespace { + +struct SimpleTableFunctionInfo : public TableFunctionInfo { + //! Fixed-column overload + child_list_t columns; + SimpleTableFunction::simple_produce_t produce; + //! Argument-taking overload + SimpleTableFunction::simple_bind_t bind; + SimpleTableFunction::simple_produce_bound_t produce_bound; +}; + +//! Carries what the scan needs from bind to init: the full column types and the user's bind-time state +struct SimpleFunctionData : public FunctionData { + unique_ptr user_data; + vector types; + //! The function's info; the TableFunction in the plan keeps it alive + optional_ptr info; + + unique_ptr Copy() const override { + auto result = make_uniq(); + result->user_data = unique_ptr_cast(user_data->Copy()); + result->types = types; + result->info = info; + return std::move(result); + } + bool Equals(const FunctionData &other_p) const override { + auto &other = other_p.Cast(); + return types == other.types && user_data->Equals(*other.user_data); + } +}; + +struct SimpleTableFunctionState : public GlobalTableFunctionState { + explicit SimpleTableFunctionState(ClientContext &context, vector types) + : collection(context, std::move(types)) { + } + + ColumnDataCollection collection; + ColumnDataScanState scan_state; +}; + +unique_ptr SimpleTableFunctionBind(ClientContext &context, TableFunctionBindInput &input, + vector &return_types, vector &names) { + auto &info = input.info->Cast(); + auto result = make_uniq(); + child_list_t columns; + if (info.bind) { + result->user_data = info.bind(context, input, columns); + } else { + columns = info.columns; + } + for (auto &col : columns) { + names.emplace_back(col.first); + return_types.push_back(col.second); + } + if (!result->user_data) { + result->user_data = make_uniq(); + } + result->types = return_types; + result->info = input.info; + return std::move(result); +} + +unique_ptr SimpleTableFunctionInit(ClientContext &context, TableFunctionInitInput &input) { + auto &bind_data = input.bind_data->Cast(); + auto &info = bind_data.info->Cast(); + + auto result = make_uniq(context, bind_data.types); + { + RowAppender rows(context, result->collection); + if (info.produce_bound) { + info.produce_bound(context, *bind_data.user_data, rows); + } else { + info.produce(context, rows); + } + } + // scan only the requested columns, in the requested order + vector column_ids; + for (auto &column_index : input.column_indexes) { + column_ids.push_back(column_index.GetPrimaryIndex()); + } + result->collection.InitializeScan(result->scan_state, std::move(column_ids)); + return std::move(result); +} + +void SimpleTableFunctionScan(ClientContext &context, TableFunctionInput &data_p, DataChunk &output) { + auto &state = data_p.global_state->Cast(); + state.collection.Scan(state.scan_state, output); +} + +TableFunction CreateInternal(const string &name, const vector &arguments, + shared_ptr info) { + TableFunction function(Identifier(name), arguments, SimpleTableFunctionScan, SimpleTableFunctionBind, + SimpleTableFunctionInit); + function.projection_pushdown = true; + function.function_info = std::move(info); + return function; +} + +} // namespace + +TableFunction SimpleTableFunction::Create(const string &name, child_list_t columns, + simple_produce_t produce) { + auto info = make_shared_ptr(); + info->columns = std::move(columns); + info->produce = std::move(produce); + return CreateInternal(name, {}, std::move(info)); +} + +TableFunction SimpleTableFunction::Create(const string &name, const vector &arguments, + named_parameter_type_map_t named_parameters, simple_bind_t bind, + simple_produce_bound_t produce) { + auto info = make_shared_ptr(); + info->bind = std::move(bind); + info->produce_bound = std::move(produce); + auto function = CreateInternal(name, arguments, std::move(info)); + if (!named_parameters.empty()) { + function.GetSignature().WithTypedKwargs("options", [&](TypedKwargs &kwargs) { + for (auto ¶meter : named_parameters) { + kwargs.Add(parameter.first, parameter.second); + } + }); + } + return function; +} + +} // namespace duckdb diff --git a/src/duckdb/src/function/table/system/duckdb_approx_database_count.cpp b/src/duckdb/src/function/table/system/duckdb_approx_database_count.cpp index e3cac5d54..197eecab5 100644 --- a/src/duckdb/src/function/table/system/duckdb_approx_database_count.cpp +++ b/src/duckdb/src/function/table/system/duckdb_approx_database_count.cpp @@ -1,42 +1,16 @@ #include "duckdb/function/table/system_functions.hpp" + +#include "duckdb/function/table/simple_table_function.hpp" #include "duckdb/main/database_manager.hpp" namespace duckdb { -struct DuckDBApproxDatabaseCountData : public GlobalTableFunctionState { - DuckDBApproxDatabaseCountData() : count(0), finished(false) { - } - idx_t count; - bool finished; -}; - -static unique_ptr DuckDBApproxDatabaseCountBind(ClientContext &context, TableFunctionBindInput &input, - vector &return_types, - vector &names) { - names.emplace_back("approx_count"); - return_types.emplace_back(LogicalType::UBIGINT); - return nullptr; -} - -unique_ptr DuckDBApproxDatabaseCountInit(ClientContext &context, - TableFunctionInitInput &input) { - auto result = make_uniq(); - result->count = DatabaseManager::Get(context).ApproxDatabaseCount(); - return std::move(result); -} - -void DuckDBApproxDatabaseCountFunction(ClientContext &context, TableFunctionInput &data_p, DataChunk &output) { - auto &data = data_p.global_state->Cast(); - if (data.finished) { - return; - } - output.data[0].Append(Value::UBIGINT(data.count)); - data.finished = true; -} - void DuckDBApproxDatabaseCountFun::RegisterFunction(BuiltinFunctions &set) { - TableFunction approx_count_fun("duckdb_approx_database_count", {}, DuckDBApproxDatabaseCountFunction, - DuckDBApproxDatabaseCountBind, DuckDBApproxDatabaseCountInit); + auto approx_count_fun = SimpleTableFunction::Create( + "duckdb_approx_database_count", {{"approx_count", LogicalType::UBIGINT}}, + [](ClientContext &context, RowAppender &rows) { + rows.Append(Value::UBIGINT(DatabaseManager::Get(context).ApproxDatabaseCount())); + }); // reads an approximate live count of the attached databases approx_count_fun.stability = FunctionStability::VOLATILE; set.AddFunction(std::move(approx_count_fun)); diff --git a/src/duckdb/src/function/table/system/duckdb_connection_count.cpp b/src/duckdb/src/function/table/system/duckdb_connection_count.cpp index 7b539f59a..e21cda08e 100644 --- a/src/duckdb/src/function/table/system/duckdb_connection_count.cpp +++ b/src/duckdb/src/function/table/system/duckdb_connection_count.cpp @@ -1,45 +1,17 @@ #include "duckdb/function/table/system_functions.hpp" +#include "duckdb/function/table/simple_table_function.hpp" #include "duckdb/main/client_context.hpp" -#include "duckdb/main/database.hpp" #include "duckdb/main/connection_manager.hpp" +#include "duckdb/main/database.hpp" namespace duckdb { -struct DuckDBConnectionCountData : public GlobalTableFunctionState { - DuckDBConnectionCountData() : count(0), finished(false) { - } - idx_t count; - bool finished; -}; - -static unique_ptr DuckDBConnectionCountBind(ClientContext &context, TableFunctionBindInput &input, - vector &return_types, - vector &names) { - names.emplace_back("count"); - return_types.emplace_back(LogicalType::UBIGINT); - return nullptr; -} - -unique_ptr DuckDBConnectionCountInit(ClientContext &context, TableFunctionInitInput &input) { - auto result = make_uniq(); - auto &conn_manager = context.db->GetConnectionManager(); - result->count = conn_manager.GetConnectionCount(); - return std::move(result); -} - -void DuckDBConnectionCountFunction(ClientContext &context, TableFunctionInput &data_p, DataChunk &output) { - auto &data = data_p.global_state->Cast(); - if (data.finished) { - return; - } - output.data[0].Append(Value::UBIGINT(data.count)); - data.finished = true; -} - void DuckDBConnectionCountFun::RegisterFunction(BuiltinFunctions &set) { - TableFunction connection_count_fun("duckdb_connection_count", {}, DuckDBConnectionCountFunction, - DuckDBConnectionCountBind, DuckDBConnectionCountInit); + auto connection_count_fun = SimpleTableFunction::Create( + "duckdb_connection_count", {{"count", LogicalType::UBIGINT}}, [](ClientContext &context, RowAppender &rows) { + rows.Append(Value::UBIGINT(context.db->GetConnectionManager().GetConnectionCount())); + }); // reads the live connection registry connection_count_fun.stability = FunctionStability::VOLATILE; set.AddFunction(std::move(connection_count_fun)); diff --git a/src/duckdb/src/function/table/system/duckdb_index_types.cpp b/src/duckdb/src/function/table/system/duckdb_index_types.cpp new file mode 100644 index 000000000..6951a53c9 --- /dev/null +++ b/src/duckdb/src/function/table/system/duckdb_index_types.cpp @@ -0,0 +1,25 @@ +#include "duckdb/function/table/system_functions.hpp" + +#include "duckdb/execution/index/index_type_set.hpp" +#include "duckdb/function/table/simple_table_function.hpp" +#include "duckdb/main/client_context.hpp" +#include "duckdb/main/config.hpp" + +namespace duckdb { + +void DuckDBIndexTypesFun::RegisterFunction(BuiltinFunctions &set) { + auto function = SimpleTableFunction::Create( + "duckdb_index_types", + {{"name", LogicalType::VARCHAR}, {"internal", LogicalType::BOOLEAN}, {"registered_by", LogicalType::VARCHAR}}, + [](ClientContext &context, RowAppender &rows) { + for (auto &type : DBConfig::GetConfig(context).GetIndexTypes().GetIndexTypes()) { + rows.Append(type.name, Value::BOOLEAN(type.internal), + type.registered_by.empty() ? Value() : Value(type.registered_by)); + } + }); + // another connection can register an index type between two scans + function.stability = FunctionStability::VOLATILE; + set.AddFunction(std::move(function)); +} + +} // namespace duckdb diff --git a/src/duckdb/src/function/table/system/duckdb_log_types.cpp b/src/duckdb/src/function/table/system/duckdb_log_types.cpp new file mode 100644 index 000000000..8549f2ccc --- /dev/null +++ b/src/duckdb/src/function/table/system/duckdb_log_types.cpp @@ -0,0 +1,28 @@ +#include "duckdb/function/table/system_functions.hpp" + +#include "duckdb/common/enum_util.hpp" +#include "duckdb/function/table/simple_table_function.hpp" +#include "duckdb/logging/log_manager.hpp" +#include "duckdb/main/client_context.hpp" + +namespace duckdb { + +void DuckDBLogTypesFun::RegisterFunction(BuiltinFunctions &set) { + auto function = SimpleTableFunction::Create( + "duckdb_log_types", + {{"name", LogicalType::VARCHAR}, + {"level", LogicalType::VARCHAR}, + {"is_structured", LogicalType::BOOLEAN}, + {"extension_name", LogicalType::VARCHAR}}, + [](ClientContext &context, RowAppender &rows) { + for (auto &type : LogManager::Get(context).GetLogTypes()) { + rows.Append(type.name, EnumUtil::ToString(type.level), Value::BOOLEAN(type.is_structured), + type.extension_name.empty() ? Value() : Value(type.extension_name)); + } + }); + // another connection can register a log type between two scans + function.stability = FunctionStability::VOLATILE; + set.AddFunction(std::move(function)); +} + +} // namespace duckdb diff --git a/src/duckdb/src/function/table/system/duckdb_settings.cpp b/src/duckdb/src/function/table/system/duckdb_settings.cpp index d91f2dfdd..b365d7f57 100644 --- a/src/duckdb/src/function/table/system/duckdb_settings.cpp +++ b/src/duckdb/src/function/table/system/duckdb_settings.cpp @@ -1,4 +1,5 @@ #include "duckdb/function/table/system_functions.hpp" +#include "duckdb/function/table/simple_table_function.hpp" #include "duckdb/main/config.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/common/enum_util.hpp" @@ -18,15 +19,7 @@ struct DuckDBSettingValue { }; }; -struct DuckDBSettingsData : public GlobalTableFunctionState { - DuckDBSettingsData() : offset(0) { - } - - vector settings; - idx_t offset; -}; - -struct DuckDBSettingsBindData : public TableFunctionData { +struct DuckDBSettingsBindData : public SimpleBindData { bool debug = false; bool deprecated = false; //! Ignore the debug and deprecated filters @@ -35,30 +28,18 @@ struct DuckDBSettingsBindData : public TableFunctionData { bool Includes(bool is_debug, bool is_deprecated) const { return include_all || (debug == is_debug && deprecated == is_deprecated); } -}; - -static unique_ptr DuckDBSettingsBind(ClientContext &context, TableFunctionBindInput &input, - vector &return_types, vector &names) { - names.emplace_back("name"); - return_types.emplace_back(LogicalType::VARCHAR); - - names.emplace_back("value"); - return_types.emplace_back(LogicalType::VARCHAR); - - names.emplace_back("description"); - return_types.emplace_back(LogicalType::VARCHAR); - names.emplace_back("input_type"); - return_types.emplace_back(LogicalType::VARCHAR); - - names.emplace_back("scope"); - return_types.emplace_back(LogicalType::VARCHAR); - - names.emplace_back("aliases"); - return_types.emplace_back(LogicalType::LIST(LogicalType::VARCHAR)); + unique_ptr Copy() const override { + return make_uniq(*this); + } +}; - names.emplace_back("typed_value"); - return_types.emplace_back(LogicalType::VARIANT()); +static unique_ptr DuckDBSettingsBind(ClientContext &context, TableFunctionBindInput &input, + child_list_t &columns) { + columns = {{"name", LogicalType::VARCHAR}, {"value", LogicalType::VARCHAR}, + {"description", LogicalType::VARCHAR}, {"input_type", LogicalType::VARCHAR}, + {"scope", LogicalType::VARCHAR}, {"aliases", LogicalType::LIST(LogicalType::VARCHAR)}, + {"typed_value", LogicalType::VARIANT()}}; auto result = make_uniq(); for (auto name : {"debug", "deprecated", "include_all"}) { @@ -86,14 +67,14 @@ static unique_ptr DuckDBSettingsBind(ClientContext &context, Table return std::move(result); } -unique_ptr DuckDBSettingsInit(ClientContext &context, TableFunctionInitInput &input) { - auto result = make_uniq(); - auto &bind_data = input.bind_data->Cast(); +static void DuckDBSettingsProduce(ClientContext &context, const SimpleBindData &bind_data_p, RowAppender &rows) { + auto &bind_data = bind_data_p.Cast(); + vector settings; - identifier_map_t> aliases; + identifier_map_t> alias_map; for (idx_t i = 0; i < DBConfig::GetAliasCount(); i++) { auto alias = DBConfig::GetAliasByIndex(i); - aliases[alias->setting_name].emplace_back(alias->alias); + alias_map[alias->setting_name].emplace_back(alias->alias); } auto &config = DBConfig::GetConfig(context); @@ -124,17 +105,17 @@ unique_ptr DuckDBSettingsInit(ClientContext &context, value.description = option->description; value.input_type = option->parameter_type; value.scope = EnumUtil::ToString(scope); - auto entry = aliases.find(option->name); - if (entry != aliases.end()) { + auto entry = alias_map.find(option->name); + if (entry != alias_map.end()) { value.aliases = std::move(entry->second); } for (auto &alias : value.aliases) { DuckDBSettingValue alias_value = value; alias_value.name = alias.GetValue(); alias_value.aliases.clear(); - result->settings.push_back(std::move(alias_value)); + settings.push_back(std::move(alias_value)); } - result->settings.push_back(std::move(value)); + settings.push_back(std::move(value)); } for (auto &ext_param : config.GetExtensionSettings()) { if (!bind_data.Includes(ext_param.second.is_debug, ext_param.second.is_deprecated)) { @@ -153,53 +134,21 @@ unique_ptr DuckDBSettingsInit(ClientContext &context, value.input_type = ext_param.second.type.ToString(); value.scope = EnumUtil::ToString(scope); - result->settings.push_back(std::move(value)); + settings.push_back(std::move(value)); } - std::sort(result->settings.begin(), result->settings.end()); - return std::move(result); -} + std::sort(settings.begin(), settings.end()); -void DuckDBSettingsFunction(ClientContext &context, TableFunctionInput &data_p, DataChunk &output) { - auto &data = data_p.global_state->Cast(); - if (data.offset >= data.settings.size()) { - // finished returning values - return; - } - // start returning values - // either fill up the chunk or return all the remaining columns - idx_t count = 0; - - // name, LogicalType::VARCHAR - auto &name = output.data[0]; - // value, LogicalType::VARCHAR - auto &value = output.data[1]; - // description, LogicalType::VARCHAR - auto &description = output.data[2]; - // input_type, LogicalType::VARCHAR - auto &input_type = output.data[3]; - // scope, LogicalType::VARCHAR - auto &scope = output.data[4]; - // aliases, LogicalType::VARCHAR[] - auto &aliases = output.data[5]; - // value, LogicalType::VARIANT - auto &typed_value = output.data[6]; - - while (data.offset < data.settings.size() && count < STANDARD_VECTOR_SIZE) { - auto &entry = data.settings[data.offset++]; - - name.Append(Value(entry.name)); - value.Append(entry.value.CastAs(context, LogicalType::VARCHAR)); - description.Append(Value(entry.description)); - input_type.Append(Value(entry.input_type)); - scope.Append(Value(entry.scope)); - aliases.Append(Value::LIST(LogicalType::VARCHAR, std::move(entry.aliases))); - typed_value.Append(entry.value.CastAs(context, LogicalType::VARIANT())); - count++; + for (auto &entry : settings) { + rows.Append(Value(entry.name), entry.value.CastAs(context, LogicalType::VARCHAR), Value(entry.description), + Value(entry.input_type), Value(entry.scope), + Value::LIST(LogicalType::VARCHAR, std::move(entry.aliases)), + entry.value.CastAs(context, LogicalType::VARIANT())); } } void DuckDBSettingsFun::RegisterFunction(BuiltinFunctions &set) { - TableFunction settings_fun("duckdb_settings", {}, DuckDBSettingsFunction, DuckDBSettingsBind, DuckDBSettingsInit); + auto settings_fun = + SimpleTableFunction::Create("duckdb_settings", {}, {}, DuckDBSettingsBind, DuckDBSettingsProduce); settings_fun.GetSignature().WithTypedKwargs("options", [](TypedKwargs &options) { options.Add("debug", LogicalType::BOOLEAN) .Add("deprecated", LogicalType::BOOLEAN) diff --git a/src/duckdb/src/function/table/system/pragma_user_agent.cpp b/src/duckdb/src/function/table/system/pragma_user_agent.cpp index 05705d5c0..9dea4ed16 100644 --- a/src/duckdb/src/function/table/system/pragma_user_agent.cpp +++ b/src/duckdb/src/function/table/system/pragma_user_agent.cpp @@ -1,49 +1,14 @@ #include "duckdb/function/table/system_functions.hpp" + +#include "duckdb/function/table/simple_table_function.hpp" #include "duckdb/main/config.hpp" namespace duckdb { -struct PragmaUserAgentData : public GlobalTableFunctionState { - PragmaUserAgentData() : finished(false) { - } - - std::string user_agent; - bool finished; -}; - -static unique_ptr PragmaUserAgentBind(ClientContext &context, TableFunctionBindInput &input, - vector &return_types, vector &names) { - names.emplace_back("user_agent"); - return_types.emplace_back(LogicalType::VARCHAR); - - return nullptr; -} - -unique_ptr PragmaUserAgentInit(ClientContext &context, TableFunctionInitInput &input) { - auto result = make_uniq(); - auto &config = DBConfig::GetConfig(context); - result->user_agent = config.UserAgent(); - - return std::move(result); -} - -void PragmaUserAgentFunction(ClientContext &context, TableFunctionInput &data_p, DataChunk &output) { - auto &data = data_p.global_state->Cast(); - - if (data.finished) { - // signal end of output - return; - } - - output.data[0].Append(Value(data.user_agent)); - - data.finished = true; -} - void PragmaUserAgent::RegisterFunction(BuiltinFunctions &set) { - TableFunction pragma_user_agent("pragma_user_agent", {}, PragmaUserAgentFunction, PragmaUserAgentBind, - PragmaUserAgentInit); - set.AddFunction(pragma_user_agent); + set.AddFunction(SimpleTableFunction::Create( + "pragma_user_agent", {{"user_agent", LogicalType::VARCHAR}}, + [](ClientContext &context, RowAppender &rows) { rows.Append(DBConfig::GetConfig(context).UserAgent()); })); } } // namespace duckdb diff --git a/src/duckdb/src/function/table/system_functions.cpp b/src/duckdb/src/function/table/system_functions.cpp index 893402a4b..56fea450b 100644 --- a/src/duckdb/src/function/table/system_functions.cpp +++ b/src/duckdb/src/function/table/system_functions.cpp @@ -29,7 +29,9 @@ void BuiltinFunctions::RegisterSQLiteFunctions() { DuckDBPreparedStatementsFun::RegisterFunction(*this); DuckDBLogFun::RegisterFunction(*this); DuckDBLogContextFun::RegisterFunction(*this); + DuckDBLogTypesFun::RegisterFunction(*this); DuckDBIndexesFun::RegisterFunction(*this); + DuckDBIndexTypesFun::RegisterFunction(*this); DuckDBSchemasFun::RegisterFunction(*this); DuckDBDependenciesFun::RegisterFunction(*this); DuckDBDialectsFun::RegisterFunction(*this); diff --git a/src/duckdb/src/function/table/table_scan.cpp b/src/duckdb/src/function/table/table_scan.cpp index 6aa72cb68..6254b9527 100644 --- a/src/duckdb/src/function/table/table_scan.cpp +++ b/src/duckdb/src/function/table/table_scan.cpp @@ -417,9 +417,8 @@ class DuckTableScanState : public TableScanGlobalState { DuckTransaction &tx; DataTable &storage; const idx_t total_rows; - //! Scan initialization info retained for creating scan states - vector storage_ids; - optional_ptr filters; + //! Prepared after dynamic-filter merging and shared with worker and read-ahead scan states + TableScanInput scan_input; optional_ptr sample_options; //! Guards scheduling setup and ordered batch index assignment mutex read_ahead_lock; @@ -444,7 +443,7 @@ class DuckTableScanState : public TableScanGlobalState { const bool supported_scan = input.max_threads > 1 && !blocks.InMemory() && !bind_data.is_create_index && !bind_data.order_options && !sample_options; if (supported_scan && - CollectionScanState::SupportsAssignmentBlockDiscovery(storage_ids, storage.GetTypes())) { + CollectionScanState::SupportsAssignmentBlockDiscovery(scan_input.GetColumnIds(), storage.GetTypes())) { const auto shard_count = BlockAllocator::Get(storage.GetAttached()).GetPoolShardCount(); if (shard_count > 1 || ClientConfig::GetConfig(context.client).verify_parallelism) { affinity_shards = shard_count; @@ -465,10 +464,12 @@ class DuckTableScanState : public TableScanGlobalState { public: //! Retains the scan initialization info shared by all scan states of this scan void InitializeScanInfo(TableFunctionInitInput &input) { + vector storage_ids; + storage_ids.reserve(input.column_indexes.size()); for (auto &col : input.column_indexes) { storage_ids.push_back(bind_data.table.GetStorageIndex(col)); } - filters = input.filters; + scan_input = TableScanInput(std::move(storage_ids), input.filters); sample_options = input.sample_options; } @@ -480,7 +481,7 @@ class DuckTableScanState : public TableScanGlobalState { scan_state.local_state.reorderer = make_uniq(*bind_data.order_options, TransactionData(tx)); } - scan_state.Initialize(storage_ids, context, filters, sample_options, total_rows); + scan_state.Initialize(scan_input, context, sample_options, total_rows); scan_state.options.force_fetch_row = Settings::Get(context); } @@ -501,7 +502,7 @@ class DuckTableScanState : public TableScanGlobalState { } unique_ptr ProduceAffinityJob(ClientContext &context, TableScanLocalState &l_state, - vector> &io_tasks) { + AsyncResult &io) { context.InterruptCheck(); if (!l_state.prepare_state) { l_state.prepare_state = make_uniq(); @@ -518,9 +519,11 @@ class DuckTableScanState : public TableScanGlobalState { if (!storage.NextParallelScanAssignment(context, state, prepare, job->assignment)) { return nullptr; } + vector> io_tasks; if (job->assignment.source == TableScanSource::PERSISTENT) { prepare.table_state.PrepareAssignmentBlocks(job->blocks, io_tasks, read_ahead->PrefetchEnabled()); } + io = AsyncResult::FromTasks(std::move(io_tasks), TaskSchedulerType::ASYNC); prepare.ReleasePins(); return std::move(job); } @@ -530,8 +533,8 @@ class DuckTableScanState : public TableScanGlobalState { AddProgress(l_state, l_state.assignment_progress.Finish()); unique_ptr claimed; const auto shard = BlockAllocator::Get(storage.GetAttached()).GetLocalPoolShard(); - auto produce = [&](vector> &tasks) { - return ProduceAffinityJob(context, l_state, tasks); + auto produce = [&](AsyncResult &io) { + return ProduceAffinityJob(context, l_state, io); }; const auto result = read_ahead->AcquireReadyJob(context, input, std::ref(produce), claimed, shard); if (result != ScanReadAheadAcquire::ACQUIRED) { @@ -616,7 +619,7 @@ class DuckTableScanState : public TableScanGlobalState { } //! Claims the next assignment as a job and registers its I/O, returns null when there are no more assignments - unique_ptr ProduceJob(ClientContext &context, vector> &io_tasks) { + unique_ptr ProduceJob(ClientContext &context, AsyncResult &io) { auto job = make_uniq(); // jobs recycle finished scan states, create a fresh one when none was available job->scan_state = state_pool.TryPop(); @@ -636,7 +639,9 @@ class DuckTableScanState : public TableScanGlobalState { } job->scan_state->InitializeColumnScans(); // preparing the first vector skips the leading vectors the zonemaps or sampling reject before registering I/O + vector> io_tasks; job->scan_state->table_state.PrepareScanIO(tx, io_tasks, true); + io = AsyncResult::FromTasks(std::move(io_tasks), TaskSchedulerType::ASYNC); return job; } @@ -669,8 +674,7 @@ class DuckTableScanState : public TableScanGlobalState { if (!l_state.job) { unique_ptr claimed; auto acquired = read_ahead->AcquireJob( - context, data_p, - [&](vector> &io_tasks) { return ProduceJob(context, io_tasks); }, claimed); + context, data_p, [&](AsyncResult &io) { return ProduceJob(context, io); }, claimed); if (acquired == ScanReadAheadAcquire::EXHAUSTED) { return false; } @@ -1394,8 +1398,7 @@ static string TableScanToSQLGuard(const LogicalGet &get, bool has_input) { if (data.partitions_to_scan) { return "bound_scan_partitions"; } - const bool has_filters = - get.table_filters.HasFilters() || get.table_filters.HasMultiColumnFilters() || get.dynamic_filters; + const bool has_filters = get.table_filters.HasAnyFilters() || get.dynamic_filters; for (auto &index : get.GetColumnIds()) { if (index.IsRowNumberColumn() && has_filters) { return "row_number_with_filters"; diff --git a/src/duckdb/src/function/table/version/pragma_version.cpp b/src/duckdb/src/function/table/version/pragma_version.cpp index dc843998a..79ef33096 100644 --- a/src/duckdb/src/function/table/version/pragma_version.cpp +++ b/src/duckdb/src/function/table/version/pragma_version.cpp @@ -1,5 +1,5 @@ #ifndef DUCKDB_PATCH_VERSION -#define DUCKDB_PATCH_VERSION "0-alpha58374" +#define DUCKDB_PATCH_VERSION "0-alpha59171" #endif #ifndef DUCKDB_MINOR_VERSION #define DUCKDB_MINOR_VERSION 1 @@ -8,10 +8,10 @@ #define DUCKDB_MAJOR_VERSION 2 #endif #ifndef DUCKDB_VERSION -#define DUCKDB_VERSION "v2.1.0-alpha58374" +#define DUCKDB_VERSION "v2.1.0-alpha59171" #endif #ifndef DUCKDB_SOURCE_ID -#define DUCKDB_SOURCE_ID "17c33f61e2" +#define DUCKDB_SOURCE_ID "0d4d6a99e5" #endif #include "duckdb/function/table/system_functions.hpp" #include "duckdb/main/database.hpp" diff --git a/src/duckdb/src/function/table_function.cpp b/src/duckdb/src/function/table_function.cpp index 5c48c258c..63d5ceda3 100644 --- a/src/duckdb/src/function/table_function.cpp +++ b/src/duckdb/src/function/table_function.cpp @@ -24,7 +24,7 @@ BaseTableFunction::BaseTableFunction(table_function_t function_, table_function_ function(function_), in_out_function(nullptr), in_out_function_final(nullptr), statistics(nullptr), statistics_extended(nullptr), dependency(nullptr), cardinality(nullptr), get_metrics(nullptr), pushdown_complex_filter(nullptr), pushdown_expression(nullptr), to_string(nullptr), table_scan_progress(nullptr), - get_partition_data(nullptr), get_bind_info(nullptr), get_table_entry(nullptr), + table_in_out_progress(nullptr), get_partition_data(nullptr), get_bind_info(nullptr), get_table_entry(nullptr), projection_expression_pushdown(nullptr), get_multi_file_reader(nullptr), supports_pushdown_type(nullptr), supports_pushdown_extract(nullptr), get_partition_info(nullptr), get_partition_stats(nullptr), get_virtual_columns(nullptr), get_row_id_columns(nullptr), set_scan_order(nullptr), serialize(nullptr), @@ -98,6 +98,7 @@ BoundTableFunction::BoundTableFunction(shared_ptr function_ to_string = function.to_string; to_sql = function.to_sql; table_scan_progress = function.table_scan_progress; + table_in_out_progress = function.table_in_out_progress; get_partition_data = function.get_partition_data; get_bind_info = function.get_bind_info; get_table_entry = function.get_table_entry; @@ -171,8 +172,8 @@ bool BaseTableFunction::operator==(const BaseTableFunction &rhs) const { statistics == rhs.statistics && dependency == rhs.dependency && cardinality == rhs.cardinality && pushdown_complex_filter == rhs.pushdown_complex_filter && pushdown_expression == rhs.pushdown_expression && to_string == rhs.to_string && to_sql == rhs.to_sql && table_scan_progress == rhs.table_scan_progress && - get_partition_data == rhs.get_partition_data && get_bind_info == rhs.get_bind_info && - get_table_entry == rhs.get_table_entry && + table_in_out_progress == rhs.table_in_out_progress && get_partition_data == rhs.get_partition_data && + get_bind_info == rhs.get_bind_info && get_table_entry == rhs.get_table_entry && projection_expression_pushdown == rhs.projection_expression_pushdown && get_multi_file_reader == rhs.get_multi_file_reader && supports_pushdown_type == rhs.supports_pushdown_type && stability == rhs.stability && get_partition_info == rhs.get_partition_info && diff --git a/src/duckdb/src/function/window/window_index_tree.cpp b/src/duckdb/src/function/window/window_index_tree.cpp index 78967c608..ea12a1334 100644 --- a/src/duckdb/src/function/window/window_index_tree.cpp +++ b/src/duckdb/src/function/window/window_index_tree.cpp @@ -6,13 +6,13 @@ namespace duckdb { WindowIndexTree::WindowIndexTree(ClientContext &context, const vector &orders, - const vector &sort_idx, const idx_t count) - : WindowMergeSortTree(context, orders, sort_idx, count) { + const vector &sort_idx, const idx_t count, bool unique) + : WindowMergeSortTree(context, orders, sort_idx, count, unique) { } WindowIndexTree::WindowIndexTree(ClientContext &context, const BoundOrderModifier &order_bys, - const vector &sort_idx, const idx_t count) - : WindowIndexTree(context, order_bys.orders, sort_idx, count) { + const vector &sort_idx, const idx_t count, bool unique) + : WindowIndexTree(context, order_bys.orders, sort_idx, count, unique) { } unique_ptr WindowIndexTree::GetLocalState(ExecutionContext &context) { diff --git a/src/duckdb/src/function/window/window_token_tree.cpp b/src/duckdb/src/function/window/window_token_tree.cpp index 31cd1f157..add81c100 100644 --- a/src/duckdb/src/function/window/window_token_tree.cpp +++ b/src/duckdb/src/function/window/window_token_tree.cpp @@ -108,6 +108,14 @@ void WindowTokenTree::Finished() { WindowMergeSortTree::Finished(); } +idx_t WindowTokenTree::Token(const idx_t row_idx) const { + if (mst64) { + return mst64->LowestLevel()[row_idx]; + } else { + return mst32->LowestLevel()[row_idx]; + } +} + template static idx_t TokenRank(const TREE &tree, const idx_t lower, const idx_t upper, const idx_t row_idx) { idx_t rank = 1; diff --git a/src/duckdb/src/function/window/window_value_function.cpp b/src/duckdb/src/function/window/window_value_function.cpp index 4d7048736..15a83f82a 100644 --- a/src/duckdb/src/function/window/window_value_function.cpp +++ b/src/duckdb/src/function/window/window_value_function.cpp @@ -16,6 +16,8 @@ #include "duckdb/planner/expression/bound_window_expression.hpp" #include "duckdb/main/settings.hpp" +#include + namespace duckdb { //===--------------------------------------------------------------------===// @@ -25,12 +27,13 @@ class WindowValueGlobalState : public WindowExecutorGlobalState { public: using WindowCollectionPtr = unique_ptr; WindowValueGlobalState(ClientContext &client, const WindowExecutor &executor, const idx_t payload_count, - const ValidityMask &partition_mask, const ValidityMask &order_mask) + const ValidityMask &partition_mask, const ValidityMask &order_mask, + const bool unique_value_tree = false) : WindowExecutorGlobalState(client, executor, payload_count, partition_mask, order_mask), value_idx(executor.child_idx[0]) { if (!executor.arg_order_idx.empty()) { - value_tree = - make_uniq(client, executor.wexpr.ArgOrders(), executor.arg_order_idx, payload_count); + value_tree = make_uniq(client, executor.wexpr.ArgOrders(), executor.arg_order_idx, + payload_count, unique_value_tree); } } @@ -251,23 +254,20 @@ unique_ptr WindowValueExecutor::GetLocal(ExecutionContext &conte // The functions LEAD and LAG can be extended to a windowed version with // two independent ORDER BY clauses just like first_value and other value // functions. -// To evaluate a windowed LEAD/LAG, one has to (1) compute the ROW_NUMBER -// of the own row, (2) adjust the row number by adding or subtracting an -// offset, (3) find the row at that offset, and (4) evaluate the expression -// provided to LEAD/LAG on this row. One can use the algorithm from Section -// 4.4 to determine the row number of the own row (step 1) and the -// algorithm from Section 4.5 to find the row with the adjusted position -// (step 3). Both algorithms are in O(𝑛 log𝑛), so the overall algorithm -// for LEAD/LAG is also O(𝑛 log𝑛). -// -// 4.4: unique WindowTokenTree -// 4.5: WindowIndexTree +// To evaluate a windowed LEAD/LAG, one has to (1) compute the position +// of the own row in the value tree, (2) adjust the position by adding or +// subtracting an offset, (3) find the value at that position, and +// (4) evaluate the expression provided to LEAD/LAG on this row. +// The position is the number of frame values before the own row in the secondary order. +// For IGNORE NULLS, the value tree omits NULL rows. The row tree still gives the +// current row a token, so we can find its insertion point even when its value is NULL. class WindowLeadLagGlobalState : public WindowValueGlobalState { public: WindowLeadLagGlobalState(ClientContext &client, const WindowExecutor &executor, const idx_t payload_count, const ValidityMask &partition_mask, const ValidityMask &order_mask) - : WindowValueGlobalState(client, executor, payload_count, partition_mask, order_mask) { + // The value tree must share the row tree's total ordering + : WindowValueGlobalState(client, executor, payload_count, partition_mask, order_mask, true) { if (value_tree) { use_framing = true; @@ -636,6 +636,43 @@ unique_ptr WindowLeadLagExecutor::GetLocal(ExecutionContext &con return make_uniq(context, glstate); } +template +static idx_t CountValuesBefore(const TREE &values, const WindowTokenTree &tokens, const FrameBounds &frame, + idx_t row_idx, idx_t payload_count) { + using Element = typename TREE::ElementType; + const auto &rows = values.LowestLevel(); + if (rows.empty() || frame.start == frame.end) { + return 0; + } + + // The leaves hold non-NULL row indices in the same secondary order as the tokens. + const auto token = tokens.Token(row_idx); + const auto pos = std::lower_bound(rows.begin(), rows.end(), token, + [&](Element row, idx_t needle) { return tokens.Token(row) < needle; }); + const auto prefix = NumericCast(pos - rows.begin()); + if (!prefix || (frame.start == 0 && frame.end == payload_count)) { + return prefix; + } + + // Count row indices in [frame.start, frame.end) within that prefix. + auto count_before = [&](idx_t bound) { + idx_t count = 0; + values.AggregateLowerBound(0, prefix, NumericCast(bound), + [&](idx_t, idx_t begin, idx_t end) { count += end - begin; }); + return count; + }; + const auto upper = count_before(frame.end); + return frame.start ? upper - count_before(frame.start) : upper; +} + +static idx_t CountValuesBefore(const WindowLeadLagGlobalState &state, const FrameBounds &frame, idx_t row_idx) { + const auto &values = *state.value_tree; + if (values.mst32) { + return CountValuesBefore(*values.mst32, *state.row_tree, frame, row_idx, state.payload_count); + } + return CountValuesBefore(*values.mst64, *state.row_tree, frame, row_idx, state.payload_count); +} + //! The index of the row at the offset - saturated if it does not fit, as it is outside the partition anyway static int64_t LeadLagIndex(ExpressionType type, int64_t row_idx, int64_t offset) { int64_t result; @@ -671,10 +708,13 @@ void WindowLeadLagExecutor::GetData(ExecutionContext &context, DataChunk &eval_c auto frame_end = FlatVector::GetData(bounds.data[FRAME_END]); if (glstate.row_tree) { - // TODO: Handle subframes (SelectNth can handle it but Rank can't) + // TODO: Handle excluded rows when ranking within the frame. auto &frames = llstate.frames; frames.resize(1); auto &frame = frames[0]; + const auto is_lead = (wexpr.GetExpressionType() == ExpressionType::WINDOW_LEAD); + const auto &ignore_nulls = *llstate.ignore_nulls; + const auto all_valid = ignore_nulls.CannotHaveNull(); for (idx_t i = 0; i < count; ++i, ++row_idx) { int64_t offset = 1; if (has_offset) { @@ -685,43 +725,38 @@ void WindowLeadLagExecutor::GetData(ExecutionContext &context, DataChunk &eval_c offset = leadlag_offset.GetCell(i); } - // (1) compute the ROW_NUMBER of the own row frame = FrameBounds(frame_begin[i], MaxValue(frame_end[i], frame_begin[i])); - const auto own_row = glstate.row_tree->Rank(frame.start, frame.end, row_idx) - 1; - // (2) adjust the row number by adding or subtracting an offset - auto val_idx = LeadLagIndex(wexpr.GetExpressionType(), NumericCast(own_row), offset); - const auto is_lead = (wexpr.GetExpressionType() == ExpressionType::WINDOW_LEAD); - if (row_idx < frame.start || frame.end <= row_idx) { - // An own row outside the frame ranks just before own_row instead of at it, - // so a zero shift is the own row itself and a forward shift lands one row earlier. - if (!offset) { - cursor.CopyCell(0, row_idx, result, i); - continue; - } - if (is_lead == (offset > 0)) { - --val_idx; - } + if (!offset) { + // A zero shift is always the own row + cursor.CopyCell(0, row_idx, result, i); + continue; } + // (1) count the values in the frame that sort before the own row + // (the own row may be NULL, so it is not counted in the value tree) + const auto val_count = all_valid ? glstate.row_tree->Rank(frame.start, frame.end, row_idx) - 1 + : CountValuesBefore(glstate, frame, row_idx); + // (2) an own row without a value ranks just before val_count instead of at it, + // so a forward shift lands one value earlier. + const auto has_value = + frame.start <= row_idx && row_idx < frame.end && (all_valid || ignore_nulls.RowIsValid(row_idx)); + const auto val_idx = (is_lead == (offset > 0)) && !has_value ? int64_t(val_count) - 1 : int64_t(val_count); + // (3) adjust the value index by adding or subtracting an offset + const auto val_offset = LeadLagIndex(wexpr.GetExpressionType(), val_idx, offset); + // (4) find the value at that index const auto frame_width = NumericCast(frame.end - frame.start); - if (val_idx >= 0 && val_idx < frame_width) { - // (3) find the row at that offset - const auto n = NumericCast(val_idx); - const auto nth_index = glstate.value_tree->SelectNth(frames, n); - // (4) evaluate the expression provided to LEAD/LAG on this row. - if (nth_index.second) { - // Overflow - if (has_default) { - leadlag_default.CopyCell(result, i); - } else { - FlatVector::SetNull(result, i, true); - } + pair nth_index(0, 1); + if (val_offset >= 0 && val_offset < frame_width) { + nth_index = glstate.value_tree->SelectNth(frames, NumericCast(val_offset)); + } + if (nth_index.second) { + // Overflow + if (has_default) { + leadlag_default.CopyCell(result, i); } else { - cursor.CopyCell(0, nth_index.first, result, i); + FlatVector::SetNull(result, i, true); } - } else if (has_default) { - leadlag_default.CopyCell(result, i); } else { - FlatVector::SetNull(result, i, true); + cursor.CopyCell(0, nth_index.first, result, i); } } return; diff --git a/src/duckdb/src/include/duckdb/catalog/default/default_coordinate_systems.hpp b/src/duckdb/src/include/duckdb/catalog/default/default_coordinate_systems.hpp index db40c05ca..f26b51de1 100644 --- a/src/duckdb/src/include/duckdb/catalog/default/default_coordinate_systems.hpp +++ b/src/duckdb/src/include/duckdb/catalog/default/default_coordinate_systems.hpp @@ -22,7 +22,7 @@ class DefaultCoordinateSystemGenerator : public DefaultGenerator { SchemaCatalogEntry &schema; public: - unique_ptr CreateDefaultEntry(ClientContext &context, const Identifier &entry_name) override; + unique_ptr CreateDefaultEntry(CatalogTransaction transaction, const Identifier &entry_name) override; vector GetDefaultEntries() override; }; diff --git a/src/duckdb/src/include/duckdb/common/allocator.hpp b/src/duckdb/src/include/duckdb/common/allocator.hpp index 2089c657b..e32ed120e 100644 --- a/src/duckdb/src/include/duckdb/common/allocator.hpp +++ b/src/duckdb/src/include/duckdb/common/allocator.hpp @@ -197,22 +197,19 @@ class HugeAllocation { idx_t GetSize() const { return allocated_size; } - //! Approximate fallback-backing ownership supplied by BlockAllocator; unknown after untracked reuse. - optional_idx GetAllocationShard() const { - return allocation_shard; - } + //! Approximate backing locality derived from the allocation. + DUCKDB_API optional_idx GetAllocationShard() const; bool IsSet() const { return pointer; } DUCKDB_API void Reset(); private: - HugeAllocation(BufferAllocator &allocator, data_ptr_t pointer, idx_t allocated_size, optional_idx allocation_shard); + HugeAllocation(BufferAllocator &allocator, data_ptr_t pointer, idx_t allocated_size); optional_ptr allocator; data_ptr_t pointer; idx_t allocated_size; - optional_idx allocation_shard; }; //! The BufferAllocator is a wrapper around the global allocator class that sends any allocations made through the @@ -234,8 +231,6 @@ class BufferAllocator : public Allocator { private: explicit BufferAllocator(StandardBufferManager &manager); - - void FreeHuge(data_ptr_t pointer, idx_t size, optional_idx allocation_shard); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/arrow/appender/append_data.hpp b/src/duckdb/src/include/duckdb/common/arrow/appender/append_data.hpp index 9b88a98ff..8944798ac 100644 --- a/src/duckdb/src/include/duckdb/common/arrow/appender/append_data.hpp +++ b/src/duckdb/src/include/duckdb/common/arrow/appender/append_data.hpp @@ -100,6 +100,11 @@ struct ArrowAppendData { //! conversion the top-level appender applies, keeping the data layout in sync with //! the schema declared by SetArrowFormat. void AppendChild(const Vector &input, idx_t from, idx_t to, idx_t input_size); + //! Appends the child of a STRUCT or ARRAY parent for the parent rows [from, to), where every parent row has + //! child_count child values. A NULL parent row does not invalidate its child values, so they can hold anything. + //! When appending the child can reject values, the child values of NULL parent rows are appended as NULL instead + void AppendChildOfParent(const Vector &child, const UnifiedVectorFormat &parent_format, idx_t from, idx_t to, + idx_t input_size, idx_t child_count = 1); //! The bytes appended so far: this column's buffers plus those of its children idx_t ByteSize() const { diff --git a/src/duckdb/src/include/duckdb/common/bignum.hpp b/src/duckdb/src/include/duckdb/common/bignum.hpp index b4a1f048f..62b7db93c 100644 --- a/src/duckdb/src/include/duckdb/common/bignum.hpp +++ b/src/duckdb/src/include/duckdb/common/bignum.hpp @@ -38,6 +38,26 @@ struct bignum_t { bignum_t &operator=(const bignum_t &rhs) = default; bignum_t &operator=(bignum_t &&rhs) = default; + //! The blob of a BIGNUM orders like its value + bool operator==(const bignum_t &rhs) const { + return data == rhs.data; + } + bool operator!=(const bignum_t &rhs) const { + return data != rhs.data; + } + bool operator<(const bignum_t &rhs) const { + return data < rhs.data; + } + bool operator>(const bignum_t &rhs) const { + return data > rhs.data; + } + bool operator<=(const bignum_t &rhs) const { + return data <= rhs.data; + } + bool operator>=(const bignum_t &rhs) const { + return data >= rhs.data; + } + void Print() const; }; diff --git a/src/duckdb/src/include/duckdb/common/enum_util.hpp b/src/duckdb/src/include/duckdb/common/enum_util.hpp index d4ee3922f..2ceb24432 100644 --- a/src/duckdb/src/include/duckdb/common/enum_util.hpp +++ b/src/duckdb/src/include/duckdb/common/enum_util.hpp @@ -324,6 +324,8 @@ enum class HTTPTransportReusePolicy : uint8_t; enum class IdentifierCaseMode : uint8_t; +enum class ImplicitLateralSubqueries : uint8_t; + enum class IndexAppendMode : uint8_t; enum class IndexBindState : uint8_t; @@ -638,6 +640,8 @@ enum class StorageVersion : uint64_t; enum class StrTimeSpecifier : uint8_t; +enum class SubqueryLateralType : uint8_t; + enum class SubqueryType : uint8_t; enum class SuggestionState : uint8_t; @@ -1171,6 +1175,9 @@ const char* EnumUtil::ToChars(HTTPTransportReusePolicy template<> const char* EnumUtil::ToChars(IdentifierCaseMode value); +template<> +const char* EnumUtil::ToChars(ImplicitLateralSubqueries value); + template<> const char* EnumUtil::ToChars(IndexAppendMode value); @@ -1642,6 +1649,9 @@ const char* EnumUtil::ToChars(StorageVersion value); template<> const char* EnumUtil::ToChars(StrTimeSpecifier value); +template<> +const char* EnumUtil::ToChars(SubqueryLateralType value); + template<> const char* EnumUtil::ToChars(SubqueryType value); @@ -2222,6 +2232,9 @@ HTTPTransportReusePolicy EnumUtil::FromString(const ch template<> IdentifierCaseMode EnumUtil::FromString(const char *value); +template<> +ImplicitLateralSubqueries EnumUtil::FromString(const char *value); + template<> IndexAppendMode EnumUtil::FromString(const char *value); @@ -2693,6 +2706,9 @@ StorageVersion EnumUtil::FromString(const char *value); template<> StrTimeSpecifier EnumUtil::FromString(const char *value); +template<> +SubqueryLateralType EnumUtil::FromString(const char *value); + template<> SubqueryType EnumUtil::FromString(const char *value); diff --git a/src/duckdb/src/include/duckdb/common/enums/file_compression_type.hpp b/src/duckdb/src/include/duckdb/common/enums/file_compression_type.hpp index 2adf02732..c157a719a 100644 --- a/src/duckdb/src/include/duckdb/common/enums/file_compression_type.hpp +++ b/src/duckdb/src/include/duckdb/common/enums/file_compression_type.hpp @@ -18,9 +18,12 @@ namespace duckdb { class FileCompressionType { public: //! Creates an UNCOMPRESSED compression type - DUCKDB_API FileCompressionType(); + constexpr FileCompressionType() : kind(Kind::UNCOMPRESSED), custom(nullptr) { + } //! Creates a compression type from a string, normalizing known aliases (e.g. "infer" -> auto detection) DUCKDB_API FileCompressionType(string compression); // NOLINT: allow implicit conversion from string + //! Whether the name is a built-in compression type or one of its aliases, which need no registered file system + DUCKDB_API static bool IsBuiltIn(const string &compression); //! Detect the compression type based on the file name DUCKDB_API static const FileCompressionType AUTO_DETECT; @@ -41,7 +44,17 @@ class FileCompressionType { DUCKDB_API const string &ToString() const; private: - string compression; + enum class Kind : uint8_t { UNCOMPRESSED, AUTO_DETECT, GZIP, ZSTD, CUSTOM }; + + constexpr explicit FileCompressionType(Kind kind_p) : kind(kind_p), custom(nullptr) { + } + static bool TryGetBuiltIn(const string &lower_compression, Kind &result); + +private: + //! Trivially destructible, so the constants above need no static initialization or destruction + Kind kind; + //! The interned (never freed) name of a CUSTOM compression type, see VirtualFileSystem::ParseCompression + const string *custom; }; DUCKDB_API string CompressionExtensionFromType(const FileCompressionType &type); diff --git a/src/duckdb/src/include/duckdb/common/enums/implicit_lateral_subqueries.hpp b/src/duckdb/src/include/duckdb/common/enums/implicit_lateral_subqueries.hpp new file mode 100644 index 000000000..b24938738 --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/enums/implicit_lateral_subqueries.hpp @@ -0,0 +1,19 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/enums/implicit_lateral_subqueries.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/constants.hpp" + +namespace duckdb { + +//! How to handle a FROM-clause subquery that references an earlier FROM item without the LATERAL keyword. +//! DEFAULT resolves to the behavior of the current release (WARN, later ERROR). +enum class ImplicitLateralSubqueries : uint8_t { DEFAULT = 0, ALLOW = 1, WARN = 2, ERROR = 3 }; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/enums/optimizer_type.hpp b/src/duckdb/src/include/duckdb/common/enums/optimizer_type.hpp index 4dd9260b8..67e8a481a 100644 --- a/src/duckdb/src/include/duckdb/common/enums/optimizer_type.hpp +++ b/src/duckdb/src/include/duckdb/common/enums/optimizer_type.hpp @@ -73,7 +73,8 @@ enum class OptimizerType : uint32_t { SET_OPERATION_AGGREGATE = 56, JOIN_TO_SEMI_JOIN = 57, MARK_JOIN_SIMPLIFIER = 58, - GROUP_BY_TOP_KEY = 59 + GROUP_BY_TOP_KEY = 59, + CONSTANT_PROPAGATION = 60 }; string OptimizerTypeToString(OptimizerType type); diff --git a/src/duckdb/src/include/duckdb/common/enums/subquery_lateral_type.hpp b/src/duckdb/src/include/duckdb/common/enums/subquery_lateral_type.hpp new file mode 100644 index 000000000..501bfbc7e --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/enums/subquery_lateral_type.hpp @@ -0,0 +1,29 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/enums/subquery_lateral_type.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/constants.hpp" + +namespace duckdb { + +//! How a FROM-clause subquery was written, used to check for implicit lateral subqueries +enum class SubqueryLateralType : uint8_t { + //! Generated by the system rather than written by the user + GENERATED = 0, + //! Written without the LATERAL keyword + IMPLICIT = 1, + //! Written with the LATERAL keyword + EXPLICIT = 2, + //! Generated wrapper whose FROM clause is part of the enclosing one (aliased parenthesized join, NEAREST BY target) + FROM_CLAUSE_WRAPPER = 3, + //! Deserialized from storage that does not record it: not checked, and printed with LATERAL + UNRECORDED = 4 +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/file_open_flags.hpp b/src/duckdb/src/include/duckdb/common/file_open_flags.hpp index 8502eed33..26c6ad53b 100644 --- a/src/duckdb/src/include/duckdb/common/file_open_flags.hpp +++ b/src/duckdb/src/include/duckdb/common/file_open_flags.hpp @@ -35,15 +35,15 @@ class FileOpenFlags { public: FileOpenFlags() = default; - FileOpenFlags(idx_t flags) : flags(flags) { // NOLINT: allow implicit conversion + constexpr FileOpenFlags(idx_t flags) : flags(flags) { // NOLINT: allow implicit conversion } - FileOpenFlags(FileLockType lock) : lock(lock) { // NOLINT: allow implicit conversion + constexpr FileOpenFlags(FileLockType lock) : lock(lock) { // NOLINT: allow implicit conversion } - FileOpenFlags(FileCompressionType compression) // NOLINT: allow implicit conversion - : compression(std::move(compression)) { + constexpr FileOpenFlags(FileCompressionType compression) // NOLINT: allow implicit conversion + : compression(compression) { } - FileOpenFlags(idx_t flags, FileLockType lock, FileCompressionType compression) - : flags(flags), lock(lock), compression(std::move(compression)) { + constexpr FileOpenFlags(idx_t flags, FileLockType lock, FileCompressionType compression) + : flags(flags), lock(lock), compression(compression) { } static constexpr FileLockType MergeLock(FileLockType a, FileLockType b) { @@ -86,7 +86,7 @@ class FileOpenFlags { } void SetCompression(FileCompressionType new_compression) { - compression = std::move(new_compression); + compression = new_compression; } CachingMode GetCachingMode() const { diff --git a/src/duckdb/src/include/duckdb/common/file_range.hpp b/src/duckdb/src/include/duckdb/common/file_range.hpp new file mode 100644 index 000000000..a2539901a --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/file_range.hpp @@ -0,0 +1,33 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/file_range.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/typedefs.hpp" + +namespace duckdb { + +//! A byte range in a file, represented by its offset and length. +struct FileRange { + FileRange(idx_t offset_p, idx_t length_p) : offset(offset_p), length(length_p) { + } + + bool Contains(const FileRange &other) const { + return other.offset >= offset && other.offset - offset <= length && + other.length <= length - (other.offset - offset); + } + + bool operator==(const FileRange &other) const { + return offset == other.offset && length == other.length; + } + + idx_t offset; + idx_t length; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/identifier.hpp b/src/duckdb/src/include/duckdb/common/identifier.hpp index 195c54154..9b9388bad 100644 --- a/src/duckdb/src/include/duckdb/common/identifier.hpp +++ b/src/duckdb/src/include/duckdb/common/identifier.hpp @@ -23,20 +23,22 @@ namespace duckdb { //! Unlike a regular string, identifiers compare case-insensitively (using StringUtil::CIEquals). //! Internally the identifier is stored as-is (preserving the original casing), but all comparisons, //! hashing and ordering are case-insensitive. +//! A default-constructed identifier is unset (absent); an identifier constructed from a string is set, even when +//! that string is empty. Comparisons and hashing treat an unset identifier like the empty identifier. class Identifier { public: Identifier() = default; //! Construction from a string literal is implicit: literals in the source are identifiers by intent. - Identifier(const char *str) : value(str) { // NOLINT: implicit conversion from literals is intentional + Identifier(const char *str) : value(str), is_set(true) { // NOLINT: implicit conversion from literals is intentional } //! Construction from a runtime string is explicit: an Identifier carries case-insensitive semantics, so //! promoting a runtime string must be a deliberate choice at the call site. - explicit Identifier(const string &str) : value(str) { + explicit Identifier(const string &str) : value(str), is_set(true) { } - explicit Identifier(string &&str) : value(std::move(str)) { + explicit Identifier(string &&str) : value(std::move(str)), is_set(true) { } //! Construction from a string view is also explicit to be safe - explicit Identifier(const std::string_view str) : value(str) { + explicit Identifier(const std::string_view str) : value(str), is_set(true) { } //! Named constructors for well-known identifiers @@ -67,11 +69,35 @@ class Identifier { return value; } + //! Serialized form of a set, empty identifier: a single NUL byte, which cannot occur in a parsed name (and is valid + //! UTF-8, so it survives JSON). An unset identifier is serialized as the empty string. + string GetSerializedName() const { + return is_set && value.empty() ? string(1, '\0') : value; + } + static Identifier FromSerializedName(string serialized) { + if (serialized.size() == 1 && serialized[0] == '\0') { + return Identifier(string()); + } + return serialized.empty() ? Identifier() : Identifier(std::move(serialized)); + } + + //! The same identifier, but set (an unset identifier becomes the empty identifier) + Identifier AsSet() const { + return Identifier(value); + } + + //! Whether the identifier is set - an unset identifier is absent, which is different from the empty identifier + bool IsSet() const { + return is_set; + } + bool empty() const { // NOLINT: match std::string interface return value.empty(); } + //! Resets the identifier to the unset state void clear() { // NOLINT: match std::string interface value.clear(); + is_set = false; } idx_t size() const { // NOLINT: match std::string interface return value.size(); @@ -91,6 +117,7 @@ class Identifier { private: string value; + bool is_set = false; }; //! Generate an internal name: the given prefix followed by a random UUID diff --git a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_function.hpp b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_function.hpp index a70a9fd50..79075b202 100644 --- a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_function.hpp +++ b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_function.hpp @@ -1007,11 +1007,12 @@ class MultiFileFunction : public TableFunction { return MultiFileDecodeResult::JOB_FINISHED; } - //! Claims the next job and schedules its I/O, filling io_tasks when the I/O was detached to the pool. + //! Claims the next job and prepares its I/O for read-ahead admission. //! Returns null when there are no more jobs to produce. - static unique_ptr> - ProduceJob(ClientContext &context, const MultiFileBindData &bind_data, MultiFileGlobalState &gstate, - vector> &io_tasks) { + static unique_ptr> ProduceJob(ClientContext &context, + const MultiFileBindData &bind_data, + MultiFileGlobalState &gstate, + AsyncResult &io) { auto job = make_uniq>(); // jobs recycle finished scan states, create a fresh one when none was available job->scan_state = gstate.state_pool.TryPop(); @@ -1021,11 +1022,7 @@ class MultiFileFunction : public TableFunction { if (!ClaimNextJob(context, bind_data, gstate, *job)) { return nullptr; } - auto scheduled = job->reader->ScheduleIO(context, *gstate.global_state, *job->scan_state); - if (scheduled.GetResultType() == AsyncResultType::BLOCKED) { - // if we got blocked, we have tasks for the pool - io_tasks = scheduled.ExtractAsyncTasks(); - } + io = job->reader->ScheduleIO(context, *gstate.global_state, *job->scan_state); return job; } @@ -1065,9 +1062,7 @@ class MultiFileFunction : public TableFunction { } unique_ptr claimed; auto acquired = read_ahead.AcquireJob( - context, data_p, - [&](vector> &io_tasks) { return ProduceJob(context, bind_data, gstate, io_tasks); }, - claimed); + context, data_p, [&](AsyncResult &io) { return ProduceJob(context, bind_data, gstate, io); }, claimed); if (acquired == ScanReadAheadAcquire::EXHAUSTED) { // finish scan states left in the recycle pool so per-file accounting completes auto pooled_states = gstate.state_pool.TakeAll(); @@ -1282,7 +1277,7 @@ class MultiFileFunction : public TableFunction { // we try to postpone expanding the glob by only expanding it once we have scanned 1% of the files // check if we have reached AT LEAST 1% of progress idx_t one_percent_min = count_info.count / 100; - if (gstate.completed_file_index < one_percent_min) { + if (gstate.completed_file_index.load(std::memory_order_relaxed) < one_percent_min) { // we have not - just report 0% return 0.0; } @@ -1295,9 +1290,10 @@ class MultiFileFunction : public TableFunction { return 100.0; } unique_lock parallel_lock(gstate.lock); - double total_progress = 100.0 * static_cast(gstate.completed_file_index); + auto completed_file_index = gstate.completed_file_index.load(std::memory_order_relaxed); + double total_progress = 100.0 * static_cast(completed_file_index); // iterate over the files we haven't completed yet - for (idx_t i = gstate.completed_file_index; i <= gstate.file_index && i < gstate.readers.size(); i++) { + for (idx_t i = completed_file_index; i <= gstate.file_index && i < gstate.readers.size(); i++) { auto &reader_data_ptr = gstate.readers[i]; if (!reader_data_ptr) { continue; @@ -1324,12 +1320,13 @@ class MultiFileFunction : public TableFunction { } progress_in_file = MaxValue(0.0, MinValue(100.0, progress_in_file)); total_progress += progress_in_file; - if (i == gstate.completed_file_index && progress_in_file >= 100) { + if (i == completed_file_index && progress_in_file >= 100) { // if the progress in this file is 100, we have completed the file // we don't need to check anymore in the next iteration - gstate.completed_file_index++; + completed_file_index++; } } + gstate.completed_file_index.store(completed_file_index, std::memory_order_relaxed); return total_progress / static_cast(total_count); } diff --git a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_states.hpp b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_states.hpp index 5e72afdc3..c05ba0a2e 100644 --- a/src/duckdb/src/include/duckdb/common/multi_file/multi_file_states.hpp +++ b/src/duckdb/src/include/duckdb/common/multi_file/multi_file_states.hpp @@ -190,7 +190,7 @@ struct MultiFileGlobalState : public GlobalTableFunctionState { //! Number of files that were actually opened by the scan atomic files_opened = 0; //! Index of the lowest file we know we have completely read - mutable idx_t completed_file_index = 0; + mutable atomic completed_file_index {0}; //! The current set of readers vector> readers; diff --git a/src/duckdb/src/include/duckdb/common/no_destructor.hpp b/src/duckdb/src/include/duckdb/common/no_destructor.hpp new file mode 100644 index 000000000..f499b428c --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/no_destructor.hpp @@ -0,0 +1,72 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/no_destructor.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/constants.hpp" + +#include +#include + +namespace duckdb { + +//! Holds a T whose destructor is never run. +//! Use it for function-local statics: other threads can still be using the object while the process exits and static +//! destructors run, so it must stay alive. It owns inline storage, so nothing is allocated and there is no leak. +//! Prefer a trivially destructible type (e.g. constexpr data) when possible - it needs neither this nor a lock. +//! +//! static const NoDestructor set(case_insensitive_set_t {"a", "b"}); +//! return *set; +template +class NoDestructor { +public: + template + explicit NoDestructor(ARGS &&...args) { + new (storage) T(std::forward(args)...); + } + NoDestructor(const NoDestructor &) = delete; + NoDestructor &operator=(const NoDestructor &) = delete; + +public: + T &operator*() { + return *Get(); + } + const T &operator*() const { + return *Get(); + } + T *operator->() { + return Get(); + } + const T *operator->() const { + return Get(); + } + T *Get() { + return std::launder(reinterpret_cast(storage)); + } + const T *Get() const { + return std::launder(reinterpret_cast(storage)); + } + +private: + alignas(T) char storage[sizeof(T)]; +}; + +} // namespace duckdb + +//! Static lifetime checks (-Wexit-time-destructors, -Wglobal-constructors) are enforced for first-party code - see +//! the STATIC_LIFETIME_WARNINGS CMake option. Use these only where a destructor must run (e.g. thread_local cleanup) or +//! a constructor must run before main (e.g. registration), and say why next to the use. +#if defined(__clang__) +#define DUCKDB_ALLOW_STATIC_LIFETIME_BEGIN \ + _Pragma("clang diagnostic push") _Pragma("clang diagnostic ignored \"-Wexit-time-destructors\"") \ + _Pragma("clang diagnostic ignored \"-Wglobal-constructors\"") +#define DUCKDB_ALLOW_STATIC_LIFETIME_END _Pragma("clang diagnostic pop") +#else +#define DUCKDB_ALLOW_STATIC_LIFETIME_BEGIN +#define DUCKDB_ALLOW_STATIC_LIFETIME_END +#endif diff --git a/src/duckdb/src/include/duckdb/common/partition_selection.hpp b/src/duckdb/src/include/duckdb/common/partition_selection.hpp new file mode 100644 index 000000000..b6980bb91 --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/partition_selection.hpp @@ -0,0 +1,82 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/partition_selection.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/fixed_size_map.hpp" +#include "duckdb/common/optional_idx.hpp" +#include "duckdb/common/types/vector.hpp" + +namespace duckdb { + +//! Reusable bookkeeping for grouping input rows by partition. +struct PartitionSelectionState { +public: + PartitionSelectionState() : partition_indices(LogicalType::UBIGINT) { + } + +public: + bool compute_reverse_partition_sel = false; + + //! Partition IDs in append order, before applying the grouped selection. + Vector partition_indices; + SelectionVector partition_sel; + SelectionVector reverse_partition_sel; + + static constexpr idx_t MAP_THRESHOLD = 256; + //! Stable ranges in partition_sel after Build; a single partition uses the input selection directly. + perfect_map_t partition_entries; + fixed_size_map_t fixed_partition_entries; + unsafe_vector partition_offsets; + +public: + //! INVALID_INDEX allows dynamically discovered partition IDs. + void Initialize(idx_t max_partition_idx); + //! append_sel maps positions in partition_indices back to input rows. + void Build(const SelectionVector &append_sel, idx_t append_count, idx_t max_partition_idx) { + D_ASSERT(append_count <= STANDARD_VECTOR_SIZE); + if (compute_reverse_partition_sel && !reverse_partition_sel.data()) { + reverse_partition_sel.Initialize(); + } + if (max_partition_idx < MAP_THRESHOLD) { + BuildInternal(append_sel, append_count, max_partition_idx); + } else { + BuildInternal(append_sel, append_count, max_partition_idx); + } + } + + template + typename std::conditional, perfect_map_t>::type &GetMap(); + + optional_idx GetPartitionIndexIfSinglePartition(bool use_fixed_size_map) const { + if (use_fixed_size_map) { + if (fixed_partition_entries.size() == 1) { + return fixed_partition_entries.begin().GetKey(); + } + } else if (partition_entries.size() == 1) { + return partition_entries.begin()->first; + } + return optional_idx(); + } + +private: + template + void BuildInternal(const SelectionVector &append_sel, idx_t append_count, idx_t max_partition_idx); +}; + +template <> +inline perfect_map_t &PartitionSelectionState::GetMap() { + return partition_entries; +} + +template <> +inline fixed_size_map_t &PartitionSelectionState::GetMap() { + return fixed_partition_entries; +} + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/random_engine.hpp b/src/duckdb/src/include/duckdb/common/random_engine.hpp index 0373ff872..e6a29493b 100644 --- a/src/duckdb/src/include/duckdb/common/random_engine.hpp +++ b/src/duckdb/src/include/duckdb/common/random_engine.hpp @@ -51,6 +51,17 @@ class RandomEngine { static uint64_t NextRandomInteger64(GENERATOR &generator) { return (static_cast(generator()) << UINT64_C(32)) | static_cast(generator()); } + //! A uniform integer in [0, bound): 64-bit words below 2^64 mod bound are rejected, so no remainder is favored + template + static uint64_t NextRandomInteger64Below(GENERATOR &generator, uint64_t bound) { + D_ASSERT(bound > 0); + const auto threshold = (UINT64_C(0) - bound) % bound; + uint64_t value; + do { + value = NextRandomInteger64(generator); + } while (value < threshold); + return value % bound; + } template static double NextRandom(GENERATOR &generator) { return std::ldexp(NextRandomInteger64(generator), -64); diff --git a/src/duckdb/src/include/duckdb/common/sorting/sort_key.hpp b/src/duckdb/src/include/duckdb/common/sorting/sort_key.hpp index 3a3b29e1d..aa48b6213 100644 --- a/src/duckdb/src/include/duckdb/common/sorting/sort_key.hpp +++ b/src/duckdb/src/include/duckdb/common/sorting/sort_key.hpp @@ -145,6 +145,10 @@ struct SortKeyPayload { } }; +//! Thrown when a key is larger than the fixed-size sort key that was selected for it. +//! The size is derived from the statistics of the sort columns, so this means that the statistics are wrong. +[[noreturn]] DUCKDB_API void ThrowSortKeyExceedsFixedSize(idx_t key_size, idx_t fixed_size); + template static bool SortKeyLessThan(const uint64_t *const &lhs, const uint64_t *const &rhs) { return (*lhs < *rhs) || ((*lhs == *rhs) && SortKeyLessThan(lhs + 1, rhs + 1)); @@ -172,7 +176,10 @@ struct FixedSortKey : std::conditional, So } void Construct(const string_t &str, data_ptr_t &) { - D_ASSERT(str.GetSize() <= SORT_KEY::INLINE_LENGTH); + if (DUCKDB_UNLIKELY(str.GetSize() > SORT_KEY::INLINE_LENGTH)) { + // the size of a fixed-size key is derived from the statistics of the sort columns + ThrowSortKeyExceedsFixedSize(str.GetSize(), SORT_KEY::INLINE_LENGTH); + } auto &sort_key = static_cast(*this); for (idx_t i = 0; i < SORT_KEY::PARTS; i++) { (&sort_key.part0)[i] = 0; diff --git a/src/duckdb/src/include/duckdb/common/static_string_table.hpp b/src/duckdb/src/include/duckdb/common/static_string_table.hpp new file mode 100644 index 000000000..bb810a189 --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/static_string_table.hpp @@ -0,0 +1,127 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/static_string_table.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/constants.hpp" +#include "duckdb/common/optional_ptr.hpp" +#include "duckdb/common/string.hpp" + +namespace duckdb { + +//! A view over a constexpr array of string literals. It is trivially destructible and constructed at compile time, so +//! unlike a static set it needs no initialization, no lock and no NoDestructor. +//! +//! static constexpr const char *const KEYWORDS[] = {"SELECT", "FROM"}; +//! return StaticStringSet(KEYWORDS).Contains(word); +class StaticStringSet { +public: + template + constexpr StaticStringSet(const char *const (&entries_p)[N]) // NOLINT: allow implicit conversion from an array + : entries(entries_p), count(N) { + } + +public: + constexpr const char *const *begin() const { // NOLINT: match stl API + return entries; + } + constexpr const char *const *end() const { // NOLINT: match stl API + return entries + count; + } + constexpr idx_t size() const { // NOLINT: match stl API + return count; + } + + //! Whether any entry compares equal to the value with == + template + bool Contains(const T &value) const { + for (auto entry : *this) { + if (value == entry) { + return true; + } + } + return false; + } + //! Whether any entry equals the value, ignoring ASCII case + bool ContainsCaseInsensitive(const string &value) const { + for (auto entry : *this) { + if (EqualsCaseInsensitive(entry, value)) { + return true; + } + } + return false; + } + + static bool EqualsCaseInsensitive(const char *literal, const string &value) { + idx_t i = 0; + for (; literal[i] != '\0'; i++) { + if (i >= value.size() || ToLower(literal[i]) != ToLower(value[i])) { + return false; + } + } + return i == value.size(); + } + +private: + static constexpr char ToLower(char c) { + return c >= 'A' && c <= 'Z' ? static_cast(c - 'A' + 'a') : c; + } + +private: + const char *const *entries; + idx_t count; +}; + +//! A view over a constexpr array of (string literal, value) pairs, see StaticStringSet. +template +class StaticStringMap { +public: + struct Entry { + const char *key; + T value; + }; + +public: + template + constexpr StaticStringMap(const Entry (&entries_p)[N]) // NOLINT: allow implicit conversion from an array + : entries(entries_p), count(N) { + } + +public: + constexpr const Entry *begin() const { // NOLINT: match stl API + return entries; + } + constexpr const Entry *end() const { // NOLINT: match stl API + return entries + count; + } + + //! The value of the entry whose key equals the argument, if any + optional_ptr Find(const string &key) const { + for (auto &entry : *this) { + if (key == entry.key) { + return entry.value; + } + } + return nullptr; + } + //! The value of the entry whose key equals the argument ignoring ASCII case, if any + optional_ptr FindCaseInsensitive(const string &key) const { + for (auto &entry : *this) { + if (StaticStringSet::EqualsCaseInsensitive(entry.key, key)) { + return entry.value; + } + } + return nullptr; + } + +private: + const Entry *entries; + idx_t count; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/type_visitor.hpp b/src/duckdb/src/include/duckdb/common/type_visitor.hpp index 2d9c08fe8..c65d9aabf 100644 --- a/src/duckdb/src/include/duckdb/common/type_visitor.hpp +++ b/src/duckdb/src/include/duckdb/common/type_visitor.hpp @@ -80,14 +80,23 @@ inline LogicalType TypeVisitor::RebuildType(const VisitorFrame &frame, vector 0); D_ASSERT(result_stack.size() >= frame.expected_children_count); const auto &type = frame.original_type; + // an untouched child shares its type info instance: when no child was replaced, return the + // original type itself, preserving its identity (alias, extension metadata). A container with + // a replaced child is rebuilt without that metadata, since the replacement may invalidate it switch (type.id()) { case LogicalTypeId::STRUCT: case LogicalTypeId::TUPLE: case LogicalTypeId::UNION: { auto children = type.id() == LogicalTypeId::UNION ? UnionType::CopyMemberTypes(type) : StructType::GetChildTypes(type); + bool modified = false; for (idx_t i = children.size(); i > 0; i--) { - children[i - 1].second = PopType(result_stack); + auto child = PopType(result_stack); + modified = modified || &child.GetTypeInfo() != &children[i - 1].second.GetTypeInfo(); + children[i - 1].second = std::move(child); + } + if (!modified) { + return type; } if (type.id() == LogicalTypeId::STRUCT) { return LogicalType::STRUCT(std::move(children)); @@ -100,12 +109,29 @@ inline LogicalType TypeVisitor::RebuildType(const VisitorFrame &frame, vector { uint32_t target_scale, string &result, optional_ptr context = nullptr); + //! Divides two unscaled values and rounds the quotient: the dividend (scale_exponent > 0) or the divisor + //! (scale_exponent < 0) is first multiplied by 10^|scale_exponent|. Returns false when the divisor is zero. The + //! result borrows from the state; consume it before resetting the state + DUCKDB_API static bool TryDivide(RescaleState &state, const bignum_t ÷nd, const bignum_t &divisor, + int64_t scale_exponent, DecimalRounding rounding, bignum_t &result); + //! Converts an unscaled value with the given scale to a FLOAT or DOUBLE, rounding once (through the decimal //! string), returns false if the value is out of range DUCKDB_API static bool TryToFloating(const bignum_t &value, uint32_t scale, float &result, diff --git a/src/duckdb/src/include/duckdb/common/types/column/column_data_collection.hpp b/src/duckdb/src/include/duckdb/common/types/column/column_data_collection.hpp index 17c223cfa..ae286dcde 100644 --- a/src/duckdb/src/include/duckdb/common/types/column/column_data_collection.hpp +++ b/src/duckdb/src/include/duckdb/common/types/column/column_data_collection.hpp @@ -20,6 +20,7 @@ struct ColumnDataCopyFunction; class ColumnDataAllocator; class ColumnDataCollection; class ColumnDataCollectionSegment; +class ColumnDataSharedChildAccounting; class ColumnDataRowCollection; struct ColumnDataSelectionTarget; struct ColumnDataChildSelections; @@ -86,6 +87,10 @@ class ColumnDataCollection { idx_t SizeInBytes() const; //! The allocation size (in bytes) of this ColumnDataCollection - this property is cached idx_t AllocationSize() const; + //! Let NULL-free large list children appended to this (buffer-managed) collection reference shared child storage, + //! so lists carried or grown across recursive CTE iterations are not copied per append. Must be called before + //! the first append. Other collections copy list children + void EnableSharedListChildren(); //! Sets the partition index of this ColumnDataCollection void SetPartitionIndex(idx_t index); @@ -235,6 +240,10 @@ class ColumnDataCollection { idx_t count; //! The data segments of the column data collection vector> segments; + //! Accounts the shared child storage the segments reference once per collection (created with the first segment) + shared_ptr shared_child_accounting; + //! Whether appended large list children reference shared child storage + bool share_list_children = false; //! The set of copy functions vector copy_functions; //! When the column data collection is marked as finished - new tuples can no longer be appended to it diff --git a/src/duckdb/src/include/duckdb/common/types/column/column_data_collection_segment.hpp b/src/duckdb/src/include/duckdb/common/types/column/column_data_collection_segment.hpp index e010637d6..785a3d651 100644 --- a/src/duckdb/src/include/duckdb/common/types/column/column_data_collection_segment.hpp +++ b/src/duckdb/src/include/duckdb/common/types/column/column_data_collection_segment.hpp @@ -9,8 +9,10 @@ #pragma once #include "duckdb/common/atomic.hpp" +#include "duckdb/common/map.hpp" #include "duckdb/common/types/column/column_data_allocator.hpp" #include "duckdb/common/types/column/column_data_collection.hpp" +#include "duckdb/common/vector/shared_child_prefix.hpp" namespace duckdb { @@ -44,10 +46,80 @@ enum class ColumnDataRepresentation : uint8_t { CONSTANT, //! Per-row dictionary codes in block data referencing a per-segment dictionary DICTIONARY, - //! Row values of a list child longer than a vector, in block data sized to exactly its count + //! Row values of a list child longer than a vector, sized to exactly its count. Stored in block data, or (in + //! collections that share list children) in shared child storage (see VectorMetaData::shared_child_slot) LARGE_FLAT }; +//! The distinct shared child storage the segments of one collection reference, so the collection accounts each +//! storage once: its allocation (the whole capacity, including room to grow) in AllocationSize, and the bytes the +//! collection's entries reference (the longest referenced prefix) in UsedSize +class ColumnDataSharedChildAccounting { +public: + //! A segment references storage 'id' of 'size' bytes, its entries 'used' bytes of it + void AddReference(idx_t id, idx_t size, idx_t used); + //! The entries of a segment that references storage 'id' now reference 'used' instead of 'previous' bytes of it + void UpdateUsed(idx_t id, idx_t previous, idx_t used); + //! A segment whose entries referenced 'used' bytes of storage 'id' no longer references it + void RemoveReference(idx_t id, idx_t used); + idx_t AllocationSize() const { + return allocation_size; + } + idx_t UsedSize() const { + return used_size; + } + +private: + struct Entry { + idx_t size; + //! The number of segments by the bytes their entries reference, the largest key is the used size + map segments_by_used; + }; + void SetUsed(Entry &entry, idx_t previous_used); + unordered_map entries; + idx_t allocation_size = 0; + idx_t used_size = 0; +}; + +//! The shared child prefixes the LARGE_FLAT entries of one segment reference, and their accounting in the collection. +//! A segment shares list children exactly if it is constructed with an accounting object, and the policy never +//! changes afterwards. Adding a reference, Reset, destruction and moving the segment into another collection keep the +//! references and the collection accounting consistent here, in one place. +class ColumnDataSegmentSharedChildren { +public: + explicit ColumnDataSegmentSharedChildren(shared_ptr accounting); + ~ColumnDataSegmentSharedChildren(); + ColumnDataSegmentSharedChildren(const ColumnDataSegmentSharedChildren &) = delete; + ColumnDataSegmentSharedChildren &operator=(const ColumnDataSegmentSharedChildren &) = delete; + + //! Whether the segment references shared child storage for large list children + bool Enabled() const { + return accounting != nullptr; + } + //! Reference 'prefix' from a new entry, returns the entry's slot + idx_t Add(SharedChildPrefix prefix); + //! The prefix the entry with 'slot' references + const SharedChildPrefix &Get(idx_t slot) const { + D_ASSERT(slot < prefixes.size()); + return prefixes[slot]; + } + //! Drop all references + void Reset(); + //! Account the referenced storage in 'target' instead (the segment moves into another collection) + void MoveAccounting(shared_ptr target); + +private: + //! Remove the references of this segment from the accounting + void ReleaseAccounting(); + + //! The prefix referenced by each entry, indexed by the entry's 'shared_child_slot' + vector prefixes; + //! The allocation and the longest referenced prefix in bytes of each distinct storage, by storage id + unordered_map> sizes; + //! Accounts the shared child storage of all segments of the collection, null if the segment does not share + shared_ptr accounting; +}; + //! The value of a CONSTANT entry struct ColumnDataConstantValue { //! The value bytes (fixed-size values and string_t entries are stored inline) @@ -101,6 +173,8 @@ struct VectorMetaData { ColumnDataConstantValue constant; //! The dictionary slot in the segment (only used for DICTIONARY entries) idx_t dictionary_slot = DConstants::INVALID_INDEX; + //! The shared list child slot in the segment (only used for LARGE_FLAT entries without block data) + idx_t shared_child_slot = DConstants::INVALID_INDEX; //! Meta data about string pointers vector swizzle_data; @@ -132,7 +206,9 @@ struct ChunkMetaData { class ColumnDataCollectionSegment { public: - ColumnDataCollectionSegment(shared_ptr allocator, vector types_p); + //! A segment shares large list children exactly if it is given the collection's 'shared_child_accounting' + ColumnDataCollectionSegment(shared_ptr allocator, vector types_p, + shared_ptr shared_child_accounting = nullptr); public: //! The allocator and allocation statistics @@ -158,6 +234,8 @@ class ColumnDataCollectionSegment { vector dictionaries; //! Map from dictionary id to a slot in "dictionaries" unordered_map dictionary_map; + //! The shared child storage LARGE_FLAT entries reference (recursive CTE tables only) + ColumnDataSegmentSharedChildren shared_children; //! The string heap for the column data collection (only used for IN_MEMORY_ALLOCATOR) shared_ptr heap; @@ -178,6 +256,9 @@ class ColumnDataCollectionSegment { //! Allocate a LARGE_FLAT entry holding exactly 'count' rows of a constant-size type VectorDataIndex AllocateLargeVector(idx_t type_size, idx_t count, ChunkMetaData &chunk_meta, ChunkManagementState *chunk_state); + //! Add a LARGE_FLAT entry referencing 'prefix' + VectorDataIndex AddSharedLargeVector(SharedChildPrefix prefix, ChunkMetaData &chunk_meta, + VectorDataIndex prev_index); //! Allocate block storage for an entry whose allocation was deferred or whose storage is replaced void AllocateVectorStorage(VectorDataIndex index, idx_t allocation_size, ChunkMetaData &chunk_meta, ChunkManagementState *chunk_state); @@ -185,6 +266,15 @@ class ColumnDataCollectionSegment { void UnswizzleEntryPointers(ChunkManagementState &state, VectorMetaData &vdata, Vector &result); //! Read the materialized dictionary values of the given slot as a zero-copy vector Vector ReadSegmentDictionary(ChunkManagementState &state, idx_t slot); + //! Whether an entry references shared list child storage instead of block data + static bool IsSharedListChild(const VectorMetaData &vdata) { + return vdata.shared_child_slot != DConstants::INVALID_INDEX; + } + //! The shared child prefix of an entry for which IsSharedListChild holds + const SharedChildPrefix &GetSharedListChild(const VectorMetaData &vdata) const { + D_ASSERT(IsSharedListChild(vdata) && vdata.representation == ColumnDataRepresentation::LARGE_FLAT); + return shared_children.Get(vdata.shared_child_slot); + } //! Load the value of a CONSTANT entry, resolving heap-resident string bytes string_t GetConstantString(ChunkManagementState &state, const VectorMetaData &vdata); @@ -207,9 +297,9 @@ class ColumnDataCollectionSegment { static idx_t GetVectorCapacity(const VectorMetaData &vdata); idx_t ChunkCount() const; - //! Get the total *used* size (not cached) + //! Get the total *used* size (not cached), without shared child storage (see shared_children) idx_t SizeInBytes() const; - //! Get the currently allocated size in bytes (cached) + //! Get the currently allocated size in bytes (cached), without shared child storage idx_t AllocationSize() const; //! Get the allocation size of the chunk idx_t GetChunkAllocationSize(idx_t chunk_index) const; diff --git a/src/duckdb/src/include/duckdb/common/types/column/partitioned_column_data.hpp b/src/duckdb/src/include/duckdb/common/types/column/partitioned_column_data.hpp index 8a4bd37df..de0747a21 100644 --- a/src/duckdb/src/include/duckdb/common/types/column/partitioned_column_data.hpp +++ b/src/duckdb/src/include/duckdb/common/types/column/partitioned_column_data.hpp @@ -8,63 +8,19 @@ #pragma once -#include "duckdb/common/fixed_size_map.hpp" -#include "duckdb/common/optional_idx.hpp" -#include "duckdb/common/perfect_map_set.hpp" +#include "duckdb/common/partition_selection.hpp" #include "duckdb/common/types/column/column_data_allocator.hpp" #include "duckdb/common/types/column/column_data_collection.hpp" namespace duckdb { //! Local state for parallel partitioning -struct PartitionedColumnDataAppendState { -public: - PartitionedColumnDataAppendState() : partition_indices(LogicalType::UBIGINT) { - } - -public: - Vector partition_indices; - SelectionVector partition_sel; - - static constexpr idx_t MAP_THRESHOLD = 256; - perfect_map_t partition_entries; - fixed_size_map_t fixed_partition_entries; - +struct PartitionedColumnDataAppendState : public PartitionSelectionState { vector> partition_append_states; //! The partitions an append writes to, reused by the next append vector partition_targets; - -public: - template - typename std::conditional, perfect_map_t>::type &GetMap() { - throw NotImplementedException("PartitionedColumnDataAppendState::GetMap for boolean value"); - } - - optional_idx GetPartitionIndexIfSinglePartition(const bool use_fixed_size_map) { - optional_idx result; - if (use_fixed_size_map) { - if (fixed_partition_entries.size() == 1) { - result = fixed_partition_entries.begin().GetKey(); - } - } else { - if (partition_entries.size() == 1) { - result = partition_entries.begin()->first; - } - } - return result; - } }; -template <> -inline perfect_map_t &PartitionedColumnDataAppendState::GetMap() { - return partition_entries; -} - -template <> -inline fixed_size_map_t &PartitionedColumnDataAppendState::GetMap() { - return fixed_partition_entries; -} - enum class PartitionedColumnDataType : uint8_t { INVALID, //! Radix partitioning on a hash column @@ -125,11 +81,6 @@ class PartitionedColumnData { void CreateAllocator(); //! Whether to use fixed size map or regular map bool UseFixedSizeMap() const; - //! Builds a selection vector in the Append state for the partitions - //! - returns true if everything belongs to the same partition - stores partition index in single_partition_idx - void BuildPartitionSel(PartitionedColumnDataAppendState &state, const idx_t append_count) const; - template - static void BuildPartitionSel(PartitionedColumnDataAppendState &state, const idx_t append_count); //! Appends a DataChunk to this PartitionedColumnData template void AppendInternal(PartitionedColumnDataAppendState &state, DataChunk &input); diff --git a/src/duckdb/src/include/duckdb/common/types/date.hpp b/src/duckdb/src/include/duckdb/common/types/date.hpp index f3a76863d..903f86091 100644 --- a/src/duckdb/src/include/duckdb/common/types/date.hpp +++ b/src/duckdb/src/include/duckdb/common/types/date.hpp @@ -98,10 +98,12 @@ class Date { static const DateSpecial NINF; // NOLINT static const DateSpecial EPOCH; // NOLINT - static const string_t MONTH_NAMES[12]; - static const string_t MONTH_NAMES_ABBREVIATED[12]; - static const string_t DAY_NAMES[7]; - static const string_t DAY_NAMES_ABBREVIATED[7]; + //! The 12 month names, January first + DUCKDB_API static const string_t *MonthNames(); + DUCKDB_API static const string_t *MonthNamesAbbreviated(); + //! The 7 day names, Sunday first + DUCKDB_API static const string_t *DayNames(); + DUCKDB_API static const string_t *DayNamesAbbreviated(); static const int32_t NORMAL_DAYS[13]; static const int32_t CUMULATIVE_DAYS[13]; static const int32_t LEAP_DAYS[13]; diff --git a/src/duckdb/src/include/duckdb/common/types/row/partitioned_tuple_data.hpp b/src/duckdb/src/include/duckdb/common/types/row/partitioned_tuple_data.hpp index 5e9e76534..3b04ad24e 100644 --- a/src/duckdb/src/include/duckdb/common/types/row/partitioned_tuple_data.hpp +++ b/src/duckdb/src/include/duckdb/common/types/row/partitioned_tuple_data.hpp @@ -8,70 +8,22 @@ #pragma once -#include "duckdb/common/fixed_size_map.hpp" -#include "duckdb/common/optional_idx.hpp" +#include "duckdb/common/partition_selection.hpp" #include "duckdb/common/optional_ptr.hpp" -#include "duckdb/common/perfect_map_set.hpp" #include "duckdb/common/types/row/tuple_data_allocator.hpp" #include "duckdb/common/types/row/tuple_data_collection.hpp" namespace duckdb { //! Local state for parallel partitioning -struct PartitionedTupleDataAppendState { -public: - PartitionedTupleDataAppendState() : partition_indices(LogicalType::UBIGINT) { - } - -public: - bool compute_reverse_partition_sel = false; - - Vector partition_indices; - SelectionVector partition_sel; - SelectionVector reverse_partition_sel; - - static constexpr idx_t MAP_THRESHOLD = 256; - perfect_map_t partition_entries; - fixed_size_map_t fixed_partition_entries; - unsafe_vector partition_offsets; - +struct PartitionedTupleDataAppendState : public PartitionSelectionState { unsafe_vector partition_pin_states; TupleDataChunkState chunk_state; //! Utility Vector for when repartitioning and copying rows straight from one collection to another unique_ptr utility_vector; - -public: - template - typename std::conditional, perfect_map_t>::type &GetMap() { - throw NotImplementedException("PartitionedTupleDataAppendState::GetMap for boolean value"); - } - - optional_idx GetPartitionIndexIfSinglePartition(const bool use_fixed_size_map) { - optional_idx result; - if (use_fixed_size_map) { - if (fixed_partition_entries.size() == 1) { - result = fixed_partition_entries.begin().GetKey(); - } - } else { - if (partition_entries.size() == 1) { - result = partition_entries.begin()->first; - } - } - return result; - } }; -template <> -inline perfect_map_t &PartitionedTupleDataAppendState::GetMap() { - return partition_entries; -} - -template <> -inline fixed_size_map_t &PartitionedTupleDataAppendState::GetMap() { - return fixed_partition_entries; -} - enum class PartitionedTupleDataType : uint8_t { INVALID, //! Radix partitioning on a hash column @@ -192,13 +144,6 @@ class PartitionedTupleData { //! Whether to use fixed size map or regular map bool UseFixedSizeMap() const; - //! Builds a selection vector in the Append state for the partitions - //! - returns true if everything belongs to the same partition - stores partition index in single_partition_idx - void BuildPartitionSel(PartitionedTupleDataAppendState &state, const SelectionVector &append_sel, - const idx_t append_count) const; - template - static void BuildPartitionSel(PartitionedTupleDataAppendState &state, const SelectionVector &append_sel, - const idx_t append_count, const idx_t max_partition_idx); //! Builds out the buffer space in the partitions void BuildBufferSpace(PartitionedTupleDataAppendState &state); template diff --git a/src/duckdb/src/include/duckdb/common/types/validity_mask.hpp b/src/duckdb/src/include/duckdb/common/types/validity_mask.hpp index f3c351bf8..06ba0aeff 100644 --- a/src/duckdb/src/include/duckdb/common/types/validity_mask.hpp +++ b/src/duckdb/src/include/duckdb/common/types/validity_mask.hpp @@ -107,6 +107,26 @@ struct TemplatedValidityMask { } return true; } + //! Drops a mask that marks its whole capacity valid, so that readers take their no-NULL paths + inline void ResetIfAllValid() { + if (!validity_mask) { + return; + } + const auto full_entries = capacity / BITS_PER_VALUE; + for (idx_t entry_idx = 0; entry_idx < full_entries; entry_idx++) { + if (!AllValid(validity_mask[entry_idx])) { + return; + } + } + const auto ragged = capacity % BITS_PER_VALUE; + if (ragged != 0) { + const auto ragged_mask = EntryWithValidBits(ragged); + if ((validity_mask[full_entries] & ragged_mask) != ragged_mask) { + return; + } + } + Reset(capacity); + } idx_t CountValid(const idx_t count) const { if (CannotHaveNull() || count == 0) { diff --git a/src/duckdb/src/include/duckdb/common/types/vector_buffer.hpp b/src/duckdb/src/include/duckdb/common/types/vector_buffer.hpp index 2c02ca0a4..06a527b92 100644 --- a/src/duckdb/src/include/duckdb/common/types/vector_buffer.hpp +++ b/src/duckdb/src/include/duckdb/common/types/vector_buffer.hpp @@ -38,7 +38,8 @@ enum class VectorBufferType : uint8_t { DICTIONARY_BUFFER, // VectorType::DICTIONARY - Any - Holds SelectionVector and dict child vector FSST_BUFFER, // VectorType::FSST - String - Holds string_t array, StringHeap and FSST table SHREDDED_BUFFER, // VectorType::SHREDDED - Variant - Holds shredded variant - SEQUENCE_BUFFER // VectorType::SEQUENCE - Any - Holds linear numeric sequence (start, increment) + SEQUENCE_BUFFER, // VectorType::SEQUENCE - Any - Holds linear numeric sequence (start, increment) + SHARED_DATA_BUFFER // VectorType::FLAT - Fixed-Size Type - Holds immutable data shared between owners }; enum class VectorAppendMode { ALLOW_RESIZE, ERROR_ON_NO_SPACE }; diff --git a/src/duckdb/src/include/duckdb/common/vector/flat_vector.hpp b/src/duckdb/src/include/duckdb/common/vector/flat_vector.hpp index 5dc609485..95f6de193 100644 --- a/src/duckdb/src/include/duckdb/common/vector/flat_vector.hpp +++ b/src/duckdb/src/include/duckdb/common/vector/flat_vector.hpp @@ -181,6 +181,13 @@ struct FlatVector { validity.Initialize(new_validity); } static void CopyValidity(Vector &vector, const Vector &source, idx_t count); + //! Drops the validity masks of the vector and its nested children that mark every row valid. Leaves non-flat + //! vectors alone. + DUCKDB_API static void DropAllValidMasks(Vector &vector); + //! Prepares a vector whose values are about to be overwritten. A vector borrowing its values (a view of shared + //! child storage) gets a fresh uninitialized buffer of 'capacity' rows instead, without copying the discarded + //! values and without changing other vectors that share the old buffer. Other vectors are left as they are + DUCKDB_API static void PrepareForOverwrite(Vector &vector, idx_t capacity); DUCKDB_API static void SetNull(Vector &vector, idx_t idx, bool is_null); static inline bool IsNull(const Vector &vector, idx_t idx) { D_ASSERT(vector.GetVectorType() == VectorType::FLAT_VECTOR); diff --git a/src/duckdb/src/include/duckdb/common/vector/shared_child_prefix.hpp b/src/duckdb/src/include/duckdb/common/vector/shared_child_prefix.hpp new file mode 100644 index 000000000..d7c7e1918 --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/vector/shared_child_prefix.hpp @@ -0,0 +1,58 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/vector/shared_child_prefix.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/common.hpp" +#include "duckdb/common/shared_ptr.hpp" + +namespace duckdb { +class BufferManager; +class SharedChildStorage; + +//! The first 'Count()' entries of shared child storage, all of them written. Only SharedChildVector creates prefixes +//! (Materialize, TryExtend and GetUnchangedPrefix), after the entries are written, so every prefix is readable. Views +//! (SharedChildVector::SetView) and collections hold prefixes, never the storage itself, so nothing outside the +//! vector layer allocates, reserves or writes shared storage. +class SharedChildPrefix { +public: + SharedChildPrefix() = default; + + explicit operator bool() const { + return storage != nullptr; + } + //! The number of written entries the prefix covers + idx_t Count() const { + return count; + } + //! The entries the storage can hold + idx_t Capacity() const; + idx_t TypeSize() const; + //! The bytes of the storage block + idx_t AllocationSize() const; + //! A process-unique identity of the storage, so accounting never confuses storage that reuses an address + idx_t StorageId() const; + //! Whether 'buffer_manager' backs the storage + bool IsBackedBy(const BufferManager &buffer_manager) const; + //! Whether both prefixes are prefixes of the same storage + bool SharesStorage(const SharedChildPrefix &other) const; + //! The first 'new_count' entries of this prefix + SharedChildPrefix Prefix(idx_t new_count) const; + //! Copy the entries into 'target' ('Count() * TypeSize()' bytes) + void CopyTo(data_ptr_t target) const; + +private: + friend struct SharedChildVector; + friend class SharedChildBuffer; + SharedChildPrefix(shared_ptr storage, idx_t count); + + shared_ptr storage; + idx_t count = 0; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/vector/shared_child_vector.hpp b/src/duckdb/src/include/duckdb/common/vector/shared_child_vector.hpp new file mode 100644 index 000000000..d5b14f008 --- /dev/null +++ b/src/duckdb/src/include/duckdb/common/vector/shared_child_vector.hpp @@ -0,0 +1,105 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/common/vector/shared_child_vector.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/vector/shared_child_prefix.hpp" +#include "duckdb/common/vector/flat_vector.hpp" +#include "duckdb/storage/buffer/buffer_handle.hpp" + +namespace duckdb { + +// Shared child storage holds NULL-free fixed-size entries (the child of large lists) in one buffer-managed block, +// shared by vectors and by the ColumnDataCollections of a recursive CTE. The block spills while no vector pins it. +// Written entries never change. The storage may grow at its end: an extension reserves the entries behind a prefix, +// writes them, and only then publishes the longer prefix. Allocation, reservation and writing are private to +// SharedChildVector, everything else holds SharedChildPrefix values, which only cover written entries. + +//! A flat vector buffer viewing 'count' entries of shared storage from 'offset'. The view pins the block while it is +//! attached. Writes never reach the storage: +//! - a data write (mutable data, SetValue of a value, copies into the buffer, reserve) copies the viewed entries into +//! private memory and releases the block and its pin, after which the buffer is a plain StandardVectorBuffer +//! - the validity is the view's own, initially all-valid without a mask (the storage holds no NULLs), a NULL write +//! allocates a private mask, and forwarding the validity elsewhere forwards that mask, never storage memory +//! - slices are views themselves +//! Pointers taken from a view (GetData, UnifiedVectorFormat) stay valid only until the next data write to it, which +//! moves the entries and releases the block. +//! A view counts the storage in its allocation size only if it created it (a list_concat result), all other views +//! borrow it and count nothing, like slices of a StandardVectorBuffer +class SharedChildBuffer : public StandardVectorBuffer { +public: + //! A view of 'count' entries of 'prefix' from 'offset' + SharedChildBuffer(const SharedChildPrefix &prefix, idx_t offset, idx_t count, bool owns_storage = false); + ~SharedChildBuffer() override; + + //! The prefix this buffer presents unchanged (attached, flat, from the start, no NULL written), or an empty prefix + SharedChildPrefix GetUnchangedPrefix() const; + + data_ptr_t GetDataMutable() override; + void ResetCapacity(idx_t capacity) override; + void SetValue(const LogicalType &type, idx_t index, const Value &val) override; + idx_t GetAllocationSize() const override; + +protected: + using StandardVectorBuffer::SliceInternal; + buffer_ptr SliceInternal(const LogicalType &type, idx_t offset, idx_t end) override; + buffer_ptr ConstantSliceInternal(const LogicalType &type, count_t count) override; + void CopyInternal(const Vector &source, const SelectionVector &source_sel, idx_t source_count, idx_t source_offset, + idx_t target_offset, idx_t copy_count) override; + void ReserveInternal(idx_t new_size) override; + +private: + SharedChildBuffer(shared_ptr storage, BufferHandle pin, idx_t offset, idx_t count, + bool owns_storage); + //! Copy the viewed entries into private memory and release the storage + void DetachData(idx_t new_capacity); + //! Release the storage and its pin + void Release(); + + shared_ptr storage; + //! Pins the block for reading while the view is attached + BufferHandle pin; + //! The first viewed entry of the storage + idx_t view_offset; + //! Whether this view created the storage and accounts it + bool owns_storage; +}; + +//! One list whose entries are appended behind a prefix +struct SharedChildExtra { + const Vector &child; + list_entry_t entry; +}; + +//! Access to list children backed by shared child storage +struct SharedChildVector { + //! The prefix 'child' presents unchanged, or an empty prefix + DUCKDB_API static SharedChildPrefix GetUnchangedPrefix(const Vector &child); + //! Make 'result' a view of 'prefix' + DUCKDB_API static void SetView(Vector &result, const SharedChildPrefix &prefix); + //! Copy 'count' entries of 'source' (selected by 'sel' from 'source_offset') into new storage of exactly 'count' + //! entries. Only constant-size types without NULLs among the selected entries can be shared: returns an empty + //! prefix for any other type (strings, lists, structs, arrays) and if a selected entry is NULL + DUCKDB_API static SharedChildPrefix Materialize(BufferManager &buffer_manager, const Vector &source, + const SelectionVector &sel, idx_t source_offset, idx_t count); + //! Extend the list 'prefix' of 'prefix_child', an unchanged view of shared storage, by the NULL-free 'extras'. + //! Writes the extras in place behind the prefix if no other extension claimed that region yet, otherwise copies + //! the prefix once into new storage with room to grow. 'result_child' becomes a view and 'result_offset' the + //! offset of the extended list in it. Returns false if the inputs do not fit (no shared prefix, a NULL extra, or + //! a result that fits a vector), callers then concatenate the regular way. + //! Limitation: the first extension of a prefix claims the region behind it, whether or not its result is kept. + //! Any other single-row list_concat on the same prefix copies, as without sharing. In a recursive CTE that is a + //! second list_concat in the recursive step (e.g. in its WHERE clause or a CASE), or one in the outer query + //! (... SELECT list_append(acc, 0) FROM r), which sees each iteration's rows before the next iteration runs and + //! then takes the region first, so the recursion copies every iteration. Results stay correct + DUCKDB_API static bool TryExtend(BufferManager &buffer_manager, const Vector &prefix_child, + const list_entry_t &prefix, const vector &extras, + Vector &result_child, idx_t &result_offset); +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/common/virtual_file_system.hpp b/src/duckdb/src/include/duckdb/common/virtual_file_system.hpp index 1eea714cf..259d92fb7 100644 --- a/src/duckdb/src/include/duckdb/common/virtual_file_system.hpp +++ b/src/duckdb/src/include/duckdb/common/virtual_file_system.hpp @@ -44,6 +44,8 @@ class VirtualFileSystem { DUCKDB_API void RegisterSubSystem(unique_ptr fs); DUCKDB_API void RegisterCompressionFilesystem(unique_ptr fs); + //! The compression type a user named: a built-in one or one a registered file system handles. Throws otherwise. + DUCKDB_API FileCompressionType ParseCompression(const string &compression); DUCKDB_API void UnregisterSubSystem(const string &name); DUCKDB_API unique_ptr ExtractSubSystem(const string &name); DUCKDB_API vector ListSubSystems(); diff --git a/src/duckdb/src/include/duckdb/execution/index/art/art_merger.hpp b/src/duckdb/src/include/duckdb/execution/index/art/art_merger.hpp index b827305cd..339530758 100644 --- a/src/duckdb/src/include/duckdb/execution/index/art/art_merger.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/art/art_merger.hpp @@ -73,7 +73,6 @@ class ARTMerger { ARTConflictType MergeNodeAndInlined(NodePtr &left_ptr, NodeEntry &entry); - array_ptr GetBytes(NodePtr &leaf_ptr); void MergeLeaves(NodePtr &left_ptr, NodeEntry &entry); NodeChildren ExtractChildren(NodePtr &node_ptr); diff --git a/src/duckdb/src/include/duckdb/execution/index/art/art_operator.hpp b/src/duckdb/src/include/duckdb/execution/index/art/art_operator.hpp index cbd4b1d0a..157502625 100644 --- a/src/duckdb/src/include/duckdb/execution/index/art/art_operator.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/art/art_operator.hpp @@ -13,7 +13,6 @@ #include "duckdb/execution/index/art/art.hpp" #include "duckdb/execution/index/art/const_prefix_handle.hpp" #include "duckdb/execution/index/art/node_handle.hpp" -#include "duckdb/execution/index/art/prefix.hpp" #include "duckdb/execution/index/art/prefix_handle.hpp" #include "duckdb/execution/index/art/leaf.hpp" #include "duckdb/execution/index/art/base_node.hpp" @@ -79,15 +78,15 @@ class ARTOperator { case NType::NODE_7_LEAF: case NType::NODE_15_LEAF: case NType::NODE_256_LEAF: { - D_ASSERT(depth + 1 == Prefix::ROW_ID_SIZE); - const auto byte = rowid[Prefix::ROW_ID_COUNT]; + D_ASSERT(depth + 1 == PrefixHandle::ROW_ID_SIZE); + const auto byte = rowid[PrefixHandle::ROW_ID_COUNT]; return current_ptr.HasByte(art, byte); } case NType::NODE_4: case NType::NODE_16: case NType::NODE_48: case NType::NODE_256: { - D_ASSERT(depth < Prefix::ROW_ID_SIZE); + D_ASSERT(depth < PrefixHandle::ROW_ID_SIZE); auto child_ptr = current_ptr.GetChildNode(art, rowid[depth]); if (child_ptr) { // Continue in the child. @@ -156,7 +155,7 @@ class ARTOperator { // status is GATE_SET, if we've passed a gate in the previous iteration. // In that case, we have not adjusted the reference. - if (status == GateStatus::GATE_NOT_SET && active_node_ptr.GetGateStatus() == GateStatus::GATE_SET) { + if (status == GateStatus::GATE_NOT_SET && active_node_ptr.IsGate(art)) { if (!art.IsUnique()) { // Enter a gate. active_key_ref = row_id; @@ -192,7 +191,7 @@ class ARTOperator { case NType::NODE_15_LEAF: case NType::NODE_256_LEAF: { // Row IDs are unique; there are never any duplicate byte conflicts. - auto byte = active_key[Prefix::ROW_ID_COUNT]; + auto byte = active_key[PrefixHandle::ROW_ID_COUNT]; NodePtr::InsertChild(art, active_node_ptr, byte); return ARTConflictType::NO_CONFLICT; } @@ -286,7 +285,7 @@ class ARTOperator { while (current.Get().HasMetadata()) { // Enter gate. - if (status == GateStatus::GATE_NOT_SET && current.Get().GetGateStatus() == GateStatus::GATE_SET) { + if (status == GateStatus::GATE_NOT_SET && current.Get().IsGate(art)) { status = GateStatus::GATE_SET; current_key_ref = row_id; depth = 0; diff --git a/src/duckdb/src/include/duckdb/execution/index/art/base_leaf.hpp b/src/duckdb/src/include/duckdb/execution/index/art/base_leaf.hpp index 85e7c03a4..5c8fb6931 100644 --- a/src/duckdb/src/include/duckdb/execution/index/art/base_leaf.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/art/base_leaf.hpp @@ -54,22 +54,12 @@ class BaseLeaf { return false; } - //! Returns a pointer to the bytes in the leaf. - //! The pointer's data is valid as long as the leaf is valid. - array_ptr GetBytes() { - return array_ptr(key, count); - } - - //! Get the first byte greater than or equal to the byte. - //! Returns true, if such a byte exists, else false. - bool GetNextByte(uint8_t &byte) const { + //! Copies the bytes of the leaf into bytes in ascending order, and returns their count. + idx_t GetBytes(array_ptr bytes) const { for (uint8_t i = 0; i < count; i++) { - if (key[i] >= byte) { - byte = key[i]; - return true; - } + bytes[i] = key[i]; } - return false; + return count; } private: diff --git a/src/duckdb/src/include/duckdb/execution/index/art/base_node.hpp b/src/duckdb/src/include/duckdb/execution/index/art/base_node.hpp index 715a66762..5cbceb62f 100644 --- a/src/duckdb/src/include/duckdb/execution/index/art/base_node.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/art/base_node.hpp @@ -109,21 +109,10 @@ class BaseNode { return nullptr; } - //! Get the first child greater than or equal to the byte. - static unsafe_optional_ptr GetNextChild(BaseNode &n, uint8_t &byte) { - for (uint8_t i = 0; i < n.count; i++) { - if (n.key[i] >= byte) { - byte = n.key[i]; - return &n.children[i]; - } - } - return nullptr; - } - //! Extracts the bytes and their respective children. //! The return value is valid as long as the arena is valid. //! The node must be freed after calling into this function. - NodeChildren ExtractChildren(ArenaAllocator &arena) { + NodeChildren ExtractChildren(ArenaAllocator &arena) const { auto mem_bytes = arena.AllocateAligned(sizeof(uint8_t) * count); array_ptr bytes(mem_bytes, count); auto mem_children = arena.AllocateAligned(sizeof(NodePtr) * count); diff --git a/src/duckdb/src/include/duckdb/execution/index/art/node.hpp b/src/duckdb/src/include/duckdb/execution/index/art/node.hpp index d8ec1ca36..ce3eb1e19 100644 --- a/src/duckdb/src/include/duckdb/execution/index/art/node.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/art/node.hpp @@ -40,7 +40,6 @@ enum class GateStatus : uint8_t { }; class ART; -class Prefix; class ARTKey; class FixedSizeAllocator; class OptionalNodePtr; @@ -114,8 +113,6 @@ struct ToStringOptions { //! The NodePtr is the pointer class of the ART index. //! It inherits from the IndexPointer, and adds ART-specific functionality. class NodePtr : public IndexPointer { - friend class Prefix; - public: //! A gate sets the leftmost bit of the metadata, binary: 1000-0000. static constexpr uint8_t AND_GATE = 0x80; @@ -163,12 +160,11 @@ class NodePtr : public IndexPointer { OptionalNodePtr GetNextChildNode(const ART &art, uint8_t &byte) const; //! Get the immutable child at byte. const unsafe_optional_ptr GetChild(ART &art, const uint8_t byte) const; - //! Get the first immutable child greater than or equal to the byte. - const unsafe_optional_ptr GetNextChild(ART &art, uint8_t &byte) const; //! Returns true, if the byte exists, else false. bool HasByte(const ART &art, const uint8_t byte) const; - //! Get the first byte greater than or equal to the byte. - bool GetNextByte(const ART &art, uint8_t &byte) const; + //! Copies the bytes of the nested leaf into bytes in ascending order, and returns their count. + //! bytes must hold at least Node256Leaf::CAPACITY bytes. + idx_t GetBytes(const ART &art, array_ptr bytes) const; //! Traverses and verifies the node. void Verify(ART &art) const; @@ -213,6 +209,19 @@ class NodePtr : public IndexPointer { inline GateStatus GetGateStatus() const { return (GetMetadata() & AND_GATE) == 0 ? GateStatus::GATE_NOT_SET : GateStatus::GATE_SET; } + //! True, if the node is a gate to a nested leaf. + //! v1.1 could write inlined leaves with a gate. These are not gates. Only indexes created before v1.5, which do not + //! record their storage version, can contain them. + inline bool IsGate(const ART &art) const { + if (GetGateStatus() == GateStatus::GATE_NOT_SET) { + return false; + } + if (GetType() != NType::LEAF_INLINED) { + return true; + } + D_ASSERT(HasNoStorageVersion(art)); + return false; + } //! Sets the gate status of a node. inline void SetGateStatus(const GateStatus status) { switch (status) { @@ -232,6 +241,8 @@ class NodePtr : public IndexPointer { } private: + //! True, if the ART does not record the storage version it was created in. + static bool HasNoStorageVersion(const ART &art); //! Prints only the children of an internal node (used for tree-style printing). string ToStringChildren(ART &art, const ToStringOptions &options) const; }; diff --git a/src/duckdb/src/include/duckdb/execution/index/art/node256.hpp b/src/duckdb/src/include/duckdb/execution/index/art/node256.hpp index 3bf842d0a..05deaaee3 100644 --- a/src/duckdb/src/include/duckdb/execution/index/art/node256.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/art/node256.hpp @@ -106,21 +106,10 @@ class Node256 { return nullptr; } - template - static unsafe_optional_ptr GetNextChild(NODE &n, uint8_t &byte) { - for (idx_t i = byte; i < CAPACITY; i++) { - if (n.children[i].HasMetadata()) { - byte = UnsafeNumericCast(i); - return &n.children[i]; - } - } - return nullptr; - } - //! Extracts the bytes and their respective children. //! The return value is valid as long as the arena is valid. //! The node must be freed after calling into this function. - NodeChildren ExtractChildren(ArenaAllocator &arena) { + NodeChildren ExtractChildren(ArenaAllocator &arena) const { auto mem_bytes = arena.AllocateAligned(sizeof(uint8_t) * count); array_ptr bytes(mem_bytes, count); auto mem_children = arena.AllocateAligned(sizeof(NodePtr) * count); diff --git a/src/duckdb/src/include/duckdb/execution/index/art/node256_leaf.hpp b/src/duckdb/src/include/duckdb/execution/index/art/node256_leaf.hpp index 4ac3e3e4f..3873ead0d 100644 --- a/src/duckdb/src/include/duckdb/execution/index/art/node256_leaf.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/art/node256_leaf.hpp @@ -45,13 +45,8 @@ class Node256Leaf { //! Returns true, if the byte exists, else false. bool HasByte(const uint8_t byte) const; - //! Returns a pointer to the bytes in the leaf. - //! The pointer data is valid as long as the arena is valid. - array_ptr GetBytes(ArenaAllocator &arena); - - //! Get the first byte greater or equal to the byte. - //! Returns true, if such a byte exists, else false. - bool GetNextByte(uint8_t &byte) const; + //! Copies the bytes of the leaf into bytes in ascending order, and returns their count. + idx_t GetBytes(array_ptr bytes) const; private: static void GrowNode15Leaf(ART &art, NodePtr &node256_leaf_ptr, NodePtr &node15_leaf_ptr); diff --git a/src/duckdb/src/include/duckdb/execution/index/art/node48.hpp b/src/duckdb/src/include/duckdb/execution/index/art/node48.hpp index e60f5213c..1edb8ac2d 100644 --- a/src/duckdb/src/include/duckdb/execution/index/art/node48.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/art/node48.hpp @@ -122,21 +122,10 @@ class Node48 { return nullptr; } - template - static unsafe_optional_ptr GetNextChild(NODE &n, uint8_t &byte) { - for (idx_t i = byte; i < Node256::CAPACITY; i++) { - if (n.child_index[i] != EMPTY_MARKER) { - byte = UnsafeNumericCast(i); - return &n.children[n.child_index[i]]; - } - } - return nullptr; - } - //! Extracts the bytes and their respective children. //! The return value is valid as long as the arena is valid. //! The node must be freed after calling into this function. - NodeChildren ExtractChildren(ArenaAllocator &arena) { + NodeChildren ExtractChildren(ArenaAllocator &arena) const { auto mem_bytes = arena.AllocateAligned(sizeof(uint8_t) * count); array_ptr bytes(mem_bytes, count); auto mem_children = arena.AllocateAligned(sizeof(NodePtr) * count); diff --git a/src/duckdb/src/include/duckdb/execution/index/art/prefix.hpp b/src/duckdb/src/include/duckdb/execution/index/art/prefix.hpp deleted file mode 100644 index 97eef7976..000000000 --- a/src/duckdb/src/include/duckdb/execution/index/art/prefix.hpp +++ /dev/null @@ -1,54 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/execution/index/art/prefix.hpp -// -// -//===----------------------------------------------------------------------===// -#pragma once - -#include "duckdb/execution/index/fixed_size_allocator.hpp" -#include "duckdb/execution/index/art/art.hpp" -#include "duckdb/execution/index/art/node.hpp" - -namespace duckdb { - -//! Prefix is a wrapper class to access a prefix. -//! The prefix contains up to the ART's prefix size bytes and an additional byte for the count. -//! It also contains a child NodePtr. -class Prefix { -public: - static constexpr NType PREFIX = NType::PREFIX; - - static constexpr uint8_t ROW_ID_SIZE = sizeof(row_t); - static constexpr uint8_t ROW_ID_COUNT = ROW_ID_SIZE - 1; - static constexpr uint8_t DEPRECATED_COUNT = 15; - // The child pointer and the in_memory boolean. - static constexpr uint8_t METADATA_SIZE = sizeof(NodePtr) + 1; - -public: - Prefix() = delete; - Prefix(const ART &art, const NodePtr node_ptr, const bool is_mutable = false, const bool set_in_memory = false); - Prefix(FixedSizeAllocator &allocator, const NodePtr node_ptr, const idx_t count); - - data_ptr_t data; - NodePtr *child_slot; - bool in_memory; - -public: - static uint8_t GetByte(const ART &art, const NodePtr &node_ptr, const uint8_t pos); - -public: - //! Removes up to pos bytes from the prefix. - //! Shifts all subsequent bytes by pos. Frees empty nodes. - static void Reduce(ART &art, NodePtr &node_ptr, const idx_t pos); - -private: - static Prefix NewInternal(ART &art, NodePtr &node_ptr, const data_ptr_t data, const uint8_t count, - const idx_t offset); - - Prefix Append(ART &art, const uint8_t byte); - void Append(ART &art, NodePtr other_ptr); - Prefix TransformToDeprecatedAppend(ART &art, FixedSizeAllocator &allocator, uint8_t byte); -}; -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/execution/index/art/prefix_handle.hpp b/src/duckdb/src/include/duckdb/execution/index/art/prefix_handle.hpp index 7e39700de..ae9cd6215 100644 --- a/src/duckdb/src/include/duckdb/execution/index/art/prefix_handle.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/art/prefix_handle.hpp @@ -22,7 +22,12 @@ struct PrefixChain; class PrefixHandle { public: static constexpr NType PREFIX = NType::PREFIX; + + static constexpr uint8_t ROW_ID_SIZE = sizeof(row_t); + static constexpr uint8_t ROW_ID_COUNT = ROW_ID_SIZE - 1; static constexpr uint8_t DEPRECATED_COUNT = 15; + // The child pointer and the count byte. + static constexpr uint8_t METADATA_SIZE = sizeof(NodePtr) + 1; public: explicit PrefixHandle(NodeHandle &&handle_p) : handle(std::move(handle_p)) { @@ -46,6 +51,10 @@ class PrefixHandle { //! is handled internally; the caller does not need to set it after splitting. static NodePtr Split(ART &art, NodePtr &prefix_ptr, NodePtr &branching_node4_ptr, const uint8_t pos); + //! Removes the bytes up to and including pos from the prefix, and merges any subsequent prefix nodes into it. + //! If no bytes remain, frees the prefix and sets node_ptr to its child. The prefix is no longer a gate. + static void Reduce(ART &art, NodePtr &node_ptr, const idx_t pos); + //! Replaces a freed Node4 that had one remaining child: concatenates parent -> byte -> child. //! parent_ptr points to the inner node above the Node4, or to the head of the prefix chain ending at the Node4. //! node4_ptr_handle refers to the NodePtr that pointed to the freed Node4, which FreeNode cleared. diff --git a/src/duckdb/src/include/duckdb/execution/index/bound_index.hpp b/src/duckdb/src/include/duckdb/execution/index/bound_index.hpp index 770e1129b..cc7b2dcd6 100644 --- a/src/duckdb/src/include/duckdb/execution/index/bound_index.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/bound_index.hpp @@ -106,7 +106,7 @@ class BoundIndex : public Index { } public: - //! Appends data to the locked index. + //! Appends data to the locked index. A returned error means it is unchanged; a throw means its state is unknown. virtual ErrorData Append(IndexLock &l, DataChunk &chunk, Vector &row_ids) DUCKDB_REQUIRES(l) = 0; //! Obtains a lock and calls Append while holding that lock. ErrorData Append(DataChunk &chunk, Vector &row_ids) DUCKDB_EXCLUDES(lock); diff --git a/src/duckdb/src/include/duckdb/execution/index/index_type.hpp b/src/duckdb/src/include/duckdb/execution/index/index_type.hpp index e93fa1f55..7bd552d4b 100644 --- a/src/duckdb/src/include/duckdb/execution/index/index_type.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/index_type.hpp @@ -206,6 +206,11 @@ class IndexType { index_build_plan_t create_plan = nullptr; // escape hatch for creating the physical plan index_create_function_t create_instance = nullptr; // function to create an instance of the index + + //! Extension that registered the index type through its loader, else empty + string registered_by; + //! True for the index types DuckDB provides (ART) + bool internal = false; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/execution/index/index_type_set.hpp b/src/duckdb/src/include/duckdb/execution/index/index_type_set.hpp index a535f4a2d..dc8aad28c 100644 --- a/src/duckdb/src/include/duckdb/execution/index/index_type_set.hpp +++ b/src/duckdb/src/include/duckdb/execution/index/index_type_set.hpp @@ -16,6 +16,14 @@ namespace duckdb { +struct RegisteredIndexType { + string name; + //! Extension that registered the index type through its loader, else empty + string registered_by; + //! True for the index types DuckDB provides (ART) + bool internal; +}; + class IndexTypeSet { mutex lock; identifier_tree_t functions; @@ -23,7 +31,11 @@ class IndexTypeSet { public: IndexTypeSet(); DUCKDB_API optional_ptr FindByName(const string &name); + //! Registers an index type (CREATE INDEX ... USING name). ExtensionLoader::RegisterIndexType sets the type's + //! registered_by before calling this, attributing the type to that extension. DUCKDB_API void RegisterIndexType(const IndexType &index_type); + //! All registered index types (CREATE INDEX ... USING name) with the extension that registered them + DUCKDB_API vector GetIndexTypes(); }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/execution/join_hashtable.hpp b/src/duckdb/src/include/duckdb/execution/join_hashtable.hpp index 7370caa1c..26d197e98 100644 --- a/src/duckdb/src/include/duckdb/execution/join_hashtable.hpp +++ b/src/duckdb/src/include/duckdb/execution/join_hashtable.hpp @@ -296,6 +296,8 @@ class JoinHashTable { struct ProbeState : SharedState { ProbeState(); + //! Discard per-iteration state while retaining scratch allocations. + void Reset(); Vector hashes; Vector ht_offsets_and_salts_v; @@ -311,6 +313,8 @@ class JoinHashTable { unique_ptr hash_executor; unique_ptr spill_hashes; SelectionVector spill_false_sel; + SelectionVector probe_filter_sel; + unique_ptr probe_filter_stats; //! Allocated only when the operator gates the compressed-probe paths on; null otherwise unique_ptr dict_state; }; @@ -582,6 +586,11 @@ class JoinHashTable { Vector &pointers_result_v, SelectionVector &match_sel, bool has_sel); private: + //! Return the candidate count using keys for PRFs or existing hashes for BFs. PRFs do not read hashes. + //! On a partial pass, probe_filter_sel contains original probe-row indices; a full pass or pause leaves the + //! incoming selection unchanged. + idx_t SelectProbeCandidates(ProbeState &state, Vector &first_key, const Vector &hashes, + optional_ptr sel, idx_t count) const; //! Insert the given set of locations into the HT with the given set of hashes_v void InsertHashes(Vector &hashes_v, TupleDataChunkState &chunk_state, InsertState &insert_state, bool parallel); //! Prepares keys by filtering NULLs @@ -652,6 +661,10 @@ class JoinHashTable { //! Prefix-range filters, indexed by key column vector> prefix_range_filters; bool should_build_prefix_range_filter = false; + enum class ProbeFilterType { NONE, BF, PRF }; + ProbeFilterType probe_filter_type = ProbeFilterType::NONE; + //! Uses the stored combined join hash, unlike the per-key filters published to scans. + unique_ptr probe_bloom_filter; //! Copying not allowed JoinHashTable(const JoinHashTable &) = delete; @@ -734,6 +747,10 @@ class JoinHashTable { return PointerTableCapacity(count) * sizeof(data_ptr_t); } + //! Choose and configure a local probe filter before finalization. The caller excludes scan pushdown, + //! external joins and perfect-hash joins; the hash table owns filter construction and probe state. + void InitializeProbeFilter(idx_t estimated_probe_count, const Value &min, const Value &max); + void SetBloomFilter(idx_t key_idx, shared_ptr filter) { D_ASSERT(key_idx < equality_predicate_columns.size()); bloom_filters.resize(equality_predicate_columns.size()); diff --git a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_reader_options.hpp b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_reader_options.hpp index 27aabdac1..434ae3f88 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_reader_options.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/csv_scanner/csv_reader_options.hpp @@ -152,7 +152,7 @@ struct CSVReaderOptions { //! If this reader is a multifile reader bool multi_file_reader = false; - void SetCompression(const string &compression); + void SetCompression(Context &context, const string &compression); bool GetHeader() const; void SetHeader(bool has_header); diff --git a/src/duckdb/src/include/duckdb/execution/operator/join/join_filter_pushdown.hpp b/src/duckdb/src/include/duckdb/execution/operator/join/join_filter_pushdown.hpp index 2ee521fd7..64e4f03e5 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/join/join_filter_pushdown.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/join/join_filter_pushdown.hpp @@ -52,6 +52,7 @@ struct JoinFilterPushdownColumn { result.storage_type = storage_type; result.mode = mode; result.input_expression = input_expression ? input_expression->Copy() : nullptr; + result.value_preserving_input = value_preserving_input; return result; } @@ -65,6 +66,9 @@ struct JoinFilterPushdownColumn { JoinFilterPushdownMode mode = JoinFilterPushdownMode::RECONSTRUCT_EXPRESSION; //! Filter input over BoundReferenceExpression(0) in the existing scan projection's type. unique_ptr input_expression; + //! Whether the statistics of the scanned column prove that every cast in input_expression succeeds and returns + //! its input value on the rows the scan returns + bool value_preserving_input = false; }; enum class DeferredRuntimeFilterType : uint8_t { BLOOM_FILTER, PREFIX_RANGE }; @@ -117,6 +121,12 @@ struct PushdownFilterTarget { struct JoinFilterPushdownUtil { static bool PushdownJoinFilterExpression(const Expression &expr, JoinFilterPushdownColumn &filter); static bool JoinTypeIsSupported(JoinType join_type); + //! Shared size guard for collecting probe-filter min/max and constructing the filter at finalization. + static bool CanBuildProbeFilter(idx_t build_count, idx_t probe_count) { + // Tiny pointer tables are cheap to probe; larger filters need enough probes to amortize construction. + static constexpr idx_t MIN_BUILD_COUNT = 1024; + return build_count >= MIN_BUILD_COUNT && build_count <= probe_count / 2; + } }; struct JoinFilterPushdownInfo { diff --git a/src/duckdb/src/include/duckdb/execution/operator/persistent/physical_batch_copy_to_file.hpp b/src/duckdb/src/include/duckdb/execution/operator/persistent/physical_batch_copy_to_file.hpp index d89b4c067..39e60c81c 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/persistent/physical_batch_copy_to_file.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/persistent/physical_batch_copy_to_file.hpp @@ -93,11 +93,8 @@ class PhysicalBatchCopyToFile : public PhysicalOperator { void AddLocalBatch(ClientContext &context, GlobalSinkState &gstate, LocalSinkState &state) const; void AddRawBatchData(ClientContext &context, GlobalSinkState &gstate_p, idx_t batch_index, unique_ptr collection) const; - void RepartitionBatches(ClientContext &context, GlobalSinkState &gstate_p, idx_t min_index, - bool final = false) const; + void RepartitionBatches(ClientContext &context, GlobalSinkState &gstate_p, bool final = false) const; void FlushBatchData(ClientContext &context, GlobalSinkState &gstate_p) const; - bool ExecuteTask(ClientContext &context, GlobalSinkState &gstate_p) const; - void ExecuteTasks(ClientContext &context, GlobalSinkState &gstate_p) const; SinkFinalizeType FinalFlush(ClientContext &context, GlobalSinkState &gstate_p) const; private: diff --git a/src/duckdb/src/include/duckdb/execution/operator/projection/physical_tableinout_function.hpp b/src/duckdb/src/include/duckdb/execution/operator/projection/physical_tableinout_function.hpp index 92b4f74b2..c5c8ea148 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/projection/physical_tableinout_function.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/projection/physical_tableinout_function.hpp @@ -35,6 +35,9 @@ class PhysicalTableInOutFunction : public PhysicalOperator { OperatorFinalizeResultType FinalExecute(ExecutionContext &context, DataChunk &chunk, GlobalOperatorState &gstate, OperatorState &state) const override; + ProgressData GetOperatorProgress(ClientContext &context, GlobalOperatorState &gstate, + const ProgressData upstream_progress) const override; + bool ParallelOperator() const override { return true; } diff --git a/src/duckdb/src/include/duckdb/execution/operator/scan/physical_positional_scan.hpp b/src/duckdb/src/include/duckdb/execution/operator/scan/physical_positional_scan.hpp index 9d7d7b2d4..4fce10aaa 100644 --- a/src/duckdb/src/include/duckdb/execution/operator/scan/physical_positional_scan.hpp +++ b/src/duckdb/src/include/duckdb/execution/operator/scan/physical_positional_scan.hpp @@ -15,20 +15,21 @@ namespace duckdb { -//! Represents a scan of a base table +//! Streams positional join inputs and pads shorter inputs with NULLs. class PhysicalPositionalScan : public PhysicalOperator { public: static constexpr const PhysicalOperatorType TYPE = PhysicalOperatorType::POSITIONAL_SCAN; public: - //! Regular Table Scan PhysicalPositionalScan(PhysicalPlan &physical_plan, vector types, PhysicalOperator &left, PhysicalOperator &right); - //! The child table functions - vector> child_tables; + //! Sources and the projections fused into their scan. + vector> inputs; public: + static bool IsSupportedInput(const PhysicalOperator &input); + bool Equals(const PhysicalOperator &other) const override; vector> GetChildren() const override; diff --git a/src/duckdb/src/include/duckdb/execution/physical_operator.hpp b/src/duckdb/src/include/duckdb/execution/physical_operator.hpp index 50e95758f..fd07023b6 100644 --- a/src/duckdb/src/include/duckdb/execution/physical_operator.hpp +++ b/src/duckdb/src/include/duckdb/execution/physical_operator.hpp @@ -123,6 +123,10 @@ class PhysicalOperator { virtual OperatorFinalResultType OperatorFinalize(Pipeline &pipeline, Event &event, ClientContext &context, OperatorFinalizeInput &input) const; + //! Incorporate intermediate operator progress without changing the upstream work units. + virtual ProgressData GetOperatorProgress(ClientContext &context, GlobalOperatorState &gstate, + const ProgressData upstream_progress) const; + virtual bool ParallelOperator() const { return false; } diff --git a/src/duckdb/src/include/duckdb/execution/radix_ht_sink_state.hpp b/src/duckdb/src/include/duckdb/execution/radix_ht_sink_state.hpp index 565f89f8b..d14fe0133 100644 --- a/src/duckdb/src/include/duckdb/execution/radix_ht_sink_state.hpp +++ b/src/duckdb/src/include/duckdb/execution/radix_ht_sink_state.hpp @@ -17,6 +17,8 @@ namespace duckdb { class RadixHTGlobalSinkState; +class RadixHTLocalSinkState; +class Pipeline; //! How aggregate state spilling and native row combining are allowed to interleave enum class SpillPhase { @@ -28,17 +30,31 @@ enum class SpillPhase { NATIVE_COMBINE_STARTED }; +//! Shared partitioning policy, memory limits and observations for a radix HT sink. struct RadixHTConfig { public: + struct LocalState { + //! Materialized rows this sink has already reported + idx_t reported_materialized_rows = 0; + }; + explicit RadixHTConfig(RadixHTGlobalSinkState &sink); void ResetForNewIteration(idx_t scheduled_workers); + //! Record local work before memory pressure can move rows out of the HT. + void ObserveMaterializedRows(LocalState &state, const GroupedAggregateHashTable &ht); + //! Choose a partition count from the local data size and shared combine work. + void AdaptToData(const GroupedAggregateHashTable &ht, optional_ptr pipeline = nullptr); void SetRadixBits(const idx_t &radix_bits_p); bool SetRadixBitsToExternal(); idx_t GetRadixBits() const; idx_t GetMaximumSinkRadixBits() const; private: + void GrowForSize(idx_t data_size); + void GrowForParallelism(idx_t local_radix_bits, optional_ptr pipeline); + idx_t RadixBitsForWork(double bytes, idx_t radix_bits, idx_t workers) const; + idx_t PartitioningBytesPerPartition() const; void SetRadixBitsInternal(idx_t radix_bits_p, bool external); idx_t InitialSinkRadixBits(idx_t num_threads) const; idx_t ExternalRadixBits(bool dynamic) const; @@ -64,10 +80,19 @@ struct RadixHTConfig { static constexpr idx_t MAXIMUM_FINAL_SINK_RADIX_BITS = 8; private: + //! Initial radix bits for this sink or recursive iteration + idx_t initial_sink_radix_bits; //! Current thread-global sink radix bits atomic sink_radix_bits; //! Maximum Sink radix bits (set based on number of threads, if not external) const idx_t maximum_sink_radix_bits; + //! Cumulative materialized rows reported at local adaptation boundaries + PaddedAtomic materialized_rows {0}; + + //! Coarse relative cost of hash combining versus copying tuple bytes + static constexpr double FINALIZE_TO_COPY_COST_RATIO = 4; + //! Limit extrapolation while only a small part of the source has been consumed. + static constexpr double MAXIMUM_WORK_ESTIMATE_MULTIPLIER = 16; //! Thresholds at which we reduce the sink radix bits //! This needed to reduce cache misses when we have very wide rows @@ -83,7 +108,7 @@ struct RadixHTConfig { static constexpr idx_t REPARTITION_RADIX_BITS = 2; //! Thread-limit divisor for state export and exported partition sizing static constexpr idx_t AGGREGATE_STATE_SPILL_DIVISOR = 8; - //! Arena-only pressure that forces external aggregation + //! Arena share of the thread limit once the thread spills static constexpr idx_t AGGREGATE_STATE_PRESSURE_DIVISOR = 2; //! Estimated memory amplification when importing exported states static constexpr idx_t EXPORTED_STATE_MEMORY_MULTIPLIER = 2; @@ -109,8 +134,8 @@ class RadixHTGlobalSinkState : public GlobalSinkState { idx_t GetThreadLimit() const { return temporary_memory_state->GetReservation() / number_of_threads / 10 * 8; } - //! Whether the aggregate arena alone approaches the thread memory limit - bool StatePressureExceeded(GroupedAggregateHashTable &ht) const; + //! Whether the aggregate arena may exceed the thread memory limit before the next check + bool StatePressureExceeded(const RadixHTLocalSinkState &lstate) const; //! HT size without the arena when there is no spill plan: the arena then stays in memory whatever the sink does idx_t SpillableSize(GroupedAggregateHashTable &ht) const; @@ -193,6 +218,8 @@ class RadixHTLocalSinkState : public LocalSinkState { idx_t local_sink_capacity; //! Spillable size of the HT after it was last abandoned idx_t size_after_abandon = 0; + //! Local observations for the shared partitioning policy + RadixHTConfig::LocalState partitioning; //! Adaptivity policy for this local sink RadixHTAdaptivity adaptivity; //! Data that is abandoned ends up here (only if we're doing external aggregation) diff --git a/src/duckdb/src/include/duckdb/execution/reservoir_sample.hpp b/src/duckdb/src/include/duckdb/execution/reservoir_sample.hpp index 38d839140..110de33dd 100644 --- a/src/duckdb/src/include/duckdb/execution/reservoir_sample.hpp +++ b/src/duckdb/src/include/duckdb/execution/reservoir_sample.hpp @@ -81,10 +81,12 @@ class ReservoirSampler { //! since all our weights are 1 (uniform sampling), we can just determine the amount of elements to skip sampler.min_weight_threshold = t_w; sampler.min_weighted_entry_index = min_key.second; - if (x_w >= 1.0 && std::isfinite(x_w)) { - sampler.next_index_to_sample = idx_t(ceil(x_w)); - } else { + //! The number of rows to skip before the next replacement: a zero gap selects the very next row + if (!std::isfinite(x_w)) { + // a zero draw or a threshold rounded to one gives no usable distance; keep the old one-row gap sampler.next_index_to_sample = 1; + } else { + sampler.next_index_to_sample = x_w <= 1.0 ? 0 : idx_t(ceil(x_w)) - 1; } sampler.num_entries_to_skip_b4_next_sample = 0; } diff --git a/src/duckdb/src/include/duckdb/execution/task_error_manager.hpp b/src/duckdb/src/include/duckdb/execution/task_error_manager.hpp index 4b395735c..0939aa868 100644 --- a/src/duckdb/src/include/duckdb/execution/task_error_manager.hpp +++ b/src/duckdb/src/include/duckdb/execution/task_error_manager.hpp @@ -9,6 +9,7 @@ #pragma once #include "duckdb/common/error_data.hpp" +#include "duckdb/common/no_destructor.hpp" #include "duckdb/common/mutex.hpp" #include "duckdb/common/atomic.hpp" #include "duckdb/common/vector.hpp" @@ -79,9 +80,9 @@ class TaskErrorManager { private: //! Allocated once, when the first error manager is created static const ErrorData &OutOfMemoryError() { - static const ErrorData error(ExceptionType::OUT_OF_MEMORY, - "Failed to allocate memory to report the error of a task"); - return error; + static const NoDestructor error(ExceptionType::OUT_OF_MEMORY, + "Failed to allocate memory to report the error of a task"); + return *error; } void PushOutOfMemoryError() { diff --git a/src/duckdb/src/include/duckdb/function/cast/cast_function_set.hpp b/src/duckdb/src/include/duckdb/function/cast/cast_function_set.hpp index 2308d2f94..e049db0eb 100644 --- a/src/duckdb/src/include/duckdb/function/cast/cast_function_set.hpp +++ b/src/duckdb/src/include/duckdb/function/cast/cast_function_set.hpp @@ -83,6 +83,10 @@ class CastFunctionSet { int64_t implicit_cast_cost = -1); DUCKDB_API void RegisterCastFunction(const LogicalType &source, const LogicalType &target, bind_cast_function_t bind, int64_t implicit_cast_cost = -1); + //! Register a bind function with per-cast info, visible as input.info while the bind function runs + DUCKDB_API void RegisterCastFunction(const LogicalType &source, const LogicalType &target, + bind_cast_function_t bind, shared_ptr bind_info, + int64_t implicit_cast_cost = -1); //! Whether a registered cast can change this default conversion, including nested casts. //! Data-dependent VARIANT conversions are treated conservatively. DUCKDB_API bool CanOverrideDefaultCast(const LogicalType &source, const LogicalType &target) const; @@ -95,7 +99,7 @@ class CastFunctionSet { DUCKDB_API void RegisterCombineTypesRule(CombineTypesRule rule); //! Run `rules` against (left, right); the first matching rule wins and writes its outcome to `success`. //! Returns false if no rule matched. - static bool TryCombineTypes(const vector &rules, LogicalTypeResolver &resolver, + static bool TryCombineTypes(array_ptr rules, LogicalTypeResolver &resolver, const LogicalType &left, const LogicalType &right, LogicalType &result, bool &success); //! Same, over this set's rules (registered + built-in) bool TryCombineTypes(LogicalTypeResolver &resolver, const LogicalType &left, const LogicalType &right, diff --git a/src/duckdb/src/include/duckdb/function/cast/default_casts.hpp b/src/duckdb/src/include/duckdb/function/cast/default_casts.hpp index 6feb3f37c..60585aba4 100644 --- a/src/duckdb/src/include/duckdb/function/cast/default_casts.hpp +++ b/src/duckdb/src/include/duckdb/function/cast/default_casts.hpp @@ -156,6 +156,13 @@ struct BoundCastInfo { void SetStability(FunctionStability stability_p) { stability = stability_p; } + //! Whether the cast can throw whatever its types are, e.g. because an extension implements it + bool IsFallible() const { + return fallible; + } + void SetFallible() { + fallible = true; + } bool HasInitLocalState() const { return init_local_state; } @@ -200,6 +207,7 @@ struct BoundCastInfo { unique_ptr cast_data; cast_statistics_t statistics = nullptr; FunctionStability stability = FunctionStability::CONSISTENT; + bool fallible = false; }; struct BindCastInput { @@ -215,6 +223,8 @@ struct BindCastInput { QueryLocation query_location; //! The stability of the bound cast, lowered by a bind that reads settings such as TimeZone and by child casts FunctionStability stability = FunctionStability::CONSISTENT; + //! Whether a child cast can throw whatever its types are, which makes the bound cast fallible too + bool fallible = false; public: DUCKDB_API BoundCastInfo GetCastFunction(const LogicalType &source, const LogicalType &target); diff --git a/src/duckdb/src/include/duckdb/function/combine_types_rule.hpp b/src/duckdb/src/include/duckdb/function/combine_types_rule.hpp index 4ffd33d01..00bf73950 100644 --- a/src/duckdb/src/include/duckdb/function/combine_types_rule.hpp +++ b/src/duckdb/src/include/duckdb/function/combine_types_rule.hpp @@ -9,6 +9,7 @@ #pragma once #include "duckdb/common/types.hpp" +#include "duckdb/common/array_ptr.hpp" namespace duckdb { class ClientContext; @@ -41,6 +42,6 @@ struct CombineTypesRule { }; //! The built-in combine rules, used to seed CastFunctionSet and as the fallback when no context is available -const vector &DefaultCombineTypesRules(); +array_ptr DefaultCombineTypesRules(); } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/function/function.hpp b/src/duckdb/src/include/duckdb/function/function.hpp index cfdb36261..797e4562e 100644 --- a/src/duckdb/src/include/duckdb/function/function.hpp +++ b/src/duckdb/src/include/duckdb/function/function.hpp @@ -82,6 +82,9 @@ struct FunctionData { DUCKDB_API virtual bool Equals(const FunctionData &other) const = 0; DUCKDB_API static bool Equals(const FunctionData *left, const FunctionData *right); DUCKDB_API virtual bool SupportStatementCache() const; + //! Whether the call that bound this data, the function and its arguments, identifies what its scan reads, i.e. + //! the bind data adds no identity of its own + DUCKDB_API virtual bool IsIdentifiedByCall() const; template TARGET &Cast() { diff --git a/src/duckdb/src/include/duckdb/function/lambda_functions.hpp b/src/duckdb/src/include/duckdb/function/lambda_functions.hpp index 73a6e5005..26834fd31 100644 --- a/src/duckdb/src/include/duckdb/function/lambda_functions.hpp +++ b/src/duckdb/src/include/duckdb/function/lambda_functions.hpp @@ -8,6 +8,7 @@ #pragma once +#include "duckdb/common/cow_ptr.hpp" #include "duckdb/common/vector/list_vector.hpp" #include "duckdb/function/function.hpp" #include "duckdb/execution/expression_executor_state.hpp" @@ -35,22 +36,22 @@ struct ListLambdaBindData final : public LambdaFunctionData { //! Return type of the scalar function LogicalType return_type; - //! Lambda expression that the expression executor executes - unique_ptr lambda_expr; + //! Execution body, shared by copies of the bind data and copied on write + cow_ptr lambda_expr; //! True, if the last parameter in a lambda parameter list represents the index of the current list element bool has_index; bool has_initial; public: unique_ptr Copy() const override { - auto lambda_expr_copy = lambda_expr ? lambda_expr->Copy() : nullptr; - return make_uniq(return_type, std::move(lambda_expr_copy), has_index, has_initial); + return make_uniq(*this); } bool Equals(const FunctionData &other_p) const override { auto &other = other_p.Cast(); - return Expression::Equals(lambda_expr, other.lambda_expr) && return_type == other.return_type && - has_index == other.has_index && has_initial == other.has_initial; + return (lambda_expr.shares_with(other.lambda_expr) || + (lambda_expr && other.lambda_expr && lambda_expr->Equals(*other.lambda_expr))) && + return_type == other.return_type && has_index == other.has_index && has_initial == other.has_initial; } //! Serializes a lambda function's bind data @@ -153,7 +154,7 @@ class LambdaFunctions { Vector &result; optional_ptr result_validity; vector column_infos; - optional_ptr lambda_expr; + optional_ptr lambda_expr; const idx_t row_count; bool has_index; diff --git a/src/duckdb/src/include/duckdb/function/scalar_function.hpp b/src/duckdb/src/include/duckdb/function/scalar_function.hpp index e0f33a21e..5fc245d25 100644 --- a/src/duckdb/src/include/duckdb/function/scalar_function.hpp +++ b/src/duckdb/src/include/duckdb/function/scalar_function.hpp @@ -64,8 +64,9 @@ struct StatementProperties; struct FunctionStatisticsPruneInput { FunctionStatisticsPruneInput(const BoundFunctionExpression &function_p, optional_ptr bind_data_p, - const vector> &child_stats_p) - : function(function_p), bind_data(bind_data_p), child_stats(child_stats_p) { + const vector> &child_stats_p, + optional_ptr context_p = nullptr) + : function(function_p), bind_data(bind_data_p), child_stats(child_stats_p), context(context_p) { } //! The bound function expression being checked (gives access to the argument expressions) @@ -74,6 +75,8 @@ struct FunctionStatisticsPruneInput { //! Statistics for each function argument (an entry is null if it could not be derived for that argument) const vector> &child_stats; + //! Available when pruning through expressions whose statistics callbacks require a client context. + optional_ptr context; //! Convenience accessor: statistics of the i-th argument, or null if absent / not derivable optional_ptr ChildStats(idx_t i) const { @@ -91,6 +94,8 @@ struct FunctionStatisticsInput { //! The bind data of the function - use write() to modify it cow_ptr &bind_data; vector &child_stats; + //! Owning slot of the expression for statistics-based rewrites. Null when the callback is + //! invoked outside the statistics propagator (e.g. join-order cardinality estimation). unique_ptr *expr_ptr; }; diff --git a/src/duckdb/src/include/duckdb/function/table/simple_table_function.hpp b/src/duckdb/src/include/duckdb/function/table/simple_table_function.hpp new file mode 100644 index 000000000..4c736b72c --- /dev/null +++ b/src/duckdb/src/include/duckdb/function/table/simple_table_function.hpp @@ -0,0 +1,68 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/function/table/simple_table_function.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/named_parameter_map.hpp" +#include "duckdb/common/types/data_chunk.hpp" +#include "duckdb/function/table_function.hpp" + +#include + +namespace duckdb { + +class ColumnDataCollection; + +//! Appends one row at a time to the result of a SimpleTableFunction; NULL via Value() +class RowAppender { +public: + RowAppender(ClientContext &context, ColumnDataCollection &collection); + ~RowAppender(); + + //! Append one row; the values are cast to the declared column types + DUCKDB_API void Append(vector values); + template + void Append(ARGS &&...args) { + Append(vector {Value(std::forward(args))...}); + } + + void Flush(); + +private: + ColumnDataCollection &collection; + DataChunk chunk; +}; + +//! Bind-time state of the argument-taking SimpleTableFunction overload; subclass it to carry state to produce +struct SimpleBindData : public FunctionData { + DUCKDB_API ~SimpleBindData() override; + + DUCKDB_API unique_ptr Copy() const override; + DUCKDB_API bool Equals(const FunctionData &other) const override; +}; + +//! Builds table functions whose whole result is materialized once per scan: declare the columns, append the rows, +//! and the helper handles binding, chunking and projection pushdown. Not for large or streaming results, parallel +//! scans, or functions that must react to filters - those use the full TableFunction API. +struct SimpleTableFunction { + using simple_produce_t = std::function; + using simple_bind_t = std::function( + ClientContext &context, TableFunctionBindInput &input, child_list_t &columns)>; + using simple_produce_bound_t = + std::function; + + //! Fixed columns, no arguments: the common system-function case + DUCKDB_API static TableFunction Create(const string &name, child_list_t columns, + simple_produce_t produce); + //! Arguments and named parameters: `bind` returns the columns (and may keep state for `produce`) + DUCKDB_API static TableFunction Create(const string &name, const vector &arguments, + named_parameter_type_map_t named_parameters, simple_bind_t bind, + simple_produce_bound_t produce); +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/function/table/system_functions.hpp b/src/duckdb/src/include/duckdb/function/table/system_functions.hpp index 4d1b25732..6bfaa14a3 100644 --- a/src/duckdb/src/include/duckdb/function/table/system_functions.hpp +++ b/src/duckdb/src/include/duckdb/function/table/system_functions.hpp @@ -163,10 +163,18 @@ struct DuckDBLogContextFun { static void RegisterFunction(BuiltinFunctions &set); }; +struct DuckDBLogTypesFun { + static void RegisterFunction(BuiltinFunctions &set); +}; + struct DuckDBIndexesFun { static void RegisterFunction(BuiltinFunctions &set); }; +struct DuckDBIndexTypesFun { + static void RegisterFunction(BuiltinFunctions &set); +}; + struct DuckDBLiveQueryMetricsFun { static void RegisterFunction(BuiltinFunctions &set); }; diff --git a/src/duckdb/src/include/duckdb/function/table_function.hpp b/src/duckdb/src/include/duckdb/function/table_function.hpp index 15cdf2e82..20bf409f6 100644 --- a/src/duckdb/src/include/duckdb/function/table_function.hpp +++ b/src/duckdb/src/include/duckdb/function/table_function.hpp @@ -518,6 +518,10 @@ class BaseTableFunction { table_function_to_sql_t to_sql = nullptr; //! (Optional) return how much of the table we have scanned up to this point (% of the data) table_function_progress_t table_scan_progress; + //! (Optional) progress for one in-out operator execution, across all input batches and workers. + //! Includes pending output and finalization; return [0, 100], or a negative value if unknown. + //! Must support concurrent reads during execution; this is not progress within the current input batch. + table_function_progress_t table_in_out_progress; //! (Optional) returns the partition info of the current scan operator table_function_get_partition_data_t get_partition_data; //! (Optional) returns extra bind info diff --git a/src/duckdb/src/include/duckdb/function/window/window_index_tree.hpp b/src/duckdb/src/include/duckdb/function/window/window_index_tree.hpp index 9422c1a7a..d2997bba7 100644 --- a/src/duckdb/src/include/duckdb/function/window/window_index_tree.hpp +++ b/src/duckdb/src/include/duckdb/function/window/window_index_tree.hpp @@ -28,9 +28,9 @@ class WindowIndexTreeLocalState : public WindowMergeSortTreeLocalState { class WindowIndexTree : public WindowMergeSortTree { public: WindowIndexTree(ClientContext &context, const vector &orders, const vector &sort_idx, - const idx_t count); + const idx_t count, bool unique = false); WindowIndexTree(ClientContext &context, const BoundOrderModifier &order_bys, const vector &sort_idx, - const idx_t count); + const idx_t count, bool unique = false); ~WindowIndexTree() override = default; unique_ptr GetLocalState(ExecutionContext &context) override; diff --git a/src/duckdb/src/include/duckdb/function/window/window_token_tree.hpp b/src/duckdb/src/include/duckdb/function/window/window_token_tree.hpp index c2790d965..0783759de 100644 --- a/src/duckdb/src/include/duckdb/function/window/window_token_tree.hpp +++ b/src/duckdb/src/include/duckdb/function/window/window_token_tree.hpp @@ -29,6 +29,9 @@ class WindowTokenTree : public WindowMergeSortTree { //! Thread-safe post-sort cleanup void Finished() override; + //! The sort position of the row + idx_t Token(const idx_t row_idx) const; + //! Find the rank of the row within the range idx_t Rank(const idx_t lower, const idx_t upper, const idx_t row_idx) const; diff --git a/src/duckdb/src/include/duckdb/logging/log_manager.hpp b/src/duckdb/src/include/duckdb/logging/log_manager.hpp index 77bc2810d..d9ff74be8 100644 --- a/src/duckdb/src/include/duckdb/logging/log_manager.hpp +++ b/src/duckdb/src/include/duckdb/logging/log_manager.hpp @@ -16,6 +16,14 @@ namespace duckdb { class LogType; +struct RegisteredLogType { + string name; + LogLevel level; + bool is_structured; + //! Extension (or alias) that registered the type through its loader, else empty + string extension_name; +}; + // Holds global logging state // - Handles configuration changes // - Creates Loggers with cached configuration @@ -75,7 +83,11 @@ class LogManager { DUCKDB_API LogConfig GetConfig(); + //! Registers a log type (CALL enable_logging(name)). ExtensionLoader::RegisterLogType sets the type's + //! extension_name before calling this, attributing the type to that extension. DUCKDB_API void RegisterLogType(unique_ptr type); + //! Name, level, structured flag and registering extension of every registered log type, sorted by name + DUCKDB_API vector GetLogTypes(); DUCKDB_API optional_ptr LookupLogType(const string &type); DUCKDB_API void RegisterDefaultLogTypes(); diff --git a/src/duckdb/src/include/duckdb/logging/log_type.hpp b/src/duckdb/src/include/duckdb/logging/log_type.hpp index 22dad84ac..22d516c0d 100644 --- a/src/duckdb/src/include/duckdb/logging/log_type.hpp +++ b/src/duckdb/src/include/duckdb/logging/log_type.hpp @@ -44,6 +44,8 @@ class LogType { bool is_structured; LogicalType type; + //! Extension (or alias) that registered the type through its loader, else empty + string extension_name; }; class DefaultLogType : public LogType { diff --git a/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_function_internal.hpp b/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_function_internal.hpp index a17e4f0f8..90e492bef 100644 --- a/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_function_internal.hpp +++ b/src/duckdb/src/include/duckdb/main/capi_v2/capi_v2_function_internal.hpp @@ -13,6 +13,7 @@ #include "duckdb/common/named_parameter_map.hpp" #include "duckdb/function/function.hpp" #include "duckdb/function/table_function.hpp" +#include "duckdb/function/scalar_function.hpp" #include "duckdb/parser/parsed_data/create_function_info.hpp" #include "duckdb/storage/statistics/base_statistics.hpp" @@ -61,6 +62,18 @@ class CV2FunctionDocs { vector categories; }; +//! Runs the init callback of a stable API scalar function, if it has one +unique_ptr CV2ScalarInitState(const BoundScalarFunction &function, + optional_ptr bind_data, + optional_ptr context); +//! Runs the exec callback of a stable API scalar function, reporting its error through `err` instead of throwing +void CV2ScalarInvoke(const BoundScalarFunction &function, optional_ptr bind_data, + optional_ptr local_state, optional_ptr context, + DataChunk &input, Vector &result, CV2ErrorInfo &err); + +//! Builds the scalar function a cast is registered from, validating that it can convert between two types. +ScalarFunction BuildScalarFunctionForCast(duckdb_v2_scalar_function_handle function, DatabaseInstance &target); + inline auto Convert(duckdb_v2_function_docs_handle docs) -> CV2FunctionDocs * { return reinterpret_cast(docs); } diff --git a/src/duckdb/src/include/duckdb/main/capi_v2/extension_api_v2.hpp b/src/duckdb/src/include/duckdb/main/capi_v2/extension_api_v2.hpp index c1c885363..263d4c4d3 100644 --- a/src/duckdb/src/include/duckdb/main/capi_v2/extension_api_v2.hpp +++ b/src/duckdb/src/include/duckdb/main/capi_v2/extension_api_v2.hpp @@ -634,19 +634,6 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_cast_function_create) (duckdb_v2_factory_handle factory, duckdb_v2_cast_function_handle *function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_cast_function_destroy)(duckdb_v2_cast_function_handle *function); - DUCKDB_V2_ERROR(*duckdb_v2_cast_function_exec_get_input) - (duckdb_v2_cast_function_exec_info_handle info, duckdb_v2_vector_handle *vector, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_cast_function_exec_get_mode) - (duckdb_v2_cast_function_exec_info_handle info, DUCKDB_V2_CAST_MODE *mode, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_cast_function_exec_get_output) - (duckdb_v2_cast_function_exec_info_handle info, duckdb_v2_vector_handle *vector, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_cast_function_exec_get_row_count) - (duckdb_v2_cast_function_exec_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_cast_function_exec_get_user_data) - (duckdb_v2_cast_function_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_cast_function_set_exec_callback) - (duckdb_v2_cast_function_handle function, duckdb_v2_cast_function_exec_callback_fn callback, - duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_cast_function_set_implicit_cast_cost) (duckdb_v2_cast_function_handle function, int64_t cost, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_cast_function_set_source_type) @@ -655,8 +642,6 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_cast_function_set_target_type) (duckdb_v2_cast_function_handle function, duckdb_v2_logical_type_handle target_type, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_cast_function_set_user_data) - (duckdb_v2_cast_function_handle function, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_column_data_collection_clear) (duckdb_v2_column_data_collection_handle collection, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_connection_register_cast_function) @@ -1794,9 +1779,27 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_data_source_exec_set_result) (duckdb_v2_data_source_exec_info_handle info, DUCKDB_V2_DATA_SOURCE_RESULT result, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_scalar_function_bind_replace_call) + (duckdb_v2_scalar_function_bind_info_handle info, const char *name, idx_t name_length, const idx_t *arg_indices, + idx_t arg_count, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_scalar_function_bind_set_argument_monotonicity) + (duckdb_v2_scalar_function_bind_info_handle info, idx_t index, DUCKDB_V2_FUNCTION_MONOTONICITY monotonicity, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_scalar_function_bind_set_property) + (duckdb_v2_scalar_function_bind_info_handle info, DUCKDB_V2_FUNCTION_PROPERTY_KEY key, + DUCKDB_V2_FUNCTION_PROPERTY_VALUE value, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_scalar_function_set_argument_monotonicity) + (duckdb_v2_scalar_function_handle function, idx_t index, DUCKDB_V2_FUNCTION_MONOTONICITY monotonicity, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_property) (duckdb_v2_table_function_handle function, DUCKDB_V2_FUNCTION_PROPERTY_KEY key, DUCKDB_V2_FUNCTION_PROPERTY_VALUE value, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_cast_function_set_function) + (duckdb_v2_cast_function_handle function, duckdb_v2_scalar_function_handle scalar_function, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_cast_function_set_try_function) + (duckdb_v2_cast_function_handle function, duckdb_v2_scalar_function_handle scalar_function, + duckdb_v2_error_info_handle *err); } duckdb_ext_api_v2; //===--------------------------------------------------------------------===// @@ -2079,16 +2082,9 @@ inline duckdb_ext_api_v2 CreateAPIv2(void) { result.duckdb_v2_table_function_set_user_data = duckdb_v2_table_function_set_user_data; result.duckdb_v2_cast_function_create = duckdb_v2_cast_function_create; result.duckdb_v2_cast_function_destroy = duckdb_v2_cast_function_destroy; - result.duckdb_v2_cast_function_exec_get_input = duckdb_v2_cast_function_exec_get_input; - result.duckdb_v2_cast_function_exec_get_mode = duckdb_v2_cast_function_exec_get_mode; - result.duckdb_v2_cast_function_exec_get_output = duckdb_v2_cast_function_exec_get_output; - result.duckdb_v2_cast_function_exec_get_row_count = duckdb_v2_cast_function_exec_get_row_count; - result.duckdb_v2_cast_function_exec_get_user_data = duckdb_v2_cast_function_exec_get_user_data; - result.duckdb_v2_cast_function_set_exec_callback = duckdb_v2_cast_function_set_exec_callback; result.duckdb_v2_cast_function_set_implicit_cast_cost = duckdb_v2_cast_function_set_implicit_cast_cost; result.duckdb_v2_cast_function_set_source_type = duckdb_v2_cast_function_set_source_type; result.duckdb_v2_cast_function_set_target_type = duckdb_v2_cast_function_set_target_type; - result.duckdb_v2_cast_function_set_user_data = duckdb_v2_cast_function_set_user_data; result.duckdb_v2_column_data_collection_clear = duckdb_v2_column_data_collection_clear; result.duckdb_v2_connection_register_cast_function = duckdb_v2_connection_register_cast_function; result.duckdb_v2_connection_register_custom_type = duckdb_v2_connection_register_custom_type; @@ -2595,7 +2591,14 @@ inline duckdb_ext_api_v2 CreateAPIv2(void) { result.duckdb_v2_copy_from_set_data_source = duckdb_v2_copy_from_set_data_source; result.duckdb_v2_data_source_exec_add_task = duckdb_v2_data_source_exec_add_task; result.duckdb_v2_data_source_exec_set_result = duckdb_v2_data_source_exec_set_result; + result.duckdb_v2_scalar_function_bind_replace_call = duckdb_v2_scalar_function_bind_replace_call; + result.duckdb_v2_scalar_function_bind_set_argument_monotonicity = + duckdb_v2_scalar_function_bind_set_argument_monotonicity; + result.duckdb_v2_scalar_function_bind_set_property = duckdb_v2_scalar_function_bind_set_property; + result.duckdb_v2_scalar_function_set_argument_monotonicity = duckdb_v2_scalar_function_set_argument_monotonicity; result.duckdb_v2_table_function_set_property = duckdb_v2_table_function_set_property; + result.duckdb_v2_cast_function_set_function = duckdb_v2_cast_function_set_function; + result.duckdb_v2_cast_function_set_try_function = duckdb_v2_cast_function_set_try_function; return result; } diff --git a/src/duckdb/src/include/duckdb/main/client_properties.hpp b/src/duckdb/src/include/duckdb/main/client_properties.hpp index ad7128090..168f4b442 100644 --- a/src/duckdb/src/include/duckdb/main/client_properties.hpp +++ b/src/duckdb/src/include/duckdb/main/client_properties.hpp @@ -31,7 +31,7 @@ struct ClientProperties { bool arrow_use_list_view = false; bool produce_arrow_string_view = false; bool arrow_lossless_conversion = false; - ArrowFormatVersion arrow_output_version = ArrowFormatVersion::V1_0; + ArrowFormatVersion arrow_output_version = ArrowFormatVersion::V1_1; optional_ptr client_context; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/main/database.hpp b/src/duckdb/src/include/duckdb/main/database.hpp index fad95a9ba..a521d03b9 100644 --- a/src/duckdb/src/include/duckdb/main/database.hpp +++ b/src/duckdb/src/include/duckdb/main/database.hpp @@ -9,6 +9,7 @@ #pragma once #include "duckdb/common/winapi.hpp" +#include "duckdb/common/no_destructor.hpp" #include "duckdb/main/capi/extension_api.hpp" #include "duckdb/main/capi_v2/extension_load_v2.hpp" #include "duckdb/main/config.hpp" @@ -163,11 +164,11 @@ struct StaticExtensionDescriber { extension.Load(loader); } static int32_t Describe(duckdb_extension_descriptor *descriptor) { - static const std::string name = T().Name(); - static const std::string version = T().Version(); + static const NoDestructor name(T().Name()); + static const NoDestructor version(T().Version()); descriptor->version = 1; - descriptor->name = name.c_str(); - descriptor->extension_version = version.c_str(); + descriptor->name = name->c_str(); + descriptor->extension_version = version->c_str(); descriptor->entry_cpp = reinterpret_cast(&Entry); return 0; } diff --git a/src/duckdb/src/include/duckdb/main/extension/extension_loader.hpp b/src/duckdb/src/include/duckdb/main/extension/extension_loader.hpp index a5aeed17b..b5685d79b 100644 --- a/src/duckdb/src/include/duckdb/main/extension/extension_loader.hpp +++ b/src/duckdb/src/include/duckdb/main/extension/extension_loader.hpp @@ -22,6 +22,8 @@ struct CreateCoordinateSystemInfo; class TableFunctionCatalogEntry; class DatabaseInstance; +class IndexType; +class LogType; struct CreateMacroInfo; struct CreateAggregateFunctionInfo; struct CreateScalarFunctionInfo; @@ -125,9 +127,18 @@ class ExtensionLoader { //! Registers a new secret type DUCKDB_API void RegisterSecretType(SecretType secret_type); + //! Registers a log type (CALL enable_logging(name)), attributed to this extension + DUCKDB_API void RegisterLogType(unique_ptr type); + + //! Registers an index type (CREATE INDEX ... USING name), attributed to this extension + DUCKDB_API void RegisterIndexType(const IndexType &index_type); + //! Registers a cast between two types DUCKDB_API void RegisterCastFunction(const LogicalType &source, const LogicalType &target, bind_cast_function_t function, int64_t implicit_cast_cost = -1); + DUCKDB_API void RegisterCastFunction(const LogicalType &source, const LogicalType &target, + bind_cast_function_t function, shared_ptr bind_info, + int64_t implicit_cast_cost = -1); DUCKDB_API void RegisterCastFunction(const LogicalType &source, const LogicalType &target, BoundCastInfo function, int64_t implicit_cast_cost = -1); diff --git a/src/duckdb/src/include/duckdb/main/extension_entries.hpp b/src/duckdb/src/include/duckdb/main/extension_entries.hpp index ca8e2cce9..6cae4dcb1 100644 --- a/src/duckdb/src/include/duckdb/main/extension_entries.hpp +++ b/src/duckdb/src/include/duckdb/main/extension_entries.hpp @@ -77,6 +77,8 @@ static constexpr ExtensionFunctionEntry EXTENSION_FUNCTIONS[] = { {"__aws__system_table__status", "aws", CatalogType::TABLE_FUNCTION_ENTRY}, {"__internal_json_copy_to_geojson", "json", CatalogType::SCALAR_FUNCTION_ENTRY}, {"__internal_json_copy_to_json", "json", CatalogType::SCALAR_FUNCTION_ENTRY}, + {"__internal_json_subscript", "json", CatalogType::SCALAR_FUNCTION_ENTRY}, + {"__tpch_dbgen_table", "tpch", CatalogType::TABLE_FUNCTION_ENTRY}, {"abs", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, {"acos", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, {"acosh", "core_functions", CatalogType::SCALAR_FUNCTION_ENTRY}, @@ -455,6 +457,7 @@ static constexpr ExtensionFunctionEntry EXTENSION_FUNCTIONS[] = { {"json", "json", CatalogType::MACRO_ENTRY}, {"json_array", "json", CatalogType::SCALAR_FUNCTION_ENTRY}, {"json_array_length", "json", CatalogType::SCALAR_FUNCTION_ENTRY}, + {"json_build_object", "json", CatalogType::SCALAR_FUNCTION_ENTRY}, {"json_contains", "json", CatalogType::SCALAR_FUNCTION_ENTRY}, {"json_copy_strftime_if_date", "json", CatalogType::MACRO_ENTRY}, {"json_copy_strftime_if_timestamp", "json", CatalogType::MACRO_ENTRY}, diff --git a/src/duckdb/src/include/duckdb/main/settings.hpp b/src/duckdb/src/include/duckdb/main/settings.hpp index af32e289a..5069a6d01 100644 --- a/src/duckdb/src/include/duckdb/main/settings.hpp +++ b/src/duckdb/src/include/duckdb/main/settings.hpp @@ -505,11 +505,13 @@ struct ArrowOutputVersionSetting { using RETURN_TYPE = ArrowFormatVersion; static constexpr const char *Name = "arrow_output_version"; static constexpr const char *Description = - "Whether strings should be produced by DuckDB in Utf8View format instead of Utf8."; + "The Arrow format version (1.0 to 1.5) that the export to the Arrow format targets. It determines which Arrow " + "types can be produced: 1.1 adds decimal256 (DECIMAL wider than 38 digits and UHUGEINT), 1.4 adds the view " + "types (BLOB as BinaryView, and Utf8View / ListView when enabled), 1.5 adds 32-bit and 64-bit decimals."; static constexpr const char *InputType = "VARCHAR"; static constexpr bool IsDebug = false; static constexpr bool IsDeprecated = false; - static constexpr const char *DefaultValue = "1.0"; + static constexpr const char *DefaultValue = "1.1"; static constexpr SettingScopeTarget Scope = SettingScopeTarget::GLOBAL_DEFAULT; static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); static void OnSet(SettingCallbackInfo &info, Value &input); @@ -2055,6 +2057,22 @@ struct ImmediateTransactionModeSetting { static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); }; +struct ImplicitLateralSubqueriesSetting { + using RETURN_TYPE = ImplicitLateralSubqueries; + static constexpr const char *Name = "implicit_lateral_subqueries"; + static constexpr const char *Description = + "How to handle a FROM-clause subquery that references an earlier FROM item without the LATERAL keyword. " + "'allow' binds it as a lateral join, 'warn' does the same but logs a deprecation warning, and 'error' throws. " + "'default' currently behaves as 'warn'."; + static constexpr const char *InputType = "VARCHAR"; + static constexpr bool IsDebug = false; + static constexpr bool IsDeprecated = false; + static constexpr const char *DefaultValue = "DEFAULT"; + static constexpr SettingScopeTarget Scope = SettingScopeTarget::LOCAL_DEFAULT; + static constexpr idx_t SettingIndex = NEXT_SETTING_INDEX(); + static void OnSet(SettingCallbackInfo &info, Value &input); +}; + struct IndexScanMaxCountSetting { using RETURN_TYPE = idx_t; static constexpr const char *Name = "index_scan_max_count"; diff --git a/src/duckdb/src/include/duckdb/optimizer/aggregate_filter_extractor.hpp b/src/duckdb/src/include/duckdb/optimizer/aggregate_filter_extractor.hpp new file mode 100644 index 000000000..af8ad6d4a --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/aggregate_filter_extractor.hpp @@ -0,0 +1,39 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/aggregate_filter_extractor.hpp +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/optional.hpp" +#include "duckdb/planner/expression.hpp" + +namespace duckdb { + +class BoundAggregateExpression; +class LogicalAggregate; +class Optimizer; + +//! Extracts input predicates before an aggregate or its branches are lowered. +class AggregateFilterExtractor { +public: + //! Construct after staging shared expressions and before building branch inputs. + AggregateFilterExtractor(Optimizer &optimizer, LogicalAggregate &aggr); + + //! Remove identical filters, or derive single-column input predicates while retaining different filters. + unique_ptr Extract(const vector &aggregate_indices); + + //! Prevent later filter pushdown from hoisting a deferred filter past a lowered ungrouped aggregate stage. + static unique_ptr GuardDeferredFilter(const LogicalAggregate &aggr, + const BoundAggregateExpression &source, + unique_ptr filter); + +private: + Optimizer &optimizer; + LogicalAggregate &aggr; + optional can_filter_input; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/column_binding_replacer.hpp b/src/duckdb/src/include/duckdb/optimizer/column_binding_replacer.hpp index 54fb21109..b7ee20c30 100644 --- a/src/duckdb/src/include/duckdb/optimizer/column_binding_replacer.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/column_binding_replacer.hpp @@ -60,10 +60,26 @@ class BindingReplacementGraph { return replacement_bindings.end(); } +private: + struct CachedReplacement { + CachedReplacement(const ReplacementBinding &replacement_p, idx_t type_version_p) + : replacement(replacement_p), type_version(type_version_p) { + } + + ReplacementBinding replacement; + idx_t type_version; + }; + + optional_ptr FindCached(ColumnBinding binding) const; + private: vector replacement_bindings; //! Index into replacement_bindings by old_binding (unique by construction) column_binding_map_t binding_slots; + //! Same slots as replacement_bindings; shortcuts must not overwrite direct edges used at output boundaries. + mutable vector cached_replacements; + //! Enriching an existing edge's type invalidates shortcuts lazily. + idx_t type_version = 0; }; //! The ColumnBindingReplacer updates column bindings (e.g., after changing the operator plan), utility for optimizers @@ -78,6 +94,7 @@ class ColumnBindingReplacer : public LogicalOperatorVisitor { void VisitOperator(LogicalOperator &op) override; //! Update bindings owned by this operator without visiting its children virtual void VisitOperatorBindings(LogicalOperator &op); + void VisitExpression(unique_ptr *expression) override; //! Add binding replacements by position void AddReplacements(const vector &old_bindings, const vector &new_bindings); //! Index replacement_bindings by old_binding for O(1) lookup. Only takes effect for replacement lists that @@ -121,6 +138,10 @@ class CorrelatedColumnBindingReplacer : public ColumnBindingReplacer { //! Applies binding replacements together with their projection-layout invariants. class ColumnBindingRewrite { public: + //! Map corresponding output positions after a value/type-preserving replacement of the same arity. + //! Restore repeated binding identities with a selection if the replacement gave them distinct bindings. + static void ReplaceOutputBindings(unique_ptr &op, const vector &old_bindings, + BindingReplacementGraph &replacements); //! Rewrite a child, preserving the parent's explicit and implicit projection selections and updating its bindings. //! The callback may replace or wrap the child and must record its binding replacements in the supplied graph. //! Callers must still rewrite affected ancestors and resolve operator types after the complete transformation. @@ -141,4 +162,25 @@ class ColumnBindingRewrite { const vector &child_bindings_after); }; +//! Iterative postorder rewrites that preserve output positions and repeated binding identities. +//! Requires fully planned input: bound subqueries must already have been flattened into operators. +class LayoutPreservingRewriter { +public: + virtual ~LayoutPreservingRewriter() = default; + + //! Repair each original operator's bindings and types before rewriting it; skip generated subtrees. + void RewritePlan(unique_ptr &op); + +protected: + //! Return false to skip this operator and its subtree. Entry hooks must not change the tree. + virtual bool EnterOperator(LogicalOperator &op) { + return true; + } + virtual void EnterChild(LogicalOperator &op, idx_t child_index) { + } + //! Preserve public output values/types by position and record their renames for original consumers. + //! Mutate only this subtree, preserve repeated binding identities and resolve new/modified operator types. + virtual void RewriteOperator(unique_ptr &op, BindingReplacementGraph &replacements) = 0; +}; + } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/constant_propagation.hpp b/src/duckdb/src/include/duckdb/optimizer/constant_propagation.hpp new file mode 100644 index 000000000..21879376f --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/constant_propagation.hpp @@ -0,0 +1,39 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/constant_propagation.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/types/value.hpp" +#include "duckdb/planner/column_binding_map.hpp" + +namespace duckdb { +class ClientContext; +class Expression; +class LogicalOperator; + +//! Propagates exact constant outputs without changing the operators that produce them. +class ConstantPropagation { +public: + explicit ConstantPropagation(ClientContext &context); + + void Optimize(LogicalOperator &op); + +private: + using ConstantMap = column_binding_map_t; + + ConstantMap Propagate(LogicalOperator &op); + void RewriteExpressions(LogicalOperator &op, const ConstantMap &constants); + bool RewriteExpression(unique_ptr &expr, const ConstantMap &constants); + static ConstantMap ExtractConstants(TableIndex table_index, const vector> &expressions); + static ConstantMap GetOutputConstants(LogicalOperator &op, const ConstantMap &constants); + +private: + ClientContext &context; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/cte_definition_scope.hpp b/src/duckdb/src/include/duckdb/optimizer/cte_definition_scope.hpp new file mode 100644 index 000000000..46edbc7a2 --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/cte_definition_scope.hpp @@ -0,0 +1,56 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/cte_definition_scope.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/optional_ptr.hpp" +#include "duckdb/common/table_index.hpp" + +#include + +namespace duckdb { + +class LogicalOperator; + +//! Borrowed CTE definitions. Enclosing scopes and definitions must outlive their consumers. +class CTEDefinitionScope { +public: + using lookup_t = std::function(TableIndex)>; + + //! Adapt an existing definition owner at the outermost scope. + explicit CTEDefinitionScope(lookup_t lookup = {}) : lookup(std::move(lookup)) { + } + explicit CTEDefinitionScope(optional_ptr parent) : parent(parent) { + } + CTEDefinitionScope(const CTEDefinitionScope &parent, TableIndex index, LogicalOperator &definition) + : parent(parent), index(index), definition(definition) { + } + +public: + optional_ptr Find(TableIndex index) const { + optional_ptr scope = *this; + while (scope) { + if (scope->definition && scope->index == index) { + return scope->definition; + } + if (scope->lookup) { + return scope->lookup(index); + } + scope = scope->parent; + } + return nullptr; + } + +private: + optional_ptr parent; + TableIndex index; + optional_ptr definition; + lookup_t lookup; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/cte_filter_helpers.hpp b/src/duckdb/src/include/duckdb/optimizer/cte_filter_helpers.hpp new file mode 100644 index 000000000..9672e2f25 --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/cte_filter_helpers.hpp @@ -0,0 +1,50 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/cte_filter_helpers.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/common.hpp" +#include "duckdb/common/optional_ptr.hpp" +#include "duckdb/common/unordered_map.hpp" +#include "duckdb/planner/column_binding.hpp" + +namespace duckdb { + +class LogicalCTERef; +class LogicalFilter; +class LogicalMaterializedCTE; +class LogicalOperator; + +//! Consumers borrowed from settled plan regions. Do not rewrite those regions while using this info. +struct CTEFilterInfo { + struct Consumer { + Consumer(LogicalCTERef &ref, optional_ptr parent); + + LogicalCTERef &ref; + optional_ptr filter; + }; + + explicit CTEFilterInfo(LogicalMaterializedCTE &cte); + + LogicalMaterializedCTE &cte; + vector consumers; + vector producer_bindings; + unordered_map consumer_indexes; + + //! Validate current layouts and record producer bindings and consumer positions. + bool ValidateProducerBindings(); + //! Collect every CTE's consumers once, for a phase that preserves the plan structure. + static unordered_map> Collect(LogicalOperator &root); + static bool ContainsRecursiveCTE(const LogicalOperator &op); + +private: + static void Collect(LogicalOperator &op, optional_ptr parent, + unordered_map> &ctes); +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/cte_filter_pusher.hpp b/src/duckdb/src/include/duckdb/optimizer/cte_filter_pusher.hpp deleted file mode 100644 index e528b4155..000000000 --- a/src/duckdb/src/include/duckdb/optimizer/cte_filter_pusher.hpp +++ /dev/null @@ -1,57 +0,0 @@ -//===----------------------------------------------------------------------===// -// DuckDB -// -// duckdb/optimizer/cte_filter_pusher.hpp -// -// -//===----------------------------------------------------------------------===// - -#pragma once - -#include "duckdb/common/insertion_order_preserving_map.hpp" - -namespace duckdb { - -class LogicalOperator; -class LogicalCTERef; -class Optimizer; - -class CTEFilterPusher { -public: - explicit CTEFilterPusher(Optimizer &optimizer); - //! Push consumer predicates and eligible join-key restrictions into materialized CTEs. - unique_ptr Optimize(unique_ptr op); - //! Discard planner guarantees before transformations that do not preserve consumer identity. - static void ClearDependencies(LogicalOperator &op); - -private: - //! CTE info needed for creating OR filters that can be pushed down - struct MaterializedCTEInfo { - explicit MaterializedCTEInfo(LogicalOperator &materialized_cte); - LogicalOperator &materialized_cte; - vector> filters; - vector> references; - bool all_cte_refs_are_filtered; - bool has_filter_dependency; - }; - -private: - //! Find all materialized CTEs and their refs - void FindCandidates(LogicalOperator &op); - //! Filters the reference of a materialized CTE on the left side of a SEMI join (or of a MARK join below a filter on - //! its mark) by what the filters on the right side imply for the join keys, when that makes every reference of the - //! CTE a filtered one - void GenerateSemiJoinFilters(LogicalOperator &op); - bool CanPushFilter(const MaterializedCTEInfo &info); - bool HasValidDependency(const MaterializedCTEInfo &info); - //! Creates an OR filter and pushes it into a materialized CTE - void PushFilterIntoCTE(MaterializedCTEInfo &info); - -private: - //! The optimizer - Optimizer &optimizer; - //! Mapping from CTE index to CTE info, order preserving so deepest CTEs are done first - InsertionOrderPreservingMap> cte_info_map; -}; - -} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/cte_join_filter_collector.hpp b/src/duckdb/src/include/duckdb/optimizer/cte_join_filter_collector.hpp index 5d9777124..c6ec0be37 100644 --- a/src/duckdb/src/include/duckdb/optimizer/cte_join_filter_collector.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/cte_join_filter_collector.hpp @@ -11,12 +11,14 @@ #include "duckdb/common/enums/expression_type.hpp" #include "duckdb/common/optional_ptr.hpp" #include "duckdb/common/unordered_map.hpp" +#include "duckdb/common/unordered_set.hpp" #include "duckdb/planner/column_binding.hpp" #include "duckdb/planner/expression.hpp" namespace duckdb { class LogicalOperator; +class LogicalComparisonJoin; class LogicalCTERef; //! A deterministic expression over a single output column of a materialized CTE @@ -27,6 +29,8 @@ struct CTEJoinFilterKey { ProjectionIndex column; CTEJoinFilterKey Copy() const; + hash_t Hash() const; + bool operator==(const CTEJoinFilterKey &other) const; //! Copy of the expression with its column reference rebound unique_ptr BindExpression(const LogicalType &type, ColumnBinding binding) const; }; @@ -43,6 +47,9 @@ struct CTEJoinFilter { vector source_keys; vector target_keys; vector comparisons; + + hash_t Hash() const; + bool operator==(const CTEJoinFilter &other) const; }; class CTEJoinFilterCollector { @@ -65,16 +72,34 @@ class CTEJoinFilterCollector { }; private: + //! Hash and compare indices by their immutable candidate, preserving vector ownership and order. + struct FilterIdentity { + const vector &filters; + + hash_t operator()(idx_t index) const { + return filters[index].Hash(); + } + bool operator()(idx_t left, idx_t right) const { + return filters[left] == filters[right]; + } + }; + explicit CTEJoinFilterCollector(const unordered_map &targets); - void VisitOperator(LogicalOperator &op); + CTEJoinFilterCollector(const CTEJoinFilterCollector &) = delete; + CTEJoinFilterCollector(CTEJoinFilterCollector &&) = delete; + bool IsTarget(const LogicalCTERef &ref) const; + //! Collect candidates bottom-up and report whether the subtree contains an eligible target. + bool VisitOperator(LogicalOperator &op); + void CollectJoinFilters(LogicalComparisonJoin &join, bool left_has_target, bool right_has_target); void PushFilter(LogicalOperator &op, const CTEJoinSource &source, const vector &source_keys, vector target_keys, const vector &comparisons); void AddFilter(const CTEJoinSource &source, const LogicalCTERef &target, const vector &source_keys, - const vector &target_keys, const vector &comparisons); + vector target_keys, const vector &comparisons); private: const unordered_map &join_targets; vector join_filters; + unordered_set filter_index; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/cte_join_filter_pusher.hpp b/src/duckdb/src/include/duckdb/optimizer/cte_join_filter_pusher.hpp index 0578fbc9d..c1ec711a9 100644 --- a/src/duckdb/src/include/duckdb/optimizer/cte_join_filter_pusher.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/cte_join_filter_pusher.hpp @@ -25,11 +25,21 @@ class CTEJoinFilterPusher { private: struct MaterializedCTEInfo { - explicit MaterializedCTEInfo(LogicalOperator &cte) : materialized_cte(cte) { + MaterializedCTEInfo(LogicalOperator &cte, idx_t definition_index) + : materialized_cte(cte), definition_index(definition_index) { } + + bool IsVisibleTo(const MaterializedCTEInfo &target) const { + return consumer_begin <= target.definition_index && target.definition_index < consumer_end; + } + LogicalOperator &materialized_cte; vector> references; - vector ancestors; + //! Preorder position in the CTE inventory. + idx_t definition_index; + //! Definitions in the consumer subtree can reference this CTE; definitions in its producer cannot. + idx_t consumer_begin = 0; + idx_t consumer_end = 0; }; void FindCandidates(LogicalOperator &op); @@ -37,8 +47,8 @@ class CTEJoinFilterPusher { private: Optimizer &optimizer; - InsertionOrderPreservingMap> cte_info_map; - vector available_ctes; + InsertionOrderPreservingMap, TableIndex, unordered_map> + cte_info_map; //! Parameter data, in case the plan is part of a prepared statement and a subtree must be copied optional_ptr parameter_data; }; diff --git a/src/duckdb/src/include/duckdb/optimizer/distinctness.hpp b/src/duckdb/src/include/duckdb/optimizer/distinctness.hpp index 0c2ea14f4..37861d271 100644 --- a/src/duckdb/src/include/duckdb/optimizer/distinctness.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/distinctness.hpp @@ -10,6 +10,7 @@ #include "duckdb/common/optional_ptr.hpp" #include "duckdb/common/reference_map.hpp" +#include "duckdb/optimizer/cte_definition_scope.hpp" #include "duckdb/common/unique_ptr.hpp" #include "duckdb/common/vector.hpp" #include "duckdb/planner/column_binding_map.hpp" @@ -20,6 +21,7 @@ class ClientContext; class Expression; class LogicalAggregate; class LogicalComparisonJoin; +class LogicalCTERef; class LogicalGet; class LogicalOperator; class LogicalProjection; @@ -40,11 +42,9 @@ enum class DistinctnessPropagation : uint8_t { //! constraints of a scanned table. They are forwarded through operators that never duplicate rows (see //! DistinctnessPropagation). Statistics (distinct counts) are estimates and are never used. //! The unique sets of an operator are computed once and cached by the identity of the operator, so that a -//! bottom-up pass over a plan stays linear. An instance is therefore only valid for the analysis of a stable plan: -//! once a pass replaces or removes an operator that has been asked about (or one below it), or changes what the -//! unique sets are derived from (the scanned columns, groups and grouping sets, projection expressions, join types -//! and join conditions), the instance must not be used anymore. Rewrites of anything else (e.g. order keys, window -//! partitions) and of operators above everything that has been asked about keep it valid. +//! bottom-up pass over a plan stays linear. After changing scanned columns, groups, projections or joins, discard +//! the affected cached nodes and their ancestors with Invalidate before reusing the instance. Changing a resolved +//! CTE definition also invalidates cached proofs for its references and their ancestors. class Distinctness { public: //! The maximum number of unique sets that a join forwards @@ -52,8 +52,10 @@ class Distinctness { public: //! A context allows cast proofs that account for registered overrides. - explicit Distinctness(DistinctnessPropagation propagation, optional_ptr context = nullptr) - : propagation(propagation), context(context) { + //! Supplying a CTE scope enables proofs through non-recursive CTE references. + explicit Distinctness(DistinctnessPropagation propagation, optional_ptr context = nullptr, + optional_ptr cte_scope = nullptr) + : propagation(propagation), context(context), cte_scope(cte_scope) { } //! Whether the output of the operator has at most one row per value of the keys @@ -62,22 +64,28 @@ class Distinctness { bool IsDistinctOn(LogicalOperator &op, const vector> &keys); //! The sets of columns the output of the operator is distinct on (cached) const vector &GetUniqueSets(LogicalOperator &op); + //! Discard a changed node before refreshing it; callers must also discard all affected cached ancestors. + void Invalidate(LogicalOperator &op); //! Gets the equality keys (= or IS NOT DISTINCT FROM) of the left (child_idx 0) or right (child_idx 1) side of a //! join. Returns false if there is no equality, or if the key of an equality is not a plain column reference static bool GetJoinEqualityKeys(const LogicalComparisonJoin &join, idx_t child_idx, column_binding_set_t &keys); private: - bool IsDistinctOnProjectedKeys(LogicalOperator &op, const column_binding_set_t &keys); + bool IsDistinctOnProjectedKeys(LogicalOperator &op, column_binding_set_t keys); vector ComputeUniqueSets(LogicalOperator &op); static vector ComputeScanUniqueSets(LogicalGet &get); static vector ComputeAggregateUniqueSets(LogicalAggregate &aggr); vector ComputeProjectionUniqueSets(LogicalProjection &projection); + vector ComputeCTEUniqueSets(LogicalCTERef &cte_ref); + static vector RemapUniqueSets(const vector &sets, + const column_binding_map_t &bindings); vector ComputeJoinUniqueSets(LogicalComparisonJoin &join); bool IsDistinctOnJoinKeys(LogicalComparisonJoin &join, idx_t child_idx); private: const DistinctnessPropagation propagation; const optional_ptr context; + optional_ptr cte_scope; reference_map_t> unique_sets; }; diff --git a/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_aggregate.hpp b/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_aggregate.hpp new file mode 100644 index 000000000..1fc91666b --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_aggregate.hpp @@ -0,0 +1,35 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/duplicate_eliminated_domain/domain_aggregate.hpp +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/helper.hpp" +#include "duckdb/common/optional.hpp" +#include "duckdb/common/vector.hpp" + +namespace duckdb { + +class DomainAnalysis; +class Expression; +class LogicalAggregate; +class LogicalOperator; + +struct AggregateKeyMatch { +public: + //! Complete grouping key, in the caller's key order. + reference aggregate; + vector group_indices; +}; + +struct DomainAggregate { +public: + static bool HasSimpleGrouping(const LogicalAggregate &aggregate); + static unique_ptr GroupKey(const LogicalAggregate &domain); + static optional Match(LogicalOperator &op, vector keys, const DomainAnalysis &analysis); +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_analysis.hpp b/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_analysis.hpp new file mode 100644 index 000000000..60f4c924d --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_analysis.hpp @@ -0,0 +1,182 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/duplicate_eliminated_domain/domain_analysis.hpp +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/reference_map.hpp" +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_key_lineage.hpp" +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_scan_source.hpp" +#include "duckdb/optimizer/relation_statistics/relation_statistics_extractor.hpp" +#include "duckdb/planner/subquery/column_binding_layout.hpp" + +namespace duckdb { + +class BaseStatistics; +class LogicalAggregate; +class LogicalCTE; +class LogicalCTERef; +class LogicalGet; +class LogicalMaterializedCTE; +class JoinFilterTargetCache; + +enum class DomainSourceRows { DIRECT, COMPLETE, FILTERED }; +enum class DomainProduction { INLINE, SHARED }; + +struct DomainDefinition { +public: + DomainDefinition(LogicalAggregate &aggregate_p, DomainProduction production_p) + : aggregate(aggregate_p), production(production_p) { + } + +public: + //! Validated duplicate elimination and how this input reads it. + reference aggregate; + DomainProduction production; +}; + +struct DomainInput { +public: + bool HasAllSourceRows() const { + return source_rows != DomainSourceRows::FILTERED; + } + bool IsDirectSource() const { + return source_rows == DomainSourceRows::DIRECT; + } + bool IsInlineDomain() const { + return domain && domain->production == DomainProduction::INLINE; + } + +public: + //! Row provenance; COMPLETE also permits grouping or computed projections. + optional_ptr row_source; + DomainSourceRows source_rows = DomainSourceRows::COMPLETE; + + //! Reader identity, visibility, and ordering in the current CTE scope. + optional_ptr single_reference; + idx_t reference_count = 0; + idx_t latest_source = 0; + bool visible_references = true; + bool shared_source = false; + + //! Recognized structures reachable through the supported operators. + optional domain; + optional_ptr aggregate; + optional_ptr closed_scan; + + //! Independent permissions for changing evaluation domains and readers. + bool safe = false; + bool repeatable = false; + bool aggregate_can_expand = false; + bool can_change_readers = false; + + //! A known fixed input population and a proven output cardinality bound. + optional_idx fixed_rows; + optional_idx maximum_rows; + + //! Work estimates used by restriction and recovery choices. + double key_production_work = 0; + double indexed_scan_work = 0; + + //! Bound repeated join estimation, including work within its physical leaves. + idx_t estimation_nodes = 1; + bool join_region = false; + + //! Published output snapshots, shared by estimates and binding lookups. + shared_ptr stats; + shared_ptr layout; +}; + +//! Publishes current-plan facts and coordinates their invalidation. +class DomainAnalysis { +public: + explicit DomainAnalysis(ClientContext &context); + ~DomainAnalysis(); + +public: + //! CTE visibility and reader counts follow the optimizer's traversal. + void Initialize(LogicalOperator &root); + void EnterOperator(LogicalOperator &op); + void EnterChild(LogicalOperator &op, idx_t child_index); + void LeaveOperator(LogicalOperator &op); + idx_t ReferenceCount(TableIndex index) const; + bool ReadsEarlierSources(LogicalOperator &op, TableIndex source) const; + optional_ptr FindOwner(TableIndex index) const; + optional_ptr FindMaterializedOwner(TableIndex index) const; + bool InRecursiveScope() const; + + //! Publish changed nodes bottom-up while reusing unchanged child facts. + void Summarize(LogicalOperator &op); + void Refresh(LogicalOperator &op); + const DomainInput &Get(const LogicalOperator &op) const; + optional_ptr Stats(const LogicalOperator &op) const; + RelationStatsExtractor &Statistics(); + + //! Key identity and containment use published layouts and producer ancestry. + ColumnBinding ResolveBinding(ColumnBinding binding) const; + optional KeySource(LogicalOperator &op, idx_t key) const; + bool ContainsKeys(LogicalOperator &original, const vector &original_keys, LogicalOperator &demand, + const vector &demand_keys) const; + const vector &Bindings(LogicalOperator &op) const; + optional_idx BindingIndex(LogicalOperator &op, ColumnBinding binding) const; + optional_idx ReferenceIndex(const Expression &expression, LogicalOperator &op) const; + optional_idx ReferenceIndex(const Expression &expression, LogicalOperator &op, const LogicalType &type) const; + bool IsDistinctOn(LogicalOperator &op, const column_binding_set_t &keys); + + //! Candidate discovery shares memoized answers within this plan. + DomainScanSource FindScanSource(const LogicalMaterializedCTE &owner, idx_t key); + bool HasRuntimeFilterTargets(LogicalAggregate &aggregate); + + //! Invalidate changed facts before refreshing affected nodes. + void Invalidate(LogicalOperator &op); + void InvalidateProjectionPath(LogicalOperator &root, LogicalOperator &target); + + //! Remove a subtree's cached facts and unregister its CTE readers before destruction. + void RemoveSubtree(LogicalOperator &op); + +private: + void SummarizeSafety(LogicalOperator &op, DomainInput &result); + void SummarizeSources(LogicalOperator &op, DomainInput &result); + void SummarizePassthrough(LogicalOperator &op, DomainInput &result); + void SummarizeReference(LogicalCTERef &ref, DomainInput &result); + void SummarizeDomain(LogicalAggregate &aggregate, DomainInput &result); + void SummarizeStructure(LogicalOperator &op, DomainInput &result); + + bool RegisterOwner(LogicalCTE &cte); + + optional EstimateStats(LogicalOperator &op, DomainInput &input); + + void CaptureColumns(LogicalOperator &op, DomainInput &result); + void CaptureKeys(LogicalOperator &op, const DomainInput &input); + void PublishKeys(LogicalMaterializedCTE &cte); + + void CaptureBounds(LogicalOperator &op, DomainInput &result); + unique_ptr ExpressionBounds(const Expression &expression) const; + +private: + //! Current operator facts and binding provenance. + ClientContext &context; + reference_map_t inputs; + column_binding_map_t origins; + column_binding_map_t> value_bounds; + DomainKeyLineage lineage; + const vector empty_bindings; + + //! Shared estimators and lazy discovery caches use the same invalidation boundary. + Distinctness distinctness; + RelationStatsExtractor statistics; + unique_ptr filter_targets; + unordered_map> scan_sources; + + //! Lexical CTE owners and reader accounting; published ancestry lives in lineage. + unordered_map> owners; + unordered_map source_order; + unordered_map reference_counts; + reference_set_t registered_references; + idx_t recursive_depth = 0; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_cost_model.hpp b/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_cost_model.hpp new file mode 100644 index 000000000..75e2a358d --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_cost_model.hpp @@ -0,0 +1,110 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/duplicate_eliminated_domain/domain_cost_model.hpp +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp" +#include "duckdb/optimizer/relation_statistics/relation_statistics_extractor.hpp" + +namespace duckdb { + +class DomainRestriction; +class DomainAnalysis; + +enum class RestrictionAction { KEEP, INSERT, REPLACE, REMOVE }; +enum class RecoveryAction { KEEP, REMOVE }; +enum class DomainKeyContainment { EXACT, SUPERSET }; + +struct DomainChoice { +public: + void Consider(const DomainChoice &candidate) { + if (candidate.savings > savings || (IsKeep() && candidate.savings == savings && !candidate.IsKeep())) { + *this = candidate; + } + } + + bool IsKeep() const { + return restriction == RestrictionAction::KEEP && recovery == RecoveryAction::KEEP; + } + +public: + //! Independent restriction/recovery actions and their combined savings. + RestrictionAction restriction = RestrictionAction::KEEP; + RecoveryAction recovery = RecoveryAction::KEEP; + double savings = 0; +}; + +struct ReleasedDomainWork { +public: + //! Producers proven to stop when a choice is applied. + optional_ptr production; + optional_ptr source; +}; + +//! Compare alternatives using the same statistics source and domain-production costs. +//! Decisions borrow one published analysis state; application invalidates affected facts. +class DomainCostModel { +public: + DomainCostModel(DomainAnalysis &analysis, LogicalAggregate &aggregate, double key_input_rows = 0, + double source_read_write_work = 0); + +public: + static double EstimateDomainProductionWork(double rows, double distinct_rows); + DomainChoice ChooseInsertion(LogicalComparisonJoin &restriction, const RelationStats &keys); + static double ExistenceBaseWork(JoinType type, const RelationStats &base, const RelationStats &domain, + const vector> &keys, double filter_work, + double indexed_scan_work); + static DomainChoice ChooseExistence(const RelationStats &outer, const RelationStats &domain, double expression_work, + double added_base_work, double released_work); + //! Compare existing restrictions, optionally with a proven replacement domain. + DomainChoice ChooseRestriction(const DomainRestriction &existing); + DomainChoice ChooseRestriction(const DomainRestriction &existing, LogicalAggregate &domain, + const RelationStats &keys, DomainKeyContainment containment); + //! Price only producers that the caller has proven will stop. + static double EstimateReleasedWork(const DomainAnalysis &analysis, ReleasedDomainWork released); + void SetReleasedWork(const ReleasedDomainWork &released); + static double RecoverySavings(double outer_rows, const RelationStats &domain, double expression_work, + idx_t single_row_joins, double released_work); + +private: + struct RestrictionCost; + optional CostRestriction(const DomainRestriction &existing); + DomainChoice ChooseReplacement(const DomainRestriction &existing, RestrictionCost &cost, LogicalAggregate &domain, + const RelationStats &keys, DomainKeyContainment containment); + void ConsiderRemoval(const DomainRestriction &existing, RestrictionCost &cost, DomainChoice &choice); + static void ConsiderRestrictionWork(RestrictionCost &cost, double work, RestrictionAction action, + DomainChoice &choice); + static bool IsCheaper(double candidate, double original); + static double EstimateSemiJoinWork(double input_rows, double output_rows, double key_rows); + static double EstimateRecoveryDomainRows(const RelationStats &domain); + static double EstimateRecoveryRowWork(double expression_work, idx_t single_row_joins); + double EstimateAggregateWork(double input_rows, double group_count) const; + double EstimateAggregateWork(const RelationStats &input, const vector &group_bindings) const; + optional EstimateRestriction(const DomainRestriction &existing, + const RelationStats &input, const RelationStats &keys); + +private: + //! One aggregate consumer borrows current analysis and its estimator caches. + DomainAnalysis &analysis; + RelationStatsExtractor &extractor; + LogicalAggregate &aggregate; + + //! Added producer work and credit for producers that stop. + double key_input_rows = 0; + double source_read_write_work = 0; + double released_work = 0; + + //! Hash-row work calibration shared by all domain choices. + static constexpr double DOMAIN_INPUT_WORK = 2; + static constexpr double DOMAIN_STARTUP_WORK = 3; + static constexpr double RELEASED_WORK_SCALE = 0.3; + static constexpr double EXPRESSION_WORK_PER_HASH_ROW = 64; + static constexpr double SINGLE_ROW_JOIN_WORK = 0.3; + static constexpr double COST_TOLERANCE = 32; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_expression.hpp b/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_expression.hpp new file mode 100644 index 000000000..688a259a5 --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_expression.hpp @@ -0,0 +1,25 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/duplicate_eliminated_domain/domain_expression.hpp +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/planner/expression.hpp" + +namespace duckdb { +class BoundColumnRefExpression; + +enum class DomainExpressionScope { ALLOW_POSITIONAL, NAMED_COLUMNS_ONLY }; + +struct DomainExpression { +public: + static optional_ptr DirectColumn(const Expression &expression); + static bool IsSafe(const Expression &expression, + DomainExpressionScope scope = DomainExpressionScope::ALLOW_POSITIONAL); + static bool IsWorkReference(const Expression &expression); +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_key_lineage.hpp b/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_key_lineage.hpp new file mode 100644 index 000000000..322006115 --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_key_lineage.hpp @@ -0,0 +1,61 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/duplicate_eliminated_domain/domain_key_lineage.hpp +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/optional.hpp" +#include "duckdb/common/optional_idx.hpp" +#include "duckdb/common/pair.hpp" +#include "duckdb/planner/column_binding_map.hpp" + +namespace duckdb { + +//! Key ancestry of published CTE definitions, preserving tuple correlation. +class DomainKeyLineage { +public: + void SetSource(ColumnBinding binding, ColumnBinding source); + optional Source(ColumnBinding binding) const; + void RemoveSource(ColumnBinding binding); + + void Publish(TableIndex producer, optional parent, bool filtered, + const vector> &sources); + bool Contains(TableIndex producer, const vector &originals, + const vector &demands) const; + +private: + optional_idx LiftKey(idx_t key, idx_t depth) const; + optional_idx CommonKey(idx_t left, idx_t right) const; + +private: + struct ProducerLineage { + public: + //! Depth and the earliest ancestor with the same source population. + idx_t depth = 1; + idx_t unfiltered_depth = 1; + }; + struct KeyLineage { + public: + KeyLineage(ColumnBinding binding_p, idx_t depth_p) : binding(binding_p), depth(depth_p) { + } + + public: + //! Published key and powers-of-two ancestors. + ColumnBinding binding; + idx_t depth; + vector ancestors; + }; + + //! Current operator bindings; invalidated with their published layouts. + column_binding_map_t key_sources; + + //! Immutable ancestry remains available after a CTE leaves lexical scope. + unordered_map producer_lineage; + column_binding_map_t producer_keys; + vector key_lineage; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_recovery.hpp b/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_recovery.hpp new file mode 100644 index 000000000..f3f7b97e4 --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_recovery.hpp @@ -0,0 +1,58 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/duplicate_eliminated_domain/domain_recovery.hpp +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_restriction.hpp" + +namespace duckdb { + +class BindingReplacementGraph; +class Optimizer; + +//! A matched recovery borrows one join and its published bindings until Apply splices the plan. +class DomainRecovery { +private: + DomainRecovery(DomainAnalysis &analysis, LogicalComparisonJoin &outer, LogicalComparisonJoin &domain_join, + vector> chain); + +public: + static optional Match(DomainAnalysis &analysis, LogicalComparisonJoin &outer); + DomainChoice Choose() const; + void Apply(Optimizer &optimizer, unique_ptr &op, const DomainChoice &choice, + BindingReplacementGraph &replacements); + +private: + bool MatchOuterKeys(const vector &source_keys); + void MatchAggregateRestriction(); + optional RecoverySavings(const ReleasedDomainWork &released) const; + unique_ptr SpliceJoin(unique_ptr &op, const BindingReplacementGraph &keys); + void PassOuterColumns(vector bindings, const BindingReplacementGraph &keys); + +private: + struct AggregateRestriction { + public: + //! An eligible restriction on the grouped input of the domain LEFT join. + LogicalAggregate &aggregate; + DomainRestriction input; + }; + + //! Row-preserving path from the outer join's RHS down to the domain LEFT join. + DomainAnalysis &analysis; + LogicalComparisonJoin &outer; + LogicalComparisonJoin &domain_join; + vector> chain; + + //! Shared CTE and outer column positions in domain output order. + TableIndex source; + vector demand_indices; + + //! A restriction can be removed independently or together with recovery. + optional restriction; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_restriction.hpp b/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_restriction.hpp new file mode 100644 index 000000000..bee77b505 --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_restriction.hpp @@ -0,0 +1,65 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/duplicate_eliminated_domain/domain_restriction.hpp +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_analysis.hpp" +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_cost_model.hpp" +#include "duckdb/planner/operator/logical_aggregate.hpp" +#include "duckdb/planner/operator/logical_comparison_join.hpp" +#include "duckdb/planner/operator/logical_projection.hpp" + +namespace duckdb { + +//! A matched input restriction and the projections between it and its aggregate. +//! Borrows the plan for one decision. Removal may destroy the matched join. +class DomainRestriction { +public: + DomainRestriction(DomainAnalysis &analysis, LogicalAggregate &aggregate, ExpressionType comparison); + DomainRestriction(DomainAnalysis &analysis, LogicalAggregate &aggregate, const vector &comparisons); + +public: + optional_ptr GetJoin() const { + return join; + } + + bool HasSimpleProjections() const; + bool CanRemove() const; + bool ContainsDemand(LogicalOperator &demand, const vector &demand_indices) const; + const JoinCondition &GetCondition(idx_t key) const { + return join->conditions[conditions[key]]; + } + bool FiltersNullKey(idx_t key) const { + return GetCondition(key).GetComparisonType() == ExpressionType::COMPARE_EQUAL && + consumer_comparisons[key] == ExpressionType::COMPARE_NOT_DISTINCT_FROM; + } + idx_t NullFilterCount() const { + idx_t count = 0; + for (idx_t key = 0; key < conditions.size(); key++) { + count += FiltersNullKey(key); + } + return count; + } + void Replace(unique_ptr &domain); + void Remove(); + +private: + optional_ptr Find(LogicalOperator &input, const vector> &keys); + +private: + //! Matched operators remain borrowed until replacement or removal. + LogicalAggregate &aggregate; + DomainAnalysis &analysis; + optional_ptr join; + vector> projections; + + //! Comparison order retains per-key NULL-filter requirements. + vector consumer_comparisons; + vector conditions; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_scan_source.hpp b/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_scan_source.hpp new file mode 100644 index 000000000..71fc4f08f --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain/domain_scan_source.hpp @@ -0,0 +1,80 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/duplicate_eliminated_domain/domain_scan_source.hpp +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/reference_map.hpp" +#include "duckdb/planner/column_binding_map.hpp" +#include "duckdb/planner/logical_operator.hpp" + +namespace duckdb { + +class ClientContext; +class DomainAnalysis; +class LogicalComparisonJoin; + +struct DomainScanSource { +public: + //! Borrowed candidate and key position in an immutable CTE definition. + optional_ptr> input; + idx_t key = 0; + + //! Output rows rank candidates; scan rows price rereading the chosen source. + double rows = 0; + double scan_rows = 0; +}; + +//! Discovers scan-backed supersets within one published, immutable CTE definition. +class DomainScanSourceFinder { +public: + DomainScanSourceFinder(ClientContext &context, const DomainAnalysis &analysis, + const unique_ptr &definition); + +public: + DomainScanSource Find(idx_t key); + +private: + struct InputKey { + public: + InputKey(const unique_ptr &input_p, idx_t key_p) : input(input_p), key(key_p) { + } + + public: + //! One output position to trace through the immutable input. + reference> input; + idx_t key; + }; + struct EqualitySource { + public: + //! Type-preserving mapping to the opposite join child. + idx_t key; + LogicalType type; + }; + struct JoinSources { + public: + //! First eligible equality for each direction; direct bindings take precedence. + column_binding_map_t left; + column_binding_map_t right; + }; + + vector GetChildren(const InputKey &input); + const JoinSources &GetJoinSources(LogicalComparisonJoin &join); + DomainScanSource GetCandidate(const InputKey &input); + +private: + //! The definition's slots and expressions remain valid until its owner leaves scope. + ClientContext &context; + const DomainAnalysis &analysis; + const unique_ptr &definition; + + //! Positive and negative results are shared by converging key paths. + reference_map_t> results; + reference_map_t join_sources; + reference_map_t scan_rows; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain_optimizer.hpp b/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain_optimizer.hpp index 6c31f0bec..9c74fc48f 100644 --- a/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain_optimizer.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/duplicate_eliminated_domain_optimizer.hpp @@ -9,14 +9,15 @@ #pragma once #include "duckdb/optimizer/column_binding_replacer.hpp" +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_analysis.hpp" namespace duckdb { class Optimizer; class LogicalAggregate; class LogicalMaterializedCTE; -//! Restrict local grouped aggregates to their consumer's demand keys. -class DuplicateEliminatedDomainOptimizer : public LogicalOperatorVisitor { +//! Choose key domains and result recovery for aggregate and existence consumers. +class DuplicateEliminatedDomainOptimizer : public LayoutPreservingRewriter { public: explicit DuplicateEliminatedDomainOptimizer(Optimizer &optimizer); @@ -24,15 +25,19 @@ class DuplicateEliminatedDomainOptimizer : public LogicalOperatorVisitor { void Optimize(unique_ptr &op); private: - void VisitOperator(unique_ptr &op) override; - bool TryOptimizeDomain(unique_ptr &op, idx_t aggregate_side, idx_t condition_index); + bool OptimizeConsumer(unique_ptr &op, BindingReplacementGraph &replacements); + bool TryOptimizeExistence(unique_ptr &op); + bool EnterOperator(LogicalOperator &op) override; + void EnterChild(LogicalOperator &op, idx_t child_index) override; + void RewriteOperator(unique_ptr &op, BindingReplacementGraph &replacements) override; + bool TryOptimizeDomain(unique_ptr &op, idx_t aggregate_side, idx_t condition_index, + BindingReplacementGraph &replacements); bool TryOptimizeRuntimeDomain(unique_ptr &op, LogicalAggregate &aggregate, idx_t aggregate_side, - idx_t demand_index, ExpressionType comparison); - bool TryPullUpOuterDomainJoin(unique_ptr &op); + idx_t demand_index, ExpressionType comparison, BindingReplacementGraph &replacements); + bool TryPullUpOuterDomainJoin(unique_ptr &op, BindingReplacementGraph &replacements); private: Optimizer &optimizer; - BindingReplacementGraph replacements; - vector> cte_scopes; + DomainAnalysis analysis; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/filter_pushdown.hpp b/src/duckdb/src/include/duckdb/optimizer/filter_pushdown.hpp index 644a0ca4a..de0211644 100644 --- a/src/duckdb/src/include/duckdb/optimizer/filter_pushdown.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/filter_pushdown.hpp @@ -9,11 +9,13 @@ #pragma once #include "duckdb/common/unordered_set.hpp" +#include "duckdb/common/optional_ptr.hpp" #include "duckdb/optimizer/filter_combiner.hpp" #include "duckdb/optimizer/rule.hpp" namespace duckdb { +class LogicalComparisonJoin; class LogicalGet; class LogicalWindow; class Optimizer; @@ -25,7 +27,10 @@ class FilterPushdown { explicit FilterPushdown(Optimizer &optimizer, ProjectionMode projection_mode = ProjectionMode::ALLOW_COMPUTED_EXPRESSIONS); - //! Perform filter pushdown + //! The single later pushdown opportunity, after consumer filters and bindings have settled. + static unique_ptr RewriteAndRestrictCTEs(Optimizer &optimizer, unique_ptr op); + + //! Perform ordinary filter pushdown unique_ptr Rewrite(unique_ptr op); //! Return a reference to the client context (from the optimizer) ClientContext &GetContext(); @@ -40,6 +45,8 @@ class FilterPushdown { //! Whether every window expression is a ranking function without arguments, e.g. row_number(), which neither fails //! nor has side effects, so a filter may change the partitions it runs for static bool OnlyRanksWithoutArguments(const LogicalWindow &window); + //! Whether this conjunct requires the MARK join's bare marker to be TRUE + static bool IsMarkFilter(const LogicalComparisonJoin &join, const Expression &filter); struct Filter { unordered_set bindings; @@ -58,15 +65,29 @@ class FilterPushdown { }; private: + struct CTEFilterState; + class CTEFilterRewriter; + FilterPushdown(const FilterPushdown &parent, ProjectionMode projection_mode); + FilterPushdown CreateChildPushdown() const; + FilterPushdown CreateChildPushdown(ProjectionMode projection_mode) const; + Optimizer &optimizer; FilterCombiner combiner; ProjectionMode projection_mode; + //! Owned by the named later entrypoint; child workers inherit it automatically. + optional_ptr cte_state; vector> filters; + //! A child worker may retain proof that its complete input is nonvolatile. Other workers start uncertified. + bool input_is_nonvolatile = false; + //! Infer left key constraints for a required match, reusing only this worker's nonvolatile-input proof. + vector> GenerateJoinFilters(LogicalComparisonJoin &join); //! Push down a LogicalAggregate op unique_ptr PushdownAggregate(unique_ptr op); //! Push down a LogicalFilter op unique_ptr PushdownFilter(unique_ptr op); + //! Rewrite materialized CTE consumers before propagating their restrictions into the producer. + unique_ptr PushdownMaterializedCTE(unique_ptr op); //! Push down a LogicalCrossProduct op unique_ptr PushdownCrossProduct(unique_ptr op); //! Push down a join operator @@ -105,7 +126,8 @@ class FilterPushdown { unique_ptr PushdownOuterJoin(unique_ptr op, unordered_set &left_bindings, unordered_set &right_bindings); - unique_ptr PushdownSemiAntiJoin(unique_ptr op); + //! Push left filters through SEMI/ANTI joins, or a MARK join whose marker must be TRUE + unique_ptr PushdownFilterJoin(unique_ptr op); // Pushdown a mark join unique_ptr PushdownMarkJoin(unique_ptr op, unordered_set &left_bindings, diff --git a/src/duckdb/src/include/duckdb/optimizer/filter_statistics.hpp b/src/duckdb/src/include/duckdb/optimizer/filter_statistics.hpp index cce14d702..d3e206f7e 100644 --- a/src/duckdb/src/include/duckdb/optimizer/filter_statistics.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/filter_statistics.hpp @@ -19,7 +19,8 @@ class FilterStatisticsOptimizer { public: explicit FilterStatisticsOptimizer(Optimizer &optimizer); - void Optimize(unique_ptr &plan); + //! Simplify filters and report whether their bindings changed enough to warrant another pushdown. + bool Optimize(unique_ptr &plan); private: bool HasMultiBindingFilter(const LogicalOperator &op) const; diff --git a/src/duckdb/src/include/duckdb/optimizer/join_elimination.hpp b/src/duckdb/src/include/duckdb/optimizer/join_elimination.hpp index 3b1f31b1a..687b7c202 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_elimination.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_elimination.hpp @@ -12,8 +12,8 @@ #include "duckdb/common/shared_ptr.hpp" #include "duckdb/common/typedefs.hpp" #include "duckdb/common/unique_ptr.hpp" -#include "duckdb/common/unordered_map.hpp" #include "duckdb/common/unordered_set.hpp" +#include "duckdb/optimizer/removed_subtree_effects.hpp" #include "duckdb/planner/expression.hpp" #include "duckdb/planner/logical_operator.hpp" #include "duckdb/planner/logical_operator_visitor.hpp" @@ -42,31 +42,6 @@ class PipelineInfo { } }; -//! What a removed subtree would no longer do, beyond returning rows: evaluate a volatile expression (nextval, random), -//! modify data, or run a table function that declares itself VOLATILE. A reference to a materialized CTE counts with -//! everything in the definition of that CTE: once the reference is gone, the columns only it read are pruned from the -//! definition, expressions included. -class RemovedSubtreeEffects { -public: - //! Registers the CTEs that are defined in the plan - explicit RemovedSubtreeEffects(LogicalOperator &plan); - - //! Whether removing the subtree would skip an effect - bool HasEffect(LogicalOperator &subtree); - -private: - void CollectDefinitions(LogicalOperator &op); - //! Whether the definition of a materialized CTE has an effect; computed once per CTE - bool DefinitionHasEffect(TableIndex cte_index); - - //! The materialized CTEs of the plan (the CTE operators; the definition is their first child) - unordered_map> materialized_ctes; - //! The recursive CTEs of the plan: a reference to one reads the working table of a recursion that is part of the - //! plan around the reference - unordered_set recursive_ctes; - unordered_map definition_has_effect; -}; - class JoinElimination : public LogicalOperatorVisitor { public: explicit JoinElimination() { diff --git a/src/duckdb/src/include/duckdb/optimizer/join_filter_pushdown_optimizer.hpp b/src/duckdb/src/include/duckdb/optimizer/join_filter_pushdown_optimizer.hpp index bbe8e0aa7..ce132876d 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_filter_pushdown_optimizer.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_filter_pushdown_optimizer.hpp @@ -16,6 +16,21 @@ namespace duckdb { class Optimizer; class LogicalCTERef; +class LogicalAggregate; +class FilterTargetCacheState; + +//! Scan-target availability for grouping keys in the current logical plan. +class JoinFilterTargetCache { +public: + JoinFilterTargetCache(); + ~JoinFilterTargetCache(); + + bool HasTargets(LogicalAggregate &aggregate); + void Invalidate(const LogicalOperator &op); + +private: + unique_ptr state; +}; enum class EqualityPropagation { DISABLED, ENABLED }; @@ -40,8 +55,8 @@ class JoinFilterPushdownOptimizer : public LogicalOperatorVisitor { static bool IsFiltering(const unique_ptr &op); private: - void CollectCTEFilters(LogicalOperator &op); - void GenerateCTEFilters(LogicalMaterializedCTE &cte); + class CTEFilterCollector; + void GenerateCTEFilters(LogicalOperator &op); void GenerateJoinFilters(LogicalComparisonJoin &join); static bool CanGenerateJoinFilters(const LogicalComparisonJoin &join); static void GetCTEFilterTargets(LogicalOperator &op, const vector &columns, @@ -49,6 +64,7 @@ class JoinFilterPushdownOptimizer : public LogicalOperatorVisitor { private: Optimizer &optimizer; + bool use_scan_statistics = false; reference_map_t> cte_filters; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_estimator.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_estimator.hpp index 272fcef2a..c3cc3626d 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_estimator.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/cardinality_estimator.hpp @@ -47,6 +47,8 @@ class CardinalityEstimator { optional_ptr FindBoundary(JoinRelationSet &set, optional_ptr ®ion); optional ProjectColumn(JoinRelationSet &set, ColumnBinding binding); + //! Estimated rows of the set that hold values of the binding, i.e. excluding NULL-extended rows + CardinalityValue EstimateValueRows(JoinRelationSet &set, ColumnBinding binding); SemiAntiJoinCardinalityEstimate EstimateMembership(const LogicalJoinStats &boundary, JoinRelationSet &left, JoinRelationSet &right, JoinType join_type, vector &domains); diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_optimizer.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_optimizer.hpp index 81690dc6a..92bbd7322 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_optimizer.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/join_order_optimizer.hpp @@ -32,14 +32,27 @@ class JoinOrderOptimizer { JoinOrderOptimizer CreateChildOptimizer(); //! Perform join reordering inside a plan unique_ptr Optimize(unique_ptr plan, optional_ptr stats = nullptr); - //! Adds/gets materialized CTE stats - void AddMaterializedCTEStats(TableIndex index, RelationStats &&stats); + //! Materialized CTE statistics and borrowed definitions visible to this join-order scope. + void AddMaterializedCTEStats(TableIndex index, RelationStats &&stats, + optional_ptr definition = nullptr); RelationStats GetMaterializedCTEStats(TableIndex index); + optional_ptr GetMaterializedCTEDefinition(TableIndex index) const; //! Adds/gets delim scan stats void AddDelimScanStats(RelationStats &stats); RelationStats GetDelimScanStats(); const shared_ptr &GetSourceStats() const; +private: + struct MaterializedCTEStats { + MaterializedCTEStats(RelationStats stats, optional_ptr definition) + : stats(std::move(stats)), definition(definition) { + } + + RelationStats stats; + //! Non-recursive definitions remain owned by the CTE while its consumer is optimized. + optional_ptr definition; + }; + private: ClientContext &context; @@ -56,8 +69,7 @@ class JoinOrderOptimizer { unordered_set join_nodes_in_full_plan; - //! Mapping from materialized CTE index to stats - unordered_map materialized_cte_stats; + unordered_map materialized_cte_stats; //! Stats of Delim Scans of the Delim Join that is currently being optimized optional_ptr delim_scan_stats; idx_t depth; diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/query_graph.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/query_graph.hpp index c00cc28e5..418163c77 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/query_graph.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/query_graph.hpp @@ -45,7 +45,7 @@ class QueryGraphEdges { struct QueryEdge { optional_ptr relations; vector> neighbors; - unordered_map> children; + unordered_map> children; }; public: @@ -70,11 +70,10 @@ class QueryGraphEdges { //! Get the QueryEdge of a specific node optional_ptr GetQueryEdge(JoinRelationSet &left); - void EnumerateNeighborsDFS(JoinRelationSet &node, reference info, idx_t index, - const std::function &callback) const; - private: QueryEdge root; + //! Flat ownership avoids recursive destruction of deep edge prefixes; child links keep stable node addresses. + vector> owned_edges; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/query_graph_manager.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/query_graph_manager.hpp index a0479449b..3a08fda3e 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/query_graph_manager.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/query_graph_manager.hpp @@ -96,6 +96,9 @@ class QueryGraphManager { GenerateJoinRelation GenerateJoins(vector> &extracted_relations, JoinRelationSet &set, CardinalityEstimator &estimator, const vector> &pending_filters); + GenerateJoinRelation ReconstructJoinNode(DPJoinNode &node, vector> &extracted_relations, + vector &children, CardinalityEstimator &estimator, + const vector> &pending_filters); public: ClientContext &context; diff --git a/src/duckdb/src/include/duckdb/optimizer/join_order/relation_manager.hpp b/src/duckdb/src/include/duckdb/optimizer/join_order/relation_manager.hpp index 123654639..7690f32f3 100644 --- a/src/duckdb/src/include/duckdb/optimizer/join_order/relation_manager.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/join_order/relation_manager.hpp @@ -8,9 +8,11 @@ #pragma once +#include "duckdb/common/optional.hpp" #include "duckdb/common/unordered_map.hpp" #include "duckdb/common/unordered_set.hpp" #include "duckdb/common/reference_map.hpp" +#include "duckdb/optimizer/cte_definition_scope.hpp" #include "duckdb/optimizer/recursive_join_planning.hpp" #include "duckdb/optimizer/join_order/cardinality_estimator.hpp" #include "duckdb/optimizer/join_order/join_relation_set.hpp" @@ -27,6 +29,7 @@ namespace duckdb { class JoinOrderOptimizer; class FilterInfo; class RelationStatsExtractor; +class Distinctness; struct JoinOrderExtraction { vector> filters; @@ -61,8 +64,7 @@ class RelationManager { //! Collect an inner-join region without optimizing or rewriting its leaves. bool ExtractJoinRelationsForEstimation(RelationStatsExtractor &extractor, LogicalOperator &op, - vector> &filter_operators, - optional_ptr parent = nullptr); + vector> &filter_operators); //! for each join filter in the logical plan op, extract the relations that are referred to on //! both sides of the join filter, along with the tables & indexes. @@ -102,7 +104,8 @@ class RelationManager { bool ExtractJoinRelation(JoinOrderOptimizer &optimizer, PendingRelation relation, vector> &filter_operators, vector &pending_relations); - bool RegisterRelation(LogicalOperator &op, optional_ptr parent, RelationStats stats); + bool RegisterRelation(LogicalOperator &op, optional_ptr parent, RelationStats stats, + optional_ptr published_distinctness = nullptr); optional_ptr GetJoinRelations(column_binding_set_t &column_bindings, JoinRelationSetManager &set_manager); void GetColumnBindingsFromExpression(const Expression &expression, column_binding_set_t &column_bindings); @@ -112,6 +115,7 @@ class RelationManager { private: ClientContext &context; + optional cte_scope; //! Set of all relations considered in the join optimizer vector> relations; reference_map_t operator_relations; diff --git a/src/duckdb/src/include/duckdb/optimizer/mark_join_simplifier.hpp b/src/duckdb/src/include/duckdb/optimizer/mark_join_simplifier.hpp index c472ce337..f41b72c98 100644 --- a/src/duckdb/src/include/duckdb/optimizer/mark_join_simplifier.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/mark_join_simplifier.hpp @@ -24,9 +24,7 @@ class MarkJoinSimplifier { void Optimize(unique_ptr &plan); private: - void Rewrite(unique_ptr &op, NotNullExpressionAnalyzer &nullability, - BindingReplacementGraph &replacements, vector> &ancestors, - bool constant_input_only); + class RewriteState; bool TrySimplifyConstantInput(unique_ptr &op, BindingReplacementGraph &replacements); bool TrySimplify(unique_ptr &op, NotNullExpressionAnalyzer &nullability, BindingReplacementGraph &replacements); diff --git a/src/duckdb/src/include/duckdb/optimizer/multi_stage_aggregate_rewriter.hpp b/src/duckdb/src/include/duckdb/optimizer/multi_stage_aggregate_rewriter.hpp index f0b463e4c..c8ca73514 100644 --- a/src/duckdb/src/include/duckdb/optimizer/multi_stage_aggregate_rewriter.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/multi_stage_aggregate_rewriter.hpp @@ -28,6 +28,7 @@ class MultiStageAggregateRewriter : public LogicalOperatorVisitor { void VisitOperator(unique_ptr &op) override; bool WasChanged() const; + bool HasNewFilters() const; private: bool TryRewrite(unique_ptr &op); @@ -40,6 +41,7 @@ class MultiStageAggregateRewriter : public LogicalOperatorVisitor { bool rewrite_distinct; optional_ptr>> statistics; bool changed = false; + bool has_new_filters = false; column_binding_map_t replacement_map; }; diff --git a/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics.hpp b/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics.hpp index c1723ae30..d4cf9770a 100644 --- a/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics.hpp @@ -11,6 +11,7 @@ #include "duckdb/common/optional_idx.hpp" #include "duckdb/common/optional.hpp" #include "duckdb/common/optional_ptr.hpp" +#include "duckdb/common/shared_ptr.hpp" #include "duckdb/common/types.hpp" #include "duckdb/planner/column_binding.hpp" #include "duckdb/planner/column_binding_map.hpp" @@ -18,6 +19,8 @@ namespace duckdb { +class BaseStatistics; + enum class DistinctCountSource : uint8_t { CARDINALITY, MIN_MAX, @@ -76,7 +79,15 @@ struct RelationColumnStats { DistinctCount current_domain; //! Structural evidence that permits using current_domain for SEMI/ANTI joins. SemiAntiJoinDomainEvidence semi_anti_join_domain_evidence; + //! For list columns: type-level statistics carrying the estimated total element count + //! (ListStats), produced by aggregate and scalar statistics callbacks and consumed by + //! UNNEST estimation. Shared, treated as immutable: rescaling replaces the pointer. + shared_ptr list_stats; + //! Immutable source bounds for non-NULL values; these do not describe output nullability. + shared_ptr value_bounds; Identifier name; + //! Base column statistics from the scan, used to bound keys derived from this column + shared_ptr base_stats; }; struct RelationStats { diff --git a/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_extractor.hpp b/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_extractor.hpp index e4b4e2976..e6c46cd9e 100644 --- a/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_extractor.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_extractor.hpp @@ -9,25 +9,32 @@ #pragma once #include "duckdb/common/optional.hpp" +#include "duckdb/common/pair.hpp" #include "duckdb/common/reference_map.hpp" +#include "duckdb/optimizer/cte_definition_scope.hpp" +#include "duckdb/optimizer/distinctness.hpp" #include "duckdb/optimizer/relation_statistics/relation_statistics.hpp" -#include - namespace duckdb { class ClientContext; class LogicalCTERef; class LogicalOperator; class JoinOrderSourceStats; +struct ColumnBindingLayout; -using relation_stats_cte_callback_t = std::function(TableIndex)>; +using relation_stats_lookup_t = std::function(LogicalOperator &)>; +//! Cached estimates require unchanged operators and CTE definitions unless invalidated after rewriting them. class RelationStatsExtractor { public: explicit RelationStatsExtractor(ClientContext &context); - RelationStatsExtractor(ClientContext &context, relation_stats_cte_callback_t cte_callback); - RelationStatsExtractor(ClientContext &context, shared_ptr source_stats); + RelationStatsExtractor(ClientContext &context, CTEDefinitionScope::lookup_t cte_lookup); + RelationStatsExtractor(ClientContext &context, shared_ptr source_stats, + CTEDefinitionScope::lookup_t cte_lookup = {}); + //! Extract reads caller-owned facts and leaves missing entries unknown. + RelationStatsExtractor(ClientContext &context, relation_stats_lookup_t lookup, + CTEDefinitionScope::lookup_t cte_lookup, optional_ptr distinctness = nullptr); public: ClientContext &GetContext() const { @@ -35,25 +42,75 @@ class RelationStatsExtractor { } optional_ptr Extract(LogicalOperator &op); + //! Estimate a join region using this extractor's leaf statistics. + optional ExtractJoinStats(LogicalOperator &op); optional_ptr GetCTEDefinition(const LogicalCTERef &cte_ref) const; + const CTEDefinitionScope &GetCTEScope() const; + //! Operator extraction counts and source capture apply to walking extractors. idx_t ExtractedOperatorCount() const; shared_ptr GetSourceStats(LogicalOperator &root); + Distinctness &GetDistinctness(); + optional_ptr GetPublishedDistinctness() const { + return lookup ? distinctness : nullptr; + } + //! Refine a grouping estimate using the domains of individual UNION arms. + optional EstimateUnionGroups(LogicalOperator &input, vector groups); + //! Discard a changed node and call for its affected ancestors before reusing this view. + void Invalidate(LogicalOperator &op); private: + struct GroupHash { + public: + uint64_t operator()(const vector &groups) const; + }; + + enum class GroupEstimateState { ACTIVE, COMPLETE }; + + struct GroupEstimate { + public: + //! Cardinality accumulated across inputs and whether any input supplied UNION evidence. + optional cardinality; + bool has_union = false; + + //! Progress in the iterative grouping walk, including pending CTE definitions. + GroupEstimateState state = GroupEstimateState::ACTIVE; + }; + using group_input_t = pair, vector>; + +private: + bool CanRefineUnionGroups(LogicalOperator &op); + const ColumnBindingLayout &GetGroupInputLayout(LogicalOperator &op); + bool MapProjectionGroups(LogicalOperator &op, vector &groups); + vector PrepareGroupEstimate(LogicalOperator &op, vector groups, GroupEstimate &estimate); optional ExtractInternal(LogicalOperator &op); - optional ExtractJoinStats(LogicalOperator &op); optional ExtractCTERef(LogicalCTERef &cte_ref); private: + //! Query context and caller-provided lookups for visible CTEs and published statistics. ClientContext &context; - relation_stats_cte_callback_t cte_callback; + CTEDefinitionScope cte_scope; + optional_ptr local_cte_scope; + relation_stats_lookup_t lookup; + + //! Walking extraction caches successful, active and failed operators. reference_map_t cache; reference_set_t active_operators; reference_set_t failed_operators; idx_t extracted_operator_count = 0; + + //! Source statistics captured during extraction or inherited from join ordering. shared_ptr source_stats; - //! A join-order caller has already captured all sources before rewriting the plan. shared_ptr inherited_source_stats; + + //! Distinctness proofs can be shared with the caller or owned by this extractor. + unique_ptr owned_distinctness; + optional_ptr distinctness; + + //! UNION grouping estimates by operator and key set, and their reusable input mappings. + reference_map_t, GroupEstimate, GroupHash>> group_estimates; + reference_map_t union_group_inputs; + reference_map_t> group_input_layouts; + reference_map_t> projection_groups; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp b/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp index b53582e5a..c9fed78a1 100644 --- a/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp @@ -66,8 +66,12 @@ class RelationStatisticsHelper { static RelationStats ExtractExplainStats(LogicalOperator &op); static optional ExtractOperatorStats(LogicalOperator &op, ClientContext &context, const vector> &child_stats); + //! The caller has already validated the child snapshots and resolved the output layout. + static optional ExtractOperatorStats(LogicalOperator &op, ClientContext &context, + const vector> &child_stats, + const vector &bindings); static optional ExtractProjectionStats(LogicalProjection &projection, - const RelationStats &child_stats); + const RelationStats &child_stats, ClientContext &context); static optional ExtractAggregationStats(LogicalAggregate &aggregate, const RelationStats &child_stats, ClientContext &context); //! Reuse the caller snapshot for aggregate input refinements. @@ -78,6 +82,11 @@ class RelationStatisticsHelper { static optional ExtractFilterStats(LogicalFilter &filter, const RelationStats &child_stats); static optional ExtractFilterStats(LogicalFilter &filter, const RelationStats &child_stats, const vector> &expressions); + //! Resolve positional predicates against the input and project the conditioned columns to the output. + static optional ExtractFilterStats(const RelationStats &child_stats, + const vector> &expressions, + const vector &input_bindings, + const vector &output_bindings); //! Condition an input snapshot without requiring an attached logical operator or changing its layout. static RelationStats ConditionFilterStats(const RelationStats &input, const vector> &expressions, @@ -85,7 +94,11 @@ class RelationStatisticsHelper { static optional ExtractLimitStats(LogicalLimit &limit, const RelationStats &child_stats); static RelationStats ExtractEmptyResultStats(LogicalEmptyResult &empty); static optional ProjectOutputStats(const RelationStats &stats, LogicalOperator &op); + static optional ProjectOutputStats(const RelationStats &stats, + const vector &bindings); static optional RebindOutputStats(const RelationStats &stats, LogicalOperator &op); + //! A frontier row estimate carries no value-domain, uniqueness or cardinality-bound evidence from its seed. + static RelationStats RecursiveReferenceStats(const RelationStats &input, CardinalityValue rows); static optional SelectTotalDomain(const vector &domains); static void ApplySemiAntiJoinStats(LogicalComparisonJoin &join, const RelationStats &left, const RelationStats &right, RelationStats &result); @@ -94,6 +107,18 @@ class RelationStatisticsHelper { CardinalityValue input_cardinality); static CardinalityValue EstimateGroupCardinality(LogicalOperator &input, const RelationStats &input_stats, vector groups, RelationStatsExtractor &extractor); + //! Whether the expression and its children have fully resolved types. Unresolved prepared parameters can leave + //! UNKNOWN types in a plan, which the statistics callbacks' input contract does not cover. Such plans are + //! re-optimized once the parameters are bound. + static bool ExpressionTypesResolved(const Expression &expr); + //! Rescale carried list statistics' element count when the rows holding the lists are duplicated. + //! Derive the list statistics of an expression from the carried column statistics. Statistics callbacks of + //! LIST-returning functions run on the recursively derived child statistics. Null when unknown. + static shared_ptr DeriveListStats(Expression &expr, const RelationColumnStatsLookup &columns, + ClientContext &context); + static shared_ptr ScaleListStats(const shared_ptr &list_stats, + CardinalityValue source_cardinality, + CardinalityValue result_cardinality); static DistinctCount EstimateCurrentDomain(const DistinctCount ¤t_domain, CardinalityValue input_cardinality, CardinalityValue output_cardinality); static void ApplyCardinality(RelationStats &stats, CardinalityValue output_cardinality); @@ -126,8 +151,14 @@ class RelationStatisticsHelper { RelationStatsExtractor &extractor); static optional_idx EstimateDirectFilterDomain(const Expression &expression, optional target_binding, idx_t maximum_domain); + //! max - min + 1 of an integer or temporal min/max range, invalid if unknown or overflowing + static optional_idx NumericStatsDistinctCount(const BaseStatistics &stats); private: + template + static optional + ExtractValidatedOperatorStats(LogicalOperator &op, ClientContext &context, + const vector> &child_stats, GET_BINDINGS get_bindings); static unique_ptr GetColumnStatistics(LogicalGet &get, ClientContext &context, const ColumnIndex &column_id); }; diff --git a/src/duckdb/src/include/duckdb/optimizer/remove_unused_columns.hpp b/src/duckdb/src/include/duckdb/optimizer/remove_unused_columns.hpp index b70d28b79..e2e020fc6 100644 --- a/src/duckdb/src/include/duckdb/optimizer/remove_unused_columns.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/remove_unused_columns.hpp @@ -25,6 +25,7 @@ class ClientContext; class LogicalColumnDataGet; class LogicalRecursiveCTE; class LogicalSecureView; +class LogicalUnnest; class Optimizer; struct ReferencedExtractComponent { @@ -169,6 +170,8 @@ class RemoveUnusedColumns : public BaseColumnPruner { void RemoveColumnsFromLogicalColumnDataGet(LogicalColumnDataGet &get); void RemoveColumnsFromLogicalGet(LogicalGet &get, unique_ptr &op_ref); void VisitSecureView(LogicalSecureView &view); + //! Marks the expressions of the UNNEST that cannot be removed without changing its row count as referenced + void MarkRequiredUnnestExpressions(LogicalUnnest &unnest); void CheckPushdownExtract(LogicalOperator &op); void RewriteExpressions(LogicalProjection &proj, idx_t expression_count); void GatherRecursiveDependencies(unique_ptr &bottom, TableIndex cte_index, diff --git a/src/duckdb/src/include/duckdb/optimizer/removed_subtree_effects.hpp b/src/duckdb/src/include/duckdb/optimizer/removed_subtree_effects.hpp new file mode 100644 index 000000000..a0dd67d98 --- /dev/null +++ b/src/duckdb/src/include/duckdb/optimizer/removed_subtree_effects.hpp @@ -0,0 +1,33 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/optimizer/removed_subtree_effects.hpp +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/unordered_map.hpp" +#include "duckdb/common/unordered_set.hpp" +#include "duckdb/planner/logical_operator.hpp" + +namespace duckdb { + +//! Effects skipped when a subtree or its rows are removed, including materialized CTE producer effects. +class RemovedSubtreeEffects { +public: + //! Registers the CTEs that are defined in the plan. + explicit RemovedSubtreeEffects(LogicalOperator &plan); + + bool HasEffect(LogicalOperator &subtree); + +private: + void CollectDefinitions(LogicalOperator &op); + bool DefinitionHasEffect(TableIndex cte_index); + + unordered_map> materialized_ctes; + unordered_set recursive_ctes; + unordered_map definition_has_effect; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/optimizer/rule/constant_folding.hpp b/src/duckdb/src/include/duckdb/optimizer/rule/constant_folding.hpp index aba6ce9c7..68b0b163b 100644 --- a/src/duckdb/src/include/duckdb/optimizer/rule/constant_folding.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/rule/constant_folding.hpp @@ -17,6 +17,8 @@ class ConstantFoldingRule : public Rule { public: explicit ConstantFoldingRule(ExpressionRewriter &rewriter); + static unique_ptr TryFold(ClientContext &context, Expression &expr); + unique_ptr Apply(LogicalOperator &op, vector> &bindings, bool &changes_made, bool is_root) override; }; diff --git a/src/duckdb/src/include/duckdb/optimizer/rule/date_trunc_simplification.hpp b/src/duckdb/src/include/duckdb/optimizer/rule/date_trunc_simplification.hpp index 50f28dd51..0e35155f6 100644 --- a/src/duckdb/src/include/duckdb/optimizer/rule/date_trunc_simplification.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/rule/date_trunc_simplification.hpp @@ -68,7 +68,7 @@ class DateTruncSimplificationRule : public Rule { bool DateIsTruncated(const BoundConstantExpression &date_part, const BoundConstantExpression &rhs); bool IsInfinity(const Value &value); void ReplaceDateTruncWithColumn(unique_ptr &column_side, unique_ptr &constant_side, - const BoundColumnRefExpression &column_part); + const BoundColumnRefExpression &column_part, const LogicalType &return_type); unique_ptr CastAndEvaluate(unique_ptr rhs, const LogicalType &return_type); }; diff --git a/src/duckdb/src/include/duckdb/optimizer/runtime_filter_cast.hpp b/src/duckdb/src/include/duckdb/optimizer/runtime_filter_cast.hpp index 74f69877b..e3b0e5a2f 100644 --- a/src/duckdb/src/include/duckdb/optimizer/runtime_filter_cast.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/runtime_filter_cast.hpp @@ -25,7 +25,7 @@ struct RuntimeFilterCastUtil { static bool IsBuiltinCast(const Expression &expr); //! Whether the expression contains (or requires) a try cast static bool RuntimeFilterUsesTryCast(const JoinFilterPushdownColumn &column); - //! Whether the expression preserves the ordering of the raw projected column + //! Whether the expression preserves the ordering of the raw projected column, from its casts or from statistics static bool PreservesStorageOrdering(const JoinFilterPushdownColumn &column); //! The type that CreateRuntimeFilterInputExpression evaluates to for this column static LogicalType GetRuntimeFilterInputType(const JoinFilterPushdownColumn &column, diff --git a/src/duckdb/src/include/duckdb/optimizer/statistics_propagator.hpp b/src/duckdb/src/include/duckdb/optimizer/statistics_propagator.hpp index c8677b49e..d062f2e9a 100644 --- a/src/duckdb/src/include/duckdb/optimizer/statistics_propagator.hpp +++ b/src/duckdb/src/include/duckdb/optimizer/statistics_propagator.hpp @@ -90,8 +90,15 @@ class StatisticsPropagator { //! Compare two sets of statistics and return whether the comparison is always true or false static FilterPropagateResult PropagateComparison(const BaseStatistics &left, const BaseStatistics &right, ExpressionType comparison); + //! Update filter statistics from a TableFilter + static void UpdateFilterStatistics(BaseStatistics &input, const TableFilter &filter); private: + //! Update filter statistics from a filter with a constant + static void UpdateFilterStatistics(BaseStatistics &input, ExpressionType comparison_type, const Value &constant); + //! Update filter statistics from an ExpressionFilter expression + static void UpdateExpressionFilterStatistics(BaseStatistics &input, const Expression &expr); + //! Propagate statistics through an operator unique_ptr PropagateStatistics(LogicalOperator &node, unique_ptr &node_ptr); @@ -124,8 +131,6 @@ class StatisticsPropagator { static Value NumericMax(const BaseStatistics &stats); static void SetNumericMin(BaseStatistics &stats, const Value &val); static void SetNumericMax(BaseStatistics &stats, const Value &val); - //! Update filter statistics from a filter with a constant - void UpdateFilterStatistics(BaseStatistics &input, ExpressionType comparison_type, const Value &constant); //! Update statistics from a filter between two stats void UpdateFilterStatistics(BaseStatistics &lstats, BaseStatistics &rstats, ExpressionType comparison_type); //! Update filter statistics from a generic comparison @@ -155,10 +160,6 @@ class StatisticsPropagator { //! Run a comparison between the statistics and the table filter; returns the prune result FilterPropagateResult PropagateTableFilter(ColumnBinding stats_binding, BaseStatistics &stats, TableFilter &filter); - //! Update filter statistics from a TableFilter - void UpdateFilterStatistics(BaseStatistics &input, const TableFilter &filter); - //! Update filter statistics from an ExpressionFilter expression - void UpdateExpressionFilterStatistics(BaseStatistics &input, const Expression &expr); //! Add cardinalities together (i.e. new max is stats.max + new_stats.max): used for union void AddCardinalities(unique_ptr &stats, NodeStatistics &new_stats); diff --git a/src/duckdb/src/include/duckdb/parallel/async_result.hpp b/src/duckdb/src/include/duckdb/parallel/async_result.hpp index be5c9f972..d81880baf 100644 --- a/src/duckdb/src/include/duckdb/parallel/async_result.hpp +++ b/src/duckdb/src/include/duckdb/parallel/async_result.hpp @@ -70,9 +70,10 @@ class AsyncResult { StateWithBlockableTasks &state); static AsyncResultType GetAsyncResultType(SourceResultType s); - //! Wraps tasks into a BLOCKED result, or HAVE_MORE_OUTPUT when there are none + //! Wraps tasks into a BLOCKED result, or HAVE_MORE_OUTPUT when there are none. + //! prepared_io_size accounts for bytes already prepared without tasks, e.g. pinned resident reads. static AsyncResult FromTasks(vector> &&tasks, - TaskSchedulerType pool_type = TaskSchedulerType::REGULAR); + TaskSchedulerType pool_type = TaskSchedulerType::REGULAR, idx_t prepared_io_size = 0); //! FINISHED when the chunk is empty, HAVE_MORE_OUTPUT otherwise static AsyncResult FromChunk(const DataChunk &chunk); //! Maps a non-BLOCKED result to a SourceResultType, IMPLICIT resolves through the chunk size @@ -81,6 +82,11 @@ class AsyncResult { //! Check whether there are tasks associated bool HasTasks() const; AsyncResultType GetResultType() const; + //! Bytes prepared outside the tasks, to retain their read-ahead charge. Read before extracting the tasks. + idx_t GetPreparedIOSize() const { + D_ASSERT(result_type != AsyncResultType::INVALID); + return prepared_io_size; + } //! Extract associated tasks, moving them away, will empty async_tasks and transform to INVALID vector> &&ExtractAsyncTasks(); @@ -97,5 +103,6 @@ class AsyncResult { vector> async_tasks {}; //! The thread pool that the async_tasks are scheduled onto when BLOCKED TaskSchedulerType pool_type {TaskSchedulerType::REGULAR}; + idx_t prepared_io_size = 0; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/parallel/concurrentqueue.hpp b/src/duckdb/src/include/duckdb/parallel/concurrentqueue.hpp index 5969165b9..741866acc 100644 --- a/src/duckdb/src/include/duckdb/parallel/concurrentqueue.hpp +++ b/src/duckdb/src/include/duckdb/parallel/concurrentqueue.hpp @@ -9,7 +9,11 @@ #pragma once #ifndef DUCKDB_NO_THREADS +#include "duckdb/common/no_destructor.hpp" +// vendored code with statics we do not control +DUCKDB_ALLOW_STATIC_LIFETIME_BEGIN #include "concurrentqueue.h" +DUCKDB_ALLOW_STATIC_LIFETIME_END #else #include diff --git a/src/duckdb/src/include/duckdb/parallel/pipeline_broadcast_exchange.hpp b/src/duckdb/src/include/duckdb/parallel/pipeline_broadcast_exchange.hpp index a4825d5c9..2fcc735e0 100644 --- a/src/duckdb/src/include/duckdb/parallel/pipeline_broadcast_exchange.hpp +++ b/src/duckdb/src/include/duckdb/parallel/pipeline_broadcast_exchange.hpp @@ -8,7 +8,6 @@ #pragma once -#include "duckdb/common/atomic.hpp" #include "duckdb/common/common.hpp" #include "duckdb/common/deque.hpp" #include "duckdb/common/enums/operator_result_type.hpp" @@ -20,6 +19,7 @@ #include "duckdb/execution/partition_info.hpp" #include "duckdb/execution/progress_data.hpp" #include "duckdb/parallel/interrupt.hpp" +#include "duckdb/parallel/sharded_counter.hpp" namespace duckdb { @@ -296,7 +296,7 @@ class PipelineBroadcastExchange { AppendReservationState append_reservation_state DUCKDB_GUARDED_BY(lock) = AppendReservationState::IDLE; idx_t active_consumers = 0; bool has_batch_scan_consumer DUCKDB_GUARDED_BY(lock) = false; - atomic produced_rows {0}; + ShardedCounter produced_rows; ProducerState producer_state DUCKDB_GUARDED_BY(lock) = ProducerState::ACTIVE; WatermarkState watermark_state = WatermarkState::BELOW_HIGH_WATERMARK; optional_ptr log_operator; diff --git a/src/duckdb/src/include/duckdb/parallel/scan_read_ahead.hpp b/src/duckdb/src/include/duckdb/parallel/scan_read_ahead.hpp index 15de1ded2..a8f24bbd3 100644 --- a/src/duckdb/src/include/duckdb/parallel/scan_read_ahead.hpp +++ b/src/duckdb/src/include/duckdb/parallel/scan_read_ahead.hpp @@ -182,10 +182,10 @@ class ScanReadAhead { } public: - //! Claims the next job and schedules its I/O, filling io_tasks when the I/O was detached to the pool. + //! Claims the next job and prepares its I/O, returning pending tasks and already-prepared bytes together. //! Returns null when there are no more jobs to produce. //! Ordered callbacks must assign the job's batch index, densely from 0 in claim order. - using ProduceJobCallback = std::function(vector> &io_tasks)>; + using ProduceJobCallback = std::function(AsyncResult &io)>; //! Settle the claimed job's scheduled I/O, blocking until it completed, and release its budget charge void WaitForJob(ScanReadAheadJob &job); @@ -251,8 +251,9 @@ class ScanReadAhead { idx_t MinimumJobCharge() const; bool TryParkForProgress(TableFunctionInput &input, idx_t epoch); void ResumeScan(const InterruptState &interrupt_state); - void ScheduleReadyJob(unique_ptr job, vector> io_tasks, - ProducerReservation &reservation); + //! Consume the preparation result and establish the job's charge before scheduling any of its tasks. + vector> TakeJobIO(ScanReadAheadJob &job, AsyncResult io); + void ScheduleReadyJob(unique_ptr job, AsyncResult io, ProducerReservation &reservation); //! Takes ownership of a completed job's reservation, publishing or retiring it exactly once. void CompleteJob(unique_ptr job); void RetireJob(idx_t budget_charge); @@ -280,7 +281,7 @@ class ScanReadAhead { //! Reserve an in-flight job slot for producing a job bool TryReserveSlot(); //! Schedule the job's I/O and admit the job to the queue - void PushJob(unique_ptr job, vector> io_tasks); + void PushJob(unique_ptr job, AsyncResult io); //! Release a read-ahead slot void ReleaseSlot(); //! Wake a thread waiting for another thread to push a job, release a slot or finish producing, or all of them diff --git a/src/duckdb/src/include/duckdb/parser/expression/function_expression.hpp b/src/duckdb/src/include/duckdb/parser/expression/function_expression.hpp index 7fe62634e..d7f5cde08 100644 --- a/src/duckdb/src/include/duckdb/parser/expression/function_expression.hpp +++ b/src/duckdb/src/include/duckdb/parser/expression/function_expression.hpp @@ -29,12 +29,22 @@ class FunctionArgument { : name(std::move(name_p)), expression(std::move(expression_p)) { } + //! Deserialization: the name in its serialized form (see Identifier::GetSerializedName) + template ::value>::type> + FunctionArgument(STRING serialized_name, unique_ptr expression_p) + : name(Identifier::FromSerializedName(std::move(serialized_name))), expression(std::move(expression_p)) { + } + const Identifier &GetName() const { return name; } + string GetSerializedName() const { + return name.GetSerializedName(); + } + bool HasName() const { - return !name.empty(); + return name.IsSet(); } unique_ptr &GetExpressionMutable() { @@ -49,7 +59,7 @@ class FunctionArgument { } bool Equals(const FunctionArgument &other) const { - if (name != other.name) { + if (name.IsSet() != other.name.IsSet() || name != other.name) { return false; } if (expression && other.expression) { @@ -61,7 +71,7 @@ class FunctionArgument { hash_t Hash() const; string ToString() const { - if (name.empty()) { + if (!name.IsSet()) { return expression->ToString(); } return StringUtil::Format("%s := %s", SQLIdentifier(name), expression->ToString()); @@ -174,6 +184,11 @@ class FunctionExpression : public ParsedExpression { return arguments; } +private: + //! Whether this is a struct_pack call with an empty member name, which is rendered as a struct literal. + //! HACK: `"" := x` does not parse because empty identifiers are rejected. Once they are allowed, remove this. + bool RendersAsStructLiteral() const; + private: //! Qualified name of the function (catalog.schema.name) QualifiedName qualified_name; diff --git a/src/duckdb/src/include/duckdb/parser/expression/type_expression.hpp b/src/duckdb/src/include/duckdb/parser/expression/type_expression.hpp index ffe595d13..0bffcdb7a 100644 --- a/src/duckdb/src/include/duckdb/parser/expression/type_expression.hpp +++ b/src/duckdb/src/include/duckdb/parser/expression/type_expression.hpp @@ -33,6 +33,8 @@ class TypeExpression : public ParsedExpression { DUCKDB_API static bool IsSQLType(LogicalTypeId id); //! Whether the complete type can be written as a SQL type expression DUCKDB_API static bool CanRepresent(const LogicalType &type); + //! Whether the type contains a STRUCT with an empty member name, which has no SQL type spelling + DUCKDB_API static bool HasEmptyStructMemberName(const LogicalType &type); const QualifiedName &GetQualifiedName() const { return qualified_name; diff --git a/src/duckdb/src/include/duckdb/parser/peg/inlined_grammar.hpp b/src/duckdb/src/include/duckdb/parser/peg/inlined_grammar.hpp index 7492f6f62..c055af3af 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/inlined_grammar.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/inlined_grammar.hpp @@ -1820,9 +1820,12 @@ const unsigned char INLINED_PEG_GRAMMAR[] = { 65, 116, 84, 105, 109, 101, 90, 111, 110, 101, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 84, 97, 105, 108, 32, 60, 45, 32, 65, 116, 84, 105, 109, 101, 90, 111, 110, 101, 79, 112, 101, 114, 97, 116, 111, 114, 32, 85, 110, 97, 114, 121, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, 65, 116, 84, 105, 109, 101, 90, 111, 110, 101, 79, 112, 101, 114, 97, 116, 111, 114, 32, 60, 45, 32, 39, 65, 84, 39, 32, 39, 84, 73, 77, 69, 39, 32, 39, 90, 79, 78, 69, 39, 10, 35, 32, 76, 69, 86, 69, 76, 32, 49, 53, 10, - 85, 110, 97, 114, 121, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 60, 45, 32, 80, 114, 101, 102, 105, 120, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 47, 32, 67, 117, 115, 116, 111, 109, 80, 114, 101, 102, 105, 120, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, + 85, 110, 97, 114, 121, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 60, 45, 32, 80, 114, 101, 102, 105, 120, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 47, 32, 80, 114, 101, 102, 105, 120, 101, 100, 67, 117, 115, 116, 111, 109, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, 80, 114, 101, 102, 105, 120, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 60, 45, 32, 80, 114, 101, 102, 105, 120, 79, 112, 101, 114, 97, 116, 111, 114, 42, 32, 66, 97, 115, 101, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, - 67, 117, 115, 116, 111, 109, 80, 114, 101, 102, 105, 120, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 60, 45, 32, 79, 112, 101, 114, 97, 116, 111, 114, 76, 105, 116, 101, 114, 97, 108, 32, 84, 105, 108, 100, 101, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, + 35, 32, 65, 32, 99, 117, 115, 116, 111, 109, 32, 111, 114, 32, 39, 126, 39, 32, 111, 112, 101, 114, 97, 116, 111, 114, 32, 116, 97, 107, 101, 115, 32, 116, 104, 101, 32, 114, 101, 115, 116, 32, 111, 102, 32, 116, 104, 101, 32, 97, 100, 100, 105, 116, 105, 118, 101, 32, 101, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 97, 115, 32, 105, 116, 115, 32, 111, 112, 101, 114, 97, 110, 100, 58, 32, 45, 32, 64, 32, 49, 32, 43, 32, 50, 32, 105, 115, 32, 45, 40, 64, 40, 49, 32, 43, 32, 50, 41, 41, 10, + 80, 114, 101, 102, 105, 120, 101, 100, 67, 117, 115, 116, 111, 109, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 60, 45, 32, 80, 114, 101, 102, 105, 120, 79, 112, 101, 114, 97, 116, 111, 114, 42, 32, 67, 117, 115, 116, 111, 109, 80, 114, 101, 102, 105, 120, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, + 67, 117, 115, 116, 111, 109, 80, 114, 101, 102, 105, 120, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 32, 60, 45, 32, 67, 117, 115, 116, 111, 109, 80, 114, 101, 102, 105, 120, 79, 112, 101, 114, 97, 116, 111, 114, 32, 84, 105, 108, 100, 101, 69, 120, 112, 114, 101, 115, 115, 105, 111, 110, 10, + 67, 117, 115, 116, 111, 109, 80, 114, 101, 102, 105, 120, 79, 112, 101, 114, 97, 116, 111, 114, 32, 60, 45, 32, 79, 112, 101, 114, 97, 116, 111, 114, 76, 105, 116, 101, 114, 97, 108, 32, 47, 32, 84, 105, 108, 100, 101, 80, 114, 101, 102, 105, 120, 79, 112, 101, 114, 97, 116, 111, 114, 10, 80, 114, 101, 102, 105, 120, 79, 112, 101, 114, 97, 116, 111, 114, 32, 60, 45, 32, 81, 117, 97, 108, 105, 102, 105, 101, 100, 79, 112, 101, 114, 97, 116, 111, 114, 32, 47, 32, 77, 105, 110, 117, 115, 80, 114, 101, 102, 105, 120, 79, 112, 101, 114, 97, 116, 111, 114, 32, 47, 32, 80, 108, 117, 115, 80, 114, 101, 102, 105, 120, 79, 112, 101, 114, 97, 116, 111, 114, 10, 77, 105, 110, 117, 115, 80, 114, 101, 102, 105, 120, 79, 112, 101, 114, 97, 116, 111, 114, 32, 60, 45, 32, 39, 45, 39, 10, 80, 108, 117, 115, 80, 114, 101, 102, 105, 120, 79, 112, 101, 114, 97, 116, 111, 114, 32, 60, 45, 32, 39, 43, 39, 10, diff --git a/src/duckdb/src/include/duckdb/parser/peg/keyword_helper/duckdb_keyword_helper.hpp b/src/duckdb/src/include/duckdb/parser/peg/keyword_helper/duckdb_keyword_helper.hpp index c152a33bd..9705ba0e8 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/keyword_helper/duckdb_keyword_helper.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/keyword_helper/duckdb_keyword_helper.hpp @@ -1,11 +1,14 @@ #pragma once +#include "duckdb/common/no_destructor.hpp" #include "duckdb/parser/peg/keyword_helper.hpp" #include "duckdb/parser/peg/keyword_helper/default_keyword_maps.hpp" namespace duckdb { class DuckDBKeywordHelper : public PEGKeywordHelper { + friend class NoDestructor; + private: DuckDBKeywordHelper(); diff --git a/src/duckdb/src/include/duckdb/parser/peg/peg_rule_id.hpp b/src/duckdb/src/include/duckdb/parser/peg/peg_rule_id.hpp index 062908be6..cc6e36df4 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/peg_rule_id.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/peg_rule_id.hpp @@ -744,7 +744,9 @@ enum class PEGRuleId : uint32_t { AtTimeZoneOperator, UnaryExpression, PrefixExpression, + PrefixedCustomExpression, CustomPrefixExpression, + CustomPrefixOperator, PrefixOperator, MinusPrefixOperator, PlusPrefixOperator, diff --git a/src/duckdb/src/include/duckdb/parser/peg/transformer/parse_result.hpp b/src/duckdb/src/include/duckdb/parser/peg/transformer/parse_result.hpp index 53e390926..9108aeaed 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/transformer/parse_result.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/transformer/parse_result.hpp @@ -1,5 +1,6 @@ #pragma once #include "utf8proc_wrapper.hpp" +#include "duckdb/common/no_destructor.hpp" #include "duckdb/common/arena_linked_list.hpp" #include "duckdb/common/array_ptr.hpp" #include "duckdb/common/exception.hpp" @@ -151,8 +152,8 @@ class ParseResult { //! The name of the rule (or matcher) that produced this result. Rule names live in the compiled grammar and //! outlive every parse, so a result points at one instead of owning a copy of it. const string &Name() const { - static const string EMPTY; - return name ? *name : EMPTY; + static const NoDestructor EMPTY; + return name ? *name : *EMPTY; } //! Only a pointer to the name is kept, so these only take a grammar object that owns it, or a result that already //! points at one. diff --git a/src/duckdb/src/include/duckdb/parser/peg/transformer/peg_transformer.hpp b/src/duckdb/src/include/duckdb/parser/peg/transformer/peg_transformer.hpp index 06e4b9845..28cf2029a 100644 --- a/src/duckdb/src/include/duckdb/parser/peg/transformer/peg_transformer.hpp +++ b/src/duckdb/src/include/duckdb/parser/peg/transformer/peg_transformer.hpp @@ -803,6 +803,8 @@ class PEGTransformerFactory { static void InitializePrefixExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizePrefixExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); + static arena_ptr + FinalizePrefixedCustomExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static void InitializeOverClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeOverClauseTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); @@ -1991,6 +1993,8 @@ class PEGTransformerFactory { FinalizeAtTimeZoneExpressionTailTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeCustomPrefixExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); + static arena_ptr FinalizeCustomPrefixOperatorTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process); static arena_ptr FinalizePrefixOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process); static arena_ptr FinalizeMinusPrefixOperatorTrampoline(PEGTransformer &transformer, @@ -3868,9 +3872,9 @@ class PEGTransformerFactory { optional>> at_time_zone_expression_tail); static unique_ptr TransformAtTimeZoneExpressionTail(PEGTransformer &transformer, unique_ptr prefix_expression); - static unique_ptr - TransformCustomPrefixExpression(PEGTransformer &transformer, const string &operator_literal, - unique_ptr other_operator_expression); + static unique_ptr TransformCustomPrefixExpression(PEGTransformer &transformer, + const string &custom_prefix_operator, + unique_ptr tilde_expression); static unique_ptr TransformBaseExpression(PEGTransformer &transformer, unique_ptr single_expression, optional>> indirection_list); diff --git a/src/duckdb/src/include/duckdb/parser/tableref/subqueryref.hpp b/src/duckdb/src/include/duckdb/parser/tableref/subqueryref.hpp index 086661f7a..d0de631fd 100644 --- a/src/duckdb/src/include/duckdb/parser/tableref/subqueryref.hpp +++ b/src/duckdb/src/include/duckdb/parser/tableref/subqueryref.hpp @@ -8,6 +8,7 @@ #pragma once +#include "duckdb/common/enums/subquery_lateral_type.hpp" #include "duckdb/parser/statement/select_statement.hpp" #include "duckdb/parser/tableref.hpp" @@ -25,9 +26,13 @@ class SubqueryRef : public TableRef { //! The subquery unique_ptr subquery; + //! Whether the subquery was written with the LATERAL keyword + SubqueryLateralType lateral = SubqueryLateralType::GENERATED; public: string ToString() const override; + //! The first FROM item cannot reference an earlier one, so it is printed without an unrecorded LATERAL + string ToString(bool first_from_item) const; bool Equals(const TableRef &other_p) const override; unique_ptr Copy() override; diff --git a/src/duckdb/src/include/duckdb/planner/binder.hpp b/src/duckdb/src/include/duckdb/planner/binder.hpp index 35be6076f..4b4d8edb0 100644 --- a/src/duckdb/src/include/duckdb/planner/binder.hpp +++ b/src/duckdb/src/include/duckdb/planner/binder.hpp @@ -272,8 +272,6 @@ class Binder : public enable_shared_from_this { public: //! Whether the expression is COUNT(tbl.*) static bool IsQualifiedCountStar(const ParsedExpression &expr); - //! Rewrites COUNT(tbl.*) into a COUNT that skips the rows NULL-extended by an outer join, or returns nullptr - unique_ptr TryRewriteQualifiedCountStar(const ParsedExpression &expr); public: DUCKDB_API BoundStatement Bind(SQLStatement &statement); @@ -500,6 +498,8 @@ class Binder : public enable_shared_from_this { CatalogEntryRetriever entry_retriever; //! Unnamed subquery index idx_t unnamed_subquery_index = 1; + //! The number of innermost enclosing scopes that are lateral scopes of the FROM clause being bound + idx_t from_clause_lateral_scopes = 0; //! Binder depth idx_t depth; @@ -640,6 +640,8 @@ class Binder : public enable_shared_from_this { BoundStatement Bind(MatchRecognizeRef &ref); //! Rewrites a NEAREST BY join into a lateral join over a top-k subquery and binds the result BoundStatement BindNearestJoin(JoinRef &ref); + //! Warns or throws when a subquery written without LATERAL references an earlier item of its FROM clause + void CheckImplicitLateralSubquery(const SubqueryRef &ref, const Binder &subquery_binder); BoundStatement Bind(SubqueryRef &ref); BoundStatement Bind(TableFunctionRef &ref); BoundStatement Bind(EmptyTableRef &ref); diff --git a/src/duckdb/src/include/duckdb/planner/expression/bound_window_expression.hpp b/src/duckdb/src/include/duckdb/planner/expression/bound_window_expression.hpp index d58606f5f..eac96182d 100644 --- a/src/duckdb/src/include/duckdb/planner/expression/bound_window_expression.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression/bound_window_expression.hpp @@ -113,14 +113,7 @@ class BoundWindowExpression : public Expression { unique_ptr &EndExprMutable() { return end_expr; } - void RetainSQLRange(optional_ptr start, optional_ptr end, - const LogicalType &order_type); - const unique_ptr &SQLRangeStart() const { - return sql_range_start; - } - const unique_ptr &SQLRangeEnd() const { - return sql_range_end; - } + void RetainSQLRange(const LogicalType &order_type); const LogicalType &SQLRangeOrderType() const { return sql_range_order_type; } @@ -221,9 +214,7 @@ class BoundWindowExpression : public Expression { unique_ptr start_expr; unique_ptr end_expr; - //! Literal SQL offsets before endpoint arithmetic; these are not execution children. - unique_ptr sql_range_start; - unique_ptr sql_range_end; + //! The type of the RANGE ordering operand before endpoint arithmetic LogicalType sql_range_order_type = LogicalType::INVALID; unique_ptr sql_range_start_boundary; diff --git a/src/duckdb/src/include/duckdb/planner/expression/window_range_info.hpp b/src/duckdb/src/include/duckdb/planner/expression/window_range_info.hpp index 74a14f349..ff4fcb2a5 100644 --- a/src/duckdb/src/include/duckdb/planner/expression/window_range_info.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression/window_range_info.hpp @@ -50,5 +50,7 @@ struct WindowRangeBoundary { static unique_ptr Capture(const Expression &expression, const Expression &order, const Expression &offset); optional_ptr Match(const Expression &expression, const Expression &order) const; + //! The type the call was bound with for its offset, before the call fitted the operand to its arithmetic + const LogicalType &LogicalOffsetType() const; }; } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/planner/expression_binder.hpp b/src/duckdb/src/include/duckdb/planner/expression_binder.hpp index 1715cdf4a..bca745dd0 100644 --- a/src/duckdb/src/include/duckdb/planner/expression_binder.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression_binder.hpp @@ -36,11 +36,11 @@ class AggregateFunctionCatalogEntry; class WindowFunctionCatalogEntry; class ScalarMacroCatalogEntry; class MacroFunction; -class ScalarMacroFunction; class CatalogEntry; class SimpleFunction; class HavingBinder; class ColumnAliasBinder; +struct QualifiedName; class LogicalOperator; class LogicalProjection; class LogicalAggregate; @@ -249,6 +249,8 @@ class ExpressionBinder { //! Enables special-handling of lambda parameters during macro replacement by tracking them in the lambda_params //! vector. void ReplaceMacroParametersInLambda(FunctionExpression &function, vector &lambda_params); + //! Replace the parameters of a macro body with the arguments the binding carries + void SubstituteMacroParameters(unique_ptr &expr, DummyBinding &binding); static LogicalType GetExpressionReturnType(const Expression &expr); @@ -291,7 +293,7 @@ class ExpressionBinder { optional_ptr bind_lambda_function, optional_ptr bind_lambda_context); BindResult BindExpression(OperatorExpression &expr, idx_t depth); - BindResult BindOperatorAsFunction(OperatorExpression &op, const Identifier &function_name, + BindResult BindOperatorAsFunction(OperatorExpression &op, const QualifiedName &function_name, vector> children); BindResult BindExpression(ParameterExpression &expr, idx_t depth); BindResult BindExpression(SubqueryExpression &expr, idx_t depth); @@ -344,8 +346,7 @@ class ExpressionBinder { virtual BindResult BindUnnest(FunctionExpression &expr, idx_t depth, bool root_expression); virtual BindResult BindMacro(FunctionExpression &expr, ScalarMacroCatalogEntry ¯o, idx_t depth, unique_ptr &expr_ptr); - void FindAggregateExprs(unique_ptr &expr, vector>> &exprs); - void UnfoldWindowMacroExpression(unique_ptr &expr, ScalarMacroFunction ¯o_def); + void FindAggregateExprs(ParsedExpression &expr, vector> &exprs); MacroFunction &UnfoldMacroExpression(FunctionExpression &function, ScalarMacroCatalogEntry ¯o_func, unique_ptr &expr, idx_t depth); diff --git a/src/duckdb/src/include/duckdb/planner/expression_binder/base_select_binder.hpp b/src/duckdb/src/include/duckdb/planner/expression_binder/base_select_binder.hpp index c713094f1..7eb9754f1 100644 --- a/src/duckdb/src/include/duckdb/planner/expression_binder/base_select_binder.hpp +++ b/src/duckdb/src/include/duckdb/planner/expression_binder/base_select_binder.hpp @@ -47,6 +47,10 @@ class BaseSelectBinder : public ExpressionBinder { virtual BindResult BindWindowExpression(WindowExpression &expr, idx_t depth); virtual BindResult BindColumnRef(unique_ptr &expr_ptr, idx_t depth, bool root_expression); + //! Rewrites a qualified COUNT or supplies its already-bound row-presence argument + unique_ptr TryRewriteQualifiedCountStar(const ParsedExpression &expr, + unique_ptr &presence); + ProjectionIndex TryBindGroup(ParsedExpression &expr); ProjectionIndex FindGroup(ParsedExpression &expr); bool MatchesGroup(ParsedExpression &expr) override; diff --git a/src/duckdb/src/include/duckdb/planner/filter/expression_filter.hpp b/src/duckdb/src/include/duckdb/planner/filter/expression_filter.hpp index d27cc96a9..a28750fca 100644 --- a/src/duckdb/src/include/duckdb/planner/filter/expression_filter.hpp +++ b/src/duckdb/src/include/duckdb/planner/filter/expression_filter.hpp @@ -53,6 +53,9 @@ class ExpressionFilter : public TableFilter { ExpressionType expression_type); //! Build a single-column filter comparing against a constant. static unique_ptr CreateComparisonFilter(ExpressionType comparison_type, Value constant); + //! Build an optional mapped filter, keeping its inputs together with their scan-column dependencies. + static unique_ptr CreateOptionalFilter(unique_ptr predicate, + vector column_indexes); static unique_ptr CreateSelectivityOptionalFilter(unique_ptr child_expr, const LogicalType &column_type, SelectivityOptionalFilterType type); @@ -75,6 +78,14 @@ class ExpressionFilter : public TableFilter { static FilterPropagateResult CheckExpressionStatistics(optional_ptr context_p, const Expression &expr, array_ptr input_stats); + //! Borrow statistics derived for function arguments; null entries denote unknown statistics. + static FilterPropagateResult + CheckExpressionStatistics(optional_ptr context_p, const Expression &expr, + const vector> &input_stats); + //! Check comparisons against non-NULL constants of the statistics' type. + static FilterPropagateResult CheckZonemapAgainstConstants(const BaseStatistics &stats, + ExpressionType comparison_type, + array_ptr values); //! Whether statistics can be propagated through this filter expression static bool CanPropagateExpressionStatistics(const Expression &expr); //! Derive statistics for an expression over one or more input columns diff --git a/src/duckdb/src/include/duckdb/planner/filter/table_filter_functions.hpp b/src/duckdb/src/include/duckdb/planner/filter/table_filter_functions.hpp index 958574cf3..f19487f0e 100644 --- a/src/duckdb/src/include/duckdb/planner/filter/table_filter_functions.hpp +++ b/src/duckdb/src/include/duckdb/planner/filter/table_filter_functions.hpp @@ -68,6 +68,8 @@ void GetThresholdAndVectorsToCheck(SelectivityOptionalFilterType type, float &se unique_ptr CreateOptionalFilterExpression(unique_ptr child_expr, const LogicalType &target_type); +//! Substitute an optional predicate's argument-local references with its actual input expressions. +unique_ptr ExpandOptionalFilterExpression(const BoundFunctionExpression &expression); unique_ptr CreateSelectivityOptionalFilterExpression(unique_ptr child_expr, const LogicalType &target_type, float selectivity_threshold, idx_t n_vectors_to_check); @@ -144,7 +146,7 @@ class BloomFilter { return memory_budget; } //! Completed buffers may be replaced only before publication. - HugeAllocation CopyBuffer(ClientContext &context) const; + void CopyBuffer(ClientContext &context, HugeAllocation &buffer) const; void ReplaceBuffer(HugeAllocation buffer); void InstallReadCopy(HugeAllocation buffer); ReadView GetReadView(idx_t buffer_index = 0) const; @@ -373,6 +375,7 @@ struct OptionalFilterScalarFun : public TableFilterOptionalFun { using TableFilterOptionalFun::GetFunction; static constexpr const char *NAME = TableFilterOptionalFun::Name; static ScalarFunction GetFunction(const LogicalType &input_type); + static ScalarFunction GetFunction(vector input_types); static FilterPropagateResult FilterPrune(const FunctionStatisticsPruneInput &input); static string ToString(const string &child_filter_string); }; diff --git a/src/duckdb/src/include/duckdb/planner/logical_operator_visitor.hpp b/src/duckdb/src/include/duckdb/planner/logical_operator_visitor.hpp index fba1c7345..7e46b1f40 100644 --- a/src/duckdb/src/include/duckdb/planner/logical_operator_visitor.hpp +++ b/src/duckdb/src/include/duckdb/planner/logical_operator_visitor.hpp @@ -41,6 +41,11 @@ class LogicalOperatorVisitor { const vector &child_bindings_after); protected: + //! Visit an expression tree iteratively, skipping replacement expressions. + void VisitExpressionIteratively(unique_ptr *expression); + //! Apply the replacement callback for one expression, without visiting its children. + bool VisitExpressionReplacement(unique_ptr *expression); + //! Automatically calls the Visit method for LogicalOperator children of the current operator. Can be overloaded to //! change this behavior. void VisitOperatorChildren(LogicalOperator &op); diff --git a/src/duckdb/src/include/duckdb/planner/operator/logical_join.hpp b/src/duckdb/src/include/duckdb/planner/operator/logical_join.hpp index 3e0a7a6a4..2a196983d 100644 --- a/src/duckdb/src/include/duckdb/planner/operator/logical_join.hpp +++ b/src/duckdb/src/include/duckdb/planner/operator/logical_join.hpp @@ -51,6 +51,8 @@ class LogicalJoin : public LogicalOperator { public: vector GetColumnBindings() override; + //! Resolve this join's layout from already resolved children. + vector GetColumnBindings(const vector &left, const vector &right); vector GetTableIndex() const override; string GetName() const override; diff --git a/src/duckdb/src/include/duckdb/planner/operator/logical_materialized_cte.hpp b/src/duckdb/src/include/duckdb/planner/operator/logical_materialized_cte.hpp index 460233558..5c90884dc 100644 --- a/src/duckdb/src/include/duckdb/planner/operator/logical_materialized_cte.hpp +++ b/src/duckdb/src/include/duckdb/planner/operator/logical_materialized_cte.hpp @@ -22,6 +22,8 @@ struct CTEFilterDependency { } bool MatchesConsumers(const vector> &references) const; + //! Discard guarantees before transformations that do not preserve consumer identity. + static void Clear(LogicalOperator &op); TableIndex row_scan; TableIndex domain_scan; diff --git a/src/duckdb/src/include/duckdb/planner/query_node/bound_select_node.hpp b/src/duckdb/src/include/duckdb/planner/query_node/bound_select_node.hpp index f4d79d6c9..857ec6fbd 100644 --- a/src/duckdb/src/include/duckdb/planner/query_node/bound_select_node.hpp +++ b/src/duckdb/src/include/duckdb/planner/query_node/bound_select_node.hpp @@ -15,6 +15,7 @@ #include "duckdb/parser/group_by_node.hpp" #include "duckdb/planner/expression_binder/select_bind_state.hpp" #include "duckdb/common/index_vector.hpp" +#include "duckdb/common/reference_map.hpp" namespace duckdb { @@ -64,6 +65,8 @@ class BoundSelectNode : public BoundQueryNode { vector> select_list; //! The FROM clause BoundStatement from_table; + //! Presence columns requested by qualified COUNT, shared by bindings on the same nullable input + reference_map_t row_presence; //! list of groups BoundGroupByNode groups; //! HAVING clause diff --git a/src/duckdb/src/include/duckdb/planner/subquery/column_binding_layout.hpp b/src/duckdb/src/include/duckdb/planner/subquery/column_binding_layout.hpp index 291a0a2d5..6271ca4d8 100644 --- a/src/duckdb/src/include/duckdb/planner/subquery/column_binding_layout.hpp +++ b/src/duckdb/src/include/duckdb/planner/subquery/column_binding_layout.hpp @@ -15,10 +15,17 @@ namespace duckdb { struct ColumnBindingLayout { - explicit ColumnBindingLayout(vector bindings_p, string error_context_p = "output layout") + enum class DuplicatePosition { FIRST, LAST }; + + explicit ColumnBindingLayout(vector bindings_p, string error_context_p = "output layout", + DuplicatePosition duplicate_position = DuplicatePosition::LAST) : bindings(std::move(bindings_p)), error_context(std::move(error_context_p)) { for (idx_t i = 0; i < bindings.size(); i++) { - positions[bindings[i]] = i; + if (duplicate_position == DuplicatePosition::FIRST) { + positions.emplace(bindings[i], i); + } else { + positions[bindings[i]] = i; + } } } diff --git a/src/duckdb/src/include/duckdb/planner/subquery/has_volatile_expressions.hpp b/src/duckdb/src/include/duckdb/planner/subquery/has_volatile_expressions.hpp index 3bd517b1a..895e03ba3 100644 --- a/src/duckdb/src/include/duckdb/planner/subquery/has_volatile_expressions.hpp +++ b/src/duckdb/src/include/duckdb/planner/subquery/has_volatile_expressions.hpp @@ -8,9 +8,11 @@ #pragma once namespace duckdb { +class Expression; class LogicalOperator; -//! Check subquery volatility, excluding the built-in error() but including its arguments. +//! Check volatility, excluding the built-in error() but including its arguments. +bool HasVolatileExpressionsIgnoringError(const Expression &expr); bool HasVolatileExpressionsIgnoringError(const LogicalOperator &op); } // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/planner/table_binding.hpp b/src/duckdb/src/include/duckdb/planner/table_binding.hpp index 75d9c5b03..bb0d11b28 100644 --- a/src/duckdb/src/include/duckdb/planner/table_binding.hpp +++ b/src/duckdb/src/include/duckdb/planner/table_binding.hpp @@ -60,8 +60,8 @@ struct Binding { idx_t GetColumnCount(); void SetColumnType(idx_t col_idx, LogicalType type); //! Marks this binding as the NULL-producing side of an outer join - void SetNullExtended(); - bool IsNullExtended() const; + void SetNullExtended(LogicalOperator &input); + optional_ptr GetNullExtendedInput() const; static BindingAlias GetAlias(const Identifier &explicit_alias, const StandardEntry &entry); static BindingAlias GetAlias(const Identifier &explicit_alias, optional_ptr entry); @@ -101,8 +101,8 @@ struct Binding { vector names; //! Name -> index for the names identifier_map_t name_map; - //! Whether rows of this binding can be NULL-extended by an outer join - bool null_extended = false; + //! Input of the first join that can NULL-extend this binding + optional_ptr null_extended_input; }; struct EntryBinding : public Binding { diff --git a/src/duckdb/src/include/duckdb/planner/table_filter_set.hpp b/src/duckdb/src/include/duckdb/planner/table_filter_set.hpp index 8fb10a5ec..53ab2d1a2 100644 --- a/src/duckdb/src/include/duckdb/planner/table_filter_set.hpp +++ b/src/duckdb/src/include/duckdb/planner/table_filter_set.hpp @@ -14,6 +14,8 @@ #include "duckdb/common/reference_map.hpp" #include "duckdb/common/types.hpp" #include "duckdb/common/map.hpp" +#include "duckdb/common/array_ptr.hpp" +#include namespace duckdb { @@ -25,6 +27,8 @@ class TableFilterSet { //! On contradiction, return UNSATISFIABLE without modifying the offending column's filter. FilterResult Finalize(); bool HasFilters() const; + //! Includes both row filters and statistics-only predicates. + bool HasAnyFilters() const; idx_t FilterCount() const; bool HasMultiColumnFilters() const; bool HasFilter(ProjectionIndex col_idx) const; @@ -36,6 +40,11 @@ class TableFilterSet { void RemoveFilterByColumnIndex(ProjectionIndex col_idx); void ClearFilters(); const vector> &GetMultiColumnFilters() const; + //! Dependencies map dense expression references to scan columns. Views are valid only during the callback. + void VisitFilters(const std::function)> &callback) const; + //! Visits each dependency, including repeated columns shared by different filters. + void VisitColumns(const std::function &callback) const; + void RemapColumns(const std::function &remap); bool Equals(TableFilterSet &other); static bool Equals(TableFilterSet *left, TableFilterSet *right); @@ -113,6 +122,8 @@ class TableFilterSet { } private: + void LoadSerializedPruningFilters(vector> filters); + map> filters; vector> multi_column_filters; }; diff --git a/src/duckdb/src/include/duckdb/storage/block_allocator.hpp b/src/duckdb/src/include/duckdb/storage/block_allocator.hpp index a7d71d02f..c2fd0e2aa 100644 --- a/src/duckdb/src/include/duckdb/storage/block_allocator.hpp +++ b/src/duckdb/src/include/duckdb/storage/block_allocator.hpp @@ -8,7 +8,6 @@ #pragma once -#include "duckdb/common/array.hpp" #include "duckdb/common/atomic.hpp" #include "duckdb/common/hugeint.hpp" #include "duckdb/common/mutex.hpp" @@ -17,17 +16,17 @@ #include "duckdb/common/shared_ptr.hpp" #include "duckdb/common/typedefs.hpp" #include "duckdb/common/unique_ptr.hpp" -#include "duckdb/storage/allocator_cache_retention.hpp" +#include "duckdb/storage/block_allocator/block_allocator_pool.hpp" namespace duckdb { class Allocator; class AllocationCache; class AttachedDatabase; +class BufferPool; class DatabaseInstance; class TaskScheduler; struct ProducerToken; -struct BlockQueue; struct BlockAllocatorLifetimeState; class BlockAllocator; class BlockAllocatorThreadLocalState; @@ -60,6 +59,7 @@ class BlockAllocator { friend class BlockAllocatorFlushTask; friend class BlockAllocatorTestHelper; friend class BufferAllocator; + friend class DatabaseInstance; friend class TaskScheduler; public: @@ -84,6 +84,8 @@ class BlockAllocator { //! Approximate locality of fixed-pool backing, unknown for other allocations optional_idx GetAllocationShard(const_data_ptr_t pointer) const; + //! Common-domain locality of an owned allocation base; unknown for fallback allocator backing. + optional_idx GetAllocationShard(const_data_ptr_t pointer, idx_t size) const; idx_t GetPoolShardCount() const; idx_t GetLocalPoolShard() const; idx_t GetFallbackShardCount() const; @@ -113,35 +115,14 @@ class BlockAllocator { //! Explicit pool geometry for tests; production construction uses the CPU-count heuristic. BlockAllocator(Allocator &allocator, idx_t block_size, idx_t pool_size, idx_t shard_count); - //! The buffer allocator's huge-page backend keeps matching allocation and release ownership. - data_ptr_t AllocateHugeData(idx_t size, optional_idx &home) const; - void FreeHugeData(data_ptr_t pointer, idx_t size, optional_idx home) const; + //! Allocate ordinary backing and advise huge pages where supported. + data_ptr_t AllocateHugeData(idx_t size) const; data_ptr_t AllocateFallbackData(idx_t size) const; - void FreeFallbackData(data_ptr_t pointer, idx_t size, optional_idx home) const; + void FreeFallbackData(data_ptr_t pointer, idx_t size) const; enum class FlushState : uint8_t { IDLE, SCHEDULED, RESCHEDULE_REQUESTED }; - enum class ReclaimMode : uint8_t { FORCE, DECAY, OPPORTUNISTIC }; - enum class PoolState : uint8_t { UNINITIALIZED, READY, UNAVAILABLE }; + using ReclaimMode = BlockAllocatorPool::ReclaimMode; - bool TryUsePool() const DUCKDB_EXCLUDES(pool_init_lock); - bool InitializePool() const DUCKDB_EXCLUDES(pool_init_lock); - bool ProtectPoolGuards(data_ptr_t pointer) const; - bool IsInitialized() const; - bool IsInPool(data_ptr_t pointer) const; - bool IsGuardBlock(uint32_t block_id) const; - idx_t GetGuardBlockCount() const; - idx_t GetUsableBlockCount() const; - - idx_t ModuloBlockSize(idx_t n) const; - idx_t DivBlockSize(idx_t n) const; - - uint32_t GetBlockID(data_ptr_t pointer) const; - data_ptr_t GetPointer(uint32_t block_id) const; - - void VerifyBlockID(uint32_t block_id) const; - - void UpdateCachedBlocks(int64_t count, idx_t slot) const; - idx_t GetCachedPoolMemory() const; void ReturnThreadLocalBlocks() const; void FlushFallbackAllocator(idx_t deallocated) const noexcept; //! Purge the fallback allocator if frees are waiting for it. Idle threads do this without pressure. @@ -156,64 +137,31 @@ class BlockAllocator { void SetScheduler(TaskScheduler &scheduler); void ClearScheduler(); + //! Bind the selected database pool before workers start, adopting any existing live padding. + void SetBufferPool(shared_ptr buffer_pool); bool TryScheduleFlush(TaskScheduler &scheduler) const DUCKDB_EXCLUDES(flush_lock); - idx_t GetFreeBlockCount() const DUCKDB_REQUIRES(flush_lock); - idx_t GetReclaimableBlockCount(ReclaimMode mode, optional_idx cache_limit = optional_idx()) const - DUCKDB_REQUIRES(flush_lock); //! Return the unprocessed portion of the initial free-block budget. idx_t FlushPool(optional_idx block_limit = optional_idx(), optional_idx task_limit = optional_idx(), ReclaimMode mode = ReclaimMode::FORCE, optional_idx cache_limit = optional_idx()) const noexcept DUCKDB_EXCLUDES(flush_lock); - idx_t FreeInternal(optional_idx block_limit, optional_idx task_limit, ReclaimMode mode, - optional_idx cache_limit = optional_idx()) const DUCKDB_EXCLUDES(flush_lock); - bool FreeContiguousBlocks(uint32_t block_id_start, uint32_t block_id_end_including) const; private: //! Identifier const hugeint_t uuid; //! Fallback allocator Allocator &allocator; - //! Cache of whole power-of-two fallback allocations, with preferred CPU-local reuse. - unique_ptr allocation_cache; - - //! Block size (power of two) + //! Shared pool implementation for fixed blocks and larger size classes. + unique_ptr pool; const idx_t block_size; - //! Shift for dividing by block size - const idx_t block_size_div_shift; - - //! Virtual reservation, including guards, rounded down to whole blocks; zero on 32-bit. - const idx_t pool_size; - //! Allocation permission is independent of the lifetime of the mapping. + //! Larger pools and the existing whole-allocation fallback cache. + unique_ptr allocation_cache; + //! Allocation permission is independent of the lifetime of all mappings. atomic enabled {true}; - //! READY publishes the mapping and queues; UNAVAILABLE prevents retrying a failed reservation. - mutable atomic pool_state; - mutable annotated_mutex pool_init_lock; - //! Immutable after publication through pool_state. - mutable data_ptr_t pool_base = nullptr; - - //! Untouched block IDs - mutable unsafe_unique_ptr untouched; - //! Touched by block IDs - unsafe_unique_ptr touched; - //! Rotates maintenance across the immutable pool ranges. - mutable idx_t reclaim_shard DUCKDB_GUARDED_BY(flush_lock) = 0; - - struct alignas(64) CachedBlockCount { - //! Cross-thread reuse can make individual balances negative. - atomic count {0}; - }; - //! Separate writers so each block reuse does not contend on a single counter. - mutable array cached_blocks; - mutable atomic next_cache_slot {0}; - //! Still charged to cached_blocks until discard succeeds. - mutable idx_t reclaiming_blocks DUCKDB_GUARDED_BY(flush_lock) = 0; //! Synchronizes returning cached blocks with allocator destruction. shared_ptr lifetime_state; - //! Recently returned volume retained for reuse before gradual decay. - mutable AllocatorCacheRetention retention; //! Protect maintenance decisions and background scheduling. mutable annotated_mutex flush_lock; //! Scheduler queue destruction invalidates this token before allocator destruction. diff --git a/src/duckdb/src/include/duckdb/storage/allocator_cache_retention.hpp b/src/duckdb/src/include/duckdb/storage/block_allocator/allocator_cache_retention.hpp similarity index 94% rename from src/duckdb/src/include/duckdb/storage/allocator_cache_retention.hpp rename to src/duckdb/src/include/duckdb/storage/block_allocator/allocator_cache_retention.hpp index 329f689db..61f4c6750 100644 --- a/src/duckdb/src/include/duckdb/storage/allocator_cache_retention.hpp +++ b/src/duckdb/src/include/duckdb/storage/block_allocator/allocator_cache_retention.hpp @@ -1,7 +1,7 @@ //===----------------------------------------------------------------------===// // DuckDB // -// duckdb/storage/allocator_cache_retention.hpp +// duckdb/storage/block_allocator/allocator_cache_retention.hpp // // //===----------------------------------------------------------------------===// diff --git a/src/duckdb/src/include/duckdb/storage/block_allocator/block_allocator_pool.hpp b/src/duckdb/src/include/duckdb/storage/block_allocator/block_allocator_pool.hpp new file mode 100644 index 000000000..8493ed343 --- /dev/null +++ b/src/duckdb/src/include/duckdb/storage/block_allocator/block_allocator_pool.hpp @@ -0,0 +1,100 @@ +//===----------------------------------------------------------------------===// +// DuckDB +// +// duckdb/storage/block_allocator/block_allocator_pool.hpp +// +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include "duckdb/common/array.hpp" +#include "duckdb/common/atomic.hpp" +#include "duckdb/common/mutex.hpp" +#include "duckdb/common/optional_idx.hpp" +#include "duckdb/common/unique_ptr.hpp" +#include "duckdb/storage/block_allocator/allocator_cache_retention.hpp" + +namespace duckdb { + +struct BlockQueue; + +//! A lazy virtual reservation divided into immutable, equal-size allocation slots and ownership shards. +//! The fixed-block TLS cache and larger size classes share its mapping, accounting and reclamation policies. +class BlockAllocatorPool { + friend class BlockAllocator; + friend class BlockAllocatorThreadLocalState; + friend class BlockAllocatorTestHelper; + friend class AllocationCache; + +public: + enum class ReclaimMode { FORCE, DECAY, OPPORTUNISTIC }; + enum class BackingPolicy { FULL_SLOT, SPARSE }; + + BlockAllocatorPool(idx_t block_size, idx_t pool_size, idx_t shard_count, BackingPolicy backing_policy); + ~BlockAllocatorPool(); + +private: + enum class PoolState { UNINITIALIZED, READY, UNAVAILABLE }; + + bool TryInitialize() const DUCKDB_EXCLUDES(pool_init_lock); + bool InitializePool() const DUCKDB_EXCLUDES(pool_init_lock); + bool ProtectPoolGuards(data_ptr_t pointer) const; + bool IsInitialized() const; + bool IsInPool(const_data_ptr_t pointer) const; + bool IsGuardBlock(uint32_t block_id) const; + idx_t GetGuardBlockCount() const; + idx_t GetUsableBlockCount() const; + idx_t GetShardCount() const; + optional_idx GetAllocationShard(const_data_ptr_t pointer) const; + + idx_t ModuloBlockSize(idx_t n) const; + idx_t DivBlockSize(idx_t n) const; + uint32_t GetBlockID(data_ptr_t pointer) const; + data_ptr_t GetPointer(uint32_t block_id) const; + void VerifyBlockID(uint32_t block_id) const; + + //! Shared-queue allocation for size classes without a TLS cache. Never first-touch another shard's slots. + data_ptr_t TryAllocate(idx_t size) const; + idx_t GetBackingSize(idx_t size) const; + bool TrimBacking(data_ptr_t pointer, idx_t size) const; + void Free(data_ptr_t pointer, idx_t cache_slot = 0) const; + void UpdateCachedBlocks(int64_t count, idx_t slot) const; + idx_t GetCachedPoolMemory() const; + idx_t GetFreeBlockCount() const DUCKDB_REQUIRES(flush_lock); + idx_t GetReclaimableBlockCount(ReclaimMode mode, optional_idx cache_limit = optional_idx()) const + DUCKDB_REQUIRES(flush_lock); + //! Return the unprocessed portion of the initial free-block budget; optionally count successful discards. + idx_t FreeInternal(optional_idx block_limit, optional_idx task_limit, ReclaimMode mode, + optional_idx cache_limit = optional_idx(), idx_t *freed_blocks = nullptr) const + DUCKDB_EXCLUDES(flush_lock); + bool FreeContiguousBlocks(uint32_t block_id_start, uint32_t block_id_end_including) const; + +private: + const idx_t block_size; + const idx_t block_size_div_shift; + //! Base-page backing for supported sparse pools; otherwise the entire slot. + const idx_t backing_granularity; + //! Includes guard slots, rounded down to whole blocks; zero on 32-bit. + const idx_t pool_size; + mutable atomic pool_state; + mutable annotated_mutex pool_init_lock; + //! Immutable after publication through pool_state. + mutable data_ptr_t pool_base = nullptr; + mutable unsafe_unique_ptr untouched; + unsafe_unique_ptr touched; + + struct alignas(64) CachedBlockCount { + //! Cross-thread reuse can make individual balances negative. + atomic count {0}; + }; + mutable array cached_blocks; + mutable atomic next_cache_slot {0}; + mutable AllocatorCacheRetention retention; + mutable annotated_mutex flush_lock; + mutable idx_t reclaim_shard DUCKDB_GUARDED_BY(flush_lock) = 0; + //! Still charged to cached_blocks until discard succeeds. + mutable idx_t reclaiming_blocks DUCKDB_GUARDED_BY(flush_lock) = 0; +}; + +} // namespace duckdb diff --git a/src/duckdb/src/include/duckdb/storage/sharded_allocator_queue.hpp b/src/duckdb/src/include/duckdb/storage/block_allocator/sharded_allocator_queue.hpp similarity index 98% rename from src/duckdb/src/include/duckdb/storage/sharded_allocator_queue.hpp rename to src/duckdb/src/include/duckdb/storage/block_allocator/sharded_allocator_queue.hpp index f9f52d73d..49735aa22 100644 --- a/src/duckdb/src/include/duckdb/storage/sharded_allocator_queue.hpp +++ b/src/duckdb/src/include/duckdb/storage/block_allocator/sharded_allocator_queue.hpp @@ -1,7 +1,7 @@ //===----------------------------------------------------------------------===// // DuckDB // -// duckdb/storage/sharded_allocator_queue.hpp +// duckdb/storage/block_allocator/sharded_allocator_queue.hpp // // //===----------------------------------------------------------------------===// diff --git a/src/duckdb/src/include/duckdb/storage/buffer/block_handle.hpp b/src/duckdb/src/include/duckdb/storage/buffer/block_handle.hpp index 87f9bc9c2..7307efe95 100644 --- a/src/duckdb/src/include/duckdb/storage/buffer/block_handle.hpp +++ b/src/duckdb/src/include/duckdb/storage/buffer/block_handle.hpp @@ -232,6 +232,8 @@ class BlockMemory : public enable_shared_from_this { void Unload(BlockLock &l); private: + friend class BlockHandle; + //! A reference to the buffer manager. BufferManager &buffer_manager; //! The block id of the block. @@ -312,6 +314,9 @@ class BlockHandle : public enable_shared_from_this { } public: + //! Pin resident memory without loading an unloaded block. + //! Returns an invalid handle if the block is unloaded or its lock is contended. + BufferHandle TryPinResident(); BufferHandle LoadFromBuffer(BlockLock &l, data_ptr_t data, unique_ptr reusable_buffer, BufferPoolReservation reservation); BufferHandle Load(BlockLock &l, Context &context, unique_ptr buffer = nullptr); diff --git a/src/duckdb/src/include/duckdb/storage/buffer/buffer_pool.hpp b/src/duckdb/src/include/duckdb/storage/buffer/buffer_pool.hpp index c87cee06d..352f6b654 100644 --- a/src/duckdb/src/include/duckdb/storage/buffer/buffer_pool.hpp +++ b/src/duckdb/src/include/duckdb/storage/buffer/buffer_pool.hpp @@ -38,6 +38,7 @@ struct BufferEvictionNode { //! The BufferPool is in charge of handling memory management for one or more databases. It defines memory limits //! and implements priority eviction among all users of the pool. class BufferPool { + friend class BlockAllocator; friend class BlockMemory; friend class BlockHandle; friend class BlockManager; @@ -58,6 +59,8 @@ class BufferPool { idx_t GetAllocatorBulkDeallocationFlushThreshold(); void UpdateUsedMemory(MemoryTag tag, int64_t size); + //! Charge optional memory only if it leaves headroom without eviction; release it through UpdateUsedMemory. + bool TryReserveMemory(MemoryTag tag, idx_t size, idx_t headroom); idx_t GetUsedMemory(bool flush = true) const; diff --git a/src/duckdb/src/include/duckdb/storage/data_table.hpp b/src/duckdb/src/include/duckdb/storage/data_table.hpp index 47cc78aba..b73c7009b 100644 --- a/src/duckdb/src/include/duckdb/storage/data_table.hpp +++ b/src/duckdb/src/include/duckdb/storage/data_table.hpp @@ -274,6 +274,9 @@ class DataTable : public enable_shared_from_this { //! Verify constraints with a chunk from the Append containing all columns of the table void VerifyAppendConstraints(ConstraintState &constraint_state, ClientContext &context, DataChunk &chunk, optional_ptr local_storage, optional_ptr manager); + //! Verify the NOT NULL and CHECK constraints of a chunk from the Update containing only the specified column_ids + void VerifyUpdateConstraints(ConstraintState &state, ClientContext &context, DataChunk &chunk, + const vector &column_ids); shared_ptr &GetDataTableInfo(); @@ -324,9 +327,6 @@ class DataTable : public enable_shared_from_this { void VerifyNewConstraint(ClientContext &context, LocalStorage &local_storage, DataTable &parent, const BoundConstraint &constraint); - //! Verify constraints with a chunk from the Update containing only the specified column_ids - void VerifyUpdateConstraints(ConstraintState &state, ClientContext &context, DataChunk &chunk, - const vector &column_ids); //! Verify constraints with a chunk from the Delete containing all columns of the table void VerifyDeleteConstraints(optional_ptr storage, TableDeleteState &state, ClientContext &context, DataChunk &chunk); diff --git a/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system.hpp b/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system.hpp index c356c69f9..2c40a3879 100644 --- a/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system.hpp +++ b/src/duckdb/src/include/duckdb/storage/external_file_cache/caching_file_system.hpp @@ -70,10 +70,12 @@ struct CachingFileHandle { //! Read [nr_bytes] bytes at the requested [location]. //! Returns a buffer handle group that keeps the data pinned in memory. DUCKDB_API FileBufferHandleGroup Read(idx_t nr_bytes, idx_t location); - //! Read [nr_bytes] bytes at [location]; within absorb_ranges ([begin, end) pairs), smaller cached blocks are + //! Read [nr_bytes] bytes at [location]; within absorb_ranges, smaller cached blocks are //! re-fetched with the gaps around them when that saves a request (see ExternalFileCache::AcquireBlocks) - DUCKDB_API FileBufferHandleGroup Read(idx_t nr_bytes, idx_t location, - const vector> &absorb_ranges); + DUCKDB_API FileBufferHandleGroup Read(idx_t nr_bytes, idx_t location, const vector &absorb_ranges); + //! Try to pin the entire range from resident cache buffers without file I/O or waiting for a fetch. + //! On a miss, releases any acquired pins and returns nullopt. + DUCKDB_API optional TryReadResident(idx_t nr_bytes, idx_t location); //! Read [nr_bytes] bytes and sets [nr_bytes] to the actually read bytes. DUCKDB_API FileBufferHandleGroup Read(idx_t &nr_bytes); //! Read and record time @@ -104,16 +106,24 @@ struct CachingFileHandle { DUCKDB_API void Seek(idx_t location); private: + enum class ReadMode { ALLOW_IO, RESIDENT_ONLY }; + optional ReadInternal(idx_t nr_bytes, idx_t location, const vector &absorb_ranges, + ReadMode mode); //! Open the file unless cached blocks allow deferring it; returns false if the file system returned no handle bool Initialize(); //! Open the underlying FileHandle if not yet open; returns nullptr if the file system returned no handle shared_ptr TryGetFileHandle(); + //! Adopt populated cache metadata if this handle can continue without opening the file. + bool TryAdoptCachedFile(shared_ptr target) DUCKDB_REQUIRES(file_handle_mutex); + //! Open and initialize a cached file before publishing the new handle state. + shared_ptr TryOpenFileHandle(shared_ptr target) DUCKDB_REQUIRES(file_handle_mutex); //! Remove the 'force_full_download' option from the file handle if present, and return whether it was present bool StripForceFullDownloadIfPresent(); //! Refresh the cached file if the global cache state has changed. shared_ptr EnsureCachedFileCurrent(); //! Whether validation metadata permits using cached blocks. bool CanUseCache(); + bool CanUseCache(const CacheValidationInfo &cached) const DUCKDB_REQUIRES(file_handle_mutex); //! Read without caching, splitting large reads of cacheable files into parallel reads of at most a block. void ReadUncached(data_ptr_t buffer, idx_t nr_bytes, idx_t location); //! Reconcile cached blocks with validation metadata observed while reading them. diff --git a/src/duckdb/src/include/duckdb/storage/external_file_cache/external_file_cache.hpp b/src/duckdb/src/include/duckdb/storage/external_file_cache/external_file_cache.hpp index 5f56e40de..b07302f28 100644 --- a/src/duckdb/src/include/duckdb/storage/external_file_cache/external_file_cache.hpp +++ b/src/duckdb/src/include/duckdb/storage/external_file_cache/external_file_cache.hpp @@ -14,7 +14,7 @@ #include "duckdb/common/optional.hpp" #include "duckdb/common/optional_idx.hpp" #include "duckdb/common/optional_ptr.hpp" -#include "duckdb/common/pair.hpp" +#include "duckdb/common/file_range.hpp" #include "duckdb/common/vector.hpp" #include "duckdb/common/shared_ptr_ipp.hpp" #include "duckdb/common/string.hpp" @@ -109,12 +109,15 @@ class ExternalFileCache { //! Number of files tracked in the ObjectCache, exposed for testing. idx_t GetCachedFileCount() const; + enum class BlockLookup { CREATE_MISSING, EXISTING_ONLY }; //! Get the blocks covering [location, location + nr_bytes), creating empty blocks for the missing bytes. - //! Within absorb_ranges ([begin, end) pairs), every smaller cached block is re-fetched with the gaps around it + //! EXISTING_ONLY returns empty on a gap or busy map and does not change the cache. Blocks still need pinning. + //! Within absorb_ranges, every smaller cached block is re-fetched with the gaps around it //! when that saves a request; elsewhere only blocks below an eighth of max_block_size are - vector> - AcquireBlocks(CachedFile &cached_file, idx_t location, idx_t nr_bytes, idx_t max_block_size, - optional_ptr>> absorb_ranges = nullptr); + vector> AcquireBlocks(CachedFile &cached_file, idx_t location, idx_t nr_bytes, + idx_t max_block_size, + optional_ptr> absorb_ranges = nullptr, + BlockLookup lookup = BlockLookup::CREATE_MISSING); //! Drop all blocks of a file, e.g. because the file changed. Readers keep the blocks they hold. void DropBlocks(CachedFile &cached_file); idx_t GetContentGeneration(CachedFile &cached_file); diff --git a/src/duckdb/src/include/duckdb/storage/standard_buffer_manager.hpp b/src/duckdb/src/include/duckdb/storage/standard_buffer_manager.hpp index 21ce51a3e..1c7ce3fb8 100644 --- a/src/duckdb/src/include/duckdb/storage/standard_buffer_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/standard_buffer_manager.hpp @@ -202,7 +202,7 @@ class StandardBufferManager : public BufferManager { //! The variables related to temporary file management TemporaryFileData temporary_directory; //! The temporary id used for managed buffers - atomic temporary_id; + PaddedAtomic temporary_id; //! Allocator associated with the buffer manager, that passes all allocations through this buffer manager BufferAllocator buffer_allocator; //! Block manager for temp data diff --git a/src/duckdb/src/include/duckdb/storage/storage_manager.hpp b/src/duckdb/src/include/duckdb/storage/storage_manager.hpp index 37f62b932..61d21fbac 100644 --- a/src/duckdb/src/include/duckdb/storage/storage_manager.hpp +++ b/src/duckdb/src/include/duckdb/storage/storage_manager.hpp @@ -160,6 +160,17 @@ class StorageManager { void CheckExpressionDecimalsAreSupported(const ParsedExpression &expression) const; //! The same check over every expression of a stored query (a view or a table macro) void CheckQueryDecimalsAreSupported(QueryNode &node) const; + //! The storage version from which a STRUCT with only empty member names is stored as such (older engines read it + //! as a TUPLE) and from which empty argument names (e.g. of {'': x}) can be stored + static constexpr StorageVersion EMPTY_MEMBER_NAMES_VERSION_ADDED = StorageVersion::V2_1_0; + //! Whether a type holds a STRUCT with only empty member names + static bool ContainsAllEmptyNamesStruct(const LogicalType &type); + //! Throws when a type written to the catalog holds a STRUCT with only empty member names this version cannot store + void CheckEmptyMemberNamesAreSupported(const LogicalType &type, const string &subject) const; + //! Throws when a stored expression holds an empty member or argument name this version cannot store + void CheckExpressionEmptyMemberNamesAreSupported(const ParsedExpression &expression) const; + //! The same check over every expression of a stored query (a view or a table macro) + void CheckQueryEmptyMemberNamesAreSupported(QueryNode &node) const; bool CompressionIsEnabled() const { return storage_options.compress_in_memory == CompressInMemory::COMPRESS; } diff --git a/src/duckdb/src/include/duckdb/storage/table/geo_column_data.hpp b/src/duckdb/src/include/duckdb/storage/table/geo_column_data.hpp index 947d20aa8..c6033dd62 100644 --- a/src/duckdb/src/include/duckdb/storage/table/geo_column_data.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/geo_column_data.hpp @@ -34,6 +34,8 @@ class GeoColumnData final : public ColumnData { idx_t end_row) override; void InitializeScan(ColumnScanState &state) override; void InitializeScanWithOffset(ColumnScanState &state, idx_t row_idx) override; + FilterPropagateResult CheckZonemap(ColumnScanState &state, const ScanFilter &filter, + optional_idx &checked_end) override; idx_t Scan(TransactionData transaction, idx_t vector_index, ColumnScanState &state, Vector &result, idx_t scan_count) override; diff --git a/src/duckdb/src/include/duckdb/storage/table/row_group.hpp b/src/duckdb/src/include/duckdb/storage/table/row_group.hpp index 986596aa0..486ee921d 100644 --- a/src/duckdb/src/include/duckdb/storage/table/row_group.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/row_group.hpp @@ -114,11 +114,19 @@ class RowGroupVersionInfo { const vector &GetDeletesPointers() const { return deletes_pointers; } + //! Whether an append was reverted, which can leave column statistics broader than the rows + bool HasRevertedAppends() const { + return has_reverted_appends; + } + void MarkRevertedAppend() { + has_reverted_appends = true; + } private: mutex lock; vector deletes_pointers; atomic deletes_is_loaded; + atomic has_reverted_appends; shared_ptr owned_version_info; atomic> version_info; }; @@ -200,6 +208,8 @@ class RowGroup : public SegmentBase { //! skipped. bool CheckZonemapSegments(CollectionScanState &state); void Scan(ScanOptions options, CollectionScanState &state, DataChunk &result); + //! Verifies that scanned ENUM values are positions in the dictionary of their type + static void VerifyScannedValues(const DataChunk &chunk); void Scan(CollectionScanState &state, DataChunk &result, TableScanType type); //! Synchronously prefetches the blocks required to scan the next row_count rows void PrefetchScanIO(CollectionScanState &state, idx_t row_count) const; @@ -280,7 +290,7 @@ class RowGroup : public SegmentBase { const ColumnSegmentInfoScanOptions &options = ColumnSegmentInfoScanOptions {}); static PartitionStatistics GetPartitionStats(SegmentNode &row_group, TransactionData transaction); //! Whether the statistics of the given column describe exactly the rows visible to the transaction. - //! Deleted, updated, or invisible rows leave the statistics as a superset of the visible values, so a + //! Deleted, updated, reverted, or invisible rows leave the statistics as a superset of the visible values, so a //! statistics bound is then not necessarily attained by any row visible to the transaction. bool ColumnStatsReflectVisibleRows(const StorageIndex &column_idx, TransactionData transaction); diff --git a/src/duckdb/src/include/duckdb/storage/table/scan_state.hpp b/src/duckdb/src/include/duckdb/storage/table/scan_state.hpp index 86d63b79e..ce7a7dcbb 100644 --- a/src/duckdb/src/include/duckdb/storage/table/scan_state.hpp +++ b/src/duckdb/src/include/duckdb/storage/table/scan_state.hpp @@ -9,6 +9,7 @@ #pragma once #include "duckdb/common/common.hpp" +#include "duckdb/common/no_destructor.hpp" #include "duckdb/common/unordered_set.hpp" #include "duckdb/storage/buffer/buffer_handle.hpp" #include "duckdb/storage/storage_lock.hpp" @@ -42,6 +43,7 @@ class ColumnData; class DuckTransaction; class RowGroupSegmentTree; class TableFilter; +class ExpressionFilter; struct AdaptiveFilterState; struct TableScanOptions; struct ScanSamplingInfo; @@ -190,20 +192,52 @@ struct ScanFilter { } }; +//! A statistics predicate bound to storage columns for the lifetime of a scan. +struct ScanFilterPruningState { + ScanFilterPruningState(const ExpressionFilter &filter, const vector &scan_columns); + + unique_ptr expression; + vector column_ids; +}; + +//! Final scan filters and the storage projection to which their pruning predicates are bound. +class TableScanInput { +public: + TableScanInput() = default; + explicit TableScanInput(vector column_ids, optional_ptr filters = nullptr); + + const vector &GetColumnIds() const { + return column_ids; + } + + const shared_ptr> &GetPruningFilters() const { + return pruning_filters; + } + +private: + friend class TableScanState; + friend class ScanFilterInfo; + + vector column_ids; + //! The physical scan owns these definitions for the lifetime of its readers. + optional_ptr filters; + shared_ptr> pruning_filters; +}; + class ScanFilterInfo { public: ~ScanFilterInfo(); - void Initialize(ClientContext &context, TableFilterSet &filters, const vector &column_ids); - const vector &GetFilterList() const { return filter_list; } - optional_ptr GetTableFilters() const { - return table_filters.get(); - } - optional_ptr> GetColumnIds() const { - return column_ids; + //! This view is valid until the scan is reinitialized. + const vector &GetPruningFilters() const { + if (pruning_filters) { + return *pruning_filters; + } + static const NoDestructor> empty; + return *empty; } optional_ptr GetAdaptiveFilter(); @@ -223,10 +257,11 @@ class ScanFilterInfo { void SetFilterAlwaysTrue(idx_t filter_idx); private: - //! The table filters (if any) - optional_ptr table_filters; - //! Maps scan projection indexes to storage column indexes - optional_ptr> column_ids; + friend class TableScanState; + void Initialize(optional_ptr context, TableScanInput &input); + + //! Immutable statistics predicates and storage inputs, shared by states of one scan execution + shared_ptr> pruning_filters; //! Adaptive filter info (if any) unique_ptr adaptive_filter; //! The set of filters @@ -427,6 +462,8 @@ class TableScanState { void Initialize(vector column_ids, optional_ptr context = nullptr, optional_ptr table_filters = nullptr, optional_ptr table_sampling = nullptr, idx_t estimated_table_row_count = 0); + void Initialize(TableScanInput input, optional_ptr context = nullptr, + optional_ptr table_sampling = nullptr, idx_t estimated_table_row_count = 0); const vector &GetColumnIds(); diff --git a/src/duckdb/src/include/duckdb_extension_v2.h b/src/duckdb/src/include/duckdb_extension_v2.h index fe18c7fd1..f8a4f7c46 100644 --- a/src/duckdb/src/include/duckdb_extension_v2.h +++ b/src/duckdb/src/include/duckdb_extension_v2.h @@ -708,19 +708,6 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_cast_function_create) (duckdb_v2_factory_handle factory, duckdb_v2_cast_function_handle *function, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR (*duckdb_v2_cast_function_destroy)(duckdb_v2_cast_function_handle *function); - DUCKDB_V2_ERROR(*duckdb_v2_cast_function_exec_get_input) - (duckdb_v2_cast_function_exec_info_handle info, duckdb_v2_vector_handle *vector, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_cast_function_exec_get_mode) - (duckdb_v2_cast_function_exec_info_handle info, DUCKDB_V2_CAST_MODE *mode, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_cast_function_exec_get_output) - (duckdb_v2_cast_function_exec_info_handle info, duckdb_v2_vector_handle *vector, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_cast_function_exec_get_row_count) - (duckdb_v2_cast_function_exec_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_cast_function_exec_get_user_data) - (duckdb_v2_cast_function_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_cast_function_set_exec_callback) - (duckdb_v2_cast_function_handle function, duckdb_v2_cast_function_exec_callback_fn callback, - duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_cast_function_set_implicit_cast_cost) (duckdb_v2_cast_function_handle function, int64_t cost, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_cast_function_set_source_type) @@ -729,8 +716,6 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_cast_function_set_target_type) (duckdb_v2_cast_function_handle function, duckdb_v2_logical_type_handle target_type, duckdb_v2_error_info_handle *err); - DUCKDB_V2_ERROR(*duckdb_v2_cast_function_set_user_data) - (duckdb_v2_cast_function_handle function, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_column_data_collection_clear) (duckdb_v2_column_data_collection_handle collection, duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_connection_register_cast_function) @@ -1868,9 +1853,27 @@ typedef struct { DUCKDB_V2_ERROR(*duckdb_v2_data_source_exec_set_result) (duckdb_v2_data_source_exec_info_handle info, DUCKDB_V2_DATA_SOURCE_RESULT result, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_scalar_function_bind_replace_call) + (duckdb_v2_scalar_function_bind_info_handle info, const char *name, idx_t name_length, const idx_t *arg_indices, + idx_t arg_count, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_scalar_function_bind_set_argument_monotonicity) + (duckdb_v2_scalar_function_bind_info_handle info, idx_t index, DUCKDB_V2_FUNCTION_MONOTONICITY monotonicity, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_scalar_function_bind_set_property) + (duckdb_v2_scalar_function_bind_info_handle info, DUCKDB_V2_FUNCTION_PROPERTY_KEY key, + DUCKDB_V2_FUNCTION_PROPERTY_VALUE value, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_scalar_function_set_argument_monotonicity) + (duckdb_v2_scalar_function_handle function, idx_t index, DUCKDB_V2_FUNCTION_MONOTONICITY monotonicity, + duckdb_v2_error_info_handle *err); DUCKDB_V2_ERROR(*duckdb_v2_table_function_set_property) (duckdb_v2_table_function_handle function, DUCKDB_V2_FUNCTION_PROPERTY_KEY key, DUCKDB_V2_FUNCTION_PROPERTY_VALUE value, duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_cast_function_set_function) + (duckdb_v2_cast_function_handle function, duckdb_v2_scalar_function_handle scalar_function, + duckdb_v2_error_info_handle *err); + DUCKDB_V2_ERROR(*duckdb_v2_cast_function_set_try_function) + (duckdb_v2_cast_function_handle function, duckdb_v2_scalar_function_handle scalar_function, + duckdb_v2_error_info_handle *err); #endif // capigen:end appended } duckdb_ext_api_v2; @@ -2715,24 +2718,6 @@ typedef struct { #define duckdb_v2_cast_function_destroy duckdb_ext_api.duckdb_v2_cast_function_destroy #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_cast_function_exec_get_input duckdb_ext_api.duckdb_v2_cast_function_exec_get_input -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_cast_function_exec_get_mode duckdb_ext_api.duckdb_v2_cast_function_exec_get_mode -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_cast_function_exec_get_output duckdb_ext_api.duckdb_v2_cast_function_exec_get_output -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_cast_function_exec_get_row_count duckdb_ext_api.duckdb_v2_cast_function_exec_get_row_count -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_cast_function_exec_get_user_data duckdb_ext_api.duckdb_v2_cast_function_exec_get_user_data -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_cast_function_set_exec_callback duckdb_ext_api.duckdb_v2_cast_function_set_exec_callback -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_cast_function_set_implicit_cast_cost duckdb_ext_api.duckdb_v2_cast_function_set_implicit_cast_cost #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -2742,9 +2727,6 @@ typedef struct { #define duckdb_v2_cast_function_set_target_type duckdb_ext_api.duckdb_v2_cast_function_set_target_type #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE -#define duckdb_v2_cast_function_set_user_data duckdb_ext_api.duckdb_v2_cast_function_set_user_data -#endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_column_data_collection_clear duckdb_ext_api.duckdb_v2_column_data_collection_clear #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE @@ -4248,8 +4230,28 @@ typedef struct { #define duckdb_v2_data_source_exec_set_result duckdb_ext_api.duckdb_v2_data_source_exec_set_result #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_scalar_function_bind_replace_call duckdb_ext_api.duckdb_v2_scalar_function_bind_replace_call +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_scalar_function_bind_set_argument_monotonicity \ + duckdb_ext_api.duckdb_v2_scalar_function_bind_set_argument_monotonicity +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_scalar_function_bind_set_property duckdb_ext_api.duckdb_v2_scalar_function_bind_set_property +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_scalar_function_set_argument_monotonicity \ + duckdb_ext_api.duckdb_v2_scalar_function_set_argument_monotonicity +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE #define duckdb_v2_table_function_set_property duckdb_ext_api.duckdb_v2_table_function_set_property #endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_cast_function_set_function duckdb_ext_api.duckdb_v2_cast_function_set_function +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +#define duckdb_v2_cast_function_set_try_function duckdb_ext_api.duckdb_v2_cast_function_set_try_function +#endif // capigen:end appended #endif // DUCKDB_BUILD_STATIC_EXTENSION diff --git a/src/duckdb/src/include/duckdb_v2.h b/src/duckdb/src/include/duckdb_v2.h index d5d9fc830..8a4c3b5aa 100644 --- a/src/duckdb/src/include/duckdb_v2.h +++ b/src/duckdb/src/include/duckdb_v2.h @@ -745,6 +745,35 @@ typedef enum DUCKDB_V2_FUNCTION_PROPERTY_VALUE { DUCKDB_V2_FUNCTION_PROPERTY_VALUE_MAX_ENUM = 0x7FFFFFFF, } DUCKDB_V2_FUNCTION_PROPERTY_VALUE; +/*! + * How the result of a scalar function changes with one of its arguments while the other arguments stay the same. The + * optimizer uses it, for example, to turn a filter on the result into a filter on the argument that can skip row groups + * by their statistics, or to keep an order through the function. Declared per argument with + * `duckdb_v2_scalar_function_set_argument_monotonicity()`, and changed for one call with + * `duckdb_v2_scalar_function_bind_set_argument_monotonicity()`. Declaring a monotonicity the function does not have + * produces wrong query results. A NULL argument or result is outside the claim. + */ +typedef enum DUCKDB_V2_FUNCTION_MONOTONICITY { + //! Nothing is known about how the result changes with the argument (default). + DUCKDB_V2_FUNCTION_MONOTONICITY_UNKNOWN = 0, + + //! The result does not change with the argument. + DUCKDB_V2_FUNCTION_MONOTONICITY_CONSTANT = 1, + + //! A greater argument never gives a smaller result. + DUCKDB_V2_FUNCTION_MONOTONICITY_NON_DECREASING = 2, + + //! A greater argument always gives a greater result. + DUCKDB_V2_FUNCTION_MONOTONICITY_STRICTLY_INCREASING = 3, + + //! A greater argument never gives a greater result. + DUCKDB_V2_FUNCTION_MONOTONICITY_NON_INCREASING = 4, + + //! A greater argument always gives a smaller result. + DUCKDB_V2_FUNCTION_MONOTONICITY_STRICTLY_DECREASING = 5, + DUCKDB_V2_FUNCTION_MONOTONICITY_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_FUNCTION_MONOTONICITY; + /* --- Struct forward declarations for function properties --- */ /* --- Types for function properties --- */ @@ -798,3607 +827,3246 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_arena_allocate(duckdb_v2_arena_handle are /* --- Struct definitions for arena --- */ /* ============================================================================ - * MODULE: cast + * MODULE: column_data_collection * ============================================================================ */ -/* --- Enums for cast --- */ - -/*! - * The mode a cast is being executed in. A normal cast must either succeed for every row or report an error, which - * aborts the query. A "try" cast (SQL TRY_CAST, and implicit casts the engine probes speculatively) tolerates per-row - * failures: the callback writes NULL for the rows it could not convert instead of aborting. Read with - * `duckdb_v2_cast_function_exec_get_mode()`, and passed to `duckdb_v2_vector_cast()`. - */ -typedef enum DUCKDB_V2_CAST_MODE { - //! A regular cast. A conversion failure reported through the error slot aborts the query. - DUCKDB_V2_CAST_MODE_NORMAL = 0, +/* --- Enums for column_data_collection --- */ - /*! - * A "try" cast. Conversion failures should be written as NULLs into the output vector; an error reported through - * the slot is swallowed and the affected rows are left NULL. - */ - DUCKDB_V2_CAST_MODE_TRY = 1, - DUCKDB_V2_CAST_MODE_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_CAST_MODE; +/* --- Struct forward declarations for column_data_collection --- */ -/* --- Struct forward declarations for cast --- */ +/* --- Types for column_data_collection --- */ -/* --- Types for cast --- */ +/*! + * A column data collection represents a set of (buffer-managed) data chunks. + * + * You can append chunks to the collection iteratively, and then scan the collection back to retrieve the chunks in + * order. DuckDB will manage the memory for the chunks, and transparently offload chunks to disk if necessary. A + * collection shall not be scanned while it is being appended to, and vice versa. A collection shall not be appended to + * concurrently, but it can be scanned concurrently by multiple threads using a shared scan state and per-thread worker + * scan states. For concurrent appends, consider creating multiple collections and "combining" them into one collection + * at the end. + */ +typedef struct _duckdb_v2_column_data_collection { + void *internal_ptr; +} * duckdb_v2_column_data_collection_handle; /*! - * An owned opaque handle to a cast function being built. Created with `duckdb_v2_cast_function_create()`, configured - * with the setter functions (e.g. `duckdb_v2_cast_function_set_source_type()`, - * `duckdb_v2_cast_function_set_exec_callback()`, etc.), made available with - * `duckdb_v2_connection_register_cast_function()` or `duckdb_v2_extension_register_cast_function()`, and destroyed with - * `duckdb_v2_cast_function_destroy()`. + * Opaque state handle for shared state across multiple threads scanning a column data collection. This is used to + * coordinate work distribution, track global progress, or store any other state that needs to be shared across threads + * during the scan of the collection. */ -typedef struct _duckdb_v2_cast_function { +typedef struct _duckdb_v2_column_data_collection_shared_scan_state { void *internal_ptr; -} * duckdb_v2_cast_function_handle; +} * duckdb_v2_column_data_collection_shared_scan_state_handle; /*! - * A borrowed opaque handle to the arguments supplied to a cast function during the execution "exec" phase. The "exec" - * callback receives this handle and can use it to access the input vector, the output vector to write into, the number - * of rows to convert, and the mode the cast is running in. + * Opaque state handle for local state while scanning a column data collection. This is used to track progress and any + * other state that needs to be maintained on a per-thread basis across calls while scanning the collection. It also + * keeps the buffers backing the most recently scanned chunk alive: chunks are scanned zero-copy, so a scanned chunk's + * data is only valid until the worker state's next scan call or its destruction. */ -typedef struct _duckdb_v2_cast_function_exec_info { +typedef struct _duckdb_v2_column_data_collection_worker_scan_state { void *internal_ptr; -} * duckdb_v2_cast_function_exec_info_handle; +} * duckdb_v2_column_data_collection_worker_scan_state_handle; -/* --- Constants for cast --- */ +/*! + * Opaque state handle for appending to a column data collection. This is used to track progress and any other state + * that needs to be maintained across calls while appending to the collection. + */ +typedef struct _duckdb_v2_column_data_collection_append_state { + void *internal_ptr; +} * duckdb_v2_column_data_collection_append_state_handle; -/* --- Function pointer typedefs for cast --- */ +/* --- Constants for column_data_collection --- */ -typedef void (*duckdb_v2_cast_function_exec_callback_fn)(duckdb_v2_cast_function_exec_info_handle info, - duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); +/* --- Function pointer typedefs for column_data_collection --- */ -/* --- Functions for cast --- */ +/* --- Functions for column_data_collection --- */ #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a new cast function through a factory. - * - * The function starts out empty: configure it with the setter functions (e.g. - * `duckdb_v2_cast_function_set_source_type()`, `duckdb_v2_cast_function_set_exec_callback()`, etc.), then make it - * available with `duckdb_v2_connection_register_cast_function()` or `duckdb_v2_extension_register_cast_function()`. The - * caller owns the returned handle and must destroy it with `duckdb_v2_cast_function_destroy()`, also after - * registration. + * Creates an empty column data collection from a factory. * - * The cast function can only be registered on the database the factory belongs to. + * Allocates a new, empty column data collection, drawing its buffers from the factory's database. The collection starts + * with no chunks and is ready to have chunks appended to it. A collection must have at least one column; an empty types + * array is rejected with INVALID_INPUT. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create the cast function through. - * @param function On success, receives the newly created cast function. Owned by the caller. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param types_array Pointer to an array of logical_type handles, one per column. This defines the schema for the + * chunks that will be stored in the collection. All chunks appended to this collection must have vectors that conform + * to these types. + * @param types_count Number of elements in the types_array. + * @param out_collection Receives the new collection handle. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_cast_function_create(duckdb_v2_factory_handle factory, - duckdb_v2_cast_function_handle *function, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_data_collection_create( + duckdb_v2_factory_handle factory, const duckdb_v2_logical_type_handle *types_array, idx_t types_count, + duckdb_v2_column_data_collection_handle *out_collection, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the type the cast converts from. + * Drops all buffered rows, keeping the column types. * - * The type is borrowed and copied. Calling this again replaces the previous source type. A source type must be set - * before registration, and it must be a fully defined concrete type. + * Drops all buffered rows and releases their memory. The column types are unchanged and the collection is immediately + * appendable again. Existing append and scan states are invalidated. Use `duckdb_v2_column_data_collection_clear()` + * instead to keep the memory for the next appends. * * history: * - unstable: v2.0.0 * - * @param function The function to set the source type of. - * @param source_type The type to cast from. Borrowed for the call only. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param collection The collection to reset. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_cast_function_set_source_type(duckdb_v2_cast_function_handle function, - duckdb_v2_logical_type_handle source_type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_data_collection_reset(duckdb_v2_column_data_collection_handle collection, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the type the cast converts to. + * Drops all buffered rows, keeping the column types and the memory. * - * The type is borrowed and copied. Calling this again replaces the previous target type. A target type must be set - * before registration, and it must be a fully defined concrete type. + * Like `duckdb_v2_column_data_collection_reset()`, but the buffers are retained rather than released, so the next + * appends write into memory that is already allocated. Use this when the collection is refilled repeatedly. The column + * types are unchanged and the collection is immediately appendable again. Existing append and scan states are + * invalidated. * * history: * - unstable: v2.0.0 * - * @param function The function to set the target type of. - * @param target_type The type to cast to. Borrowed for the call only. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param collection The collection to clear. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_cast_function_set_target_type(duckdb_v2_cast_function_handle function, - duckdb_v2_logical_type_handle target_type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_data_collection_clear(duckdb_v2_column_data_collection_handle collection, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets what it costs to apply this cast implicitly. + * Destroys a column data collection and all its chunks. * - * The binder uses the cost to choose between candidate implicit casts: a lower non-negative cost makes the cast more - * likely to be picked, a higher one less likely. Built-in widening casts sit in the [0, 20] range, so a cost above 100 - * effectively puts this cast last. A negative cost -- the default -- means the cast is never applied implicitly and is - * reached only through an explicit CAST or TRY_CAST. + * Cleans up the collection and all resources associated with it, including all contained chunks. Sets the collection + * handle to NULL. * * history: * - unstable: v2.0.0 * - * @param function The function to set the implicit cast cost of. - * @param cost The cost. Negative disables implicit casting. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param collection The collection to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_cast_function_set_implicit_cast_cost(duckdb_v2_cast_function_handle function, - int64_t cost, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR +duckdb_v2_column_data_collection_destroy(duckdb_v2_column_data_collection_handle *collection); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets arbitrary user data on the cast function. + * Merges the source collection into the target collection, consuming the source in the process. * - * Associates an opaque pointer with the function, retrievable from the exec callback via - * `duckdb_v2_cast_function_exec_get_user_data()`. The opaque handle bundles the pointer with an optional destructor, - * invoked when the data is no longer needed. The data is read-only during execution: the same pointer is shared by - * every thread running the cast. + * Transfers all chunks from the source collection to the target collection. This destroys the source collection, + * setting the source handle to NULL. The two collections must have the same column types, and must have been created + * from factories of the same database: the transferred chunks keep their original buffers, so combining collections + * from different databases would tie the target to a buffer manager it does not own. * * history: * - unstable: v2.0.0 * - * @param function The function to set the user data of. - * @param data Opaque handle bundling the user data pointer plus an optional destructor. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param target The collection to merge into. After the call, this collection will contain all chunks from both + * collections. + * @param source The collection to merge from. This collection will be destroyed by this operation and its handle set to + * NULL. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_cast_function_set_user_data(duckdb_v2_cast_function_handle function, - duckdb_v2_opaque *data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_data_collection_combine(duckdb_v2_column_data_collection_handle target, + duckdb_v2_column_data_collection_handle *source, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the exec callback of the cast function. + * Returns the total number of rows across all chunks in the collection. * - * The exec callback implements the conversion: it is invoked during query execution with a batch of input values and - * must fill the output vector. An exec callback must be set before registration. + * Sums the row counts of all chunks in the collection. This is the total number of rows represented by the collection, + * which may be more than the number of rows in any individual chunk. * * history: * - unstable: v2.0.0 * - * @param function The function to set the exec callback of. - * @param callback The exec callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param collection The collection to inspect. + * @param out_row_count Receives the total row count. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_cast_function_set_exec_callback( - duckdb_v2_cast_function_handle function, duckdb_v2_cast_function_exec_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_data_collection_row_count( + duckdb_v2_column_data_collection_handle collection, idx_t *out_row_count, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_cast_function_set_user_data()`. + * Initializes an append state for the collection. + * + * Returns an append state handle that can be used to append chunks to the collection while maintaining any necessary + * state across calls. * * history: * - unstable: v2.0.0 * - * @param info The exec info handle. - * @param data Receives the user data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param collection The collection to prepare for appending. + * @param out_state Receives the new append state handle. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_cast_function_exec_get_user_data(duckdb_v2_cast_function_exec_info_handle info, - void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_data_collection_append_state_create( + duckdb_v2_column_data_collection_handle collection, duckdb_v2_column_data_collection_append_state_handle *out_state, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns how many rows this execution must convert. + * Destroys an append state handle. * - * The number of rows held by the input vector, and the number of entries the callback must write to the output vector. - * Note that this may be less than a full vector: a constant input is converted as a single row and the result is - * expanded by the engine. + * Cleans up any resources associated with the append state. After this call, the state handle must not be used again. * * history: * - unstable: v2.0.0 * - * @param info The exec info handle. - * @param count Receives the number of rows. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param state The append state to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_cast_function_exec_get_row_count(duckdb_v2_cast_function_exec_info_handle info, - idx_t *count, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR +duckdb_v2_column_data_collection_append_state_destroy(duckdb_v2_column_data_collection_append_state_handle *state); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the input vector holding the values to convert. + * Appends a data chunk to the collection. * - * The vector holds the source type's values for the current batch; use `duckdb_v2_cast_function_exec_get_row_count()` - * for the number of rows. Borrowed; valid only for the duration of the callback. + * Appends a copy of the given chunk to the end of the collection. The chunk's column count and types must equal the + * collection's exactly; a mismatch is rejected with INVALID_INPUT before anything is copied. VARCHAR values must + * already contain valid UTF-8; this function does not validate text. Complex-typed vectors may be flattened in place by + * the copy. * * history: * - unstable: v2.0.0 * - * @param info The exec info handle. - * @param vector Receives the borrowed input vector. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param collection The collection to append to. + * @param state The append state to use this append operation. + * @param chunk The chunk to append. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_cast_function_exec_get_input(duckdb_v2_cast_function_exec_info_handle info, - duckdb_v2_vector_handle *vector, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_data_collection_append( + duckdb_v2_column_data_collection_handle collection, duckdb_v2_column_data_collection_append_state_handle state, + duckdb_v2_data_chunk_handle chunk, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the output vector the exec callback must write into. + * Initializes a shared scan state for the collection. * - * The callback must write one entry per input row; use `duckdb_v2_cast_function_exec_get_row_count()` for the number of - * rows. Borrowed; valid only for the duration of the callback. + * Returns a shared scan state handle that can be used by multiple threads to coordinate scanning of the collection. + * Caller owns the returned state and must destroy it via column_data_collection_shared_scan_state_destroy when done. * * history: * - unstable: v2.0.0 * - * @param info The exec info handle. - * @param vector Receives the borrowed output vector to write into. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param collection The collection to prepare for shared scanning. + * @param out_state Receives the new shared scan state handle. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_cast_function_exec_get_output(duckdb_v2_cast_function_exec_info_handle info, - duckdb_v2_vector_handle *vector, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_data_collection_shared_scan_state_create( + duckdb_v2_column_data_collection_handle collection, + duckdb_v2_column_data_collection_shared_scan_state_handle *out_state, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the mode the cast is being executed in. + * Destroys a shared scan state handle. * - * In `CAST_MODE_TRY` a conversion failure should be written as a NULL into the output vector rather than reported - * through the error slot, since the engine discards the error and keeps whatever the callback left in the output. + * Cleans up any resources associated with the shared scan state. After this call, the state handle must not be used + * again. * * history: * - unstable: v2.0.0 * - * @param info The exec info handle. - * @param mode Receives the cast mode. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param state The shared scan state to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_cast_function_exec_get_mode(duckdb_v2_cast_function_exec_info_handle info, - DUCKDB_V2_CAST_MODE *mode, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_data_collection_shared_scan_state_destroy( + duckdb_v2_column_data_collection_shared_scan_state_handle *state); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the cast function, making it available to CAST and TRY_CAST. + * Initializes a worker scan state for the collection. * - * The cast is registered on the connection's database and takes effect immediately for every connection; it is not part - * of the connection's transaction, so a rollback does not undo it. Registration requires a source type, a target type - * and an exec callback; both types must be fully defined concrete types. Registering a cast for a pair that already has - * one replaces it. The cast function must have been created through a factory of the same database. The caller still - * owns the handle after registration and must destroy it with `duckdb_v2_cast_function_destroy()`, which does not - * affect the registered function. + * Returns a "local" scan state handle for a worker thread to use while scanning the collection. This allows each thread + * to maintain its own progress and any other necessary information across multiple scan calls, while still coordinating + * with other threads via the shared scan state. * * history: * - unstable: v2.0.0 * - * @param conn The connection to register on. - * @param function The cast function to register. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param collection The collection to prepare for worker scanning. + * @param out_state Receives the new worker scan state handle. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_register_cast_function(duckdb_v2_connection_handle conn, - duckdb_v2_cast_function_handle function, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_data_collection_worker_scan_state_create( + duckdb_v2_column_data_collection_handle collection, + duckdb_v2_column_data_collection_worker_scan_state_handle *out_state, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the cast function, making it available to CAST and TRY_CAST. + * Destroys a worker scan state handle. * - * The cast is registered on the loading extension's database. Use this from the extension's load callback. Registration - * requires a source type, a target type and an exec callback; both types must be fully defined concrete types. - * Registering a cast for a pair that already has one replaces it. The cast function must have been created through a - * factory of the same database. The caller still owns the handle after registration and must destroy it with - * `duckdb_v2_cast_function_destroy()`, which does not affect the registered function. + * Cleans up any resources associated with the worker scan state. After this call, the state handle must not be used + * again. * * history: * - unstable: v2.0.0 * - * @param extension The loading extension. - * @param function The cast function to register. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param state The worker scan state to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_cast_function(duckdb_v2_extension_handle extension, - duckdb_v2_cast_function_handle function, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_data_collection_worker_scan_state_destroy( + duckdb_v2_column_data_collection_worker_scan_state_handle *state); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys the cast function, releasing its resources. + * Scans the collection to retrieve the next data chunk, using shared state for coordination across threads and + * worker-local state for individual progress tracking. * - * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent - * double-destruction. Destroying the handle after registration does not affect the registered function. + * Retrieves the next chunk of data from the collection based on the provided shared scan state and worker-local scan + * state. The output chunk's column count and types must equal the collection's exactly; a mismatch is rejected with + * INVALID_INPUT. + * + * The scan is zero-copy where possible: the output chunk's vectors may reference the collection's buffers, kept alive + * by the worker scan state. The chunk's data is therefore only valid until the next scan call with the same worker + * state, or until the worker state or the collection is destroyed, whichever comes first. Copy the data out (or append + * it to another collection) before continuing the scan if it must outlive that window. * * history: * - unstable: v2.0.0 * - * @param function The function to destroy. + * @param collection The collection to scan. + * @param shared_state The shared scan state to use for coordinating across threads. + * @param worker_state The worker-local scan state to use for this thread's scan operation. + * @param out_chunk The output chunk to write to. + * @param did_produce_chunk Receives true when a chunk was produced by this call, or false when the scan has completed + * (the chunk is then reset to empty). + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_cast_function_destroy(duckdb_v2_cast_function_handle *function); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_data_collection_scan( + duckdb_v2_column_data_collection_handle collection, + duckdb_v2_column_data_collection_shared_scan_state_handle shared_state, + duckdb_v2_column_data_collection_worker_scan_state_handle worker_state, duckdb_v2_data_chunk_handle out_chunk, + bool *did_produce_chunk, duckdb_v2_error_info_handle *err); #endif -/* --- Struct definitions for cast --- */ +/* --- Struct definitions for column_data_collection --- */ /* ============================================================================ - * MODULE: column_data_collection + * MODULE: configuration * ============================================================================ */ -/* --- Enums for column_data_collection --- */ - -/* --- Struct forward declarations for column_data_collection --- */ - -/* --- Types for column_data_collection --- */ +/* --- Enums for configuration --- */ /*! - * A column data collection represents a set of (buffer-managed) data chunks. - * - * You can append chunks to the collection iteratively, and then scan the collection back to retrieve the chunks in - * order. DuckDB will manage the memory for the chunks, and transparently offload chunks to disk if necessary. A - * collection shall not be scanned while it is being appended to, and vice versa. A collection shall not be appended to - * concurrently, but it can be scanned concurrently by multiple threads using a shared scan state and per-thread worker - * scan states. For concurrent appends, consider creating multiple collections and "combining" them into one collection - * at the end. + * The scope of an option's value. Writes take DEFAULT, GLOBAL or SESSION: DEFAULT writes to the option's default scope + * (`duckdb_v2_option_get_default_scope()`), like SQL `SET name = value`; GLOBAL writes through to the instance, visible + * to all connections, like `SET GLOBAL`; SESSION writes to one connection's session only, like `SET SESSION`. Reads + * report GLOBAL or SESSION, as DuckDB attributes the value: an option no scope sets reads as GLOBAL, its default, and a + * legacy option read through a connection or context reads as SESSION. */ -typedef struct _duckdb_v2_column_data_collection { - void *internal_ptr; -} * duckdb_v2_column_data_collection_handle; +typedef enum DUCKDB_V2_SETTING_SCOPE { + //! Write only: the option's default scope (`duckdb_v2_option_get_default_scope()`), not its default value. + DUCKDB_V2_SETTING_SCOPE_DEFAULT = 0, -/*! - * Opaque state handle for shared state across multiple threads scanning a column data collection. This is used to - * coordinate work distribution, track global progress, or store any other state that needs to be shared across threads - * during the scan of the collection. - */ -typedef struct _duckdb_v2_column_data_collection_shared_scan_state { - void *internal_ptr; -} * duckdb_v2_column_data_collection_shared_scan_state_handle; + //! The instance's value, visible to all connections. + DUCKDB_V2_SETTING_SCOPE_GLOBAL = 1, -/*! - * Opaque state handle for local state while scanning a column data collection. This is used to track progress and any - * other state that needs to be maintained on a per-thread basis across calls while scanning the collection. It also - * keeps the buffers backing the most recently scanned chunk alive: chunks are scanned zero-copy, so a scanned chunk's - * data is only valid until the worker state's next scan call or its destruction. - */ -typedef struct _duckdb_v2_column_data_collection_worker_scan_state { - void *internal_ptr; -} * duckdb_v2_column_data_collection_worker_scan_state_handle; + //! A connection's session value. + DUCKDB_V2_SETTING_SCOPE_SESSION = 2, + DUCKDB_V2_SETTING_SCOPE_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_SETTING_SCOPE; -/*! - * Opaque state handle for appending to a column data collection. This is used to track progress and any other state - * that needs to be maintained across calls while appending to the collection. - */ -typedef struct _duckdb_v2_column_data_collection_append_state { - void *internal_ptr; -} * duckdb_v2_column_data_collection_append_state_handle; +/* --- Struct forward declarations for configuration --- */ -/* --- Constants for column_data_collection --- */ +/* --- Types for configuration --- */ -/* --- Function pointer typedefs for column_data_collection --- */ +/* --- Constants for configuration --- */ -/* --- Functions for column_data_collection --- */ +/* --- Function pointer typedefs for configuration --- */ + +/* --- Functions for configuration --- */ #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates an empty column data collection from a factory. + * Borrows the config of an instance: the GLOBAL scope. * - * Allocates a new, empty column data collection, drawing its buffers from the factory's database. The collection starts - * with no chunks and is ready to have chunks appended to it. A collection must have at least one column; an empty types - * array is rejected with INVALID_INPUT. + * Reads report GLOBAL, and writes are `SET GLOBAL`. Writing at SESSION scope returns ERROR_INPUT_INVALID: an instance + * has no session. Options that can only be chosen at startup are passed to `duckdb_v2_instance_create_with_options()`. + * The returned handle is borrowed: it is valid for as long as the instance is, and must not be destroyed. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param types_array Pointer to an array of logical_type handles, one per column. This defines the schema for the - * chunks that will be stored in the collection. All chunks appended to this collection must have vectors that conform - * to these types. - * @param types_count Number of elements in the types_array. - * @param out_collection Receives the new collection handle. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param instance The instance. + * @param out_config Receives the borrowed config. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_data_collection_create( - duckdb_v2_factory_handle factory, const duckdb_v2_logical_type_handle *types_array, idx_t types_count, - duckdb_v2_column_data_collection_handle *out_collection, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_get_config(duckdb_v2_instance_handle instance, + duckdb_v2_config_handle *out_config, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Drops all buffered rows, keeping the column types. + * Borrows the config of a connection. * - * Drops all buffered rows and releases their memory. The column types are unchanged and the collection is immediately - * appendable again. Existing append and scan states are invalidated. Use `duckdb_v2_column_data_collection_clear()` - * instead to keep the memory for the next appends. + * Reads follow the connection's cascade: its SESSION value if it set one, otherwise the GLOBAL value, otherwise the + * default. Writes accept any scope the option supports. The returned handle is borrowed: it is valid for as long as the + * connection is, and must not be destroyed. * * history: * - unstable: v2.0.0 * - * @param collection The collection to reset. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param conn The connection. + * @param out_config Receives the borrowed config. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_data_collection_reset(duckdb_v2_column_data_collection_handle collection, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_get_config(duckdb_v2_connection_handle conn, + duckdb_v2_config_handle *out_config, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Drops all buffered rows, keeping the column types and the memory. + * Borrows the config of a context. * - * Like `duckdb_v2_column_data_collection_reset()`, but the buffers are retained rather than released, so the next - * appends write into memory that is already allocated. Use this when the collection is refilled repeatedly. The column - * types are unchanged and the collection is immediately appendable again. Existing append and scan states are - * invalidated. + * The same scope `duckdb_v2_connection_get_config()` gives for the context's connection. The returned handle is + * borrowed: it is valid for as long as the context is, and must not be destroyed. * * history: * - unstable: v2.0.0 * - * @param collection The collection to clear. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param ctx The context. + * @param out_config Receives the borrowed config. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_data_collection_clear(duckdb_v2_column_data_collection_handle collection, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_get_config(duckdb_v2_context_handle ctx, + duckdb_v2_config_handle *out_config, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys a column data collection and all its chunks. + * Reads the effective value of an option in this config, and the scope it came from. * - * Cleans up the collection and all resources associated with it, including all contained chunks. Sets the collection - * handle to NULL. + * Aliases resolve transparently, and an unknown name returns ERROR_INPUT_INVALID. The caller destroys the returned + * value. * * history: * - unstable: v2.0.0 * - * @param collection The collection to destroy. + * @param config The config to read from. + * @param name Option name (canonical or alias). + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param out_value Receives the value, typed as the option. Owned by the caller. + * @param out_scope Receives the scope the value came from. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR -duckdb_v2_column_data_collection_destroy(duckdb_v2_column_data_collection_handle *collection); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_config_get_option_value(duckdb_v2_config_handle config, const char *name, + idx_t name_length, duckdb_v2_value_handle *out_value, + DUCKDB_V2_SETTING_SCOPE *out_scope, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Merges the source collection into the target collection, consuming the source in the process. + * Writes an option in this config. * - * Transfers all chunks from the source collection to the target collection. This destroys the source collection, - * setting the source handle to NULL. The two collections must have the same column types, and must have been created - * from factories of the same database: the transferred chunks keep their original buffers, so combining collections - * from different databases would tie the target to a buffer manager it does not own. + * `scope` chooses the destination, mirroring SQL: + * - DEFAULT writes to the option's default scope, like a bare `SET name = value`. + * - GLOBAL writes through to the instance, visible to all connections, like `SET GLOBAL`. + * - SESSION writes to one connection's session only, like `SET SESSION`. + * A scope neither the option (`duckdb_v2_option_supports_scope()`) nor the config supports returns ERROR_INPUT_INVALID; + * an instance's config supports only GLOBAL. The value is cast to the option's type as SQL `SET` does. An unknown name + * is rejected unless an extension that defines it can be autoloaded. An option that can only be chosen at startup is + * rejected: pass it to `duckdb_v2_instance_create_with_options()`. * * history: * - unstable: v2.0.0 * - * @param target The collection to merge into. After the call, this collection will contain all chunks from both - * collections. - * @param source The collection to merge from. This collection will be destroyed by this operation and its handle set to - * NULL. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param config The config to write to. + * @param name Option name (canonical or alias). + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param value The value, cast to the option's type as SQL `SET` does. Borrowed. + * @param scope Target scope: DEFAULT, GLOBAL, or SESSION. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_data_collection_combine(duckdb_v2_column_data_collection_handle target, - duckdb_v2_column_data_collection_handle *source, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_config_set_option_value(duckdb_v2_config_handle config, const char *name, + idx_t name_length, duckdb_v2_value_handle value, + DUCKDB_V2_SETTING_SCOPE scope, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the total number of rows across all chunks in the collection. + * Writes an option in this config from text, the form SQL `SET` accepts. * - * Sums the row counts of all chunks in the collection. This is the total number of rows represented by the collection, - * which may be more than the number of rows in any individual chunk. + * `duckdb_v2_config_set_option_value()` with the text as a VARCHAR value: the engine casts it to the option's type, so + * this is the one-call form for a setting spelled the way SQL spells it, e.g. "1GB" for memory_limit. Scope handling + * and errors are `duckdb_v2_config_set_option_value()`'s. * * history: * - unstable: v2.0.0 * - * @param collection The collection to inspect. - * @param out_row_count Receives the total row count. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_data_collection_row_count( - duckdb_v2_column_data_collection_handle collection, idx_t *out_row_count, duckdb_v2_error_info_handle *err); + * @param config The config to write to. + * @param name Option name (canonical or alias). + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param setting The setting, in the textual form SQL `SET` accepts. + * @param setting_length The length of `setting` in bytes. `setting` need not be null-terminated and may be NULL only + * when this is 0. + * @param scope Target scope: DEFAULT, GLOBAL, or SESSION. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_config_set_option_text(duckdb_v2_config_handle config, const char *name, + idx_t name_length, const char *setting, + idx_t setting_length, DUCKDB_V2_SETTING_SCOPE scope, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Initializes an append state for the collection. + * Describes a config option registered on this config's instance, by name. * - * Returns an append state handle that can be used to append chunks to the collection while maintaining any necessary - * state across calls. + * Allocates an option descriptor: canonical name, default value, description, supported and default scopes, and + * aliases. Aliases resolve transparently — passing an alias returns the canonical option, with the alias listed in its + * alias array. An unknown name returns ERROR_INPUT_INVALID, which includes an option of an extension that has not + * loaded yet. The caller destroys the returned option. * * history: * - unstable: v2.0.0 * - * @param collection The collection to prepare for appending. - * @param out_state Receives the new append state handle. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param config The config whose instance registered the options. + * @param name Option name (canonical or alias). + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param out_option Receives the option descriptor. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_data_collection_append_state_create( - duckdb_v2_column_data_collection_handle collection, duckdb_v2_column_data_collection_append_state_handle *out_state, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_config_get_option_by_name(duckdb_v2_config_handle config, const char *name, + idx_t name_length, duckdb_v2_option_handle *out_option, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys an append state handle. + * Returns the number of config options registered on this config's instance. * - * Cleans up any resources associated with the append state. After this call, the state handle must not be used again. + * Counts core options plus the extension options registered on this instance. Aliases are NOT counted separately; each + * one is reachable through its canonical option's alias array. * * history: * - unstable: v2.0.0 * - * @param state The append state to destroy. + * @param config The config whose instance registered the options. + * @param out_count Receives the option count. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR -duckdb_v2_column_data_collection_append_state_destroy(duckdb_v2_column_data_collection_append_state_handle *state); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_config_get_option_count(duckdb_v2_config_handle config, idx_t *out_count, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Appends a data chunk to the collection. + * Describes the config option at the given index on this config's instance. * - * Appends a copy of the given chunk to the end of the collection. The chunk's column count and types must equal the - * collection's exactly; a mismatch is rejected with INVALID_INPUT before anything is copied. VARCHAR values must - * already contain valid UTF-8; this function does not validate text. Complex-typed vectors may be flattened in place by - * the copy. + * Index space: [0, core_count) addresses core options, [core_count, total) extension options. The mapping is stable for + * as long as no extension registers new options. An out-of-range index returns ERROR_INPUT_INVALID. The caller destroys + * the returned option. * * history: * - unstable: v2.0.0 * - * @param collection The collection to append to. - * @param state The append state to use this append operation. - * @param chunk The chunk to append. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param config The config whose instance registered the options. + * @param index The option index, in [0, option_count). + * @param out_option Receives the option descriptor. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_data_collection_append( - duckdb_v2_column_data_collection_handle collection, duckdb_v2_column_data_collection_append_state_handle state, - duckdb_v2_data_chunk_handle chunk, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_config_get_option_by_index(duckdb_v2_config_handle config, idx_t index, + duckdb_v2_option_handle *out_option, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Initializes a shared scan state for the collection. + * Destroys an option descriptor. * - * Returns a shared scan state handle that can be used by multiple threads to coordinate scanning of the collection. - * Caller owns the returned state and must destroy it via column_data_collection_shared_scan_state_destroy when done. + * Frees the handle along with the strings it owns. On success the slot is set to null. Safe to call on an already-null + * slot. * * history: * - unstable: v2.0.0 * - * @param collection The collection to prepare for shared scanning. - * @param out_state Receives the new shared scan state handle. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param option The option handle to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_data_collection_shared_scan_state_create( - duckdb_v2_column_data_collection_handle collection, - duckdb_v2_column_data_collection_shared_scan_state_handle *out_state, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_option_destroy(duckdb_v2_option_handle *option); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys a shared scan state handle. + * Borrows the option's canonical name. * - * Cleans up any resources associated with the shared scan state. After this call, the state handle must not be used - * again. + * When the option was resolved from an alias, this still reports the canonical name; the alias is reachable via + * `duckdb_v2_option_get_alias()`. * * history: * - unstable: v2.0.0 * - * @param state The shared scan state to destroy. + * @param option The option. + * @param out_name Receives a borrowed pointer to the option name. Valid until the option is destroyed. + * @param out_name_length Receives the length of `*out_name` in bytes. `*out_name` is not guaranteed to be + * null-terminated. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_data_collection_shared_scan_state_destroy( - duckdb_v2_column_data_collection_shared_scan_state_handle *state); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_option_get_name(duckdb_v2_option_handle option, const char **out_name, + idx_t *out_name_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Initializes a worker scan state for the collection. + * Returns the option's static default, as a value of the option's type. * - * Returns a "local" scan state handle for a worker thread to use while scanning the collection. This allows each thread - * to maintain its own progress and any other necessary information across multiple scan calls, while still coordinating - * with other threads via the shared scan state. + * A NULL value for an option whose declaration has no default. The caller destroys the returned value. * * history: * - unstable: v2.0.0 * - * @param collection The collection to prepare for worker scanning. - * @param out_state Receives the new worker scan state handle. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param option The option. + * @param out_value Receives the default value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_data_collection_worker_scan_state_create( - duckdb_v2_column_data_collection_handle collection, - duckdb_v2_column_data_collection_worker_scan_state_handle *out_state, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_option_get_default_value(duckdb_v2_option_handle option, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys a worker scan state handle. - * - * Cleans up any resources associated with the worker scan state. After this call, the state handle must not be used - * again. + * Borrows the option's human-readable description. * * history: * - unstable: v2.0.0 * - * @param state The worker scan state to destroy. + * @param option The option. + * @param out_description Receives a borrowed pointer to the description. Valid until the option is destroyed. + * @param out_description_length Receives the length of `*out_description` in bytes. `*out_description` is not + * guaranteed to be null-terminated. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_data_collection_worker_scan_state_destroy( - duckdb_v2_column_data_collection_worker_scan_state_handle *state); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_option_get_description(duckdb_v2_option_handle option, + const char **out_description, + idx_t *out_description_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Scans the collection to retrieve the next data chunk, using shared state for coordination across threads and - * worker-local state for individual progress tracking. - * - * Retrieves the next chunk of data from the collection based on the provided shared scan state and worker-local scan - * state. The output chunk's column count and types must equal the collection's exactly; a mismatch is rejected with - * INVALID_INPUT. + * Reports whether the option may be written at a scope. * - * The scan is zero-copy where possible: the output chunk's vectors may reference the collection's buffers, kept alive - * by the worker scan state. The chunk's data is therefore only valid until the next scan call with the same worker - * state, or until the worker state or the collection is destroyed, whichever comes first. Copy the data out (or append - * it to another collection) before continuing the scan if it must outlive that window. + * GLOBAL and SESSION are the scopes to ask about; DEFAULT is supported by every option that supports either. A write at + * an unsupported scope returns ERROR_INPUT_INVALID. * * history: * - unstable: v2.0.0 * - * @param collection The collection to scan. - * @param shared_state The shared scan state to use for coordinating across threads. - * @param worker_state The worker-local scan state to use for this thread's scan operation. - * @param out_chunk The output chunk to write to. - * @param did_produce_chunk Receives true when a chunk was produced by this call, or false when the scan has completed - * (the chunk is then reset to empty). - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param option The option. + * @param scope The scope to ask about. + * @param out_supported Receives whether a write at the scope is accepted. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_data_collection_scan( - duckdb_v2_column_data_collection_handle collection, - duckdb_v2_column_data_collection_shared_scan_state_handle shared_state, - duckdb_v2_column_data_collection_worker_scan_state_handle worker_state, duckdb_v2_data_chunk_handle out_chunk, - bool *did_produce_chunk, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_option_supports_scope(duckdb_v2_option_handle option, + DUCKDB_V2_SETTING_SCOPE scope, bool *out_supported, + duckdb_v2_error_info_handle *err); #endif -/* --- Struct definitions for column_data_collection --- */ - -/* ============================================================================ - * MODULE: configuration - * ============================================================================ */ - -/* --- Enums for configuration --- */ - -/*! - * The scope of an option's value. Writes take DEFAULT, GLOBAL or SESSION: DEFAULT writes to the option's default scope - * (`duckdb_v2_option_get_default_scope()`), like SQL `SET name = value`; GLOBAL writes through to the instance, visible - * to all connections, like `SET GLOBAL`; SESSION writes to one connection's session only, like `SET SESSION`. Reads - * report GLOBAL or SESSION, as DuckDB attributes the value: an option no scope sets reads as GLOBAL, its default, and a - * legacy option read through a connection or context reads as SESSION. - */ -typedef enum DUCKDB_V2_SETTING_SCOPE { - //! Write only: the option's default scope (`duckdb_v2_option_get_default_scope()`), not its default value. - DUCKDB_V2_SETTING_SCOPE_DEFAULT = 0, - - //! The instance's value, visible to all connections. - DUCKDB_V2_SETTING_SCOPE_GLOBAL = 1, - - //! A connection's session value. - DUCKDB_V2_SETTING_SCOPE_SESSION = 2, - DUCKDB_V2_SETTING_SCOPE_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_SETTING_SCOPE; - -/* --- Struct forward declarations for configuration --- */ - -/* --- Types for configuration --- */ - -/* --- Constants for configuration --- */ - -/* --- Function pointer typedefs for configuration --- */ - -/* --- Functions for configuration --- */ - #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Borrows the config of an instance: the GLOBAL scope. - * - * Reads report GLOBAL, and writes are `SET GLOBAL`. Writing at SESSION scope returns ERROR_INPUT_INVALID: an instance - * has no session. Options that can only be chosen at startup are passed to `duckdb_v2_instance_create_with_options()`. - * The returned handle is borrowed: it is valid for as long as the instance is, and must not be destroyed. + * Returns the scope a DEFAULT write of the option goes to: GLOBAL or SESSION. * * history: * - unstable: v2.0.0 * - * @param instance The instance. - * @param out_config Receives the borrowed config. + * @param option The option. + * @param out_scope Receives the default scope. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_get_config(duckdb_v2_instance_handle instance, - duckdb_v2_config_handle *out_config, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_option_get_default_scope(duckdb_v2_option_handle option, + DUCKDB_V2_SETTING_SCOPE *out_scope, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Borrows the config of a connection. + * Returns the number of aliases registered for this option. * - * Reads follow the connection's cascade: its SESSION value if it set one, otherwise the GLOBAL value, otherwise the - * default. Writes accept any scope the option supports. The returned handle is borrowed: it is valid for as long as the - * connection is, and must not be destroyed. + * Zero for an extension option; extension options carry no aliases. * * history: * - unstable: v2.0.0 * - * @param conn The connection. - * @param out_config Receives the borrowed config. + * @param option The option. + * @param out_count Receives the alias count. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_get_config(duckdb_v2_connection_handle conn, - duckdb_v2_config_handle *out_config, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_option_get_alias_count(duckdb_v2_option_handle option, idx_t *out_count, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Borrows the config of a context. + * Borrows the alias name at the given index. * - * The same scope `duckdb_v2_connection_get_config()` gives for the context's connection. The returned handle is - * borrowed: it is valid for as long as the context is, and must not be destroyed. + * An out-of-range index returns ERROR_INPUT_INVALID. * * history: * - unstable: v2.0.0 * - * @param ctx The context. - * @param out_config Receives the borrowed config. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * @param option The option. + * @param index The alias index, in [0, alias_count). + * @param out_alias Receives a borrowed pointer to the alias. Valid until the option is destroyed. + * @param out_alias_length Receives the length of `*out_alias` in bytes. `*out_alias` is not guaranteed to be + * null-terminated. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_get_config(duckdb_v2_context_handle ctx, - duckdb_v2_config_handle *out_config, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_option_get_alias(duckdb_v2_option_handle option, idx_t index, + const char **out_alias, idx_t *out_alias_length, + duckdb_v2_error_info_handle *err); #endif +/* --- Struct definitions for configuration --- */ + +/* ============================================================================ + * MODULE: connection + * ============================================================================ */ + +/* --- Enums for connection --- */ + +/* --- Struct forward declarations for connection --- */ + +/* --- Types for connection --- */ + +/* --- Constants for connection --- */ + +/* --- Function pointer typedefs for connection --- */ + +/* --- Functions for connection --- */ + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Reads the effective value of an option in this config, and the scope it came from. + * Opens a connection to an instance. * - * Aliases resolve transparently, and an unknown name returns ERROR_INPUT_INVALID. The caller destroys the returned - * value. + * Each connection carries its own client context and session-scoped (LOCAL) settings. Connections to the same instance + * share its catalog, buffer pool, and transaction manager. A connection may be created before any database is attached + * to the instance; until one is, only the system catalog and the connection's temporary catalog are visible. The caller + * destroys it via `duckdb_v2_connection_destroy()`. * * history: * - unstable: v2.0.0 * - * @param config The config to read from. - * @param name Option name (canonical or alias). - * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be - * NULL only when this is 0. - * @param out_value Receives the value, typed as the option. Owned by the caller. - * @param out_scope Receives the scope the value came from. + * @param instance The instance to connect to. + * @param out_conn Receives the new connection handle. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_config_get_option_value(duckdb_v2_config_handle config, const char *name, - idx_t name_length, duckdb_v2_value_handle *out_value, - DUCKDB_V2_SETTING_SCOPE *out_scope, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_create(duckdb_v2_instance_handle instance, + duckdb_v2_connection_handle *out_conn, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Writes an option in this config. + * Opens a connection that runs in the transaction of a context. * - * `scope` chooses the destination, mirroring SQL: - * - DEFAULT writes to the option's default scope, like a bare `SET name = value`. - * - GLOBAL writes through to the instance, visible to all connections, like `SET GLOBAL`. - * - SESSION writes to one connection's session only, like `SET SESSION`. - * A scope neither the option (`duckdb_v2_option_supports_scope()`) nor the config supports returns ERROR_INPUT_INVALID; - * an instance's config supports only GLOBAL. The value is cast to the option's type as SQL `SET` does. An unknown name - * is rejected unless an extension that defines it can be autoloaded. An option that can only be chosen at startup is - * rejected: pass it to `duckdb_v2_instance_create_with_options()`. + * Lets a callback run SQL inside the transaction it is called in, such as a table function's bind callback reading a + * table. The connection sees everything the context's transaction sees, including its uncommitted changes and the + * context's temporary objects, and what it changes is part of that transaction. A statement of the connection that + * fails invalidates the transaction as a failure of the context's own statement would. It starts with the context's + * search path (`USE`, `SET schema`, `SET search_path`), so unqualified names resolve as they do in the context's own + * statements. + * + * The connection cannot start, commit or roll back a transaction: those statements fail with + * ERROR_DATABASE_TRANSACTION, and like any failing statement invalidate the transaction. The connection stays in the + * transaction until it is destroyed, which neither commits nor rolls the transaction back. Destroy it before the + * transaction ends, typically before the callback returns: a transaction that is committed while such a connection is + * still open is rolled back instead, and the connection's statements fail from then on. Interrupting the context's + * query also interrupts the connection's. The caller destroys it via `duckdb_v2_connection_destroy()`. * * history: * - unstable: v2.0.0 * - * @param config The config to write to. - * @param name Option name (canonical or alias). - * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be - * NULL only when this is 0. - * @param value The value, cast to the option's type as SQL `SET` does. Borrowed. - * @param scope Target scope: DEFAULT, GLOBAL, or SESSION. + * @param ctx The context whose transaction the connection runs in. It must have an active transaction. + * @param out_conn Receives the new connection handle. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_config_set_option_value(duckdb_v2_config_handle config, const char *name, - idx_t name_length, duckdb_v2_value_handle value, - DUCKDB_V2_SETTING_SCOPE scope, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_create_in_transaction(duckdb_v2_context_handle ctx, + duckdb_v2_connection_handle *out_conn, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Writes an option in this config from text, the form SQL `SET` accepts. + * Destroys the connection. * - * `duckdb_v2_config_set_option_value()` with the text as a VARCHAR value: the engine casts it to the option's type, so - * this is the one-call form for a setting spelled the way SQL spells it, e.g. "1GB" for memory_limit. Scope handling - * and errors are `duckdb_v2_config_set_option_value()`'s. + * Always succeeds. Releases the connection's reference on the underlying database instance, which survives for as long + * as anything else still references it. On success the handle is set to null. Safe to call on an already-null slot. * * history: * - unstable: v2.0.0 * - * @param config The config to write to. - * @param name Option name (canonical or alias). - * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be - * NULL only when this is 0. - * @param setting The setting, in the textual form SQL `SET` accepts. - * @param setting_length The length of `setting` in bytes. `setting` need not be null-terminated and may be NULL only - * when this is 0. - * @param scope Target scope: DEFAULT, GLOBAL, or SESSION. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param conn The connection to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_config_set_option_text(duckdb_v2_config_handle config, const char *name, - idx_t name_length, const char *setting, - idx_t setting_length, DUCKDB_V2_SETTING_SCOPE scope, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_destroy(duckdb_v2_connection_handle *conn); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Describes a config option registered on this config's instance, by name. + * Interrupts the query currently executing on the connection. * - * Allocates an option descriptor: canonical name, default value, description, supported and default scopes, and - * aliases. Aliases resolve transparently — passing an alias returns the canonical option, with the alias listed in its - * alias array. An unknown name returns ERROR_INPUT_INVALID, which includes an option of an extension that has not - * loaded yet. The caller destroys the returned option. + * The cross-thread (but not cross-connection) cancellation entry point for streaming results: safe to call from any + * thread within the execution of a query through a connection, including while another thread steps the query's result. + * A no-op when no query is active. Cancellation surfaces on the consuming side as step status CANCELLED + * (`duckdb_v2_result_step()`), or as ERROR_RUNTIME_INTERRUPT (`duckdb_v2_result_fetch_chunk()`). * * history: * - unstable: v2.0.0 * - * @param config The config whose instance registered the options. - * @param name Option name (canonical or alias). - * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be - * NULL only when this is 0. - * @param out_option Receives the option descriptor. + * @param conn The connection whose active query to interrupt. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_config_get_option_by_name(duckdb_v2_config_handle config, const char *name, - idx_t name_length, duckdb_v2_option_handle *out_option, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_interrupt(duckdb_v2_connection_handle conn, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of config options registered on this config's instance. + * Captures a snapshot of the active query's execution progress. * - * Counts core options plus the extension options registered on this instance. Aliases are NOT counted separately; each - * one is reachable through its canonical option's alias array. + * Reads the percentage and row counts from one consistent snapshot of the query currently executing on the connection. + * Safe to call from any thread, including while another thread steps the query's result. + * + * Progress is published only when the enable_progress_bar option is set; the bridge does not enable tracking itself. + * Both row counts are 0 when no information is available. The percentage is -1 when tracking is disabled, no query is + * active, or no progress has been published yet. * * history: * - unstable: v2.0.0 * - * @param config The config whose instance registered the options. - * @param out_count Receives the option count. + * @param conn The connection. + * @param out_percentage Receives the percentage complete in [0, 100], -1 if tracking is disabled, no query is active, + * or no progress has been published yet. + * @param out_rows_processed Receives the number of rows processed so far. + * @param out_total_rows_to_process Receives the total number of rows the query will process. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_config_get_option_count(duckdb_v2_config_handle config, idx_t *out_count, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_progress_get(duckdb_v2_connection_handle conn, double *out_percentage, + uint64_t *out_rows_processed, + uint64_t *out_total_rows_to_process, duckdb_v2_error_info_handle *err); #endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE +/* --- Struct definitions for connection --- */ + +/* ============================================================================ + * MODULE: context state + * ============================================================================ */ + +/* --- Enums for context state --- */ + +/* --- Struct forward declarations for context state --- */ + +/* --- Types for context state --- */ + /*! - * Describes the config option at the given index on this config's instance. - * - * Index space: [0, core_count) addresses core options, [core_count, total) extension options. The mapping is stable for - * as long as no extension registers new options. An out-of-range index returns ERROR_INPUT_INVALID. The caller destroys - * the returned option. - * - * history: - * - unstable: v2.0.0 - * - * @param config The config whose instance registered the options. - * @param index The option index, in [0, option_count). - * @param out_option Receives the option descriptor. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR + * A borrowed opaque handle to connection state being set up, received by the init callback of + * `duckdb_v2_context_get_or_create_state()` or `duckdb_v2_connection_get_or_create_state()` and valid only for the + * duration of that call. Configure it with `duckdb_v2_context_state_set_user_data()` and the callback setters; whatever + * is not set stays inert. */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_config_get_option_by_index(duckdb_v2_config_handle config, idx_t index, - duckdb_v2_option_handle *out_option, - duckdb_v2_error_info_handle *err); -#endif +typedef struct _duckdb_v2_context_state { + void *internal_ptr; +} * duckdb_v2_context_state_handle; -#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys an option descriptor. - * - * Frees the handle along with the strings it owns. On success the slot is set to null. Safe to call on an already-null - * slot. - * - * history: - * - unstable: v2.0.0 - * - * @param option The option handle to destroy. - * @return DUCKDB_V2_ERROR + * A borrowed opaque handle to the profile of the query that just ended, received by a connection state's profiling + * callback and valid only for the duration of that call. Add text to it with `duckdb_v2_context_state_profile_write()`. */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_option_destroy(duckdb_v2_option_handle *option); -#endif +typedef struct _duckdb_v2_context_state_profile { + void *internal_ptr; +} * duckdb_v2_context_state_profile_handle; + +/* --- Constants for context state --- */ + +/* --- Function pointer typedefs for context state --- */ -#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Borrows the option's canonical name. - * - * When the option was resolved from an alias, this still reports the canonical name; the alias is reachable via - * `duckdb_v2_option_get_alias()`. + * Sets up the connection state of a key that has none yet. * - * history: - * - unstable: v2.0.0 + * Runs outside the lock of the connection's registered states, so it may use the context, state functions included. + * When the key gets registered while the init runs, by another thread or by the init itself, the state registered first + * is kept, and the one this init set up is released as if the init had failed. A failure reported through `err` leaves + * the key unregistered and fails the call that triggered the init. + */ +typedef void (*duckdb_v2_context_state_init_callback_fn)(duckdb_v2_context_handle context, void *user_data, + duckdb_v2_context_state_handle state, + duckdb_v2_error_info_handle *err); + +/*! + * Called when a query starts on the connection, before any of it runs. Called at most once per query, also for the + * queries DuckDB runs on behalf of another. No transaction is guaranteed to be active. * - * @param option The option. - * @param out_name Receives a borrowed pointer to the option name. Valid until the option is destroyed. - * @param out_name_length Receives the length of `*out_name` in bytes. `*out_name` is not guaranteed to be - * null-terminated. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR + * An error reported through `err` fails the query. The query still ends: the query end callbacks of all states, the + * rejecting one included, receive the error, and a transaction the query started is rolled back. Inside an explicit + * transaction the failure aborts the transaction, as any failed query does. */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_option_get_name(duckdb_v2_option_handle option, const char **out_name, - idx_t *out_name_length, duckdb_v2_error_info_handle *err); -#endif +typedef void (*duckdb_v2_context_state_query_begin_callback_fn)(duckdb_v2_context_handle context, void *user_data, + duckdb_v2_error_info_handle *err); -#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the option's static default, as a value of the option's type. + * Called when a query ends on the connection, whether it succeeded, failed or was cancelled. The place to drop what was + * only meant to last for one query. No transaction is guaranteed to be active. * - * A NULL value for an option whose declaration has no default. The caller destroys the returned value. + * The callback cannot fail: there is nothing left to fail. + */ +typedef void (*duckdb_v2_context_state_query_end_callback_fn)(duckdb_v2_context_handle context, void *user_data, + const char *error, idx_t error_length); + +/*! + * Called when a transaction starts on the connection, explicitly or automatically. The transaction is active. + * + * An error reported through `err` fails the statement starting the transaction and rolls the transaction back: the + * transaction rollback callbacks of all states run. A query whose transaction is rejected this way does not begin, and + * its query begin and end callbacks do not run. + */ +typedef void (*duckdb_v2_context_state_transaction_begin_callback_fn)(duckdb_v2_context_handle context, void *user_data, + duckdb_v2_error_info_handle *err); + +/*! + * Called when a transaction ends on the connection: after it committed, or after it was rolled back, either explicitly + * or because its statement failed. A transaction whose commit fails is reported as rolled back. No transaction is + * active any longer. + * + * The callback cannot fail: the transaction has already ended, and its fate does not depend on the callback. + */ +typedef void (*duckdb_v2_context_state_transaction_end_callback_fn)(duckdb_v2_context_handle context, void *user_data); + +/*! + * Called when the text rendering of the profile of a query is written, as `EXPLAIN ANALYZE` does, to let the state add + * to it. What the state writes comes out next to what other connection states wrote. + */ +typedef void (*duckdb_v2_context_state_profiling_callback_fn)(duckdb_v2_context_state_profile_handle profile, + void *user_data, duckdb_v2_error_info_handle *err); + +/* --- Functions for context state --- */ + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Gets the state registered under a key on the connection of a context, creating it first if there is none. + * + * The init callback sets up a new state. When several threads race to get the same key, each may run its init, but only + * one state is registered, and all of them receive it. The state lives until `duckdb_v2_context_remove_state()` or + * until the connection is destroyed, and then releases its user data through the destructor bundled with it. The data + * pointer received is the state's user data, valid for as long as the state is. + * + * Keys are case-sensitive and shared by everything that registers state on the connection, DuckDB's extensions + * included: prefix them with the name of the extension. A key held by something that is not state of this API fails the + * call. * * history: * - unstable: v2.0.0 * - * @param option The option. - * @param out_value Receives the default value. + * @param context The context whose connection to take the state from. + * @param key The key of the state. Borrowed and copied. + * @param key_length The length of `key` in bytes. `key` need not be null-terminated and may be NULL only when this is + * 0. + * @param init Sets up the state if the key has none yet. + * @param init_user_data Handed to the init callback. Borrowed for the duration of the call. + * @param data Receives the user data of the state, or null if it set none. Optional. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_option_get_default_value(duckdb_v2_option_handle option, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_get_or_create_state(duckdb_v2_context_handle context, const char *key, + idx_t key_length, + duckdb_v2_context_state_init_callback_fn init, + void *init_user_data, void **data, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Borrows the option's human-readable description. + * Gets the state registered under a key on a connection, creating it first if there is none. The same as + * `duckdb_v2_context_get_or_create_state()`, for a connection that is not seen from inside DuckDB. * * history: * - unstable: v2.0.0 * - * @param option The option. - * @param out_description Receives a borrowed pointer to the description. Valid until the option is destroyed. - * @param out_description_length Receives the length of `*out_description` in bytes. `*out_description` is not - * guaranteed to be null-terminated. + * @param conn The connection to take the state from. + * @param key The key of the state. Borrowed and copied. + * @param key_length The length of `key` in bytes. `key` need not be null-terminated and may be NULL only when this is + * 0. + * @param init Sets up the state if the key has none yet. + * @param init_user_data Handed to the init callback. Borrowed for the duration of the call. + * @param data Receives the user data of the state, or null if it set none. Optional. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_option_get_description(duckdb_v2_option_handle option, - const char **out_description, - idx_t *out_description_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_get_or_create_state(duckdb_v2_connection_handle conn, const char *key, + idx_t key_length, + duckdb_v2_context_state_init_callback_fn init, + void *init_user_data, void **data, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Reports whether the option may be written at a scope. + * Looks up the state registered under a key on the connection of a context, without creating it. * - * GLOBAL and SESSION are the scopes to ask about; DEFAULT is supported by every option that supports either. A write at - * an unsupported scope returns ERROR_INPUT_INVALID. + * `found` receives false if there is no state under the key, and `data` is then left untouched. The data pointer is + * valid until the state is removed or the connection is destroyed. * * history: * - unstable: v2.0.0 * - * @param option The option. - * @param scope The scope to ask about. - * @param out_supported Receives whether a write at the scope is accepted. + * @param context The context whose connection to look the state up on. + * @param key The key of the state. Borrowed for the duration of the call. + * @param key_length The length of `key` in bytes. `key` need not be null-terminated and may be NULL only when this is + * 0. + * @param found Receives whether the key has state. + * @param data Receives the user data of the state, or null if it set none. Optional. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_option_supports_scope(duckdb_v2_option_handle option, - DUCKDB_V2_SETTING_SCOPE scope, bool *out_supported, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_get_state(duckdb_v2_context_handle context, const char *key, + idx_t key_length, bool *found, void **data, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the scope a DEFAULT write of the option goes to: GLOBAL or SESSION. + * Looks up the state registered under a key on a connection. The same as `duckdb_v2_context_get_state()`. * * history: * - unstable: v2.0.0 * - * @param option The option. - * @param out_scope Receives the default scope. + * @param conn The connection to look the state up on. + * @param key The key of the state. Borrowed for the duration of the call. + * @param key_length The length of `key` in bytes. `key` need not be null-terminated and may be NULL only when this is + * 0. + * @param found Receives whether the key has state. + * @param data Receives the user data of the state, or null if it set none. Optional. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_option_get_default_scope(duckdb_v2_option_handle option, - DUCKDB_V2_SETTING_SCOPE *out_scope, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_get_state(duckdb_v2_connection_handle conn, const char *key, + idx_t key_length, bool *found, void **data, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of aliases registered for this option. + * Removes the state registered under a key on the connection of a context, destroying its user data. Removing a key + * that has no state is not an error. * - * Zero for an extension option; extension options carry no aliases. + * The callbacks of the state do not run for any later step of the query or transaction that is under way, and the data + * pointer handed out earlier must not be used any longer. A step already in progress, such as a query begin whose + * callback of another state removes this one, may still run the callback of this state; the user data is then released + * when that step is over. The destructor of the user data runs outside the lock of the connection's registered states, + * so it may use the connection. * * history: * - unstable: v2.0.0 * - * @param option The option. - * @param out_count Receives the alias count. + * @param context The context whose connection to remove the state from. + * @param key The key of the state. Borrowed for the duration of the call. + * @param key_length The length of `key` in bytes. `key` need not be null-terminated and may be NULL only when this is + * 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_option_get_alias_count(duckdb_v2_option_handle option, idx_t *out_count, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_remove_state(duckdb_v2_context_handle context, const char *key, + idx_t key_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Borrows the alias name at the given index. - * - * An out-of-range index returns ERROR_INPUT_INVALID. + * Removes the state registered under a key on a connection. The same as `duckdb_v2_context_remove_state()`. * * history: * - unstable: v2.0.0 * - * @param option The option. - * @param index The alias index, in [0, alias_count). - * @param out_alias Receives a borrowed pointer to the alias. Valid until the option is destroyed. - * @param out_alias_length Receives the length of `*out_alias` in bytes. `*out_alias` is not guaranteed to be - * null-terminated. + * @param conn The connection to remove the state from. + * @param key The key of the state. Borrowed for the duration of the call. + * @param key_length The length of `key` in bytes. `key` need not be null-terminated and may be NULL only when this is + * 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_option_get_alias(duckdb_v2_option_handle option, idx_t index, - const char **out_alias, idx_t *out_alias_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_remove_state(duckdb_v2_connection_handle conn, const char *key, + idx_t key_length, duckdb_v2_error_info_handle *err); #endif -/* --- Struct definitions for configuration --- */ - -/* ============================================================================ - * MODULE: connection - * ============================================================================ */ - -/* --- Enums for connection --- */ - -/* --- Struct forward declarations for connection --- */ - -/* --- Types for connection --- */ - -/* --- Constants for connection --- */ - -/* --- Function pointer typedefs for connection --- */ - -/* --- Functions for connection --- */ - #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Opens a connection to an instance. + * Sets the user data of the state, handed to all of its callbacks. * - * Each connection carries its own client context and session-scoped (LOCAL) settings. Connections to the same instance - * share its catalog, buffer pool, and transaction manager. A connection may be created before any database is attached - * to the instance; until one is, only the system catalog and the connection's temporary catalog are visible. The caller - * destroys it via `duckdb_v2_connection_destroy()`. + * The opaque handle bundles the pointer with an optional destructor, invoked when the state is removed or its + * connection is destroyed. If the state could not be created after all, because its init callback reported an error or + * the key got registered meanwhile, the destructor is invoked right away. * * history: * - unstable: v2.0.0 * - * @param instance The instance to connect to. - * @param out_conn Receives the new connection handle. + * @param state The state to set the user data of. + * @param data Opaque handle bundling the user data pointer plus an optional destructor. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_create(duckdb_v2_instance_handle instance, - duckdb_v2_connection_handle *out_conn, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_state_set_user_data(duckdb_v2_context_state_handle state, + duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Opens a connection that runs in the transaction of a context. - * - * Lets a callback run SQL inside the transaction it is called in, such as a table function's bind callback reading a - * table. The connection sees everything the context's transaction sees, including its uncommitted changes and the - * context's temporary objects, and what it changes is part of that transaction. A statement of the connection that - * fails invalidates the transaction as a failure of the context's own statement would. It starts with the context's - * search path (`USE`, `SET schema`, `SET search_path`), so unqualified names resolve as they do in the context's own - * statements. - * - * The connection cannot start, commit or roll back a transaction: those statements fail with - * ERROR_DATABASE_TRANSACTION, and like any failing statement invalidate the transaction. The connection stays in the - * transaction until it is destroyed, which neither commits nor rolls the transaction back. Destroy it before the - * transaction ends, typically before the callback returns: a transaction that is committed while such a connection is - * still open is rolled back instead, and the connection's statements fail from then on. Interrupting the context's - * query also interrupts the connection's. The caller destroys it via `duckdb_v2_connection_destroy()`. + * Sets the callback called when a query starts on the connection. * * history: * - unstable: v2.0.0 * - * @param ctx The context whose transaction the connection runs in. It must have an active transaction. - * @param out_conn Receives the new connection handle. + * @param state The state to set the callback of. + * @param callback The callback. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_create_in_transaction(duckdb_v2_context_handle ctx, - duckdb_v2_connection_handle *out_conn, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_state_set_query_begin_callback( + duckdb_v2_context_state_handle state, duckdb_v2_context_state_query_begin_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys the connection. - * - * Always succeeds. Releases the connection's reference on the underlying database instance, which survives for as long - * as anything else still references it. On success the handle is set to null. Safe to call on an already-null slot. + * Sets the callback called when a query ends on the connection. * * history: * - unstable: v2.0.0 * - * @param conn The connection to destroy. + * @param state The state to set the callback of. + * @param callback The callback. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_destroy(duckdb_v2_connection_handle *conn); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_state_set_query_end_callback( + duckdb_v2_context_state_handle state, duckdb_v2_context_state_query_end_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Interrupts the query currently executing on the connection. - * - * The cross-thread (but not cross-connection) cancellation entry point for streaming results: safe to call from any - * thread within the execution of a query through a connection, including while another thread steps the query's result. - * A no-op when no query is active. Cancellation surfaces on the consuming side as step status CANCELLED - * (`duckdb_v2_result_step()`), or as ERROR_RUNTIME_INTERRUPT (`duckdb_v2_result_fetch_chunk()`). + * Sets the callback called when a transaction starts on the connection. * * history: * - unstable: v2.0.0 * - * @param conn The connection whose active query to interrupt. + * @param state The state to set the callback of. + * @param callback The callback. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_interrupt(duckdb_v2_connection_handle conn, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_state_set_transaction_begin_callback( + duckdb_v2_context_state_handle state, duckdb_v2_context_state_transaction_begin_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Captures a snapshot of the active query's execution progress. + * Sets the callback called when a transaction on the connection committed. * - * Reads the percentage and row counts from one consistent snapshot of the query currently executing on the connection. - * Safe to call from any thread, including while another thread steps the query's result. + * history: + * - unstable: v2.0.0 * - * Progress is published only when the enable_progress_bar option is set; the bridge does not enable tracking itself. - * Both row counts are 0 when no information is available. The percentage is -1 when tracking is disabled, no query is - * active, or no progress has been published yet. + * @param state The state to set the callback of. + * @param callback The callback. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_state_set_transaction_commit_callback( + duckdb_v2_context_state_handle state, duckdb_v2_context_state_transaction_end_callback_fn callback, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the callback called when a transaction on the connection was rolled back. * * history: * - unstable: v2.0.0 * - * @param conn The connection. - * @param out_percentage Receives the percentage complete in [0, 100], -1 if tracking is disabled, no query is active, - * or no progress has been published yet. - * @param out_rows_processed Receives the number of rows processed so far. - * @param out_total_rows_to_process Receives the total number of rows the query will process. + * @param state The state to set the callback of. + * @param callback The callback. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_progress_get(duckdb_v2_connection_handle conn, double *out_percentage, - uint64_t *out_rows_processed, - uint64_t *out_total_rows_to_process, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_state_set_transaction_rollback_callback( + duckdb_v2_context_state_handle state, duckdb_v2_context_state_transaction_end_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif -/* --- Struct definitions for connection --- */ +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the callback called when the profile of a query is written, to let the state add to it. + * + * history: + * - unstable: v2.0.0 + * + * @param state The state to set the callback of. + * @param callback The callback. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_state_set_profiling_callback( + duckdb_v2_context_state_handle state, duckdb_v2_context_state_profiling_callback_fn callback, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Adds text to the profile being written. The text is borrowed and copied. + * + * history: + * - unstable: v2.0.0 + * + * @param profile The profile to add to. + * @param text The text to add. + * @param text_length The length of `text` in bytes. `text` need not be null-terminated and may be NULL only when this + * is 0. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_state_profile_write(duckdb_v2_context_state_profile_handle profile, + const char *text, idx_t text_length, + duckdb_v2_error_info_handle *err); +#endif + +/* --- Struct definitions for context state --- */ /* ============================================================================ - * MODULE: context state + * MODULE: crypto * ============================================================================ */ -/* --- Enums for context state --- */ +/* --- Enums for crypto --- */ -/* --- Struct forward declarations for context state --- */ +//! A cipher, meaning an algorithm together with its mode of operation. New ciphers are new values. +typedef enum DUCKDB_V2_CRYPTO_CIPHER { + //! AES-GCM. 12-byte IV, optional additional authenticated data, 16-byte authentication tag. + DUCKDB_V2_CRYPTO_CIPHER_AES_GCM = 1, -/* --- Types for context state --- */ + //! AES-CTR. 16-byte IV (initial counter block), no authentication tag. + DUCKDB_V2_CRYPTO_CIPHER_AES_CTR = 2, + DUCKDB_V2_CRYPTO_CIPHER_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_CRYPTO_CIPHER; + +//! The direction of a cipher stream. +typedef enum DUCKDB_V2_CRYPTO_MODE { + //! Encrypt plaintext into ciphertext. + DUCKDB_V2_CRYPTO_MODE_ENCRYPT = 0, + + //! Decrypt ciphertext into plaintext. + DUCKDB_V2_CRYPTO_MODE_DECRYPT = 1, + DUCKDB_V2_CRYPTO_MODE_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_CRYPTO_MODE; + +//! A hash function, for hashing and HMAC. +typedef enum DUCKDB_V2_CRYPTO_HASH_FUNCTION { + //! MD5, 16-byte digest. Not collision resistant; for legacy formats only. + DUCKDB_V2_CRYPTO_HASH_MD5 = 0, + + //! SHA-1, 20-byte digest. Not collision resistant; for legacy formats only. + DUCKDB_V2_CRYPTO_HASH_SHA1 = 1, + + //! SHA-256, 32-byte digest. + DUCKDB_V2_CRYPTO_HASH_SHA256 = 2, + DUCKDB_V2_CRYPTO_HASH_FUNCTION_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_CRYPTO_HASH_FUNCTION; + +/* --- Struct forward declarations for crypto --- */ + +/* --- Types for crypto --- */ /*! - * A borrowed opaque handle to connection state being set up, received by the init callback of - * `duckdb_v2_context_get_or_create_state()` or `duckdb_v2_connection_get_or_create_state()` and valid only for the - * duration of that call. Configure it with `duckdb_v2_context_state_set_user_data()` and the callback setters; whatever - * is not set stays inert. + * An owned opaque handle to a streaming cipher (see `CRYPTO_CIPHER`). Created with `duckdb_v2_crypto_cipher_create()`, + * initialized with `duckdb_v2_crypto_cipher_init()`, fed with `duckdb_v2_crypto_cipher_update()`, completed with + * `duckdb_v2_crypto_cipher_finalize()`, and destroyed with `duckdb_v2_crypto_cipher_destroy()`. Not safe for concurrent + * use. */ -typedef struct _duckdb_v2_context_state { +typedef struct _duckdb_v2_crypto_cipher { void *internal_ptr; -} * duckdb_v2_context_state_handle; +} * duckdb_v2_crypto_cipher_handle; /*! - * A borrowed opaque handle to the profile of the query that just ended, received by a connection state's profiling - * callback and valid only for the duration of that call. Add text to it with `duckdb_v2_context_state_profile_write()`. + * An owned opaque handle to a crypto provider being built. Created with `duckdb_v2_crypto_provider_create()`, + * configured with the setters, registered with `duckdb_v2_instance_register_crypto_provider()` or + * `duckdb_v2_extension_register_crypto_provider()`, and destroyed with `duckdb_v2_crypto_provider_destroy()`. */ -typedef struct _duckdb_v2_context_state_profile { +typedef struct _duckdb_v2_crypto_provider { void *internal_ptr; -} * duckdb_v2_context_state_profile_handle; +} * duckdb_v2_crypto_provider_handle; -/* --- Constants for context state --- */ +/* --- Constants for crypto --- */ -/* --- Function pointer typedefs for context state --- */ +/* --- Function pointer typedefs for crypto --- */ -/*! - * Sets up the connection state of a key that has none yet. - * - * Runs outside the lock of the connection's registered states, so it may use the context, state functions included. - * When the key gets registered while the init runs, by another thread or by the init itself, the state registered first - * is kept, and the one this init set up is released as if the init had failed. A failure reported through `err` leaves - * the key unregistered and fails the call that triggered the init. - */ -typedef void (*duckdb_v2_context_state_init_callback_fn)(duckdb_v2_context_handle context, void *user_data, - duckdb_v2_context_state_handle state, - duckdb_v2_error_info_handle *err); +typedef void (*duckdb_v2_crypto_provider_cipher_create_callback_fn)(void *user_data, DUCKDB_V2_CRYPTO_CIPHER cipher, + DUCKDB_V2_CRYPTO_MODE mode, const uint8_t *key, + idx_t key_length, void **stream, + duckdb_v2_error_info_handle *err); -/*! - * Called when a query starts on the connection, before any of it runs. Called at most once per query, also for the - * queries DuckDB runs on behalf of another. No transaction is guaranteed to be active. - * - * An error reported through `err` fails the query. The query still ends: the query end callbacks of all states, the - * rejecting one included, receive the error, and a transaction the query started is rolled back. Inside an explicit - * transaction the failure aborts the transaction, as any failed query does. - */ -typedef void (*duckdb_v2_context_state_query_begin_callback_fn)(duckdb_v2_context_handle context, void *user_data, - duckdb_v2_error_info_handle *err); +typedef void (*duckdb_v2_crypto_provider_cipher_init_callback_fn)(void *user_data, void *stream, const uint8_t *iv, + idx_t iv_length, const uint8_t *aad, idx_t aad_length, + duckdb_v2_error_info_handle *err); -/*! - * Called when a query ends on the connection, whether it succeeded, failed or was cancelled. The place to drop what was - * only meant to last for one query. No transaction is guaranteed to be active. - * - * The callback cannot fail: there is nothing left to fail. - */ -typedef void (*duckdb_v2_context_state_query_end_callback_fn)(duckdb_v2_context_handle context, void *user_data, - const char *error, idx_t error_length); +typedef void (*duckdb_v2_crypto_provider_cipher_update_callback_fn)(void *user_data, void *stream, const uint8_t *in, + idx_t in_length, uint8_t *out, idx_t out_capacity, + idx_t *out_length, + duckdb_v2_error_info_handle *err); -/*! - * Called when a transaction starts on the connection, explicitly or automatically. The transaction is active. - * - * An error reported through `err` fails the statement starting the transaction and rolls the transaction back: the - * transaction rollback callbacks of all states run. A query whose transaction is rejected this way does not begin, and - * its query begin and end callbacks do not run. - */ -typedef void (*duckdb_v2_context_state_transaction_begin_callback_fn)(duckdb_v2_context_handle context, void *user_data, +typedef void (*duckdb_v2_crypto_provider_cipher_finalize_callback_fn)(void *user_data, void *stream, uint8_t *tag, + idx_t tag_length, duckdb_v2_error_info_handle *err); -/*! - * Called when a transaction ends on the connection: after it committed, or after it was rolled back, either explicitly - * or because its statement failed. A transaction whose commit fails is reported as rolled back. No transaction is - * active any longer. - * - * The callback cannot fail: the transaction has already ended, and its fate does not depend on the callback. - */ -typedef void (*duckdb_v2_context_state_transaction_end_callback_fn)(duckdb_v2_context_handle context, void *user_data); +typedef void (*duckdb_v2_crypto_provider_cipher_destroy_callback_fn)(void *user_data, void *stream); -/*! - * Called when the text rendering of the profile of a query is written, as `EXPLAIN ANALYZE` does, to let the state add - * to it. What the state writes comes out next to what other connection states wrote. - */ -typedef void (*duckdb_v2_context_state_profiling_callback_fn)(duckdb_v2_context_state_profile_handle profile, - void *user_data, duckdb_v2_error_info_handle *err); +typedef void (*duckdb_v2_crypto_provider_hash_callback_fn)(void *user_data, DUCKDB_V2_CRYPTO_HASH_FUNCTION function, + const uint8_t *in, idx_t in_length, uint8_t *out, + duckdb_v2_error_info_handle *err); -/* --- Functions for context state --- */ +typedef void (*duckdb_v2_crypto_provider_hmac_callback_fn)(void *user_data, DUCKDB_V2_CRYPTO_HASH_FUNCTION function, + const uint8_t *key, idx_t key_length, const uint8_t *in, + idx_t in_length, uint8_t *out, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_crypto_provider_random_callback_fn)(void *user_data, uint8_t *out, idx_t length, + duckdb_v2_error_info_handle *err); + +/* --- Functions for crypto --- */ #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Gets the state registered under a key on the connection of a context, creating it first if there is none. - * - * The init callback sets up a new state. When several threads race to get the same key, each may run its init, but only - * one state is registered, and all of them receive it. The state lives until `duckdb_v2_context_remove_state()` or - * until the connection is destroyed, and then releases its user data through the destructor bundled with it. The data - * pointer received is the state's user data, valid for as long as the state is. - * - * Keys are case-sensitive and shared by everything that registers state on the connection, DuckDB's extensions - * included: prefix them with the name of the extension. A key held by something that is not state of this API fails the - * call. + * Retrieves the size in bytes of the digest, and of the HMAC, of a hash function. * * history: * - unstable: v2.0.0 * - * @param context The context whose connection to take the state from. - * @param key The key of the state. Borrowed and copied. - * @param key_length The length of `key` in bytes. `key` need not be null-terminated and may be NULL only when this is - * 0. - * @param init Sets up the state if the key has none yet. - * @param init_user_data Handed to the init callback. Borrowed for the duration of the call. - * @param data Receives the user data of the state, or null if it set none. Optional. + * @param function The hash function. + * @param size Receives the size in bytes. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_get_or_create_state(duckdb_v2_context_handle context, const char *key, - idx_t key_length, - duckdb_v2_context_state_init_callback_fn init, - void *init_user_data, void **data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_hash_digest_size(DUCKDB_V2_CRYPTO_HASH_FUNCTION function, idx_t *size, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Gets the state registered under a key on a connection, creating it first if there is none. The same as - * `duckdb_v2_context_get_or_create_state()`, for a connection that is not seen from inside DuckDB. + * Retrieves whether the instance's crypto provider supports hashing with the function. * * history: * - unstable: v2.0.0 * - * @param conn The connection to take the state from. - * @param key The key of the state. Borrowed and copied. - * @param key_length The length of `key` in bytes. `key` need not be null-terminated and may be NULL only when this is - * 0. - * @param init Sets up the state if the key has none yet. - * @param init_user_data Handed to the init callback. Borrowed for the duration of the call. - * @param data Receives the user data of the state, or null if it set none. Optional. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param instance The instance whose provider to ask. + * @param function The hash function. + * @param supported Receives whether hashing is supported. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_get_or_create_state(duckdb_v2_connection_handle conn, const char *key, - idx_t key_length, - duckdb_v2_context_state_init_callback_fn init, - void *init_user_data, void **data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_supports_hash(duckdb_v2_instance_handle instance, + DUCKDB_V2_CRYPTO_HASH_FUNCTION function, bool *supported, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Looks up the state registered under a key on the connection of a context, without creating it. - * - * `found` receives false if there is no state under the key, and `data` is then left untouched. The data pointer is - * valid until the state is removed or the connection is destroyed. + * Retrieves whether the instance's crypto provider supports HMAC with the function. * * history: * - unstable: v2.0.0 * - * @param context The context whose connection to look the state up on. - * @param key The key of the state. Borrowed for the duration of the call. - * @param key_length The length of `key` in bytes. `key` need not be null-terminated and may be NULL only when this is - * 0. - * @param found Receives whether the key has state. - * @param data Receives the user data of the state, or null if it set none. Optional. + * @param instance The instance whose provider to ask. + * @param function The hash function. + * @param supported Receives whether HMAC is supported. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_get_state(duckdb_v2_context_handle context, const char *key, - idx_t key_length, bool *found, void **data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_supports_hmac(duckdb_v2_instance_handle instance, + DUCKDB_V2_CRYPTO_HASH_FUNCTION function, bool *supported, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Looks up the state registered under a key on a connection. The same as `duckdb_v2_context_get_state()`. + * Hashes `data` with the instance's crypto provider. + * + * Fails if the provider does not support the function; see `duckdb_v2_crypto_supports_hash()`. * * history: * - unstable: v2.0.0 * - * @param conn The connection to look the state up on. - * @param key The key of the state. Borrowed for the duration of the call. - * @param key_length The length of `key` in bytes. `key` need not be null-terminated and may be NULL only when this is - * 0. - * @param found Receives whether the key has state. - * @param data Receives the user data of the state, or null if it set none. Optional. + * @param instance The instance whose provider to use. + * @param function The hash function. + * @param data The bytes to hash. May be null if `length` is 0. + * @param length The number of bytes. + * @param digest Receives the digest. + * @param digest_capacity The capacity of `digest`, at least `duckdb_v2_crypto_hash_digest_size()`. + * @param digest_length Receives the number of digest bytes written. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_get_state(duckdb_v2_connection_handle conn, const char *key, - idx_t key_length, bool *found, void **data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_hash(duckdb_v2_instance_handle instance, + DUCKDB_V2_CRYPTO_HASH_FUNCTION function, const uint8_t *data, + idx_t length, uint8_t *digest, idx_t digest_capacity, + idx_t *digest_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Removes the state registered under a key on the connection of a context, destroying its user data. Removing a key - * that has no state is not an error. + * Computes the HMAC of `data` under `key` with the instance's crypto provider. * - * The callbacks of the state do not run for any later step of the query or transaction that is under way, and the data - * pointer handed out earlier must not be used any longer. A step already in progress, such as a query begin whose - * callback of another state removes this one, may still run the callback of this state; the user data is then released - * when that step is over. The destructor of the user data runs outside the lock of the connection's registered states, - * so it may use the connection. + * Fails if the provider does not support the function; see `duckdb_v2_crypto_supports_hmac()`. * * history: * - unstable: v2.0.0 * - * @param context The context whose connection to remove the state from. - * @param key The key of the state. Borrowed for the duration of the call. - * @param key_length The length of `key` in bytes. `key` need not be null-terminated and may be NULL only when this is - * 0. + * @param instance The instance whose provider to use. + * @param function The hash function. + * @param key The HMAC key. + * @param key_length The key length in bytes. + * @param data The bytes to authenticate. May be null if `length` is 0. + * @param length The number of bytes. + * @param mac Receives the MAC. + * @param mac_capacity The capacity of `mac`, at least `duckdb_v2_crypto_hash_digest_size()`. + * @param mac_length Receives the number of MAC bytes written. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_remove_state(duckdb_v2_context_handle context, const char *key, - idx_t key_length, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_hmac(duckdb_v2_instance_handle instance, + DUCKDB_V2_CRYPTO_HASH_FUNCTION function, const uint8_t *key, + idx_t key_length, const uint8_t *data, idx_t length, uint8_t *mac, + idx_t mac_capacity, idx_t *mac_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Removes the state registered under a key on a connection. The same as `duckdb_v2_context_remove_state()`. + * Fills `data` with cryptographically secure random bytes from the instance's crypto provider, e.g. for IVs. + * + * Fails when the instance has no provider DuckDB considers secure for writing; see the module notes. * * history: * - unstable: v2.0.0 * - * @param conn The connection to remove the state from. - * @param key The key of the state. Borrowed for the duration of the call. - * @param key_length The length of `key` in bytes. `key` need not be null-terminated and may be NULL only when this is - * 0. + * @param instance The instance whose provider to use. + * @param data Receives the random bytes. + * @param length The number of bytes to produce. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_remove_state(duckdb_v2_connection_handle conn, const char *key, - idx_t key_length, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_random_bytes(duckdb_v2_instance_handle instance, uint8_t *data, + idx_t length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the user data of the state, handed to all of its callbacks. + * Creates a streaming cipher. * - * The opaque handle bundles the pointer with an optional destructor, invoked when the state is removed or its - * connection is destroyed. If the state could not be created after all, because its init callback reported an error or - * the key got registered meanwhile, the destructor is invoked right away. + * The key is copied and wiped when the cipher is destroyed. Encrypting requires a provider DuckDB considers secure for + * writing; decrypting does not. The cipher must be initialized with `duckdb_v2_crypto_cipher_init()` before use. * * history: * - unstable: v2.0.0 * - * @param state The state to set the user data of. - * @param data Opaque handle bundling the user data pointer plus an optional destructor. + * @param instance The instance whose provider to use. + * @param cipher The cipher. + * @param mode Whether to encrypt or decrypt. + * @param key The key. Borrowed and copied. + * @param key_length The key length in bytes: 16, 24 or 32. + * @param stream On success, receives the new cipher. Owned by the caller. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_state_set_user_data(duckdb_v2_context_state_handle state, - duckdb_v2_opaque *data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_cipher_create(duckdb_v2_instance_handle instance, + DUCKDB_V2_CRYPTO_CIPHER cipher, DUCKDB_V2_CRYPTO_MODE mode, + const uint8_t *key, idx_t key_length, + duckdb_v2_crypto_cipher_handle *stream, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the callback called when a query starts on the connection. + * Starts the stream with an IV and, for GCM, additional authenticated data. + * + * The IV length and AAD support depend on the cipher: AES-GCM takes a 12-byte IV and optional AAD, AES-CTR a 16-byte IV + * and no AAD. May be called once per cipher. * * history: * - unstable: v2.0.0 * - * @param state The state to set the callback of. - * @param callback The callback. + * @param stream The cipher. + * @param iv The IV. Borrowed. + * @param iv_length The IV length in bytes. + * @param aad The additional authenticated data, or null. Borrowed. + * @param aad_length The AAD length in bytes, 0 if none. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_state_set_query_begin_callback( - duckdb_v2_context_state_handle state, duckdb_v2_context_state_query_begin_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_cipher_init(duckdb_v2_crypto_cipher_handle stream, const uint8_t *iv, + idx_t iv_length, const uint8_t *aad, idx_t aad_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the callback called when a query ends on the connection. + * Processes the next chunk of the stream. + * + * Once an update or finalize fails in the provider, the cipher rejects every further call and can only be destroyed. + * `out_capacity` must be at least `in_length`. `in` and `out` may be the same buffer. For decryption with GCM, the + * plaintext must not be trusted before `duckdb_v2_crypto_cipher_finalize()` succeeds. * * history: * - unstable: v2.0.0 * - * @param state The state to set the callback of. - * @param callback The callback. + * @param stream The cipher. + * @param in The input bytes. + * @param in_length The number of input bytes. + * @param out Receives the output bytes. + * @param out_capacity The capacity of `out` in bytes. + * @param out_length Receives the number of bytes written. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_state_set_query_end_callback( - duckdb_v2_context_state_handle state, duckdb_v2_context_state_query_end_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_cipher_update(duckdb_v2_crypto_cipher_handle stream, const uint8_t *in, + idx_t in_length, uint8_t *out, idx_t out_capacity, + idx_t *out_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the callback called when a transaction starts on the connection. + * Completes the stream. + * + * GCM encryption: writes the 16-byte authentication tag into `tag`. GCM decryption: verifies the 16-byte `tag`, failing + * with an input error when it does not match, after which the cipher can only be destroyed. CTR: `tag` must be null and + * `tag_length` 0. * * history: * - unstable: v2.0.0 * - * @param state The state to set the callback of. - * @param callback The callback. + * @param stream The cipher. + * @param tag The tag buffer (GCM), or null. + * @param tag_length The tag length in bytes - 16 for GCM, 0 for CTR. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_state_set_transaction_begin_callback( - duckdb_v2_context_state_handle state, duckdb_v2_context_state_transaction_begin_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_cipher_finalize(duckdb_v2_crypto_cipher_handle stream, uint8_t *tag, + idx_t tag_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the callback called when a transaction on the connection committed. + * Destroys the cipher, wiping its key. Null-safe; the handle is set to null on return. * * history: * - unstable: v2.0.0 * - * @param state The state to set the callback of. - * @param callback The callback. + * @param stream The cipher to destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_cipher_destroy(duckdb_v2_crypto_cipher_handle *stream); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Creates a new, empty crypto provider through a factory. + * + * The provider can only be registered on the instance the factory belongs to. The caller owns the handle and must + * destroy it with `duckdb_v2_crypto_provider_destroy()`, also after registration. + * + * history: + * - unstable: v2.0.0 + * + * @param factory The factory to create the provider through. + * @param provider On success, receives the new provider. Owned by the caller. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_state_set_transaction_commit_callback( - duckdb_v2_context_state_handle state, duckdb_v2_context_state_transaction_end_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_provider_create(duckdb_v2_factory_handle factory, + duckdb_v2_crypto_provider_handle *provider, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the callback called when a transaction on the connection was rolled back. + * Sets user data handed to every callback of the provider, destroyed with the registered provider (or with the handle + * if never registered). * * history: * - unstable: v2.0.0 * - * @param state The state to set the callback of. - * @param callback The callback. + * @param provider The provider. + * @param data Opaque handle bundling the user data pointer plus an optional destructor. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_state_set_transaction_rollback_callback( - duckdb_v2_context_state_handle state, duckdb_v2_context_state_transaction_end_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_provider_set_user_data(duckdb_v2_crypto_provider_handle provider, + duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the callback called when the profile of a query is written, to let the state add to it. + * Sets the callback that creates a cipher stream. + * + * The create, init, update and finalize callbacks are required before registration, and together must support every + * `CRYPTO_CIPHER` value: currently AES-GCM and AES-CTR, with 16-, 24- and 32-byte keys. * * history: * - unstable: v2.0.0 * - * @param state The state to set the callback of. - * @param callback The callback. + * @param provider The provider. + * @param callback The create callback to set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_state_set_profiling_callback( - duckdb_v2_context_state_handle state, duckdb_v2_context_state_profiling_callback_fn callback, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_provider_set_cipher_create_callback( + duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_cipher_create_callback_fn callback, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Adds text to the profile being written. The text is borrowed and copied. + * Sets the callback that starts a cipher stream. + * + * The callback must accept 16-byte GCM IVs: encrypted databases in the legacy v0 format use them, unlike + * `duckdb_v2_crypto_cipher_init()`, which takes 12. * * history: * - unstable: v2.0.0 * - * @param profile The profile to add to. - * @param text The text to add. - * @param text_length The length of `text` in bytes. `text` need not be null-terminated and may be NULL only when this - * is 0. + * @param provider The provider. + * @param callback The init callback to set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_state_profile_write(duckdb_v2_context_state_profile_handle profile, - const char *text, idx_t text_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_provider_set_cipher_init_callback( + duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_cipher_init_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif -/* --- Struct definitions for context state --- */ - -/* ============================================================================ - * MODULE: crypto - * ============================================================================ */ - -/* --- Enums for crypto --- */ - -//! A cipher, meaning an algorithm together with its mode of operation. New ciphers are new values. -typedef enum DUCKDB_V2_CRYPTO_CIPHER { - //! AES-GCM. 12-byte IV, optional additional authenticated data, 16-byte authentication tag. - DUCKDB_V2_CRYPTO_CIPHER_AES_GCM = 1, - - //! AES-CTR. 16-byte IV (initial counter block), no authentication tag. - DUCKDB_V2_CRYPTO_CIPHER_AES_CTR = 2, - DUCKDB_V2_CRYPTO_CIPHER_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_CRYPTO_CIPHER; - -//! The direction of a cipher stream. -typedef enum DUCKDB_V2_CRYPTO_MODE { - //! Encrypt plaintext into ciphertext. - DUCKDB_V2_CRYPTO_MODE_ENCRYPT = 0, - - //! Decrypt ciphertext into plaintext. - DUCKDB_V2_CRYPTO_MODE_DECRYPT = 1, - DUCKDB_V2_CRYPTO_MODE_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_CRYPTO_MODE; - -//! A hash function, for hashing and HMAC. -typedef enum DUCKDB_V2_CRYPTO_HASH_FUNCTION { - //! MD5, 16-byte digest. Not collision resistant; for legacy formats only. - DUCKDB_V2_CRYPTO_HASH_MD5 = 0, - - //! SHA-1, 20-byte digest. Not collision resistant; for legacy formats only. - DUCKDB_V2_CRYPTO_HASH_SHA1 = 1, - - //! SHA-256, 32-byte digest. - DUCKDB_V2_CRYPTO_HASH_SHA256 = 2, - DUCKDB_V2_CRYPTO_HASH_FUNCTION_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_CRYPTO_HASH_FUNCTION; - -/* --- Struct forward declarations for crypto --- */ - -/* --- Types for crypto --- */ - -/*! - * An owned opaque handle to a streaming cipher (see `CRYPTO_CIPHER`). Created with `duckdb_v2_crypto_cipher_create()`, - * initialized with `duckdb_v2_crypto_cipher_init()`, fed with `duckdb_v2_crypto_cipher_update()`, completed with - * `duckdb_v2_crypto_cipher_finalize()`, and destroyed with `duckdb_v2_crypto_cipher_destroy()`. Not safe for concurrent - * use. - */ -typedef struct _duckdb_v2_crypto_cipher { - void *internal_ptr; -} * duckdb_v2_crypto_cipher_handle; - -/*! - * An owned opaque handle to a crypto provider being built. Created with `duckdb_v2_crypto_provider_create()`, - * configured with the setters, registered with `duckdb_v2_instance_register_crypto_provider()` or - * `duckdb_v2_extension_register_crypto_provider()`, and destroyed with `duckdb_v2_crypto_provider_destroy()`. - */ -typedef struct _duckdb_v2_crypto_provider { - void *internal_ptr; -} * duckdb_v2_crypto_provider_handle; - -/* --- Constants for crypto --- */ - -/* --- Function pointer typedefs for crypto --- */ - -typedef void (*duckdb_v2_crypto_provider_cipher_create_callback_fn)(void *user_data, DUCKDB_V2_CRYPTO_CIPHER cipher, - DUCKDB_V2_CRYPTO_MODE mode, const uint8_t *key, - idx_t key_length, void **stream, - duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_crypto_provider_cipher_init_callback_fn)(void *user_data, void *stream, const uint8_t *iv, - idx_t iv_length, const uint8_t *aad, idx_t aad_length, - duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_crypto_provider_cipher_update_callback_fn)(void *user_data, void *stream, const uint8_t *in, - idx_t in_length, uint8_t *out, idx_t out_capacity, - idx_t *out_length, - duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_crypto_provider_cipher_finalize_callback_fn)(void *user_data, void *stream, uint8_t *tag, - idx_t tag_length, - duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_crypto_provider_cipher_destroy_callback_fn)(void *user_data, void *stream); - -typedef void (*duckdb_v2_crypto_provider_hash_callback_fn)(void *user_data, DUCKDB_V2_CRYPTO_HASH_FUNCTION function, - const uint8_t *in, idx_t in_length, uint8_t *out, - duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_crypto_provider_hmac_callback_fn)(void *user_data, DUCKDB_V2_CRYPTO_HASH_FUNCTION function, - const uint8_t *key, idx_t key_length, const uint8_t *in, - idx_t in_length, uint8_t *out, - duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_crypto_provider_random_callback_fn)(void *user_data, uint8_t *out, idx_t length, - duckdb_v2_error_info_handle *err); - -/* --- Functions for crypto --- */ - #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the size in bytes of the digest, and of the HMAC, of a hash function. + * Sets the callback that processes a chunk of a cipher stream. * * history: * - unstable: v2.0.0 * - * @param function The hash function. - * @param size Receives the size in bytes. + * @param provider The provider. + * @param callback The update callback to set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_hash_digest_size(DUCKDB_V2_CRYPTO_HASH_FUNCTION function, idx_t *size, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_provider_set_cipher_update_callback( + duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_cipher_update_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves whether the instance's crypto provider supports hashing with the function. + * Sets the callback that completes a cipher stream. * * history: * - unstable: v2.0.0 * - * @param instance The instance whose provider to ask. - * @param function The hash function. - * @param supported Receives whether hashing is supported. + * @param provider The provider. + * @param callback The finalize callback to set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_supports_hash(duckdb_v2_instance_handle instance, - DUCKDB_V2_CRYPTO_HASH_FUNCTION function, bool *supported, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_provider_set_cipher_finalize_callback( + duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_cipher_finalize_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves whether the instance's crypto provider supports HMAC with the function. + * Sets the optional callback that releases a cipher stream. * * history: * - unstable: v2.0.0 * - * @param instance The instance whose provider to ask. - * @param function The hash function. - * @param supported Receives whether HMAC is supported. + * @param provider The provider. + * @param callback Optional. The destroy callback to set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_supports_hmac(duckdb_v2_instance_handle instance, - DUCKDB_V2_CRYPTO_HASH_FUNCTION function, bool *supported, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_provider_set_cipher_destroy_callback( + duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_cipher_destroy_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Hashes `data` with the instance's crypto provider. - * - * Fails if the provider does not support the function; see `duckdb_v2_crypto_supports_hash()`. + * Sets the hash callback and the functions it supports. Optional: DuckDB's built-in implementation serves every + * function the callback does not declare. * * history: * - unstable: v2.0.0 * - * @param instance The instance whose provider to use. - * @param function The hash function. - * @param data The bytes to hash. May be null if `length` is 0. - * @param length The number of bytes. - * @param digest Receives the digest. - * @param digest_capacity The capacity of `digest`, at least `duckdb_v2_crypto_hash_digest_size()`. - * @param digest_length Receives the number of digest bytes written. + * @param provider The provider. + * @param callback The callback. + * @param functions The functions the callback supports. Borrowed and copied. + * @param function_count The number of functions. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_hash(duckdb_v2_instance_handle instance, - DUCKDB_V2_CRYPTO_HASH_FUNCTION function, const uint8_t *data, - idx_t length, uint8_t *digest, idx_t digest_capacity, - idx_t *digest_length, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_provider_set_hash_callback( + duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_hash_callback_fn callback, + const DUCKDB_V2_CRYPTO_HASH_FUNCTION *functions, idx_t function_count, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Computes the HMAC of `data` under `key` with the instance's crypto provider. - * - * Fails if the provider does not support the function; see `duckdb_v2_crypto_supports_hmac()`. + * Sets the HMAC callback and the functions it supports. Optional: DuckDB's built-in implementation serves every + * function the callback does not declare. * * history: * - unstable: v2.0.0 * - * @param instance The instance whose provider to use. - * @param function The hash function. - * @param key The HMAC key. - * @param key_length The key length in bytes. - * @param data The bytes to authenticate. May be null if `length` is 0. - * @param length The number of bytes. - * @param mac Receives the MAC. - * @param mac_capacity The capacity of `mac`, at least `duckdb_v2_crypto_hash_digest_size()`. - * @param mac_length Receives the number of MAC bytes written. + * @param provider The provider. + * @param callback The callback. + * @param functions The functions the callback supports. Borrowed and copied. + * @param function_count The number of functions. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_hmac(duckdb_v2_instance_handle instance, - DUCKDB_V2_CRYPTO_HASH_FUNCTION function, const uint8_t *key, - idx_t key_length, const uint8_t *data, idx_t length, uint8_t *mac, - idx_t mac_capacity, idx_t *mac_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_provider_set_hmac_callback( + duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_hmac_callback_fn callback, + const DUCKDB_V2_CRYPTO_HASH_FUNCTION *functions, idx_t function_count, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Fills `data` with cryptographically secure random bytes from the instance's crypto provider, e.g. for IVs. - * - * Fails when the instance has no provider DuckDB considers secure for writing; see the module notes. + * Sets the random bytes callback. Required before registration: DuckDB generates the IVs and salts of encrypted writes + * with it. * * history: * - unstable: v2.0.0 * - * @param instance The instance whose provider to use. - * @param data Receives the random bytes. - * @param length The number of bytes to produce. + * @param provider The provider. + * @param callback The callback. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_random_bytes(duckdb_v2_instance_handle instance, uint8_t *data, - idx_t length, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_provider_set_random_callback( + duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_random_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a streaming cipher. + * Registers the provider as the instance's crypto provider, used by encrypted databases, Parquet encryption and the + * primitives above. * - * The key is copied and wiped when the cipher is destroyed. Encrypting requires a provider DuckDB considers secure for - * writing; decrypting does not. The cipher must be initialized with `duckdb_v2_crypto_cipher_init()` before use. + * Requires the cipher and random bytes callbacks. Register before the instance uses its crypto provider; see the module + * notes. Fails when the instance already has a provider (e.g. httpfs is loaded) or when the provider was created + * through a factory of another instance. The `force_mbedtls_unsafe` setting still overrides it. The caller still owns + * the handle and must destroy it with `duckdb_v2_crypto_provider_destroy()`. * * history: * - unstable: v2.0.0 * - * @param instance The instance whose provider to use. - * @param cipher The cipher. - * @param mode Whether to encrypt or decrypt. - * @param key The key. Borrowed and copied. - * @param key_length The key length in bytes: 16, 24 or 32. - * @param stream On success, receives the new cipher. Owned by the caller. + * @param instance The instance to register on. + * @param provider The provider to register. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_cipher_create(duckdb_v2_instance_handle instance, - DUCKDB_V2_CRYPTO_CIPHER cipher, DUCKDB_V2_CRYPTO_MODE mode, - const uint8_t *key, idx_t key_length, - duckdb_v2_crypto_cipher_handle *stream, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_register_crypto_provider(duckdb_v2_instance_handle instance, + duckdb_v2_crypto_provider_handle provider, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Starts the stream with an IV and, for GCM, additional authenticated data. - * - * The IV length and AAD support depend on the cipher: AES-GCM takes a 12-byte IV and optional AAD, AES-CTR a 16-byte IV - * and no AAD. May be called once per cipher. + * Registers the provider on the loading extension's instance. Use this from the extension's load callback. Follows the + * rules of `duckdb_v2_instance_register_crypto_provider()`. * * history: * - unstable: v2.0.0 * - * @param stream The cipher. - * @param iv The IV. Borrowed. - * @param iv_length The IV length in bytes. - * @param aad The additional authenticated data, or null. Borrowed. - * @param aad_length The AAD length in bytes, 0 if none. + * @param extension The loading extension. + * @param provider The provider to register. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_cipher_init(duckdb_v2_crypto_cipher_handle stream, const uint8_t *iv, - idx_t iv_length, const uint8_t *aad, idx_t aad_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_crypto_provider(duckdb_v2_extension_handle extension, + duckdb_v2_crypto_provider_handle provider, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Processes the next chunk of the stream. - * - * Once an update or finalize fails in the provider, the cipher rejects every further call and can only be destroyed. - * `out_capacity` must be at least `in_length`. `in` and `out` may be the same buffer. For decryption with GCM, the - * plaintext must not be trusted before `duckdb_v2_crypto_cipher_finalize()` succeeds. + * Destroys the provider handle. Null-safe; the handle is set to null on return. Does not affect a registered provider. * * history: * - unstable: v2.0.0 * - * @param stream The cipher. - * @param in The input bytes. - * @param in_length The number of input bytes. - * @param out Receives the output bytes. - * @param out_capacity The capacity of `out` in bytes. - * @param out_length Receives the number of bytes written. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param provider The provider to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_cipher_update(duckdb_v2_crypto_cipher_handle stream, const uint8_t *in, - idx_t in_length, uint8_t *out, idx_t out_capacity, - idx_t *out_length, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_provider_destroy(duckdb_v2_crypto_provider_handle *provider); #endif +/* --- Struct definitions for crypto --- */ + +/* ============================================================================ + * MODULE: custom type + * ============================================================================ */ + +/* --- Enums for custom type --- */ + +/* --- Struct forward declarations for custom type --- */ + +/* --- Types for custom type --- */ + +/*! + * An owned opaque handle to a custom type being built. Created with `duckdb_v2_custom_type_create()`, configured with + * `duckdb_v2_custom_type_set_name()` and `duckdb_v2_custom_type_set_base_type()`, made available with + * `duckdb_v2_connection_register_custom_type()` or `duckdb_v2_extension_register_custom_type()`, and destroyed with + * `duckdb_v2_custom_type_destroy()`. + */ +typedef struct _duckdb_v2_custom_type { + void *internal_ptr; +} * duckdb_v2_custom_type_handle; + +/* --- Constants for custom type --- */ + +/* --- Function pointer typedefs for custom type --- */ + +/* --- Functions for custom type --- */ + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Completes the stream. + * Creates a new custom type through a factory. * - * GCM encryption: writes the 16-byte authentication tag into `tag`. GCM decryption: verifies the 16-byte `tag`, failing - * with an input error when it does not match, after which the cipher can only be destroyed. CTR: `tag` must be null and - * `tag_length` 0. + * The type starts out empty: configure it with `duckdb_v2_custom_type_set_name()` and + * `duckdb_v2_custom_type_set_base_type()`, then make it available with `duckdb_v2_connection_register_custom_type()` or + * `duckdb_v2_extension_register_custom_type()`. The caller owns the returned handle and must destroy it with + * `duckdb_v2_custom_type_destroy()`, also after registration. + * + * The custom type can only be registered on the database the factory belongs to. * * history: * - unstable: v2.0.0 * - * @param stream The cipher. - * @param tag The tag buffer (GCM), or null. - * @param tag_length The tag length in bytes - 16 for GCM, 0 for CTR. + * @param factory The factory to create the custom type through. + * @param type On success, receives the newly created custom type. Owned by the caller. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_cipher_finalize(duckdb_v2_crypto_cipher_handle stream, uint8_t *tag, - idx_t tag_length, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_type_create(duckdb_v2_factory_handle factory, + duckdb_v2_custom_type_handle *type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys the cipher, wiping its key. Null-safe; the handle is set to null on return. + * Sets the name of the custom type. + * + * This is the name the type is referred to by in SQL, and the alias carried by every logical type instance of it. The + * name is borrowed and copied. Calling this again replaces the previous name. A name must be set before registration. * * history: * - unstable: v2.0.0 * - * @param stream The cipher to destroy. + * @param type The type to set the name of. + * @param name The name to set. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_cipher_destroy(duckdb_v2_crypto_cipher_handle *stream); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_type_set_name(duckdb_v2_custom_type_handle type, const char *name, + idx_t name_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a new, empty crypto provider through a factory. + * Sets the base type of the custom type. * - * The provider can only be registered on the instance the factory belongs to. The caller owns the handle and must - * destroy it with `duckdb_v2_crypto_provider_destroy()`, also after registration. + * The custom type shares the base type's internal representation but is logically distinct, so it can carry its own + * cast functions. The type is borrowed and copied. Calling this again replaces the previous base type. A base type must + * be set before registration, and it must be a fully defined concrete type -- ANY is a signature wildcard, not + * something a registered type can be built on. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create the provider through. - * @param provider On success, receives the new provider. Owned by the caller. + * @param type The type to set the base type of. + * @param base_type The logical type to base the custom type on. Borrowed for the call only. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_provider_create(duckdb_v2_factory_handle factory, - duckdb_v2_crypto_provider_handle *provider, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_type_set_base_type(duckdb_v2_custom_type_handle type, + duckdb_v2_logical_type_handle base_type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets user data handed to every callback of the provider, destroyed with the registered provider (or with the handle - * if never registered). + * Registers the custom type, making it available for use in SQL queries. + * + * The type is registered on the connection's database, visible to every connection, in the connection's transaction: + * inside an explicit transaction, it is invisible to other connections until the transaction commits, and a rollback + * undoes it. Registration requires a name and a complete base type. The custom type must have been created through a + * factory of the same database. The caller still owns the handle after registration and must destroy it with + * `duckdb_v2_custom_type_destroy()`, which does not affect the registered type. * * history: * - unstable: v2.0.0 * - * @param provider The provider. - * @param data Opaque handle bundling the user data pointer plus an optional destructor. + * @param conn The connection to register on. + * @param type The custom type to register. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_provider_set_user_data(duckdb_v2_crypto_provider_handle provider, - duckdb_v2_opaque *data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_register_custom_type(duckdb_v2_connection_handle conn, + duckdb_v2_custom_type_handle type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the callback that creates a cipher stream. + * Registers the custom type, making it available for use in SQL queries. * - * The create, init, update and finalize callbacks are required before registration, and together must support every - * `CRYPTO_CIPHER` value: currently AES-GCM and AES-CTR, with 16-, 24- and 32-byte keys. + * The type is registered on the loading extension's database and attributed to the extension. Use this from the + * extension's load callback. Registration requires a name and a complete base type. The custom type must have been + * created through a factory of the same database. The caller still owns the handle after registration and must destroy + * it with `duckdb_v2_custom_type_destroy()`, which does not affect the registered type. * * history: * - unstable: v2.0.0 * - * @param provider The provider. - * @param callback The create callback to set. + * @param extension The loading extension. + * @param type The custom type to register. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_provider_set_cipher_create_callback( - duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_cipher_create_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_custom_type(duckdb_v2_extension_handle extension, + duckdb_v2_custom_type_handle type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the callback that starts a cipher stream. + * Destroys the custom type, releasing its resources. * - * The callback must accept 16-byte GCM IVs: encrypted databases in the legacy v0 format use them, unlike - * `duckdb_v2_crypto_cipher_init()`, which takes 12. + * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent + * double-destruction. Destroying the handle after registration does not affect the registered type. * * history: * - unstable: v2.0.0 * - * @param provider The provider. - * @param callback The init callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param type The type to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_provider_set_cipher_init_callback( - duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_cipher_init_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_type_destroy(duckdb_v2_custom_type_handle *type); #endif +/* --- Struct definitions for custom type --- */ + +/* ============================================================================ + * MODULE: data_chunk + * ============================================================================ */ + +/* --- Enums for data_chunk --- */ + +/* --- Struct forward declarations for data_chunk --- */ + +/* --- Types for data_chunk --- */ + +/* --- Constants for data_chunk --- */ + +/* --- Function pointer typedefs for data_chunk --- */ + +/* --- Functions for data_chunk --- */ + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the callback that processes a chunk of a cipher stream. + * Creates an empty data chunk with the given column types, drawing its allocator from a factory. + * + * The chunk's vectors are allocated through the factory's database, so the memory is accounted to that database. + * Allocates one FLAT vector per element of the types array, each at default capacity. Every vector starts at size 0; + * set it with vector_set_size once the vector is populated. The chunk is caller-owned and must be destroyed via + * data_chunk_destroy. * * history: * - unstable: v2.0.0 * - * @param provider The provider. - * @param callback The update callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param types Pointer to an array of logical_type handles, one per column. + * @param column_count Number of elements in the types array. + * @param out_chunk Receives the new chunk handle. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_provider_set_cipher_update_callback( - duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_cipher_update_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_chunk_create(duckdb_v2_factory_handle factory, + const duckdb_v2_logical_type_handle *types, idx_t column_count, + duckdb_v2_data_chunk_handle *out_chunk, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the callback that completes a cipher stream. + * Creates a deep copy of a data chunk, drawing its allocator from a factory. + * + * Allocates a new chunk with the source chunk's column types and copies all rows into it, through the factory's + * database. The copy is flattened and owns all its data, so it stays valid after the source chunk or whatever backs it + * (such as a column data collection scan state) is destroyed. The returned chunk is caller-owned and must be destroyed + * via data_chunk_destroy. * * history: * - unstable: v2.0.0 * - * @param provider The provider. - * @param callback The finalize callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param chunk The chunk to copy. Left unchanged. + * @param out_chunk Receives the new chunk handle. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_provider_set_cipher_finalize_callback( - duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_cipher_finalize_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_chunk_copy(duckdb_v2_factory_handle factory, + duckdb_v2_data_chunk_handle chunk, + duckdb_v2_data_chunk_handle *out_chunk, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional callback that releases a cipher stream. + * Destroys a data chunk handle. + * + * Null-safe: passing nullptr or a slot already set to nullptr is a no-op. On success the slot is set to nullptr. Any + * vector previously borrowed from this chunk becomes invalid. * * history: * - unstable: v2.0.0 * - * @param provider The provider. - * @param callback Optional. The destroy callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param chunk The chunk to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_provider_set_cipher_destroy_callback( - duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_cipher_destroy_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_chunk_destroy(duckdb_v2_data_chunk_handle *chunk); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the hash callback and the functions it supports. Optional: DuckDB's built-in implementation serves every - * function the callback does not declare. + * Empties a data chunk so it can be filled again. + * + * The chunk's size becomes 0, and each of its vectors becomes a writable FLAT vector of its type again, as on creation, + * so a chunk can be reused for one batch after another instead of being created for each. Data, views and pointers + * taken from the chunk or its vectors beforehand do not survive this. Must not be called on a chunk DuckDB lends to a + * callback for reading. * * history: * - unstable: v2.0.0 * - * @param provider The provider. - * @param callback The callback. - * @param functions The functions the callback supports. Borrowed and copied. - * @param function_count The number of functions. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param chunk The chunk to clear. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_provider_set_hash_callback( - duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_hash_callback_fn callback, - const DUCKDB_V2_CRYPTO_HASH_FUNCTION *functions, idx_t function_count, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_chunk_clear(duckdb_v2_data_chunk_handle chunk, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the HMAC callback and the functions it supports. Optional: DuckDB's built-in implementation serves every - * function the callback does not declare. + * Returns the row count of a data chunk. * * history: * - unstable: v2.0.0 * - * @param provider The provider. - * @param callback The callback. - * @param functions The functions the callback supports. Borrowed and copied. - * @param function_count The number of functions. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param chunk The chunk. + * @param out_size Receives the row count. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_provider_set_hmac_callback( - duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_hmac_callback_fn callback, - const DUCKDB_V2_CRYPTO_HASH_FUNCTION *functions, idx_t function_count, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_chunk_get_size(duckdb_v2_data_chunk_handle chunk, idx_t *out_size, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the random bytes callback. Required before registration: DuckDB generates the IVs and salts of encrypted writes - * with it. + * Returns the number of rows a data chunk can hold, e.g. how many rows the exec callback of a table function may write + * into its output chunk in one call. * * history: * - unstable: v2.0.0 * - * @param provider The provider. - * @param callback The callback. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param chunk The chunk. + * @param out_capacity Receives the number of rows the chunk can hold. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_provider_set_random_callback( - duckdb_v2_crypto_provider_handle provider, duckdb_v2_crypto_provider_random_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_chunk_get_capacity(duckdb_v2_data_chunk_handle chunk, idx_t *out_capacity, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the provider as the instance's crypto provider, used by encrypted databases, Parquet encryption and the - * primitives above. + * Returns the number of vectors in a data chunk. * - * Requires the cipher and random bytes callbacks. Register before the instance uses its crypto provider; see the module - * notes. Fails when the instance already has a provider (e.g. httpfs is loaded) or when the provider was created - * through a factory of another instance. The `force_mbedtls_unsafe` setting still overrides it. The caller still owns - * the handle and must destroy it with `duckdb_v2_crypto_provider_destroy()`. + * Equals the column count of the producing result. * * history: * - unstable: v2.0.0 * - * @param instance The instance to register on. - * @param provider The provider to register. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param chunk The chunk. + * @param out_count Receives the vector count. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_register_crypto_provider(duckdb_v2_instance_handle instance, - duckdb_v2_crypto_provider_handle provider, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_chunk_get_vector_count(duckdb_v2_data_chunk_handle chunk, idx_t *out_count, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the provider on the loading extension's instance. Use this from the extension's load callback. Follows the - * rules of `duckdb_v2_instance_register_crypto_provider()`. - * - * history: - * - unstable: v2.0.0 + * Borrows the vector at the given index in a data chunk. * - * @param extension The loading extension. - * @param provider The provider to register. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_crypto_provider(duckdb_v2_extension_handle extension, - duckdb_v2_crypto_provider_handle provider, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Destroys the provider handle. Null-safe; the handle is set to null on return. Does not affect a registered provider. + * The returned handle is borrowed and valid until the chunk is destroyed; do not destroy it. An out-of-range index + * returns ERROR_INPUT_INVALID. * * history: * - unstable: v2.0.0 * - * @param provider The provider to destroy. + * @param chunk The chunk. + * @param index The vector index, in [0, vector_count). + * @param out_vector Receives the borrowed vector handle. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_crypto_provider_destroy(duckdb_v2_crypto_provider_handle *provider); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_chunk_get_vector(duckdb_v2_data_chunk_handle chunk, idx_t index, + duckdb_v2_vector_handle *out_vector, + duckdb_v2_error_info_handle *err); #endif -/* --- Struct definitions for crypto --- */ +/* --- Struct definitions for data_chunk --- */ /* ============================================================================ - * MODULE: custom type + * MODULE: environment * ============================================================================ */ -/* --- Enums for custom type --- */ - -/* --- Struct forward declarations for custom type --- */ +/* --- Enums for environment --- */ -/* --- Types for custom type --- */ +/* --- Struct forward declarations for environment --- */ -/*! - * An owned opaque handle to a custom type being built. Created with `duckdb_v2_custom_type_create()`, configured with - * `duckdb_v2_custom_type_set_name()` and `duckdb_v2_custom_type_set_base_type()`, made available with - * `duckdb_v2_connection_register_custom_type()` or `duckdb_v2_extension_register_custom_type()`, and destroyed with - * `duckdb_v2_custom_type_destroy()`. - */ -typedef struct _duckdb_v2_custom_type { - void *internal_ptr; -} * duckdb_v2_custom_type_handle; +/* --- Types for environment --- */ -/* --- Constants for custom type --- */ +/* --- Constants for environment --- */ -/* --- Function pointer typedefs for custom type --- */ +/* --- Function pointer typedefs for environment --- */ -/* --- Functions for custom type --- */ +/* --- Functions for environment --- */ #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a new custom type through a factory. - * - * The type starts out empty: configure it with `duckdb_v2_custom_type_set_name()` and - * `duckdb_v2_custom_type_set_base_type()`, then make it available with `duckdb_v2_connection_register_custom_type()` or - * `duckdb_v2_extension_register_custom_type()`. The caller owns the returned handle and must destroy it with - * `duckdb_v2_custom_type_destroy()`, also after registration. - * - * The custom type can only be registered on the database the factory belongs to. + * Creates the V2 environment. Call once at program start. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create the custom type through. - * @param type On success, receives the newly created custom type. Owned by the caller. + * @param out_env Receives the new environment handle. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_type_create(duckdb_v2_factory_handle factory, - duckdb_v2_custom_type_handle *type, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_environment_create(duckdb_v2_environment_handle *out_env, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the name of the custom type. + * Destroys the environment. * - * This is the name the type is referred to by in SQL, and the alias carried by every logical type instance of it. The - * name is borrowed and copied. Calling this again replaces the previous name. A name must be set before registration. + * Refuses with ERROR_RESOURCE_IN_USE while any instance created through this environment is still alive; destroy those + * instances first, then retry. On success the handle is set to null. * * history: * - unstable: v2.0.0 * - * @param type The type to set the name of. - * @param name The name to set. Borrowed and copied. - * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be - * NULL only when this is 0. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param env The environment. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_type_set_name(duckdb_v2_custom_type_handle type, const char *name, - idx_t name_length, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_environment_destroy(duckdb_v2_environment_handle *env); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the base type of the custom type. + * Returns the number of instances currently alive under the environment. * - * The custom type shares the base type's internal representation but is logically distinct, so it can carry its own - * cast functions. The type is borrowed and copied. Calling this again replaces the previous base type. A base type must - * be set before registration, and it must be a fully defined concrete type -- ANY is a signature wildcard, not - * something a registered type can be built on. + * A diagnostic accessor, for tracking down leaked instances when `duckdb_v2_environment_destroy()` returns + * ERROR_RESOURCE_IN_USE. The count is a snapshot and may change before the next call. * * history: * - unstable: v2.0.0 * - * @param type The type to set the base type of. - * @param base_type The logical type to base the custom type on. Borrowed for the call only. + * @param env The environment. + * @param out_count Receives the number of live instances. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_type_set_base_type(duckdb_v2_custom_type_handle type, - duckdb_v2_logical_type_handle base_type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_environment_get_instance_count(duckdb_v2_environment_handle env, + idx_t *out_count, + duckdb_v2_error_info_handle *err); #endif +/* --- Struct definitions for environment --- */ + +/* ============================================================================ + * MODULE: error + * ============================================================================ */ + +/* --- Enums for error --- */ + +/* --- Struct forward declarations for error --- */ + +/* --- Types for error --- */ + +/* --- Constants for error --- */ + +/* --- Function pointer typedefs for error --- */ + +/* --- Functions for error --- */ + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the custom type, making it available for use in SQL queries. + * Retrieves the error code associated with an error info handle. * - * The type is registered on the connection's database, visible to every connection, in the connection's transaction: - * inside an explicit transaction, it is invisible to other connections until the transaction commits, and a rollback - * undoes it. Registration requires a name and a complete base type. The custom type must have been created through a - * factory of the same database. The caller still owns the handle after registration and must destroy it with - * `duckdb_v2_custom_type_destroy()`, which does not affect the registered type. + * On success, writes the info's error code to `*out_code`. On failure (e.g. if `info` is invalid), leaves `*out_code` + * unchanged and returns a non-success error code. * * history: * - unstable: v2.0.0 * - * @param conn The connection to register on. - * @param type The custom type to register. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param info The error info handle to query. + * @param out_code The error code associated with the info, if the call succeeds. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_register_custom_type(duckdb_v2_connection_handle conn, - duckdb_v2_custom_type_handle type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_error_info_get_code(duckdb_v2_error_info_handle info, DUCKDB_V2_ERROR *out_code); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the custom type, making it available for use in SQL queries. + * Retrieves the error text associated with an error info handle. * - * The type is registered on the loading extension's database and attributed to the extension. Use this from the - * extension's load callback. Registration requires a name and a complete base type. The custom type must have been - * created through a factory of the same database. The caller still owns the handle after registration and must destroy - * it with `duckdb_v2_custom_type_destroy()`, which does not affect the registered type. + * Returns a borrowed view of the info's error text. The text is owned by DuckDB and is valid until the info is + * destroyed or a new text is set; callers must not free it, and must not read it once the info has been destroyed. * * history: * - unstable: v2.0.0 * - * @param extension The loading extension. - * @param type The custom type to register. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param info The error info handle to query. + * @param out_text Receives a borrowed pointer to the text. Owned by DuckDB; valid until the info handle is destroyed. + * @param out_text_length Receives the length of `*out_text` in bytes. `*out_text` is not guaranteed to be + * null-terminated. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_custom_type(duckdb_v2_extension_handle extension, - duckdb_v2_custom_type_handle type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_error_info_get_text(duckdb_v2_error_info_handle info, const char **out_text, + idx_t *out_text_length); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys the custom type, releasing its resources. + * Retrieves the error text body without the leading category prefix. * - * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent - * double-destruction. Destroying the handle after registration does not affect the registered type. + * Returns a borrowed view of the same text error_info_get_text reports, minus the leading " Error: " prefix. This + * is the authoritative unprefixed body: the API exposes no type name, so the prefix cannot be reconstructed and the + * body cannot be derived from error_info_get_text. Unprefixed does not mean plain — the body keeps whatever form it was + * rendered in (a LINE/caret block by default, JSON under errors_as_json). NULL with a zero length when there is no + * text. The text is owned by DuckDB and valid until the info handle is destroyed. * * history: * - unstable: v2.0.0 * - * @param type The type to destroy. + * @param info The error info handle to query. + * @param out_raw_text Receives a borrowed pointer to the raw text. Owned by DuckDB; valid until the info handle is + * destroyed. + * @param out_raw_text_length Receives the length of `*out_raw_text` in bytes. `*out_raw_text` is not guaranteed to be + * null-terminated. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_type_destroy(duckdb_v2_custom_type_handle *type); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_error_info_get_raw_text(duckdb_v2_error_info_handle info, + const char **out_raw_text, idx_t *out_raw_text_length); #endif -/* --- Struct definitions for custom type --- */ - -/* ============================================================================ - * MODULE: data_chunk - * ============================================================================ */ - -/* --- Enums for data_chunk --- */ - -/* --- Struct forward declarations for data_chunk --- */ - -/* --- Types for data_chunk --- */ - -/* --- Constants for data_chunk --- */ - -/* --- Function pointer typedefs for data_chunk --- */ - -/* --- Functions for data_chunk --- */ - #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates an empty data chunk with the given column types, drawing its allocator from a factory. + * Sets the error code for an error info handle. * - * The chunk's vectors are allocated through the factory's database, so the memory is accounted to that database. - * Allocates one FLAT vector per element of the types array, each at default capacity. Every vector starts at size 0; - * set it with vector_set_size once the vector is populated. The chunk is caller-owned and must be destroyed via - * data_chunk_destroy. + * On success, replaces the info's error code with the provided one. On failure, nothing is changed. Accepts a `nullptr` + * info handle, in which case the call is a no-op and returns ERROR_NONE. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param types Pointer to an array of logical_type handles, one per column. - * @param column_count Number of elements in the types array. - * @param out_chunk Receives the new chunk handle. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The error info handle to set. On success, updated with the provided code. + * @param code The error code to set in the info. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_chunk_create(duckdb_v2_factory_handle factory, - const duckdb_v2_logical_type_handle *types, idx_t column_count, - duckdb_v2_data_chunk_handle *out_chunk, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_error_info_set_code(duckdb_v2_error_info_handle info, DUCKDB_V2_ERROR code); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a deep copy of a data chunk, drawing its allocator from a factory. + * Sets the error text for an error info handle. * - * Allocates a new chunk with the source chunk's column types and copies all rows into it, through the factory's - * database. The copy is flattened and owns all its data, so it stays valid after the source chunk or whatever backs it - * (such as a column data collection scan state) is destroyed. The returned chunk is caller-owned and must be destroyed - * via data_chunk_destroy. + * On success, replaces the info's text with the provided one; DuckDB allocates its own copy of the string. On failure, + * nothing is changed. Accepts a `nullptr` info handle, in which case the call is a no-op and returns ERROR_NONE. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param chunk The chunk to copy. Left unchanged. - * @param out_chunk Receives the new chunk handle. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The error info handle to set. On success, updated with the provided text. + * @param text The error text to set in the info. + * @param text_length The length of `text` in bytes. `text` need not be null-terminated and may be NULL only when this + * is 0. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_chunk_copy(duckdb_v2_factory_handle factory, - duckdb_v2_data_chunk_handle chunk, - duckdb_v2_data_chunk_handle *out_chunk, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_error_info_set_text(duckdb_v2_error_info_handle info, const char *text, + idx_t text_length); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys a data chunk handle. + * Destroys an error info handle and frees its resources. * - * Null-safe: passing nullptr or a slot already set to nullptr is a no-op. On success the slot is set to nullptr. Any - * vector previously borrowed from this chunk becomes invalid. + * Null-safe: calling with a null handle, or a null pointer-to-handle, is a no-op and returns ERROR_NONE. On return + * `*info` is set to nullptr. Safe to call on any info DuckDB returned. * * history: * - unstable: v2.0.0 * - * @param chunk The chunk to destroy. + * @param info The error info handle to destroy. Set to nullptr on return. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_chunk_destroy(duckdb_v2_data_chunk_handle *chunk); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_error_info_destroy(duckdb_v2_error_info_handle *info); #endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Empties a data chunk so it can be filled again. - * - * The chunk's size becomes 0, and each of its vectors becomes a writable FLAT vector of its type again, as on creation, - * so a chunk can be reused for one batch after another instead of being created for each. Data, views and pointers - * taken from the chunk or its vectors beforehand do not survive this. Must not be called on a chunk DuckDB lends to a - * callback for reading. - * - * history: - * - unstable: v2.0.0 - * - * @param chunk The chunk to clear. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_chunk_clear(duckdb_v2_data_chunk_handle chunk, - duckdb_v2_error_info_handle *err); -#endif +/* --- Struct definitions for error --- */ -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Returns the row count of a data chunk. - * - * history: - * - unstable: v2.0.0 - * - * @param chunk The chunk. - * @param out_size Receives the row count. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_chunk_get_size(duckdb_v2_data_chunk_handle chunk, idx_t *out_size, - duckdb_v2_error_info_handle *err); -#endif +/* ============================================================================ + * MODULE: extension + * ============================================================================ */ -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Returns the number of rows a data chunk can hold, e.g. how many rows the exec callback of a table function may write - * into its output chunk in one call. - * - * history: - * - unstable: v2.0.0 - * - * @param chunk The chunk. - * @param out_capacity Receives the number of rows the chunk can hold. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_chunk_get_capacity(duckdb_v2_data_chunk_handle chunk, idx_t *out_capacity, - duckdb_v2_error_info_handle *err); -#endif +/* --- Enums for extension --- */ + +/* --- Struct forward declarations for extension --- */ + +typedef struct duckdb_v2_extension_input duckdb_v2_extension_input; + +/* --- Types for extension --- */ + +/* --- Constants for extension --- */ + +/* --- Function pointer typedefs for extension --- */ -#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of vectors in a data chunk. - * - * Equals the column count of the producing result. - * - * history: - * - unstable: v2.0.0 + * Hands back the function-pointer table for the API version the extension was built against, or NULL if this DuckDB + * cannot serve it. * - * @param chunk The chunk. - * @param out_count Receives the vector count. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. - * @return DUCKDB_V2_ERROR + * The extension calls it exactly once, first, through DUCKDB_EXTENSION_API_INIT; nothing else in the API may be called + * before it succeeds. A NULL return means the load has already failed and DuckDB has recorded why, so the entrypoint + * must return without touching the error slot. Statically linked extensions resolve DuckDB's symbols at link time and + * never call it, so for those the field is NULL. */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_chunk_get_vector_count(duckdb_v2_data_chunk_handle chunk, idx_t *out_count, - duckdb_v2_error_info_handle *err); -#endif +typedef const void *(*duckdb_v2_extension_get_api_fn)(duckdb_v2_extension_handle extension, const char *version, + idx_t version_length); + +/* --- Functions for extension --- */ + +/* --- Struct definitions for extension --- */ -#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Borrows the vector at the given index in a data chunk. - * - * The returned handle is borrowed and valid until the chunk is destroyed; do not destroy it. An out-of-range index - * returns ERROR_INPUT_INVALID. - * - * history: - * - unstable: v2.0.0 - * - * @param chunk The chunk. - * @param index The vector index, in [0, vector_count). - * @param out_vector Receives the borrowed vector handle. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. - * @return DUCKDB_V2_ERROR + * The single argument to a V2 C extension entrypoint. Borrowed for the duration of the call: none of its fields outlive + * the entrypoint, and the extension destroys none of them. */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_data_chunk_get_vector(duckdb_v2_data_chunk_handle chunk, idx_t index, - duckdb_v2_vector_handle *out_vector, - duckdb_v2_error_info_handle *err); -#endif +struct duckdb_v2_extension_input { + //! Fetches the versioned function-pointer table. NULL for a statically linked extension. + duckdb_v2_extension_get_api_fn get_api; -/* --- Struct definitions for data_chunk --- */ + //! The extension being loaded, and the token get_api takes. + duckdb_v2_extension_handle extension; + + /*! + * A borrowed context to read and run queries through, with a transaction already active. Valid only until the + * extension entrypoint returns; do not retain or destroy it. + */ + duckdb_v2_context_handle context; + + /*! + * A live error slot: never NULL, and never pointing at NULL. Populate it with error_info_set_code, and optionally + * error_info_set_text, to fail the load. Do not destroy it -- DuckDB owns it. Pass a slot of your own to calls + * whose failure you intend to handle, so only a failure you mean to abort the load with lands here. + */ + duckdb_v2_error_info_handle *err; +}; /* ============================================================================ - * MODULE: environment + * MODULE: factory * ============================================================================ */ -/* --- Enums for environment --- */ +/* --- Enums for factory --- */ -/* --- Struct forward declarations for environment --- */ +/* --- Struct forward declarations for factory --- */ -/* --- Types for environment --- */ +/* --- Types for factory --- */ -/* --- Constants for environment --- */ +/* --- Constants for factory --- */ -/* --- Function pointer typedefs for environment --- */ +/* --- Function pointer typedefs for factory --- */ -/* --- Functions for environment --- */ +/* --- Functions for factory --- */ #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates the V2 environment. Call once at program start. + * Borrows the factory of an instance. + * + * The factory creates the built-in types and their values, casts with the built-in casts only, and allocates data + * chunks and column data collections through the instance. Anything that needs a catalog — catalog-registered types, + * qualified type names — returns ERROR_INPUT_INVALID. The returned handle is borrowed: it is valid for as long as the + * instance is, and must not be destroyed. * * history: * - unstable: v2.0.0 * - * @param out_env Receives the new environment handle. + * @param instance The instance. + * @param out_factory Receives the borrowed factory. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_environment_create(duckdb_v2_environment_handle *out_env, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_get_factory(duckdb_v2_instance_handle instance, + duckdb_v2_factory_handle *out_factory, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys the environment. + * Borrows the factory of a connection. * - * Refuses with ERROR_RESOURCE_IN_USE while any instance created through this environment is still alive; destroy those - * instances first, then retry. On success the handle is set to null. + * The factory reaches the connection's catalog and settings. Catalog lookups run in the connection's active + * transaction, or in a transaction of their own when none is open; nothing else opens a transaction. The returned + * handle is borrowed: it is valid for as long as the connection is, and must not be destroyed. * * history: * - unstable: v2.0.0 * - * @param env The environment. + * @param conn The connection. + * @param out_factory Receives the borrowed factory. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_environment_destroy(duckdb_v2_environment_handle *env); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_get_factory(duckdb_v2_connection_handle conn, + duckdb_v2_factory_handle *out_factory, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of instances currently alive under the environment. + * Borrows the factory of a context. * - * A diagnostic accessor, for tracking down leaked instances when `duckdb_v2_environment_destroy()` returns - * ERROR_RESOURCE_IN_USE. The count is a snapshot and may change before the next call. + * The factory reaches the context's catalog and settings, within the transaction the context already has. The returned + * handle is borrowed: it is valid for as long as the context is, and must not be destroyed. * * history: * - unstable: v2.0.0 * - * @param env The environment. - * @param out_count Receives the number of live instances. + * @param ctx The context. + * @param out_factory Receives the borrowed factory. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_environment_get_instance_count(duckdb_v2_environment_handle env, - idx_t *out_count, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_get_factory(duckdb_v2_context_handle ctx, + duckdb_v2_factory_handle *out_factory, + duckdb_v2_error_info_handle *err); #endif -/* --- Struct definitions for environment --- */ +/* --- Struct definitions for factory --- */ /* ============================================================================ - * MODULE: error + * MODULE: file system * ============================================================================ */ -/* --- Enums for error --- */ +/* --- Enums for file system --- */ -/* --- Struct forward declarations for error --- */ +/*! + * How `duckdb_v2_file_system_open()` opens a file. These are not a bitmask -- apply them one at a time with + * `duckdb_v2_file_open_options_set_flag()`, calling it once per behaviour you want, e.g. `FILE_FLAG_WRITE` then + * `FILE_FLAG_CREATE` to write to a file and create it when it does not exist. + */ +typedef enum DUCKDB_V2_FILE_FLAG { + //! Not a flag. The zero value, so that an uninitialized variable does not name a behaviour; applying it is an + //! error. + DUCKDB_V2_FILE_FLAG_INVALID = 0, -/* --- Types for error --- */ + //! Open the file with "read" capabilities. + DUCKDB_V2_FILE_FLAG_READ = 1, -/* --- Constants for error --- */ + //! Open the file with "write" capabilities. + DUCKDB_V2_FILE_FLAG_WRITE = 2, -/* --- Function pointer typedefs for error --- */ + //! Create the file if it does not exist, and open it as it is if it does. + DUCKDB_V2_FILE_FLAG_CREATE = 3, -/* --- Functions for error --- */ + /*! + * Create the file if it does not exist, and truncate it to empty if it does. To fail instead of truncating, combine + * `FILE_FLAG_CREATE` with `FILE_FLAG_EXCLUSIVE_CREATE`. + */ + DUCKDB_V2_FILE_FLAG_CREATE_NEW = 4, -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Retrieves the error code associated with an error info handle. - * - * On success, writes the info's error code to `*out_code`. On failure (e.g. if `info` is invalid), leaves `*out_code` - * unchanged and returns a non-success error code. + //! Open the file in "append" mode. + DUCKDB_V2_FILE_FLAG_APPEND = 5, + + //! Fail if the file already exists. A modifier on `FILE_FLAG_CREATE`, and meaningless without it. + DUCKDB_V2_FILE_FLAG_EXCLUSIVE_CREATE = 6, + + /*! + * The file will be read and written at explicit offsets from several threads at once. Pass it whenever + * `duckdb_v2_file_read_at()` or `duckdb_v2_file_write_at()` are used concurrently -- a file system that would + * otherwise assume sequential access, by caching, buffering, or keeping a single cursor, needs to know not to. + */ + DUCKDB_V2_FILE_FLAG_PARALLEL_ACCESS = 7, + + /*! + * Read the file through DuckDB's external file cache, which keeps the bytes that were read in memory, so that later + * reads of the same file - also by later queries - do not have to read them again. Whether a local file is cached + * is decided by the `cache_local_files` setting. Only meaningful for reading. + */ + DUCKDB_V2_FILE_FLAG_EXTERNAL_FILE_CACHE = 8, + DUCKDB_V2_FILE_FLAG_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_FILE_FLAG; + +/* --- Struct forward declarations for file system --- */ + +/* --- Types for file system --- */ + +/*! + * A borrowed opaque handle to a file system. Obtained from `duckdb_v2_instance_get_file_system()`, + * `duckdb_v2_connection_get_file_system()` or `duckdb_v2_context_get_file_system()`, and used to open files with + * `duckdb_v2_file_system_open()`. Borrowed: the handle belongs to the instance, connection or context it came from, is + * valid only for as long as that is, and must not be destroyed. + */ +typedef struct _duckdb_v2_file_system { + void *internal_ptr; +} * duckdb_v2_file_system_handle; + +/*! + * An owned opaque handle to the options a file is opened with. Created with `duckdb_v2_file_open_options_create()`, + * configured with `duckdb_v2_file_open_options_set_flag()` and `duckdb_v2_file_open_options_set_value()`, passed to + * `duckdb_v2_file_system_open()`, and destroyed with `duckdb_v2_file_open_options_destroy()`. One options object can + * open any number of files, and destroying it does not affect files already opened with it. + */ +typedef struct _duckdb_v2_file_open_options { + void *internal_ptr; +} * duckdb_v2_file_open_options_handle; + +/*! + * An owned opaque handle to an open file, produced by `duckdb_v2_file_system_open()` and destroyed with + * `duckdb_v2_file_destroy()`. Read, write, seek and sync through the `file_*` functions. Only usable while the file + * system it was opened through is still valid. + */ +typedef struct _duckdb_v2_file { + void *internal_ptr; +} * duckdb_v2_file_handle; + +/* --- Constants for file system --- */ + +/* --- Function pointer typedefs for file system --- */ + +/*! + * Receives one path matched by `duckdb_v2_file_system_path_glob()`. + * + * The view is borrowed for the duration of the call only, and is not guaranteed to be null-terminated. Report an error + * through `err`, a live slot that must not be destroyed, to stop the glob: `duckdb_v2_file_system_path_glob()` then + * fails with that error. The callback must not throw or unwind across the boundary. + */ +typedef void (*duckdb_v2_file_system_path_glob_callback_fn)(const char *path, idx_t path_length, void *user_data, + duckdb_v2_error_info_handle *err); + +/* --- Functions for file system --- */ + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Borrows the file system of a context. + * + * The returned handle is borrowed: it is valid only for as long as the context is, and must not be destroyed. * * history: * - unstable: v2.0.0 * - * @param info The error info handle to query. - * @param out_code The error code associated with the info, if the call succeeds. + * @param context The context to take the file system from. + * @param file_system Receives the borrowed file system. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_error_info_get_code(duckdb_v2_error_info_handle info, DUCKDB_V2_ERROR *out_code); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_get_file_system(duckdb_v2_context_handle context, + duckdb_v2_file_system_handle *file_system, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the error text associated with an error info handle. + * Borrows the file system of an instance. * - * Returns a borrowed view of the info's error text. The text is owned by DuckDB and is valid until the info is - * destroyed or a new text is set; callers must not free it, and must not read it once the info has been destroyed. + * Paths are resolved with the instance's GLOBAL settings and secrets, and file I/O is not attributed to any query. + * + * The returned handle is borrowed: it is valid only for as long as the instance is, and must not be destroyed. * * history: * - unstable: v2.0.0 * - * @param info The error info handle to query. - * @param out_text Receives a borrowed pointer to the text. Owned by DuckDB; valid until the info handle is destroyed. - * @param out_text_length Receives the length of `*out_text` in bytes. `*out_text` is not guaranteed to be - * null-terminated. + * @param instance The instance to take the file system from. + * @param file_system Receives the borrowed file system. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_error_info_get_text(duckdb_v2_error_info_handle info, const char **out_text, - idx_t *out_text_length); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_get_file_system(duckdb_v2_instance_handle instance, + duckdb_v2_file_system_handle *file_system, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the error text body without the leading category prefix. + * Borrows the file system of a connection. * - * Returns a borrowed view of the same text error_info_get_text reports, minus the leading " Error: " prefix. This - * is the authoritative unprefixed body: the API exposes no type name, so the prefix cannot be reconstructed and the - * body cannot be derived from error_info_get_text. Unprefixed does not mean plain — the body keeps whatever form it was - * rendered in (a LINE/caret block by default, JSON under errors_as_json). NULL with a zero length when there is no - * text. The text is owned by DuckDB and valid until the info handle is destroyed. + * Paths are resolved with the connection's settings and secrets, and file I/O is attributed to its running query, as + * through `duckdb_v2_context_get_file_system()` in a callback. + * + * The returned handle is borrowed: it is valid only for as long as the connection is, and must not be destroyed. * * history: * - unstable: v2.0.0 * - * @param info The error info handle to query. - * @param out_raw_text Receives a borrowed pointer to the raw text. Owned by DuckDB; valid until the info handle is - * destroyed. - * @param out_raw_text_length Receives the length of `*out_raw_text` in bytes. `*out_raw_text` is not guaranteed to be - * null-terminated. + * @param conn The connection to take the file system from. + * @param file_system Receives the borrowed file system. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_error_info_get_raw_text(duckdb_v2_error_info_handle info, - const char **out_raw_text, idx_t *out_raw_text_length); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_get_file_system(duckdb_v2_connection_handle conn, + duckdb_v2_file_system_handle *file_system, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the error code for an error info handle. + * Creates a set of open options for a file system. * - * On success, replaces the info's error code with the provided one. On failure, nothing is changed. Accepts a `nullptr` - * info handle, in which case the call is a no-op and returns ERROR_NONE. + * The options start out empty: give them flags with `duckdb_v2_file_open_options_set_flag()`, which is required, and + * optionally attach values with `duckdb_v2_file_open_options_set_value()`. They are then passed to + * `duckdb_v2_file_system_open()`, and can be reused for as many opens as you like. The caller owns the returned handle + * and must destroy it with `duckdb_v2_file_open_options_destroy()`. + * + * The options belong to the file system they were created from, since which values mean anything depends on which file + * system ends up handling the path. * * history: * - unstable: v2.0.0 * - * @param info The error info handle to set. On success, updated with the provided code. - * @param code The error code to set in the info. + * @param file_system The file system the options are for. + * @param options On success, receives the new options. Owned by the caller; destroy via + * `duckdb_v2_file_open_options_destroy()`. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_error_info_set_code(duckdb_v2_error_info_handle info, DUCKDB_V2_ERROR code); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_open_options_create(duckdb_v2_file_system_handle file_system, + duckdb_v2_file_open_options_handle *options, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the error text for an error info handle. + * Applies one flag to the options. * - * On success, replaces the info's text with the provided one; DuckDB allocates its own copy of the string. On failure, - * nothing is changed. Accepts a `nullptr` info handle, in which case the call is a no-op and returns ERROR_NONE. + * Additive: call it once per behaviour you want, and applying the same flag twice is harmless. At least one flag must + * be applied before the options can open anything, since the flags are what say whether the file is being read or + * written. There is no way to take a flag back -- build a fresh set of options instead. + * + * `FILE_FLAG_INVALID` names no behaviour and is rejected, as is any value that is not a `DUCKDB_V2_FILE_FLAG`. * * history: * - unstable: v2.0.0 * - * @param info The error info handle to set. On success, updated with the provided text. - * @param text The error text to set in the info. - * @param text_length The length of `text` in bytes. `text` need not be null-terminated and may be NULL only when this - * is 0. + * @param options The options to apply the flag to. + * @param flag The flag to apply. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_error_info_set_text(duckdb_v2_error_info_handle info, const char *text, - idx_t text_length); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_open_options_set_flag(duckdb_v2_file_open_options_handle options, + DUCKDB_V2_FILE_FLAG flag, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys an error info handle and frees its resources. + * Attaches a named value to the options. * - * Null-safe: calling with a null handle, or a null pointer-to-handle, is a no-op and returns ERROR_NONE. On return - * `*info` is set to nullptr. Safe to call on any info DuckDB returned. + * These are hints for whichever file system ends up handling the path, and what they mean is that file system's + * business: a value it does not recognise is ignored rather than rejected, and the same name can mean different things + * to different file systems. They are the same values a file system reports when listing files, so a known file size or + * modification time learned from a listing can be handed straight back to avoid re-reading it. + * + * The name and the value are borrowed and copied, so the caller may destroy the value immediately after. Setting the + * same name again replaces the previous value. Names are case-sensitive. * * history: * - unstable: v2.0.0 * - * @param info The error info handle to destroy. Set to nullptr on return. + * @param options The options to set the value on. + * @param name The name of the value. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` need not be null-terminated and may be NULL only when this + * is 0. + * @param value The value. Borrowed and copied. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_error_info_destroy(duckdb_v2_error_info_handle *info); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_open_options_set_value(duckdb_v2_file_open_options_handle options, + const char *name, idx_t name_length, + duckdb_v2_value_handle value, + duckdb_v2_error_info_handle *err); #endif -/* --- Struct definitions for error --- */ - -/* ============================================================================ - * MODULE: extension - * ============================================================================ */ - -/* --- Enums for extension --- */ - -/* --- Struct forward declarations for extension --- */ - -typedef struct duckdb_v2_extension_input duckdb_v2_extension_input; - -/* --- Types for extension --- */ - -/* --- Constants for extension --- */ - -/* --- Function pointer typedefs for extension --- */ - +#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Hands back the function-pointer table for the API version the extension was built against, or NULL if this DuckDB - * cannot serve it. + * Destroys the options, releasing their resources. * - * The extension calls it exactly once, first, through DUCKDB_EXTENSION_API_INIT; nothing else in the API may be called - * before it succeeds. A NULL return means the load has already failed and DuckDB has recorded why, so the entrypoint - * must return without touching the error slot. Statically linked extensions resolve DuckDB's symbols at link time and - * never call it, so for those the field is NULL. + * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent + * double-destruction. Files already opened with these options are unaffected. + * + * history: + * - unstable: v2.0.0 + * + * @param options The options to destroy. + * @return DUCKDB_V2_ERROR */ -typedef const void *(*duckdb_v2_extension_get_api_fn)(duckdb_v2_extension_handle extension, const char *version, - idx_t version_length); - -/* --- Functions for extension --- */ - -/* --- Struct definitions for extension --- */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_open_options_destroy(duckdb_v2_file_open_options_handle *options); +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * The single argument to a V2 C extension entrypoint. Borrowed for the duration of the call: none of its fields outlive - * the entrypoint, and the extension destroys none of them. - */ -struct duckdb_v2_extension_input { - //! Fetches the versioned function-pointer table. NULL for a statically linked extension. - duckdb_v2_extension_get_api_fn get_api; - - //! The extension being loaded, and the token get_api takes. - duckdb_v2_extension_handle extension; - - /*! - * A borrowed context to read and run queries through, with a transaction already active. Valid only until the - * extension entrypoint returns; do not retain or destroy it. - */ - duckdb_v2_context_handle context; - - /*! - * A live error slot: never NULL, and never pointing at NULL. Populate it with error_info_set_code, and optionally - * error_info_set_text, to fail the load. Do not destroy it -- DuckDB owns it. Pass a slot of your own to calls - * whose failure you intend to handle, so only a failure you mean to abort the load with lands here. - */ - duckdb_v2_error_info_handle *err; -}; - -/* ============================================================================ - * MODULE: factory - * ============================================================================ */ - -/* --- Enums for factory --- */ - -/* --- Struct forward declarations for factory --- */ - -/* --- Types for factory --- */ - -/* --- Constants for factory --- */ - -/* --- Function pointer typedefs for factory --- */ - -/* --- Functions for factory --- */ - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Borrows the factory of an instance. + * Opens a file. * - * The factory creates the built-in types and their values, casts with the built-in casts only, and allocates data - * chunks and column data collections through the instance. Anything that needs a catalog — catalog-registered types, - * qualified type names — returns ERROR_INPUT_INVALID. The returned handle is borrowed: it is valid for as long as the - * instance is, and must not be destroyed. + * Opens the file at the given path through the file system, which routes it the way the engine would -- a path handled + * by a registered virtual or remote file system goes there rather than to local disk. The returned handle is owned by + * the caller and must be destroyed with `duckdb_v2_file_destroy()`. + * + * The options carry the flags and any file-system-specific values; see `duckdb_v2_file_open_options_create()`. Opening + * without having set flags fails, since the flags are what say whether the file is being read or written. + * + * Failure to open -- a missing file without `FILE_FLAG_CREATE`, insufficient permissions, an existing file under + * `FILE_FLAG_EXCLUSIVE_CREATE` -- is reported as an error. + * + * Flag combinations that contradict each other, such as naming neither read nor write or combining `FILE_FLAG_CREATE` + * with `FILE_FLAG_CREATE_NEW`, are a programming error rather than a supported input. An assertion build catches them; + * elsewhere the behaviour is whatever the underlying file system does with them. * * history: * - unstable: v2.0.0 * - * @param instance The instance. - * @param out_factory Receives the borrowed factory. + * @param file_system The file system to open the file through. + * @param file_path The path of the file to open. Borrowed for the call only. + * @param file_path_length The length of `file_path` in bytes. `file_path` need not be null-terminated and may be NULL + * only when this is 0. + * @param options How to open the file. Borrowed for the call only, and reusable across opens. + * @param file On success, receives the open file. Owned by the caller; destroy via `duckdb_v2_file_destroy()`. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_get_factory(duckdb_v2_instance_handle instance, - duckdb_v2_factory_handle *out_factory, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_open(duckdb_v2_file_system_handle file_system, const char *file_path, + idx_t file_path_length, + duckdb_v2_file_open_options_handle options, + duckdb_v2_file_handle *file, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Borrows the factory of a connection. + * Reports whether a file exists at the given path. * - * The factory reaches the connection's catalog and settings. Catalog lookups run in the connection's active - * transaction, or in a transaction of their own when none is open; nothing else opens a transaction. The returned - * handle is borrowed: it is valid for as long as the connection is, and must not be destroyed. + * The path is routed the way `duckdb_v2_file_system_open()` routes it, so asking about a path handled by a remote file + * system may reach out to it. A directory is not a file, and reports false. * * history: * - unstable: v2.0.0 * - * @param conn The connection. - * @param out_factory Receives the borrowed factory. + * @param file_system The file system to ask. + * @param path The path to check. Borrowed for the call only. + * @param path_length The length of `path` in bytes. `path` need not be null-terminated and may be NULL only when this + * is 0. + * @param out_exists Receives whether a file exists at the path. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_get_factory(duckdb_v2_connection_handle conn, - duckdb_v2_factory_handle *out_factory, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_path_exists(duckdb_v2_file_system_handle file_system, + const char *path, idx_t path_length, bool *out_exists, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Borrows the factory of a context. + * Reports whether a path names a remote file, e.g. one under `s3://`, `https://`, `gcs://` or `azure://`. * - * The factory reaches the context's catalog and settings, within the transaction the context already has. The returned - * handle is borrowed: it is valid for as long as the context is, and must not be destroyed. + * Decided from the path alone: no file system is consulted, so it answers even when the extension providing the remote + * file system is not loaded. * * history: * - unstable: v2.0.0 * - * @param ctx The context. - * @param out_factory Receives the borrowed factory. + * @param file_system The file system the path is meant for. + * @param path The path to check. Borrowed for the call only. + * @param path_length The length of `path` in bytes. `path` need not be null-terminated and may be NULL only when this + * is 0. + * @param out_is_remote Receives whether the path names a remote file. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_get_factory(duckdb_v2_context_handle ctx, - duckdb_v2_factory_handle *out_factory, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_path_is_remote(duckdb_v2_file_system_handle file_system, + const char *path, idx_t path_length, + bool *out_is_remote, + duckdb_v2_error_info_handle *err); #endif -/* --- Struct definitions for factory --- */ - -/* ============================================================================ - * MODULE: file system - * ============================================================================ */ - -/* --- Enums for file system --- */ - -/*! - * How `duckdb_v2_file_system_open()` opens a file. These are not a bitmask -- apply them one at a time with - * `duckdb_v2_file_open_options_set_flag()`, calling it once per behaviour you want, e.g. `FILE_FLAG_WRITE` then - * `FILE_FLAG_CREATE` to write to a file and create it when it does not exist. - */ -typedef enum DUCKDB_V2_FILE_FLAG { - //! Not a flag. The zero value, so that an uninitialized variable does not name a behaviour; applying it is an - //! error. - DUCKDB_V2_FILE_FLAG_INVALID = 0, - - //! Open the file with "read" capabilities. - DUCKDB_V2_FILE_FLAG_READ = 1, - - //! Open the file with "write" capabilities. - DUCKDB_V2_FILE_FLAG_WRITE = 2, - - //! Create the file if it does not exist, and open it as it is if it does. - DUCKDB_V2_FILE_FLAG_CREATE = 3, - - /*! - * Create the file if it does not exist, and truncate it to empty if it does. To fail instead of truncating, combine - * `FILE_FLAG_CREATE` with `FILE_FLAG_EXCLUSIVE_CREATE`. - */ - DUCKDB_V2_FILE_FLAG_CREATE_NEW = 4, - - //! Open the file in "append" mode. - DUCKDB_V2_FILE_FLAG_APPEND = 5, - - //! Fail if the file already exists. A modifier on `FILE_FLAG_CREATE`, and meaningless without it. - DUCKDB_V2_FILE_FLAG_EXCLUSIVE_CREATE = 6, - - /*! - * The file will be read and written at explicit offsets from several threads at once. Pass it whenever - * `duckdb_v2_file_read_at()` or `duckdb_v2_file_write_at()` are used concurrently -- a file system that would - * otherwise assume sequential access, by caching, buffering, or keeping a single cursor, needs to know not to. - */ - DUCKDB_V2_FILE_FLAG_PARALLEL_ACCESS = 7, - - /*! - * Read the file through DuckDB's external file cache, which keeps the bytes that were read in memory, so that later - * reads of the same file - also by later queries - do not have to read them again. Whether a local file is cached - * is decided by the `cache_local_files` setting. Only meaningful for reading. - */ - DUCKDB_V2_FILE_FLAG_EXTERNAL_FILE_CACHE = 8, - DUCKDB_V2_FILE_FLAG_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_FILE_FLAG; - -/* --- Struct forward declarations for file system --- */ - -/* --- Types for file system --- */ - -/*! - * A borrowed opaque handle to a file system. Obtained from `duckdb_v2_instance_get_file_system()`, - * `duckdb_v2_connection_get_file_system()` or `duckdb_v2_context_get_file_system()`, and used to open files with - * `duckdb_v2_file_system_open()`. Borrowed: the handle belongs to the instance, connection or context it came from, is - * valid only for as long as that is, and must not be destroyed. - */ -typedef struct _duckdb_v2_file_system { - void *internal_ptr; -} * duckdb_v2_file_system_handle; - -/*! - * An owned opaque handle to the options a file is opened with. Created with `duckdb_v2_file_open_options_create()`, - * configured with `duckdb_v2_file_open_options_set_flag()` and `duckdb_v2_file_open_options_set_value()`, passed to - * `duckdb_v2_file_system_open()`, and destroyed with `duckdb_v2_file_open_options_destroy()`. One options object can - * open any number of files, and destroying it does not affect files already opened with it. - */ -typedef struct _duckdb_v2_file_open_options { - void *internal_ptr; -} * duckdb_v2_file_open_options_handle; - -/*! - * An owned opaque handle to an open file, produced by `duckdb_v2_file_system_open()` and destroyed with - * `duckdb_v2_file_destroy()`. Read, write, seek and sync through the `file_*` functions. Only usable while the file - * system it was opened through is still valid. - */ -typedef struct _duckdb_v2_file { - void *internal_ptr; -} * duckdb_v2_file_handle; - -/* --- Constants for file system --- */ - -/* --- Function pointer typedefs for file system --- */ - -/*! - * Receives one path matched by `duckdb_v2_file_system_path_glob()`. - * - * The view is borrowed for the duration of the call only, and is not guaranteed to be null-terminated. Report an error - * through `err`, a live slot that must not be destroyed, to stop the glob: `duckdb_v2_file_system_path_glob()` then - * fails with that error. The callback must not throw or unwind across the boundary. - */ -typedef void (*duckdb_v2_file_system_path_glob_callback_fn)(const char *path, idx_t path_length, void *user_data, - duckdb_v2_error_info_handle *err); - -/* --- Functions for file system --- */ - #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Borrows the file system of a context. + * Expands a path as the file system does when opening it: a leading `~` becomes the home directory, as the + * `home_directory` setting configures it. * - * The returned handle is borrowed: it is valid only for as long as the context is, and must not be destroyed. + * A path without anything to expand is handed back as it is. The expanded path is handed to `sink` in a single call. * * history: * - unstable: v2.0.0 * - * @param context The context to take the file system from. - * @param file_system Receives the borrowed file system. + * @param file_system The file system whose settings expand the path. + * @param path The path to expand. Borrowed for the call only. + * @param path_length The length of `path` in bytes. `path` need not be null-terminated and may be NULL only when this + * is 0. + * @param sink Receives the expanded path in a single call. Borrowed for the duration of that call; see text_sink for + * the full contract. + * @param user_data Opaque pointer passed through to sink untouched. May be NULL. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_context_get_file_system(duckdb_v2_context_handle context, - duckdb_v2_file_system_handle *file_system, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_path_expand(duckdb_v2_file_system_handle file_system, + const char *path, idx_t path_length, + duckdb_v2_text_sink_fn sink, void *user_data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Borrows the file system of an instance. - * - * Paths are resolved with the instance's GLOBAL settings and secrets, and file I/O is not attributed to any query. + * Finds the files matching a glob pattern, e.g. `*.csv` or `data_?.json` in a directory, handing each matched path to + * `callback`. * - * The returned handle is borrowed: it is valid only for as long as the instance is, and must not be destroyed. + * The pattern is routed the way `duckdb_v2_file_system_open()` routes a path, so globbing a remote path may reach out + * to the file system handling it, and is only supported where that file system supports it. A pattern without glob + * characters matches the file it names, if there is one. Matching nothing is not an error. In which order the paths are + * handed over is up to the file system. * * history: * - unstable: v2.0.0 * - * @param instance The instance to take the file system from. - * @param file_system Receives the borrowed file system. + * @param file_system The file system to glob in. + * @param pattern The glob pattern. Borrowed for the call only. + * @param pattern_length The length of `pattern` in bytes. `pattern` need not be null-terminated and may be NULL only + * when this is 0. + * @param callback Invoked once per matched path. + * @param user_data Opaque pointer passed through to `callback` untouched. May be NULL. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_get_file_system(duckdb_v2_instance_handle instance, - duckdb_v2_file_system_handle *file_system, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_path_glob(duckdb_v2_file_system_handle file_system, + const char *pattern, idx_t pattern_length, + duckdb_v2_file_system_path_glob_callback_fn callback, + void *user_data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Borrows the file system of a connection. - * - * Paths are resolved with the connection's settings and secrets, and file I/O is attributed to its running query, as - * through `duckdb_v2_context_get_file_system()` in a callback. + * Moves, or renames, a file from one path to another. * - * The returned handle is borrowed: it is valid only for as long as the connection is, and must not be destroyed. + * The move is handled by the file system `source` routes to, the way `duckdb_v2_file_system_open()` routes a path; + * moving a file between two file systems is not supported. Whether an existing file at `target` is replaced, and + * whether the move is atomic, is up to that file system. * * history: * - unstable: v2.0.0 * - * @param conn The connection to take the file system from. - * @param file_system Receives the borrowed file system. + * @param file_system The file system to move the file in. + * @param source The path of the file to move. Borrowed for the call only. + * @param source_length The length of `source` in bytes. `source` need not be null-terminated and may be NULL only when + * this is 0. + * @param target The path to move the file to. Borrowed for the call only. + * @param target_length The length of `target` in bytes. `target` need not be null-terminated and may be NULL only when + * this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_get_file_system(duckdb_v2_connection_handle conn, - duckdb_v2_file_system_handle *file_system, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_path_move(duckdb_v2_file_system_handle file_system, + const char *source, idx_t source_length, + const char *target, idx_t target_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a set of open options for a file system. - * - * The options start out empty: give them flags with `duckdb_v2_file_open_options_set_flag()`, which is required, and - * optionally attach values with `duckdb_v2_file_open_options_set_value()`. They are then passed to - * `duckdb_v2_file_system_open()`, and can be reused for as many opens as you like. The caller owns the returned handle - * and must destroy it with `duckdb_v2_file_open_options_destroy()`. + * Removes the file at a path, if there is one. * - * The options belong to the file system they were created from, since which values mean anything depends on which file - * system ends up handling the path. + * The path is routed the way `duckdb_v2_file_system_open()` routes it. A path with no file is not an error: + * `out_removed` then receives false. A file that exists but cannot be removed is. * * history: * - unstable: v2.0.0 * - * @param file_system The file system the options are for. - * @param options On success, receives the new options. Owned by the caller; destroy via - * `duckdb_v2_file_open_options_destroy()`. + * @param file_system The file system to remove the file from. + * @param path The path of the file to remove. Borrowed for the call only. + * @param path_length The length of `path` in bytes. `path` need not be null-terminated and may be NULL only when this + * is 0. + * @param out_removed Optional. Receives whether a file was removed. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_open_options_create(duckdb_v2_file_system_handle file_system, - duckdb_v2_file_open_options_handle *options, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_path_remove(duckdb_v2_file_system_handle file_system, + const char *path, idx_t path_length, bool *out_removed, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Applies one flag to the options. + * Reads from the file into a caller-supplied buffer. * - * Additive: call it once per behaviour you want, and applying the same flag twice is harmless. At least one flag must - * be applied before the options can open anything, since the flags are what say whether the file is being read or - * written. There is no way to take a flag back -- build a fresh set of options instead. + * Reads up to `buffer_size` bytes from the file's current position, advancing it by however many were read. Fewer bytes + * than asked for is normal at the end of the file, and zero means there is nothing left; neither is an error. The file + * must have been opened with `FILE_FLAG_READ`. * - * `FILE_FLAG_INVALID` names no behaviour and is rejected, as is any value that is not a `DUCKDB_V2_FILE_FLAG`. + * Use `duckdb_v2_file_read_at()` to read at an explicit offset instead, which leaves the position alone and so can run + * on several threads at once. * * history: * - unstable: v2.0.0 * - * @param options The options to apply the flag to. - * @param flag The flag to apply. + * @param file The file to read from. + * @param buffer A caller-owned buffer of at least `buffer_size` bytes, receiving what was read. + * @param buffer_size The maximum number of bytes to read. + * @param bytes_read Receives how many bytes were actually read, which may be fewer than `buffer_size` at the end of the + * file. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_open_options_set_flag(duckdb_v2_file_open_options_handle options, - DUCKDB_V2_FILE_FLAG flag, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_read(duckdb_v2_file_handle file, void *buffer, idx_t buffer_size, + idx_t *bytes_read, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Attaches a named value to the options. + * Writes a caller-supplied buffer to the file. * - * These are hints for whichever file system ends up handling the path, and what they mean is that file system's - * business: a value it does not recognise is ignored rather than rejected, and the same name can mean different things - * to different file systems. They are the same values a file system reports when listing files, so a known file size or - * modification time learned from a listing can be handed straight back to avoid re-reading it. + * Writes up to `buffer_size` bytes at the file's current position, advancing it by however many were written. The file + * must have been opened with `FILE_FLAG_WRITE` or `FILE_FLAG_APPEND`. Writes may be buffered; use + * `duckdb_v2_file_sync()` to force them out. * - * The name and the value are borrowed and copied, so the caller may destroy the value immediately after. Setting the - * same name again replaces the previous value. Names are case-sensitive. + * Use `duckdb_v2_file_write_at()` to write at an explicit offset instead, which leaves the position alone and so can + * run on several threads at once. * * history: * - unstable: v2.0.0 * - * @param options The options to set the value on. - * @param name The name of the value. Borrowed and copied. - * @param name_length The length of `name` in bytes. `name` need not be null-terminated and may be NULL only when this - * is 0. - * @param value The value. Borrowed and copied. + * @param file The file to write to. + * @param buffer A caller-owned buffer of at least `buffer_size` bytes, holding what to write. + * @param buffer_size The number of bytes to write. + * @param bytes_written Receives how many bytes were actually written. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_open_options_set_value(duckdb_v2_file_open_options_handle options, - const char *name, idx_t name_length, - duckdb_v2_value_handle value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_write(duckdb_v2_file_handle file, const void *buffer, idx_t buffer_size, + idx_t *bytes_written, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys the options, releasing their resources. + * Reads from a fixed offset, without moving the file's position. * - * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent - * double-destruction. Files already opened with these options are unaffected. + * Reads exactly `buffer_size` bytes starting at `location`. Unlike `duckdb_v2_file_read()`, a short read is an error + * rather than a result: reaching the end of the file before `buffer_size` bytes fails, so there is no count to report + * back. The file's read/write position is untouched, which is what makes this safe to call from several threads at once + * -- provided the file was opened with `FILE_FLAG_PARALLEL_ACCESS`. + * + * The file must have been opened with `FILE_FLAG_READ`. * * history: * - unstable: v2.0.0 * - * @param options The options to destroy. + * @param file The file to read from. + * @param buffer A caller-owned buffer of at least `buffer_size` bytes, receiving what was read. + * @param buffer_size The number of bytes to read. All of them are read, or the call fails. + * @param location The absolute byte offset to read from, measured from the start of the file. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_open_options_destroy(duckdb_v2_file_open_options_handle *options); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_read_at(duckdb_v2_file_handle file, void *buffer, idx_t buffer_size, + idx_t location, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Opens a file. - * - * Opens the file at the given path through the file system, which routes it the way the engine would -- a path handled - * by a registered virtual or remote file system goes there rather than to local disk. The returned handle is owned by - * the caller and must be destroyed with `duckdb_v2_file_destroy()`. - * - * The options carry the flags and any file-system-specific values; see `duckdb_v2_file_open_options_create()`. Opening - * without having set flags fails, since the flags are what say whether the file is being read or written. + * Writes at a fixed offset, without moving the file's position. * - * Failure to open -- a missing file without `FILE_FLAG_CREATE`, insufficient permissions, an existing file under - * `FILE_FLAG_EXCLUSIVE_CREATE` -- is reported as an error. + * Writes exactly `buffer_size` bytes starting at `location`, extending the file when the offset is past its end. Unlike + * `duckdb_v2_file_write()` there is no count to report back: all of the bytes are written, or the call fails. The + * file's read/write position is untouched, which is what makes this safe to call from several threads at once -- + * provided the file was opened with `FILE_FLAG_PARALLEL_ACCESS`, and that the threads write disjoint ranges. * - * Flag combinations that contradict each other, such as naming neither read nor write or combining `FILE_FLAG_CREATE` - * with `FILE_FLAG_CREATE_NEW`, are a programming error rather than a supported input. An assertion build catches them; - * elsewhere the behaviour is whatever the underlying file system does with them. + * The file must have been opened with `FILE_FLAG_WRITE`. Writes may be buffered; use `duckdb_v2_file_sync()` to force + * them out. * * history: * - unstable: v2.0.0 * - * @param file_system The file system to open the file through. - * @param file_path The path of the file to open. Borrowed for the call only. - * @param file_path_length The length of `file_path` in bytes. `file_path` need not be null-terminated and may be NULL - * only when this is 0. - * @param options How to open the file. Borrowed for the call only, and reusable across opens. - * @param file On success, receives the open file. Owned by the caller; destroy via `duckdb_v2_file_destroy()`. + * @param file The file to write to. + * @param buffer A caller-owned buffer of at least `buffer_size` bytes, holding what to write. + * @param buffer_size The number of bytes to write. All of them are written, or the call fails. + * @param location The absolute byte offset to write at, measured from the start of the file. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_open(duckdb_v2_file_system_handle file_system, const char *file_path, - idx_t file_path_length, - duckdb_v2_file_open_options_handle options, - duckdb_v2_file_handle *file, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_write_at(duckdb_v2_file_handle file, const void *buffer, idx_t buffer_size, + idx_t location, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Reports whether a file exists at the given path. - * - * The path is routed the way `duckdb_v2_file_system_open()` routes it, so asking about a path handled by a remote file - * system may reach out to it. A directory is not a file, and reports false. + * Returns the file's current read/write position, as a byte offset from the start of the file. * * history: * - unstable: v2.0.0 * - * @param file_system The file system to ask. - * @param path The path to check. Borrowed for the call only. - * @param path_length The length of `path` in bytes. `path` need not be null-terminated and may be NULL only when this - * is 0. - * @param out_exists Receives whether a file exists at the path. + * @param file The file to query. + * @param position Receives the current position, as a byte offset from the start of the file. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_path_exists(duckdb_v2_file_system_handle file_system, - const char *path, idx_t path_length, bool *out_exists, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_tell(duckdb_v2_file_handle file, idx_t *position, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Reports whether a path names a remote file, e.g. one under `s3://`, `https://`, `gcs://` or `azure://`. - * - * Decided from the path alone: no file system is consulted, so it answers even when the extension providing the remote - * file system is not loaded. + * Returns the total size of the file in bytes. * * history: * - unstable: v2.0.0 * - * @param file_system The file system the path is meant for. - * @param path The path to check. Borrowed for the call only. - * @param path_length The length of `path` in bytes. `path` need not be null-terminated and may be NULL only when this - * is 0. - * @param out_is_remote Receives whether the path names a remote file. + * @param file The file to query. + * @param size Receives the total size of the file in bytes. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_path_is_remote(duckdb_v2_file_system_handle file_system, - const char *path, idx_t path_length, - bool *out_is_remote, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_size(duckdb_v2_file_handle file, idx_t *size, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Expands a path as the file system does when opening it: a leading `~` becomes the home directory, as the - * `home_directory` setting configures it. + * Moves the file's read/write position. * - * A path without anything to expand is handed back as it is. The expanded path is handed to `sink` in a single call. + * Sets the position to an absolute byte offset from the start of the file; subsequent reads and writes start there. + * Seeking past the end is allowed, and reading from there yields nothing. * * history: * - unstable: v2.0.0 * - * @param file_system The file system whose settings expand the path. - * @param path The path to expand. Borrowed for the call only. - * @param path_length The length of `path` in bytes. `path` need not be null-terminated and may be NULL only when this - * is 0. - * @param sink Receives the expanded path in a single call. Borrowed for the duration of that call; see text_sink for - * the full contract. - * @param user_data Opaque pointer passed through to sink untouched. May be NULL. + * @param file The file to seek within. + * @param position The absolute byte offset to seek to, measured from the start of the file. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_path_expand(duckdb_v2_file_system_handle file_system, - const char *path, idx_t path_length, - duckdb_v2_text_sink_fn sink, void *user_data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_seek(duckdb_v2_file_handle file, idx_t position, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Finds the files matching a glob pattern, e.g. `*.csv` or `data_?.json` in a directory, handing each matched path to - * `callback`. + * Flushes buffered writes to persistent storage. * - * The pattern is routed the way `duckdb_v2_file_system_open()` routes a path, so globbing a remote path may reach out - * to the file system handling it, and is only supported where that file system supports it. A pattern without glob - * characters matches the file it names, if there is one. Matching nothing is not an error. In which order the paths are - * handed over is up to the file system. + * Forces anything still buffered out to storage, which is what makes writes durable across a crash or a process exit. + * Closing or destroying the handle flushes as well. * * history: * - unstable: v2.0.0 * - * @param file_system The file system to glob in. - * @param pattern The glob pattern. Borrowed for the call only. - * @param pattern_length The length of `pattern` in bytes. `pattern` need not be null-terminated and may be NULL only - * when this is 0. - * @param callback Invoked once per matched path. - * @param user_data Opaque pointer passed through to `callback` untouched. May be NULL. + * @param file The file to synchronize. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_path_glob(duckdb_v2_file_system_handle file_system, - const char *pattern, idx_t pattern_length, - duckdb_v2_file_system_path_glob_callback_fn callback, - void *user_data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_sync(duckdb_v2_file_handle file, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Moves, or renames, a file from one path to another. + * Closes the file without destroying the handle. * - * The move is handled by the file system `source` routes to, the way `duckdb_v2_file_system_open()` routes a path; - * moving a file between two file systems is not supported. Whether an existing file at `target` is replaced, and - * whether the move is atomic, is up to that file system. + * Releases the operating-system resources behind the file, such as its descriptor. The handle itself stays valid and + * must still be destroyed with `duckdb_v2_file_destroy()`, but it can no longer read, write or seek. * * history: * - unstable: v2.0.0 * - * @param file_system The file system to move the file in. - * @param source The path of the file to move. Borrowed for the call only. - * @param source_length The length of `source` in bytes. `source` need not be null-terminated and may be NULL only when - * this is 0. - * @param target The path to move the file to. Borrowed for the call only. - * @param target_length The length of `target` in bytes. `target` need not be null-terminated and may be NULL only when - * this is 0. + * @param file The file to close. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_path_move(duckdb_v2_file_system_handle file_system, - const char *source, idx_t source_length, - const char *target, idx_t target_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_close(duckdb_v2_file_handle file, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Removes the file at a path, if there is one. + * Destroys the file, closing it if it is still open. * - * The path is routed the way `duckdb_v2_file_system_open()` routes it. A path with no file is not an error: - * `out_removed` then receives false. A file that exists but cannot be removed is. - * - * history: - * - unstable: v2.0.0 - * - * @param file_system The file system to remove the file from. - * @param path The path of the file to remove. Borrowed for the call only. - * @param path_length The length of `path` in bytes. `path` need not be null-terminated and may be NULL only when this - * is 0. - * @param out_removed Optional. Receives whether a file was removed. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_system_path_remove(duckdb_v2_file_system_handle file_system, - const char *path, idx_t path_length, bool *out_removed, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Reads from the file into a caller-supplied buffer. - * - * Reads up to `buffer_size` bytes from the file's current position, advancing it by however many were read. Fewer bytes - * than asked for is normal at the end of the file, and zero means there is nothing left; neither is an error. The file - * must have been opened with `FILE_FLAG_READ`. - * - * Use `duckdb_v2_file_read_at()` to read at an explicit offset instead, which leaves the position alone and so can run - * on several threads at once. - * - * history: - * - unstable: v2.0.0 - * - * @param file The file to read from. - * @param buffer A caller-owned buffer of at least `buffer_size` bytes, receiving what was read. - * @param buffer_size The maximum number of bytes to read. - * @param bytes_read Receives how many bytes were actually read, which may be fewer than `buffer_size` at the end of the - * file. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_read(duckdb_v2_file_handle file, void *buffer, idx_t buffer_size, - idx_t *bytes_read, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Writes a caller-supplied buffer to the file. - * - * Writes up to `buffer_size` bytes at the file's current position, advancing it by however many were written. The file - * must have been opened with `FILE_FLAG_WRITE` or `FILE_FLAG_APPEND`. Writes may be buffered; use - * `duckdb_v2_file_sync()` to force them out. - * - * Use `duckdb_v2_file_write_at()` to write at an explicit offset instead, which leaves the position alone and so can - * run on several threads at once. - * - * history: - * - unstable: v2.0.0 - * - * @param file The file to write to. - * @param buffer A caller-owned buffer of at least `buffer_size` bytes, holding what to write. - * @param buffer_size The number of bytes to write. - * @param bytes_written Receives how many bytes were actually written. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_write(duckdb_v2_file_handle file, const void *buffer, idx_t buffer_size, - idx_t *bytes_written, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Reads from a fixed offset, without moving the file's position. - * - * Reads exactly `buffer_size` bytes starting at `location`. Unlike `duckdb_v2_file_read()`, a short read is an error - * rather than a result: reaching the end of the file before `buffer_size` bytes fails, so there is no count to report - * back. The file's read/write position is untouched, which is what makes this safe to call from several threads at once - * -- provided the file was opened with `FILE_FLAG_PARALLEL_ACCESS`. - * - * The file must have been opened with `FILE_FLAG_READ`. - * - * history: - * - unstable: v2.0.0 - * - * @param file The file to read from. - * @param buffer A caller-owned buffer of at least `buffer_size` bytes, receiving what was read. - * @param buffer_size The number of bytes to read. All of them are read, or the call fails. - * @param location The absolute byte offset to read from, measured from the start of the file. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_read_at(duckdb_v2_file_handle file, void *buffer, idx_t buffer_size, - idx_t location, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Writes at a fixed offset, without moving the file's position. - * - * Writes exactly `buffer_size` bytes starting at `location`, extending the file when the offset is past its end. Unlike - * `duckdb_v2_file_write()` there is no count to report back: all of the bytes are written, or the call fails. The - * file's read/write position is untouched, which is what makes this safe to call from several threads at once -- - * provided the file was opened with `FILE_FLAG_PARALLEL_ACCESS`, and that the threads write disjoint ranges. - * - * The file must have been opened with `FILE_FLAG_WRITE`. Writes may be buffered; use `duckdb_v2_file_sync()` to force - * them out. - * - * history: - * - unstable: v2.0.0 - * - * @param file The file to write to. - * @param buffer A caller-owned buffer of at least `buffer_size` bytes, holding what to write. - * @param buffer_size The number of bytes to write. All of them are written, or the call fails. - * @param location The absolute byte offset to write at, measured from the start of the file. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_write_at(duckdb_v2_file_handle file, const void *buffer, idx_t buffer_size, - idx_t location, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Returns the file's current read/write position, as a byte offset from the start of the file. - * - * history: - * - unstable: v2.0.0 - * - * @param file The file to query. - * @param position Receives the current position, as a byte offset from the start of the file. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_tell(duckdb_v2_file_handle file, idx_t *position, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Returns the total size of the file in bytes. - * - * history: - * - unstable: v2.0.0 - * - * @param file The file to query. - * @param size Receives the total size of the file in bytes. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_size(duckdb_v2_file_handle file, idx_t *size, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Moves the file's read/write position. - * - * Sets the position to an absolute byte offset from the start of the file; subsequent reads and writes start there. - * Seeking past the end is allowed, and reading from there yields nothing. - * - * history: - * - unstable: v2.0.0 - * - * @param file The file to seek within. - * @param position The absolute byte offset to seek to, measured from the start of the file. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_seek(duckdb_v2_file_handle file, idx_t position, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Flushes buffered writes to persistent storage. - * - * Forces anything still buffered out to storage, which is what makes writes durable across a crash or a process exit. - * Closing or destroying the handle flushes as well. - * - * history: - * - unstable: v2.0.0 - * - * @param file The file to synchronize. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_sync(duckdb_v2_file_handle file, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Closes the file without destroying the handle. - * - * Releases the operating-system resources behind the file, such as its descriptor. The handle itself stays valid and - * must still be destroyed with `duckdb_v2_file_destroy()`, but it can no longer read, write or seek. - * - * history: - * - unstable: v2.0.0 - * - * @param file The file to close. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_file_close(duckdb_v2_file_handle file, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Destroys the file, closing it if it is still open. - * - * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent - * double-destruction. + * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent + * double-destruction. * * history: * - unstable: v2.0.0 @@ -8131,2313 +7799,2177 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_token_iterator_destroy(duckdb_v2_token_it /* --- Struct definitions for tokenizer --- */ /* ============================================================================ - * MODULE: aggregate + * MODULE: vector * ============================================================================ */ -/* --- Enums for aggregate --- */ - -/* --- Struct forward declarations for aggregate --- */ - -/* --- Types for aggregate --- */ +/* --- Enums for vector --- */ /*! - * An owned opaque handle to a custom aggregate function being built. Created with - * `duckdb_v2_aggregate_function_create()`, configured with the setter functions (e.g. - * `duckdb_v2_aggregate_function_set_name()`, `duckdb_v2_aggregate_function_set_update_callback()`, etc.) and the - * signature obtained via `duckdb_v2_aggregate_function_get_signature()`, made available with - * `duckdb_v2_connection_register_aggregate_function()` or `duckdb_v2_extension_register_aggregate_function()`, and - * destroyed with `duckdb_v2_aggregate_function_destroy()`. + * Internal representation of a vector, with FSST / SEQUENCE / SHREDDED collapsed into OTHER: the view getter rejects + * those and requires an explicit vector_flatten first. OTHER is the 0-value, so a zero-initialized out-param reads as + * "unspecified, needs flatten" rather than silently looking like FLAT. */ -typedef struct _duckdb_v2_aggregate_function { - void *internal_ptr; -} * duckdb_v2_aggregate_function_handle; +typedef enum DUCKDB_V2_VECTOR_TYPE { + //! Default for zero-init. Covers FSST / SEQUENCE / SHREDDED — call vector_flatten first. + DUCKDB_V2_VECTOR_TYPE_OTHER = 0, -/*! - * A borrowed opaque handle to the result of an aggregate function's "bind" phase. The "bind" callback receives this - * handle next to a `duckdb_v2_function_bind_info_handle`, which gives access to the arguments, the user data and the - * bind data, and can use it to set the return type of the call site being bound. - */ -typedef struct _duckdb_v2_aggregate_function_bind_info { - void *internal_ptr; -} * duckdb_v2_aggregate_function_bind_info_handle; + //! Standard per-row storage. + DUCKDB_V2_VECTOR_TYPE_FLAT = 1, -/*! - * A borrowed opaque handle to the arguments supplied to an aggregate function during the "stats" phase of query - * optimization. The "stats" callback receives this handle and can use it to read the statistics of the arguments of the - * call site and narrow the statistics of its result. - */ -typedef struct _duckdb_v2_aggregate_function_stats_info { - void *internal_ptr; -} * duckdb_v2_aggregate_function_stats_info_handle; - -/*! - * A borrowed opaque handle to the arguments supplied to an aggregate function during the state sizing "size" phase. The - * "size" callback receives this handle and must use it to report the size of a single aggregate state in bytes. - */ -typedef struct _duckdb_v2_aggregate_function_size_info { - void *internal_ptr; -} * duckdb_v2_aggregate_function_size_info_handle; - -/*! - * A borrowed opaque handle to the arguments supplied to an aggregate function during the state initialization "init" - * phase. The "init" callback receives this handle and can use it to access the array of aggregate states it must - * initialize in place. - */ -typedef struct _duckdb_v2_aggregate_function_init_info { - void *internal_ptr; -} * duckdb_v2_aggregate_function_init_info_handle; - -/*! - * A borrowed opaque handle to the arguments supplied to an aggregate function during the "update" phase. The "update" - * callback receives this handle and can use it to access the input argument vectors, the number of rows to process, and - * the aggregate state each row must be aggregated into. - */ -typedef struct _duckdb_v2_aggregate_function_update_info { - void *internal_ptr; -} * duckdb_v2_aggregate_function_update_info_handle; - -/*! - * A borrowed opaque handle to the arguments supplied to an aggregate function during the "combine" phase. The "combine" - * callback receives this handle and can use it to access the source and target aggregate state arrays to merge. - */ -typedef struct _duckdb_v2_aggregate_function_combine_info { - void *internal_ptr; -} * duckdb_v2_aggregate_function_combine_info_handle; + //! A single value applies to every row in the vector. + DUCKDB_V2_VECTOR_TYPE_CONSTANT = 2, -/*! - * A borrowed opaque handle to the arguments supplied to an aggregate function during the "finalize" phase. The - * "finalize" callback receives this handle and can use it to access the aggregate states and the result vector and - * offset to write their final values to. - */ -typedef struct _duckdb_v2_aggregate_function_finalize_info { - void *internal_ptr; -} * duckdb_v2_aggregate_function_finalize_info_handle; + //! Data + selection vector indirection into another vector. + DUCKDB_V2_VECTOR_TYPE_DICTIONARY = 3, + DUCKDB_V2_VECTOR_TYPE_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_VECTOR_TYPE; /*! - * A borrowed opaque handle to the arguments supplied to an aggregate function during the state destruction "destroy" - * phase. The "destroy" callback receives this handle and can use it to access the array of aggregate states whose - * resources must be released. + * The mode a cast is being executed in. A normal cast must either succeed for every row or report an error, which + * aborts the query. A "try" cast (SQL TRY_CAST, and implicit casts the engine probes speculatively) tolerates per-row + * failures: the callback writes NULL for the rows it could not convert instead of aborting, and still reports the + * failure through the error slot once the batch is written: that makes the cast return "not every row converted", which + * callers that probe a cast, such as the CSV sniffer, rely on. Passed to `duckdb_v2_vector_cast()`; see + * `duckdb_v2_cast_function_set_function()` and `duckdb_v2_cast_function_set_try_function()` for the functions that + * implement the two modes of a cast. */ -typedef struct _duckdb_v2_aggregate_function_destroy_info { - void *internal_ptr; -} * duckdb_v2_aggregate_function_destroy_info_handle; +typedef enum DUCKDB_V2_CAST_MODE { + //! A regular cast. A conversion failure reported through the error slot aborts the query. + DUCKDB_V2_CAST_MODE_NORMAL = 0, -/* --- Constants for aggregate --- */ + /*! + * A "try" cast. Conversion failures should be written as NULLs into the output vector and reported through the + * error slot once the batch is written; the error is swallowed, the rows the callback wrote stay, and the cast + * reports that not every row converted. A callback that leaves a row NULL without reporting an error tells the + * engine the row converted. + */ + DUCKDB_V2_CAST_MODE_TRY = 1, + DUCKDB_V2_CAST_MODE_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_CAST_MODE; -/* --- Function pointer typedefs for aggregate --- */ +/* --- Struct forward declarations for vector --- */ -typedef void (*duckdb_v2_aggregate_function_bind_callback_fn)(duckdb_v2_function_bind_info_handle info, - duckdb_v2_aggregate_function_bind_info_handle result, - duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); +typedef struct duckdb_v2_vector_view duckdb_v2_vector_view; -typedef void (*duckdb_v2_aggregate_function_stats_callback_fn)(duckdb_v2_aggregate_function_stats_info_handle info, - duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); +typedef struct duckdb_v2_list_entry duckdb_v2_list_entry; -typedef void (*duckdb_v2_aggregate_function_size_callback_fn)(duckdb_v2_aggregate_function_size_info_handle info, - duckdb_v2_error_info_handle *err); +typedef struct duckdb_v2_hugeint_t duckdb_v2_hugeint_t; -typedef void (*duckdb_v2_aggregate_function_init_callback_fn)(duckdb_v2_aggregate_function_init_info_handle info, - duckdb_v2_error_info_handle *err); +typedef struct duckdb_v2_uhugeint_t duckdb_v2_uhugeint_t; -typedef void (*duckdb_v2_aggregate_function_update_callback_fn)(duckdb_v2_aggregate_function_update_info_handle info, - duckdb_v2_error_info_handle *err); +typedef struct duckdb_v2_interval_t duckdb_v2_interval_t; -typedef void (*duckdb_v2_aggregate_function_combine_callback_fn)(duckdb_v2_aggregate_function_combine_info_handle info, - duckdb_v2_error_info_handle *err); +/* --- Types for vector --- */ -typedef void (*duckdb_v2_aggregate_function_finalize_callback_fn)( - duckdb_v2_aggregate_function_finalize_info_handle info, duckdb_v2_error_info_handle *err); +/* --- Constants for vector --- */ -typedef void (*duckdb_v2_aggregate_function_destroy_callback_fn)(duckdb_v2_aggregate_function_destroy_info_handle info, - duckdb_v2_error_info_handle *err); +/* --- Function pointer typedefs for vector --- */ -/* --- Functions for aggregate --- */ +/* --- Functions for vector --- */ #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a new aggregate function through a factory. - * - * The function starts out empty: configure it with the setter functions (e.g. - * `duckdb_v2_aggregate_function_set_name()`, `duckdb_v2_aggregate_function_set_update_callback()`, etc.) and the - * signature obtained via `duckdb_v2_aggregate_function_get_signature()`, then make it available with - * `duckdb_v2_connection_register_aggregate_function()` or `duckdb_v2_extension_register_aggregate_function()`. The - * caller owns the returned handle and must destroy it with `duckdb_v2_aggregate_function_destroy()`, also after - * registration. + * Returns the internal representation kind: flat, constant, or dictionary. * - * The aggregate function can only be registered on the database the factory belongs to. + * Reports VECTOR_TYPE_OTHER for FSST / SEQUENCE / SHREDDED vectors, which must be passed through vector_flatten before + * vector_get_view will read them. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create the aggregate function through. - * @param function On success, receives the newly created aggregate function. Owned by the caller. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector. + * @param out_type Receives the representation kind. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_create(duckdb_v2_factory_handle factory, - duckdb_v2_aggregate_function_handle *function, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_get_vector_type(duckdb_v2_vector_handle vector, + DUCKDB_V2_VECTOR_TYPE *out_type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the name of the aggregate function. + * Returns the vector's logical type. * - * The name is borrowed and copied. Calling this again replaces the previous name. A name must be set before - * registration. + * The returned logical type is the same type that was passed to vector_reference, or the type that was set on creation. + * It is caller-owned; destroy it via logical_type_destroy. * * history: * - unstable: v2.0.0 * - * @param function The function to set the name of. - * @param name The name to set. Borrowed and copied. - * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be - * NULL only when this is 0. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector. + * @param out_type Receives the caller-owned logical type handle. Destroy via logical_type_destroy. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_name(duckdb_v2_aggregate_function_handle function, - const char *name, idx_t name_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_get_logical_type(duckdb_v2_vector_handle vector, + duckdb_v2_logical_type_handle *out_type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the documentation of the function so it can be filled in. + * Reads a vector as a unified view of data, validity, selection, and count. * - * Set a description with `duckdb_v2_function_docs_set_description()`, and add examples and categories with - * `duckdb_v2_function_docs_add_example()` and `duckdb_v2_function_docs_add_category()`. The documentation is modified - * in place, describes this overload only, and is registered with the function. Optional. + * Populates out_view with borrowed pointers, valid until the owning chunk is destroyed. view.data addresses the + * vector's elements, to be cast to the layout its logical type implies: a typed leaf array for the primitives, + * hugeint_t / uhugeint_t / interval_t for those kinds, bytes for VARCHAR / BLOB / BIT / BIGNUM, list_entry for LIST and + * MAP, and nothing at all for ARRAY / STRUCT / UNION, whose data lives in their children. + * + * DECIMAL and ENUM are typed leaf arrays too, over a storage tier that follows from the type; both mappings are + * contract. A DECIMAL of width <= 4 stores int16, <= 9 int32, <= 18 int64, and <= 38 int128, boundaries inclusive, with + * the width and scale available from logical_type_get_param. An ENUM stores its dictionary indices as uint8 for a + * dictionary of at most 255 entries, uint16 for at most 65535, and uint32 beyond that, boundaries inclusive and an + * empty dictionary uint8; logical_type_get_param resolves an index to its entry. + * + * Rejects VECTOR_TYPE_OTHER; call vector_flatten first. + * + * Reading a DICTIONARY vector has one side effect: the dictionary's underlying child is flattened in place if it is not + * already FLAT. The parent vector stays DICTIONARY, and only the child's storage shape changes, but any pointer + * previously borrowed into that child — from an earlier vector_get_view on a vector aliasing the same buffer, say — is + * invalidated. This is the only mutation vector_get_view performs; compare vector_flatten, which materializes the whole + * vector to FLAT. * * history: * - unstable: v2.0.0 * - * @param function The function to get the documentation of. - * @param docs The returned documentation. Borrowed and valid for the lifetime of the function handle. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector to read. + * @param out_view Receives the view. Its pointers are borrowed and valid until the owning chunk is destroyed. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_get_docs(duckdb_v2_aggregate_function_handle function, - duckdb_v2_function_docs_handle *docs, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_get_view(duckdb_v2_vector_handle vector, duckdb_v2_vector_view *out_view, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the function's signature so it can be configured. + * Returns the number of elements in the vector. * - * Add parameters with `duckdb_v2_function_signature_add_parameter()` and set the return type with - * `duckdb_v2_function_signature_set_return_type()`. The signature is modified in place; the function must be given a - * signature with a return type before registration. + * The size is the number of logical elements the vector represents, which for a nested kind can differ from the size of + * its children. An ARRAY vector of size 10 whose array size is 3, for instance, has 10 logical elements while its + * single child vector has 30. * * history: * - unstable: v2.0.0 * - * @param function The function to get the signature of. - * @param sig The returned signature. Borrowed and valid for the lifetime of the function handle. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector. + * @param out_size Receives the number of elements. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_get_signature(duckdb_v2_aggregate_function_handle function, - duckdb_v2_function_signature_handle *sig, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_get_size(duckdb_v2_vector_handle vector, idx_t *out_size, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets arbitrary user data on the aggregate function. + * Sets the number of elements in the vector. * - * Associates an opaque pointer with the function, retrievable from each callback via its user data accessor (e.g. - * `duckdb_v2_function_bind_get_user_data()`, `duckdb_v2_aggregate_function_update_get_user_data()`, etc.). The opaque - * handle bundles the pointer with an optional destructor, invoked when the data is no longer needed. + * The counterpart of vector_get_size: it declares how many logical elements the vector now holds. It reserves enough + * space for size logical elements. * * history: * - unstable: v2.0.0 * - * @param function The function to set the user data of. - * @param data Opaque handle bundling the user data pointer plus an optional destructor. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector. + * @param size The new number of logical elements. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_user_data(duckdb_v2_aggregate_function_handle function, - duckdb_v2_opaque *data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_set_size(duckdb_v2_vector_handle vector, idx_t size, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets a property on the aggregate function. + * Reads one cell of a vector as an owned value. * - * Configures a function property that influences planning and execution, such as stability, NULL handling, fallibility, - * collation handling, or the aggregate-specific order/DISTINCT dependence. The value must be one of the - * `DUCKDB_V2_FUNCTION_PROPERTY_VALUE` entries belonging to `key`; passing a value that does not belong to the key, or a - * key that is not valid for aggregate functions, results in an error. + * The total fallback reader. It reads any logical row of any vector representation without flattening — FLAT, CONSTANT, + * DICTIONARY, and the compressed kinds the view getter rejects — and covers every type kind, including those with no + * committed view layout (today VARIANT and GEOMETRY), where it is the only way to reach a cell. + * + * Each call allocates one owned value, which makes this a single-cell bridge rather than a per-row loop primitive; use + * vector_get_view on hot paths. The row index is logical and bounds-checked against vector_get_size. The returned value + * is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param function The function to set the property of. - * @param key The property to set. - * @param value The value to set for the property. Must belong to `key`. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector to read from. + * @param row The logical row index, in [0, vector_get_size). + * @param out_value Receives the owned cell value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_property(duckdb_v2_aggregate_function_handle function, - DUCKDB_V2_FUNCTION_PROPERTY_KEY key, - DUCKDB_V2_FUNCTION_PROPERTY_VALUE value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_get_value(duckdb_v2_vector_handle vector, idx_t row, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets a generic, named property on the aggregate function. - * - * Generic properties are free-form `name = value` pairs that the engine or extensions can read from a function, e.g. - * `duckdb.collation.combinable = true` marks a collation function as combinable. Setting a property that is already set - * replaces its value. Reading a property that is not set yields NULL, which boolean properties treat as false. + * Writes one cell of a FLAT vector from a value. * - * history: + * The total fallback writer. It covers every type kind, including those with no committed view layout (today VARIANT + * and GEOMETRY), where it is the only way to write a cell. The value is borrowed and copied in, then cast to the + * vector's type through the non-strict default cast; a cast failure surfaces from the call. A NULL value clears the + * row's validity. + * + * Requires a FLAT vector: constant, dictionary, and compressed representations are not row-addressable, so call + * vector_flatten first. Each call performs one value write, which makes this a single-cell bridge rather than a per-row + * loop primitive; use the typed mutable-data paths on hot paths. The row index is logical and bounds-checked against + * vector_get_size. + * + * history: * - unstable: v2.0.0 * - * @param function The function to set the property of. - * @param name The name of the property, e.g. `duckdb.collation.combinable`. - * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be - * NULL only when this is 0. - * @param value The value of the property. Borrowed (copied in). - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector to write to. + * @param row The logical row index, in [0, vector_get_size). + * @param value The borrowed value to write. Copied in; cast to the vector's type. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_generic_property( - duckdb_v2_aggregate_function_handle function, const char *name, idx_t name_length, duckdb_v2_value_handle value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_set_value(duckdb_v2_vector_handle vector, idx_t row, + duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Reads a generic, named property of the aggregate function, as set by - * `duckdb_v2_aggregate_function_set_generic_property()`. + * Returns a mutable pointer to the data of a FLAT or CONSTANT vector. * - * A property that is not set is not an error: `out_value` then receives NULL. + * Any other representation returns ERROR_INPUT_INVALID. The pointer is valid until the owning chunk is destroyed, and + * the vector's storage shape must not change — through a flatten, say — while it is in use. + * + * When writing VARCHAR values, the caller must ensure that the bytes contain valid UTF-8. * * history: * - unstable: v2.0.0 * - * @param function The function to read the property of. - * @param name The name of the property, e.g. `duckdb.collation.combinable`. - * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be - * NULL only when this is 0. - * @param out_value Receives the value of the property, owned by the caller, or NULL if the property is not set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector. + * @param out_data Receives a mutable pointer to the data. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_get_generic_property( - duckdb_v2_aggregate_function_handle function, const char *name, idx_t name_length, - duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_get_data_mutable(duckdb_v2_vector_handle vector, void **out_data, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional bind callback of the aggregate function. + * Forces a vector into FLAT representation, in place. * - * The bind callback is invoked during query planning for each call site of the function. Through its - * `duckdb_v2_function_bind_info_handle` it can inspect the argument types and constant argument values and set "bind - * data" that is shared with the other callbacks. Through its `duckdb_v2_aggregate_function_bind_info_handle` it can set - * a concrete return type. + * A no-op for a vector that is already FLAT. For a CONSTANT, DICTIONARY, FSST, SEQUENCE, or SHREDDED vector it + * materializes the per-row data and switches the representation to FLAT. Call it before vector_get_view if you would + * rather not handle CONSTANT and DICTIONARY semantics in the view; it is required for any vector reporting + * VECTOR_TYPE_OTHER. * * history: * - unstable: v2.0.0 * - * @param function The function to set the bind callback of. - * @param callback The bind callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector to flatten. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_bind_callback( - duckdb_v2_aggregate_function_handle function, duckdb_v2_aggregate_function_bind_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_flatten(duckdb_v2_vector_handle vector, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the size callback of the aggregate function. + * Casts every row of a vector into another vector, using a factory. * - * The size callback reports the size of a single aggregate state in bytes via - * `duckdb_v2_aggregate_function_size_set_state_size()`; DuckDB uses it to allocate state memory. A size callback must - * be set before registration. + * The conversion is the one SQL `CAST` / `TRY_CAST` performs, registered custom casts included, from the type of + * `source` to the type of `target`. It covers as many rows as `source` holds (`duckdb_v2_vector_get_size()`), of any + * representation. `target` is replaced by the result, as `duckdb_v2_vector_reference()` would, taking its size: data + * and views taken from it beforehand do not survive the call, and nothing it held before carries over. In + * CAST_MODE_NORMAL a row that does not convert fails the call with the engine's conversion error, and the contents of + * `target` are unspecified. In CAST_MODE_TRY such rows are NULL in `target` instead and the call succeeds; compare the + * validity of `source` and `target` to find them. `cast_err` then receives the conversion error of one of them, e.g. to + * report why the cast did not convert every row. + * + * A connection's or callback's factory casts with that client's cast functions and settings (e.g. TimeZone). An + * instance's factory supports only the built-in casts, with default settings. `source` and `target` must be different + * vectors; `target` is typically a vector of a data chunk created by the caller, or the result vector of a callback. * * history: * - unstable: v2.0.0 * - * @param function The function to set the size callback of. - * @param callback The size callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory supplying the cast functions. + * @param source The vector to cast. Borrowed for the call only. + * @param target The vector to write the cast rows into. Its logical type is the target type. + * @param mode Whether a row that does not convert fails the call, or becomes NULL. + * @param out_converted Optional. Receives whether every row converted. Always true when a CAST_MODE_NORMAL cast + * succeeds. + * @param cast_err Optional. When a CAST_MODE_TRY cast succeeds without converting every row, receives an opaque info + * handle with the conversion error of one row that did not convert, which the caller must destroy via + * error_info_destroy. Otherwise receives NULL. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_size_callback( - duckdb_v2_aggregate_function_handle function, duckdb_v2_aggregate_function_size_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_cast(duckdb_v2_factory_handle factory, duckdb_v2_vector_handle source, + duckdb_v2_vector_handle target, DUCKDB_V2_CAST_MODE mode, + bool *out_converted, duckdb_v2_error_info_handle *cast_err, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the init callback of the aggregate function. + * Repoints a vector at another vector's data, without copying. * - * The init callback initializes freshly allocated aggregate states in place, obtained via - * `duckdb_v2_aggregate_function_init_get_states()`. An init callback must be set before registration. + * `vector` takes on the storage of `source`: no data moves, and the two alias the same buffers until one of them is + * reset or re-referenced. Works for any type, including nested types. The source's logical type must equal the + * vector's; a mismatch returns ERROR_INPUT_INVALID. The source's data must outlive every read of `vector`. Use it to + * hand an already-materialized vector straight to an output vector without a per-row copy. * * history: * - unstable: v2.0.0 * - * @param function The function to set the init callback of. - * @param callback The init callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector to repoint at the source's data. + * @param source The vector whose data to reference. Its logical type must equal the vector's. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_init_callback( - duckdb_v2_aggregate_function_handle function, duckdb_v2_aggregate_function_init_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_reference(duckdb_v2_vector_handle vector, duckdb_v2_vector_handle source, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the update callback of the aggregate function. + * Turns the vector into a CONSTANT vector holding the given value. * - * The update callback is invoked during query execution with a batch of input rows: row i of every argument vector must - * be aggregated into state i of the state array. An update callback must be set before registration. + * Afterwards the vector holds a single element that applies to every logical row; write it through + * vector_get_data_mutable, which returns a pointer to that one element. For a STRUCT vector the change propagates to + * every child. The value's logical type must equal the vector's; a mismatch returns ERROR_INPUT_INVALID. * * history: * - unstable: v2.0.0 * - * @param function The function to set the update callback of. - * @param callback The update callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector to make constant. + * @param value The value every row takes. Its logical type must equal the vector's. + * @param count The number of elements in the vector. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_update_callback( - duckdb_v2_aggregate_function_handle function, duckdb_v2_aggregate_function_update_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_make_constant(duckdb_v2_vector_handle vector, + duckdb_v2_value_handle value, idx_t count, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the combine callback of the aggregate function. + * Sets a vector to a SEQUENCE representation. * - * The combine callback merges partial aggregate states computed in parallel: source state i must be combined into - * target state i. A combine callback must be set before registration. + * Afterwards the vector represents the arithmetic sequence start, start+increment, start+2*increment, ... over count + * elements. No data pointer is involved; the three parameters describe the sequence completely. * * history: * - unstable: v2.0.0 * - * @param function The function to set the combine callback of. - * @param callback The combine callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector to turn into a sequence. + * @param start The first value of the sequence. + * @param increment The step between consecutive values. + * @param count The number of elements in the sequence. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_combine_callback( - duckdb_v2_aggregate_function_handle function, duckdb_v2_aggregate_function_combine_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_make_sequence(duckdb_v2_vector_handle vector, int64_t start, + int64_t increment, idx_t count, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the finalize callback of the aggregate function. + * Sets one row of a FLAT vector to NULL, nested children included. * - * The finalize callback produces the function's result: state i must be finalized into result row offset + i of the - * result vector. A finalize callback must be set before registration. + * Clears the row's validity and broadcasts the NULL recursively to every descendant element under that row — STRUCT + * fields, and ARRAY elements strided by the array size — maintaining DuckDB's nested NULL invariant: when a STRUCT or + * ARRAY row is NULL, every descendant element under it must be NULL too. LIST children are left untouched, since their + * consumers gate on the list's own validity. Which kinds propagate is normative DuckDB behavior that evolves with the + * type system, which makes this the total NULL write path: equivalent to vector_set_value with a NULL value, without + * the per-call value allocation. + * + * Requires a FLAT vector: constant, dictionary, and compressed representations are not row-addressable, so call + * vector_flatten first. The row index is logical and bounds-checked against vector_get_size. * * history: * - unstable: v2.0.0 * - * @param function The function to set the finalize callback of. - * @param callback The finalize callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector to write to. + * @param row The logical row index, in [0, vector_get_size). + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_finalize_callback( - duckdb_v2_aggregate_function_handle function, duckdb_v2_aggregate_function_finalize_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_set_null(duckdb_v2_vector_handle vector, idx_t row, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the destroy callback for the aggregate function. Optional: only needed when aggregate states own resources that - * must be released. The callback runs on states that are discarded without being finalized; it must not fail, an error - * reported through its error slot is ignored. + * Returns a mutable pointer to the validity mask of a FLAT vector. + * + * Allocates the mask on first use, so the returned pointer is always non-null. Each uint64_t word covers 64 rows: bit N + * of word W is row W*64+N. A set bit means valid; a cleared bit means NULL. + * + * A raw mask write marks only this vector's rows. Clearing a STRUCT or ARRAY parent bit leaves the descendant elements + * untouched, which violates DuckDB's nested NULL invariant — a NULL STRUCT or ARRAY row requires NULL descendants — so + * set nested rows NULL through vector_set_null instead. When writing nested masks raw anyway, invalidate the child + * masks up front and mark elements valid as the values are written. * * history: * - unstable: v2.0.0 * - * @param function The function to set the destroy callback of. - * @param callback The destroy callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector. + * @param out_validity Receives a mutable pointer to the validity mask. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_destroy_callback( - duckdb_v2_aggregate_function_handle function, duckdb_v2_aggregate_function_destroy_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_flat_get_validity_mutable(duckdb_v2_vector_handle vector, + uint64_t **out_validity, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional stats callback of the aggregate function. + * Sets the validity of a CONSTANT vector. * - * The stats callback is invoked during query optimization for each call site of the function, after it has been bound. - * Through its `duckdb_v2_aggregate_function_stats_info_handle` it reads the statistics of the arguments and narrows the - * statistics of the result, which the engine then uses to simplify the query. A function without a stats callback gives - * the engine no statistics for its result. + * A constant vector holds a single element, so one flag decides whether every row reads as the value or as NULL. * * history: * - unstable: v2.0.0 * - * @param function The function to set the stats callback of. - * @param callback The stats callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The constant vector. + * @param validity True to mark the vector's single element valid, false to mark it NULL. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_stats_callback( - duckdb_v2_aggregate_function_handle function, duckdb_v2_aggregate_function_stats_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_constant_set_valid(duckdb_v2_vector_handle vector, bool validity, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the concrete return type of the call site being bound. + * Borrows a string-backed vector's arena for writing. * - * Overrides the return type declared in the signature. Register the function with an ANY return type and set the - * concrete type here, derived from the argument types, to build a function whose result type depends on its input. The - * type is borrowed and copied. + * Allocates the arena on first use. Valid for VARCHAR, BLOB, BIT, and BIGNUM vectors, and returns ERROR_INPUT_INVALID + * for anything else. This call is the single string-ness check, which is why arena_allocate itself performs none. The + * arena is borrowed — never destroy it — and stays valid until the vector is flattened, reallocated, or destroyed. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. - * @param return_type The return type to set. Borrowed for the call only. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The string-backed vector whose arena to borrow. + * @param out_arena Receives the borrowed arena handle. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_bind_set_return_type( - duckdb_v2_aggregate_function_bind_info_handle info, duckdb_v2_logical_type_handle return_type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_get_arena(duckdb_v2_vector_handle vector, + duckdb_v2_arena_handle *out_arena, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_aggregate_function_set_user_data()`. - * - * history: - * - unstable: v2.0.0 + * Returns the number of child vectors a nested vector exposes. * - * @param info The size info handle. - * @param data Receives the user data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_size_get_user_data( - duckdb_v2_aggregate_function_size_info_handle info, void **data, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Retrieves the bind data set by the function's bind callback. + * 1 for LIST, MAP and ARRAY; the field count for STRUCT; member_count + 1 for UNION, the tag plus the members; and 0 + * for any non-nested kind. vector_get_child documents what each index addresses. * * history: * - unstable: v2.0.0 * - * @param info The size info handle. - * @param data Receives the bind data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The vector. + * @param out_count Receives the number of child vectors. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_size_get_bind_data( - duckdb_v2_aggregate_function_size_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_get_child_count(duckdb_v2_vector_handle vector, idx_t *out_count, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the size of a single aggregate state, in bytes. The size callback must set this; DuckDB uses it to allocate - * state memory. + * Borrows a child vector by index. * - * history: - * - unstable: v2.0.0 + * What each index addresses, by kind: LIST and ARRAY expose [0] = the elements; MAP [0] = the entries, a STRUCT(key, + * value) whose children are the keys and the values; STRUCT and TUPLE [i] = field i; and UNION [0] = the tag with + * [1..N] = the members. Note that value_get_child diverges on UNION, exposing only the active member. * - * @param info The size info handle. - * @param size The size of a single aggregate state, in bytes. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_size_set_state_size( - duckdb_v2_aggregate_function_size_info_handle info, idx_t size, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Retrieves the user data set via `duckdb_v2_aggregate_function_set_user_data()`. + * The returned child is borrowed and lives as long as the owning chunk. Returns ERROR_INPUT_INVALID if the vector has + * no children, or if the index is out of range. * * history: * - unstable: v2.0.0 * - * @param info The init info handle. - * @param data Receives the user data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param vector The nested vector to descend into. + * @param index The child index, in [0, vector_get_child_count). + * @param out_child Receives the borrowed child vector. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_init_get_user_data( - duckdb_v2_aggregate_function_init_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_get_child(duckdb_v2_vector_handle vector, idx_t index, + duckdb_v2_vector_handle *out_child, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's bind callback. - * - * history: - * - unstable: v2.0.0 + * Decodes BIGNUM storage bytes into a caller-supplied magnitude buffer + sign flag. * - * @param info The init info handle. - * @param data Receives the bind data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_init_get_bind_data( - duckdb_v2_aggregate_function_init_info_handle info, void **data, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Returns how many aggregate states this invocation must initialize. This is the length of the array returned by - * `duckdb_v2_aggregate_function_init_get_states()`. + * in_data and in_length are the value's raw storage bytes, exactly as they sit in a vector's bignum payload or as + * value_get_blob reports them for a BIGNUM value. Those bytes are opaque: the storage encoding is not a committed part + * of this API, and this function is the only thing that interprets them. * - * history: - * - unstable: v2.0.0 + * Writes the big-endian magnitude bytes into out_data and the sign flag into out_is_negative; reconstruct the integer + * as (-1)**out_is_negative * unsigned_big_endian(out_data[0..out_length]). Materializing the bytes is unavoidable, + * since a negative bignum stores its magnitude bit-inverted, but the buffer belongs to the caller: this function never + * allocates and hands back nothing to free. * - * @param info The init info handle. - * @param count Receives the number of states. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_init_get_state_count( - duckdb_v2_aggregate_function_init_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Returns the array of aggregate states to initialize, one pointer per state. Each state points to uninitialized memory - * of the size reported by the size callback; the init callback must initialize all of them in place. + * Pass out_data = NULL to size the buffer without decoding. out_length then receives the exact number of magnitude + * bytes and out_is_negative the sign, and out_capacity is ignored. The size comes straight out of the storage header, + * so the query is O(1) and exact — a size call followed by a decode call never needs a retry loop. * - * history: - * - unstable: v2.0.0 + * With out_data != NULL, out_capacity must be at least out_length bytes, or the call returns ERROR_INPUT_OBJECT_SIZE + * with out_length set to the required size and out_data left untouched. On success exactly out_length bytes are + * written, and the rest of the buffer is not modified. * - * @param info The init info handle. - * @param states Receives the array of aggregate state pointers. Borrowed; valid only for the duration of the callback. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_init_get_states( - duckdb_v2_aggregate_function_init_info_handle info, void ***states, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Retrieves the user data set via `duckdb_v2_aggregate_function_set_user_data()`. + * Returns ERROR_INPUT_INVALID if in_data is NULL, or if in_length is too short to hold a bignum header. * * history: * - unstable: v2.0.0 * - * @param info The update info handle. - * @param data Receives the user data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param in_data The value's raw BIGNUM storage bytes. + * @param in_length Size of in_data in bytes. + * @param out_data Caller-owned buffer receiving the magnitude bytes, or NULL to only report the required size in + * out_length. + * @param out_capacity Bytes available in out_data. Ignored when out_data is NULL. + * @param out_length Receives the magnitude size in bytes, written on success and on ERROR_INPUT_OBJECT_SIZE. + * @param out_is_negative Receives true if the value is negative, false otherwise. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_update_get_user_data( - duckdb_v2_aggregate_function_update_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_bignum_decode(const uint8_t *in_data, idx_t in_length, uint8_t *out_data, + idx_t out_capacity, idx_t *out_length, bool *out_is_negative, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's bind callback. - * - * history: - * - unstable: v2.0.0 + * Encodes a magnitude + sign flag into BIGNUM storage bytes. * - * @param info The update info handle. - * @param data Receives the bind data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_update_get_bind_data( - duckdb_v2_aggregate_function_update_info_handle info, void **data, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Returns how many input rows this invocation carries. This is the length of the argument vectors and of the state - * array: row i of every argument vector must be aggregated into state i. + * The inverse of bignum_decode. in_data and in_length are the big-endian magnitude bytes and is_negative the sign; + * out_data receives the raw storage bytes for that integer, in the form a BIGNUM vector payload expects. Those bytes + * are opaque: the storage encoding is not a committed part of this API. * - * history: - * - unstable: v2.0.0 + * Pass out_data = NULL to size the buffer without encoding. out_length then receives the exact number of storage bytes, + * and out_capacity is ignored. The size is a fixed function of in_length, so the query is O(1) and exact. * - * @param info The update info handle. - * @param count Receives the number of rows. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_update_get_row_count( - duckdb_v2_aggregate_function_update_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Returns how many argument vectors this invocation carries, split into the four parts of the argument list. + * With out_data != NULL, out_capacity must be at least out_length bytes, or the call returns ERROR_INPUT_OBJECT_SIZE + * with out_length set to the required size and out_data left untouched. On success exactly out_length bytes are + * written, and the rest of the buffer is not modified. * - * The parts and their order are those the bind callback saw through `duckdb_v2_function_bind_get_arg_count()`, and the - * vectors are at the same indices. Valid indices for `duckdb_v2_aggregate_function_update_get_arg()` are [0, the sum of - * the four counts). Every out-parameter may be NULL, in which case nothing is written to it. + * The magnitude must be canonical, matching what bignum_decode produces: in_length >= 1 with no leading zero bytes, so + * the value zero is the single byte 0x00 with is_negative = false. A NULL in_data, an in_length of 0, a leading zero + * byte, or a negative zero returns ERROR_INPUT_INVALID; a magnitude beyond the maximum bignum width returns + * ERROR_INPUT_OUT_OF_RANGE. * * history: * - unstable: v2.0.0 * - * @param info The update info handle. - * @param positional_fixed Optional. Receives the number of positional-only and standard parameters. - * @param positional_variadic Optional. Receives the number of arguments `*args` received, 0 when the signature has - * none. - * @param named_fixed Optional. Receives the number of named-only parameters. - * @param named_variadic Optional. Receives the number of arguments `**kwargs` received, 0 when the signature has none. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param in_data Big-endian magnitude bytes, with no leading zero bytes. + * @param in_length Size of in_data in bytes. Must be >= 1. + * @param is_negative True to encode a negative value. + * @param out_data Caller-owned buffer receiving the storage bytes, or NULL to only report the required size in + * out_length. + * @param out_capacity Bytes available in out_data. Ignored when out_data is NULL. + * @param out_length Receives the storage size in bytes — written on success and on ERROR_INPUT_OBJECT_SIZE. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_update_get_arg_count( - duckdb_v2_aggregate_function_update_info_handle info, idx_t *positional_fixed, idx_t *positional_variadic, - idx_t *named_fixed, idx_t *named_variadic, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_bignum_encode(const uint8_t *in_data, idx_t in_length, bool is_negative, + uint8_t *out_data, idx_t out_capacity, idx_t *out_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the argument vector at the given index. + * Validates all `text_length` bytes of `text` as UTF-8, including bytes after embedded NUL characters. * - * The index is the one the bind callback used for the argument, e.g. the index - * `duckdb_v2_function_bind_get_arg_index()` found for a name. The vector holds the argument's values for the current - * batch; use `duckdb_v2_aggregate_function_update_get_row_count()` for the number of rows. Fails if the index is out of - * bounds. Borrowed; valid only for the duration of the callback. + * Returns ERROR_INPUT_INVALID if any of: + * - text is NULL and text_length is nonzero. + * - The input contains malformed UTF-8. + * + * A NULL text with a zero length is valid. * * history: * - unstable: v2.0.0 * - * @param info The update info handle. - * @param index The index of the argument. - * @param vector Receives the borrowed argument vector. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param text The bytes to validate. + * @param text_length The length of `text` in bytes. `text` need not be null-terminated and may be NULL only when this + * is 0. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR -duckdb_v2_aggregate_function_update_get_arg(duckdb_v2_aggregate_function_update_info_handle info, idx_t index, - duckdb_v2_vector_handle *vector, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_validate_utf8(const char *text, idx_t text_length, + duckdb_v2_error_info_handle *err); #endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Returns the array of aggregate states to update, one pointer per input row: row i of every argument vector must be - * aggregated into state i. Different rows may point to the same state. - * - * history: - * - unstable: v2.0.0 - * - * @param info The update info handle. - * @param states Receives the array of aggregate state pointers. Borrowed; valid only for the duration of the callback. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR +/* --- Struct definitions for vector --- */ + +struct duckdb_v2_vector_view { + const void *data; + const uint64_t *validity; + const duckdb_v2_sel_t *sel; + idx_t count; +}; + +struct duckdb_v2_list_entry { + idx_t offset; + idx_t length; +}; + +struct duckdb_v2_hugeint_t { + uint64_t lower; + int64_t upper; +}; + +struct duckdb_v2_uhugeint_t { + uint64_t lower; + uint64_t upper; +}; + +struct duckdb_v2_interval_t { + int32_t months; + int32_t days; + int64_t micros; +}; + +/* ============================================================================ + * MODULE: aggregate + * ============================================================================ */ + +/* --- Enums for aggregate --- */ + +/* --- Struct forward declarations for aggregate --- */ + +/* --- Types for aggregate --- */ + +/*! + * An owned opaque handle to a custom aggregate function being built. Created with + * `duckdb_v2_aggregate_function_create()`, configured with the setter functions (e.g. + * `duckdb_v2_aggregate_function_set_name()`, `duckdb_v2_aggregate_function_set_update_callback()`, etc.) and the + * signature obtained via `duckdb_v2_aggregate_function_get_signature()`, made available with + * `duckdb_v2_connection_register_aggregate_function()` or `duckdb_v2_extension_register_aggregate_function()`, and + * destroyed with `duckdb_v2_aggregate_function_destroy()`. */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_update_get_states( - duckdb_v2_aggregate_function_update_info_handle info, void ***states, duckdb_v2_error_info_handle *err); -#endif +typedef struct _duckdb_v2_aggregate_function { + void *internal_ptr; +} * duckdb_v2_aggregate_function_handle; + +/*! + * A borrowed opaque handle to the result of an aggregate function's "bind" phase. The "bind" callback receives this + * handle next to a `duckdb_v2_function_bind_info_handle`, which gives access to the arguments, the user data and the + * bind data, and can use it to set the return type of the call site being bound. + */ +typedef struct _duckdb_v2_aggregate_function_bind_info { + void *internal_ptr; +} * duckdb_v2_aggregate_function_bind_info_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to an aggregate function during the "stats" phase of query + * optimization. The "stats" callback receives this handle and can use it to read the statistics of the arguments of the + * call site and narrow the statistics of its result. + */ +typedef struct _duckdb_v2_aggregate_function_stats_info { + void *internal_ptr; +} * duckdb_v2_aggregate_function_stats_info_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to an aggregate function during the state sizing "size" phase. The + * "size" callback receives this handle and must use it to report the size of a single aggregate state in bytes. + */ +typedef struct _duckdb_v2_aggregate_function_size_info { + void *internal_ptr; +} * duckdb_v2_aggregate_function_size_info_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to an aggregate function during the state initialization "init" + * phase. The "init" callback receives this handle and can use it to access the array of aggregate states it must + * initialize in place. + */ +typedef struct _duckdb_v2_aggregate_function_init_info { + void *internal_ptr; +} * duckdb_v2_aggregate_function_init_info_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to an aggregate function during the "update" phase. The "update" + * callback receives this handle and can use it to access the input argument vectors, the number of rows to process, and + * the aggregate state each row must be aggregated into. + */ +typedef struct _duckdb_v2_aggregate_function_update_info { + void *internal_ptr; +} * duckdb_v2_aggregate_function_update_info_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to an aggregate function during the "combine" phase. The "combine" + * callback receives this handle and can use it to access the source and target aggregate state arrays to merge. + */ +typedef struct _duckdb_v2_aggregate_function_combine_info { + void *internal_ptr; +} * duckdb_v2_aggregate_function_combine_info_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to an aggregate function during the "finalize" phase. The + * "finalize" callback receives this handle and can use it to access the aggregate states and the result vector and + * offset to write their final values to. + */ +typedef struct _duckdb_v2_aggregate_function_finalize_info { + void *internal_ptr; +} * duckdb_v2_aggregate_function_finalize_info_handle; + +/*! + * A borrowed opaque handle to the arguments supplied to an aggregate function during the state destruction "destroy" + * phase. The "destroy" callback receives this handle and can use it to access the array of aggregate states whose + * resources must be released. + */ +typedef struct _duckdb_v2_aggregate_function_destroy_info { + void *internal_ptr; +} * duckdb_v2_aggregate_function_destroy_info_handle; + +/* --- Constants for aggregate --- */ + +/* --- Function pointer typedefs for aggregate --- */ + +typedef void (*duckdb_v2_aggregate_function_bind_callback_fn)(duckdb_v2_function_bind_info_handle info, + duckdb_v2_aggregate_function_bind_info_handle result, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_aggregate_function_stats_callback_fn)(duckdb_v2_aggregate_function_stats_info_handle info, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_aggregate_function_size_callback_fn)(duckdb_v2_aggregate_function_size_info_handle info, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_aggregate_function_init_callback_fn)(duckdb_v2_aggregate_function_init_info_handle info, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_aggregate_function_update_callback_fn)(duckdb_v2_aggregate_function_update_info_handle info, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_aggregate_function_combine_callback_fn)(duckdb_v2_aggregate_function_combine_info_handle info, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_aggregate_function_finalize_callback_fn)( + duckdb_v2_aggregate_function_finalize_info_handle info, duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_aggregate_function_destroy_callback_fn)(duckdb_v2_aggregate_function_destroy_info_handle info, + duckdb_v2_error_info_handle *err); + +/* --- Functions for aggregate --- */ #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_aggregate_function_set_user_data()`. + * Creates a new aggregate function through a factory. + * + * The function starts out empty: configure it with the setter functions (e.g. + * `duckdb_v2_aggregate_function_set_name()`, `duckdb_v2_aggregate_function_set_update_callback()`, etc.) and the + * signature obtained via `duckdb_v2_aggregate_function_get_signature()`, then make it available with + * `duckdb_v2_connection_register_aggregate_function()` or `duckdb_v2_extension_register_aggregate_function()`. The + * caller owns the returned handle and must destroy it with `duckdb_v2_aggregate_function_destroy()`, also after + * registration. + * + * The aggregate function can only be registered on the database the factory belongs to. * * history: * - unstable: v2.0.0 * - * @param info The combine info handle. - * @param data Receives the user data pointer, or null if none was set. + * @param factory The factory to create the aggregate function through. + * @param function On success, receives the newly created aggregate function. Owned by the caller. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_combine_get_user_data( - duckdb_v2_aggregate_function_combine_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_create(duckdb_v2_factory_handle factory, + duckdb_v2_aggregate_function_handle *function, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's bind callback. + * Sets the name of the aggregate function. + * + * The name is borrowed and copied. Calling this again replaces the previous name. A name must be set before + * registration. * * history: * - unstable: v2.0.0 * - * @param info The combine info handle. - * @param data Receives the bind data pointer, or null if none was set. + * @param function The function to set the name of. + * @param name The name to set. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_combine_get_bind_data( - duckdb_v2_aggregate_function_combine_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_name(duckdb_v2_aggregate_function_handle function, + const char *name, idx_t name_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns how many source/target state pairs this invocation must combine. This is the length of both the sources and - * the targets array. + * Returns the documentation of the function so it can be filled in. + * + * Set a description with `duckdb_v2_function_docs_set_description()`, and add examples and categories with + * `duckdb_v2_function_docs_add_example()` and `duckdb_v2_function_docs_add_category()`. The documentation is modified + * in place, describes this overload only, and is registered with the function. Optional. * * history: * - unstable: v2.0.0 * - * @param info The combine info handle. - * @param count Receives the number of state pairs. + * @param function The function to get the documentation of. + * @param docs The returned documentation. Borrowed and valid for the lifetime of the function handle. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_combine_get_state_count( - duckdb_v2_aggregate_function_combine_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_get_docs(duckdb_v2_aggregate_function_handle function, + duckdb_v2_function_docs_handle *docs, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the array of source aggregate states, one pointer per pair. Source i must be combined into target i; the - * source must not be modified. + * Returns the function's signature so it can be configured. + * + * Add parameters with `duckdb_v2_function_signature_add_parameter()` and set the return type with + * `duckdb_v2_function_signature_set_return_type()`. The signature is modified in place; the function must be given a + * signature with a return type before registration. * * history: * - unstable: v2.0.0 * - * @param info The combine info handle. - * @param states Receives the array of source aggregate state pointers. Borrowed; valid only for the duration of the - * callback. + * @param function The function to get the signature of. + * @param sig The returned signature. Borrowed and valid for the lifetime of the function handle. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_combine_get_sources( - duckdb_v2_aggregate_function_combine_info_handle info, void ***states, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_get_signature(duckdb_v2_aggregate_function_handle function, + duckdb_v2_function_signature_handle *sig, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the array of target aggregate states, one pointer per pair. Source i must be combined into target i. + * Sets arbitrary user data on the aggregate function. + * + * Associates an opaque pointer with the function, retrievable from each callback via its user data accessor (e.g. + * `duckdb_v2_function_bind_get_user_data()`, `duckdb_v2_aggregate_function_update_get_user_data()`, etc.). The opaque + * handle bundles the pointer with an optional destructor, invoked when the data is no longer needed. * * history: * - unstable: v2.0.0 * - * @param info The combine info handle. - * @param states Receives the array of target aggregate state pointers. Borrowed; valid only for the duration of the - * callback. + * @param function The function to set the user data of. + * @param data Opaque handle bundling the user data pointer plus an optional destructor. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_combine_get_targets( - duckdb_v2_aggregate_function_combine_info_handle info, void ***states, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_user_data(duckdb_v2_aggregate_function_handle function, + duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_aggregate_function_set_user_data()`. + * Sets a property on the aggregate function. + * + * Configures a function property that influences planning and execution, such as stability, NULL handling, fallibility, + * collation handling, or the aggregate-specific order/DISTINCT dependence. The value must be one of the + * `DUCKDB_V2_FUNCTION_PROPERTY_VALUE` entries belonging to `key`; passing a value that does not belong to the key, or a + * key that is not valid for aggregate functions, results in an error. * * history: * - unstable: v2.0.0 * - * @param info The finalize info handle. - * @param data Receives the user data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * @param function The function to set the property of. + * @param key The property to set. + * @param value The value to set for the property. Must belong to `key`. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_finalize_get_user_data( - duckdb_v2_aggregate_function_finalize_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_property(duckdb_v2_aggregate_function_handle function, + DUCKDB_V2_FUNCTION_PROPERTY_KEY key, + DUCKDB_V2_FUNCTION_PROPERTY_VALUE value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's bind callback. + * Sets a generic, named property on the aggregate function. + * + * Generic properties are free-form `name = value` pairs that the engine or extensions can read from a function, e.g. + * `duckdb.collation.combinable = true` marks a collation function as combinable. Setting a property that is already set + * replaces its value. Reading a property that is not set yields NULL, which boolean properties treat as false. * * history: * - unstable: v2.0.0 * - * @param info The finalize info handle. - * @param data Receives the bind data pointer, or null if none was set. + * @param function The function to set the property of. + * @param name The name of the property, e.g. `duckdb.collation.combinable`. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param value The value of the property. Borrowed (copied in). * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_finalize_get_bind_data( - duckdb_v2_aggregate_function_finalize_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_generic_property( + duckdb_v2_aggregate_function_handle function, const char *name, idx_t name_length, duckdb_v2_value_handle value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns how many aggregate states this invocation must finalize. This is the length of the state array and the number - * of rows to write to the result vector. + * Reads a generic, named property of the aggregate function, as set by + * `duckdb_v2_aggregate_function_set_generic_property()`. + * + * A property that is not set is not an error: `out_value` then receives NULL. * * history: * - unstable: v2.0.0 * - * @param info The finalize info handle. - * @param count Receives the number of states. + * @param function The function to read the property of. + * @param name The name of the property, e.g. `duckdb.collation.combinable`. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param out_value Receives the value of the property, owned by the caller, or NULL if the property is not set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_finalize_get_state_count( - duckdb_v2_aggregate_function_finalize_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_get_generic_property( + duckdb_v2_aggregate_function_handle function, const char *name, idx_t name_length, + duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the array of aggregate states to finalize, one pointer per state. State i must be finalized into result row - * offset + i. + * Sets the optional bind callback of the aggregate function. + * + * The bind callback is invoked during query planning for each call site of the function. Through its + * `duckdb_v2_function_bind_info_handle` it can inspect the argument types and constant argument values and set "bind + * data" that is shared with the other callbacks. Through its `duckdb_v2_aggregate_function_bind_info_handle` it can set + * a concrete return type. * * history: * - unstable: v2.0.0 * - * @param info The finalize info handle. - * @param states Receives the array of aggregate state pointers. Borrowed; valid only for the duration of the callback. + * @param function The function to set the bind callback of. + * @param callback The bind callback to set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_finalize_get_states( - duckdb_v2_aggregate_function_finalize_info_handle info, void ***states, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_bind_callback( + duckdb_v2_aggregate_function_handle function, duckdb_v2_aggregate_function_bind_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the result vector the finalize callback must write into. + * Sets the size callback of the aggregate function. * - * State i must be finalized into result row offset + i, with the offset from - * `duckdb_v2_aggregate_function_finalize_get_result_offset()`. Borrowed; valid only for the duration of the callback. + * The size callback reports the size of a single aggregate state in bytes via + * `duckdb_v2_aggregate_function_size_set_state_size()`; DuckDB uses it to allocate state memory. A size callback must + * be set before registration. * * history: * - unstable: v2.0.0 * - * @param info The finalize info handle. - * @param vector Receives the borrowed result vector to write into. + * @param function The function to set the size callback of. + * @param callback The size callback to set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR -duckdb_v2_aggregate_function_finalize_get_result(duckdb_v2_aggregate_function_finalize_info_handle info, - duckdb_v2_vector_handle *vector, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_size_callback( + duckdb_v2_aggregate_function_handle function, duckdb_v2_aggregate_function_size_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the offset in the result vector at which to start writing: state i must be finalized into result row offset + - * i. + * Sets the init callback of the aggregate function. + * + * The init callback initializes freshly allocated aggregate states in place, obtained via + * `duckdb_v2_aggregate_function_init_get_states()`. An init callback must be set before registration. * * history: * - unstable: v2.0.0 * - * @param info The finalize info handle. - * @param offset Receives the result offset. + * @param function The function to set the init callback of. + * @param callback The init callback to set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_finalize_get_result_offset( - duckdb_v2_aggregate_function_finalize_info_handle info, idx_t *offset, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_init_callback( + duckdb_v2_aggregate_function_handle function, duckdb_v2_aggregate_function_init_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_aggregate_function_set_user_data()`. + * Sets the update callback of the aggregate function. + * + * The update callback is invoked during query execution with a batch of input rows: row i of every argument vector must + * be aggregated into state i of the state array. An update callback must be set before registration. * * history: * - unstable: v2.0.0 * - * @param info The destroy info handle. - * @param data Receives the user data pointer, or null if none was set. + * @param function The function to set the update callback of. + * @param callback The update callback to set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_destroy_get_user_data( - duckdb_v2_aggregate_function_destroy_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_update_callback( + duckdb_v2_aggregate_function_handle function, duckdb_v2_aggregate_function_update_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's bind callback. + * Sets the combine callback of the aggregate function. + * + * The combine callback merges partial aggregate states computed in parallel: source state i must be combined into + * target state i. A combine callback must be set before registration. * * history: * - unstable: v2.0.0 * - * @param info The destroy info handle. - * @param data Receives the bind data pointer, or null if none was set. + * @param function The function to set the combine callback of. + * @param callback The combine callback to set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_destroy_get_bind_data( - duckdb_v2_aggregate_function_destroy_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_combine_callback( + duckdb_v2_aggregate_function_handle function, duckdb_v2_aggregate_function_combine_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns how many aggregate states this invocation must destroy. This is the length of the state array. + * Sets the finalize callback of the aggregate function. + * + * The finalize callback produces the function's result: state i must be finalized into result row offset + i of the + * result vector. A finalize callback must be set before registration. * * history: * - unstable: v2.0.0 * - * @param info The destroy info handle. - * @param count Receives the number of states. + * @param function The function to set the finalize callback of. + * @param callback The finalize callback to set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_destroy_get_state_count( - duckdb_v2_aggregate_function_destroy_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_finalize_callback( + duckdb_v2_aggregate_function_handle function, duckdb_v2_aggregate_function_finalize_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the array of aggregate states to destroy, one pointer per state. The callback must release any resources the - * states own. + * Sets the destroy callback for the aggregate function. Optional: only needed when aggregate states own resources that + * must be released. The callback runs on states that are discarded without being finalized; it must not fail, an error + * reported through its error slot is ignored. * * history: * - unstable: v2.0.0 * - * @param info The destroy info handle. - * @param states Receives the array of aggregate state pointers. Borrowed; valid only for the duration of the callback. + * @param function The function to set the destroy callback of. + * @param callback The destroy callback to set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_destroy_get_states( - duckdb_v2_aggregate_function_destroy_info_handle info, void ***states, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_destroy_callback( + duckdb_v2_aggregate_function_handle function, duckdb_v2_aggregate_function_destroy_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_aggregate_function_set_user_data()`. + * Sets the optional stats callback of the aggregate function. + * + * The stats callback is invoked during query optimization for each call site of the function, after it has been bound. + * Through its `duckdb_v2_aggregate_function_stats_info_handle` it reads the statistics of the arguments and narrows the + * statistics of the result, which the engine then uses to simplify the query. A function without a stats callback gives + * the engine no statistics for its result. * * history: * - unstable: v2.0.0 * - * @param info The stats info handle. - * @param data Receives the user data pointer, or null if none was set. + * @param function The function to set the stats callback of. + * @param callback The stats callback to set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_stats_get_user_data( - duckdb_v2_aggregate_function_stats_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_set_stats_callback( + duckdb_v2_aggregate_function_handle function, duckdb_v2_aggregate_function_stats_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's bind callback. + * Sets the concrete return type of the call site being bound. + * + * Overrides the return type declared in the signature. Register the function with an ANY return type and set the + * concrete type here, derived from the argument types, to build a function whose result type depends on its input. The + * type is borrowed and copied. * * history: * - unstable: v2.0.0 * - * @param info The stats info handle. - * @param data Receives the bind data pointer, or null if none was set. + * @param info The bind info handle. + * @param return_type The return type to set. Borrowed for the call only. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_stats_get_bind_data( - duckdb_v2_aggregate_function_stats_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_bind_set_return_type( + duckdb_v2_aggregate_function_bind_info_handle info, duckdb_v2_logical_type_handle return_type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns how many arguments the call site has, split into the four parts of the argument list. - * - * The parts and their order are those the bind callback saw through `duckdb_v2_function_bind_get_arg_count()`, and the - * arguments are at the same indices. Valid indices for `duckdb_v2_aggregate_function_stats_get_arg_stats()` are [0, the - * sum of the four counts). Every out-parameter may be NULL, in which case nothing is written to it. + * Retrieves the user data set via `duckdb_v2_aggregate_function_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param info The stats info handle. - * @param positional_fixed Optional. Receives the number of positional-only and standard parameters. - * @param positional_variadic Optional. Receives the number of arguments `*args` received, 0 when the signature has - * none. - * @param named_fixed Optional. Receives the number of named-only parameters. - * @param named_variadic Optional. Receives the number of arguments `**kwargs` received, 0 when the signature has none. + * @param info The size info handle. + * @param data Receives the user data pointer, or null if none was set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_stats_get_arg_count( - duckdb_v2_aggregate_function_stats_info_handle info, idx_t *positional_fixed, idx_t *positional_variadic, - idx_t *named_fixed, idx_t *named_variadic, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_size_get_user_data( + duckdb_v2_aggregate_function_size_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the statistics of the argument at the given index. - * - * The index is the one the bind callback used for the argument. The statistics are read-only. Fails if the index is out - * of bounds. Borrowed; valid only for the duration of the callback. + * Retrieves the bind data set by the function's bind callback. * * history: * - unstable: v2.0.0 * - * @param info The stats info handle. - * @param index The index of the argument. - * @param stats Receives the borrowed, read-only statistics of the argument. + * @param info The size info handle. + * @param data Receives the bind data pointer, or null if none was set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR -duckdb_v2_aggregate_function_stats_get_arg_stats(duckdb_v2_aggregate_function_stats_info_handle info, idx_t index, - duckdb_v2_stats_handle *stats, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_size_get_bind_data( + duckdb_v2_aggregate_function_size_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the statistics of the call site's result, for the callback to narrow. - * - * The statistics start out unknown, with every kind of value possible. They describe every result the aggregate - * produces, including the result of a group with no input rows, such as an ungrouped aggregate over an empty table. - * Borrowed; valid only for the duration of the callback. + * Sets the size of a single aggregate state, in bytes. The size callback must set this; DuckDB uses it to allocate + * state memory. * * history: * - unstable: v2.0.0 * - * @param info The stats info handle. - * @param stats Receives the borrowed, writable statistics of the call site's result. + * @param info The size info handle. + * @param size The size of a single aggregate state, in bytes. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR -duckdb_v2_aggregate_function_stats_get_result_stats(duckdb_v2_aggregate_function_stats_info_handle info, - duckdb_v2_stats_handle *stats, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_size_set_state_size( + duckdb_v2_aggregate_function_size_info_handle info, idx_t size, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the aggregate function, making it available for use in SQL queries. - * - * The function is registered on the connection's database, visible to every connection, in the connection's - * transaction: inside an explicit transaction, it is invisible to other connections until the transaction commits, and - * a rollback undoes it. Registration requires a name, the size, init, update, combine and finalize callbacks, and a - * signature with a complete return type; an ANY return type is accepted only together with a bind callback that sets - * the concrete type per call site. The aggregate function must have been created through a factory of the same - * database. The caller still owns the handle after registration and must destroy it with - * `duckdb_v2_aggregate_function_destroy()`, which does not affect the registered function. + * Retrieves the user data set via `duckdb_v2_aggregate_function_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param conn The connection to register on. - * @param function The aggregate function to register. + * @param info The init info handle. + * @param data Receives the user data pointer, or null if none was set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_register_aggregate_function( - duckdb_v2_connection_handle conn, duckdb_v2_aggregate_function_handle function, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_init_get_user_data( + duckdb_v2_aggregate_function_init_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the aggregate function, making it available for use in SQL queries. - * - * The function is registered on the loading extension's database and attributed to the extension. Use this from the - * extension's load callback. Registration requires a name, the size, init, update, combine and finalize callbacks, and - * a signature with a complete return type; an ANY return type is accepted only together with a bind callback that sets - * the concrete type per call site. The aggregate function must have been created through a factory of the same - * database. The caller still owns the handle after registration and must destroy it with - * `duckdb_v2_aggregate_function_destroy()`, which does not affect the registered function. + * Retrieves the bind data set by the function's bind callback. * * history: * - unstable: v2.0.0 * - * @param extension The loading extension. - * @param function The aggregate function to register. + * @param info The init info handle. + * @param data Receives the bind data pointer, or null if none was set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_aggregate_function( - duckdb_v2_extension_handle extension, duckdb_v2_aggregate_function_handle function, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_init_get_bind_data( + duckdb_v2_aggregate_function_init_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys the aggregate function, releasing its resources. - * - * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent - * double-destruction. Destroying the handle after registration does not affect the registered function. + * Returns how many aggregate states this invocation must initialize. This is the length of the array returned by + * `duckdb_v2_aggregate_function_init_get_states()`. * * history: * - unstable: v2.0.0 * - * @param function The function to destroy. + * @param info The init info handle. + * @param count Receives the number of states. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_destroy(duckdb_v2_aggregate_function_handle *function); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_init_get_state_count( + duckdb_v2_aggregate_function_init_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); #endif -/* --- Struct definitions for aggregate --- */ - -/* ============================================================================ - * MODULE: catalog - * ============================================================================ */ - -/* --- Enums for catalog --- */ - -/* --- Struct forward declarations for catalog --- */ - -/* --- Types for catalog --- */ - -/*! - * An owned snapshot of one base table taken at creation: where the name resolved, the table's columns, and per-column - * catalog facts. Later DDL does not update it. Create with `duckdb_v2_connection_describe_table()`, read the resolved - * location via `duckdb_v2_table_description_get_qname()`, and the columns via - * `duckdb_v2_table_description_get_column_count()` and `duckdb_v2_table_description_get_column()`. Destroy via - * `duckdb_v2_table_description_destroy()`. - */ -typedef struct _duckdb_v2_table_description { - void *internal_ptr; -} * duckdb_v2_table_description_handle; - +#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * An owned snapshot of one column of a described table: its name, type, and catalog facts. Obtain with - * `duckdb_v2_table_description_get_column()`, read with `duckdb_v2_column_description_get_name()`, - * `duckdb_v2_column_description_get_type()`, `duckdb_v2_column_description_has_default()` and - * `duckdb_v2_column_description_has_generated()`, and destroy with `duckdb_v2_column_description_destroy()`. + * Returns the array of aggregate states to initialize, one pointer per state. Each state points to uninitialized memory + * of the size reported by the size callback; the init callback must initialize all of them in place. + * + * history: + * - unstable: v2.0.0 + * + * @param info The init info handle. + * @param states Receives the array of aggregate state pointers. Borrowed; valid only for the duration of the callback. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR */ -typedef struct _duckdb_v2_column_description { - void *internal_ptr; -} * duckdb_v2_column_description_handle; - -/* --- Constants for catalog --- */ - -/* --- Function pointer typedefs for catalog --- */ - -/* --- Functions for catalog --- */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_init_get_states( + duckdb_v2_aggregate_function_init_info_handle info, void ***states, duckdb_v2_error_info_handle *err); +#endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Resolves a table name and snapshots its description. - * - * Resolves name in the connection's catalogs and returns an owned description of the table it names. name may be - * partial: an unqualified or schema-qualified name resolves through the connection's search path, exactly as the same - * name resolves in SQL. A two-part name tries the first part as a schema and as an attached database, as SQL does, and - * is rejected when both readings exist. A name that resolves to nothing is rejected with the engine's missing-table - * error. A name that resolves to a view is rejected with the same error: a description snapshots a base table, and a - * view is not one, so it is reported as a table that does not exist. + * Retrieves the user data set via `duckdb_v2_aggregate_function_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param conn The connection whose catalogs and search path resolve the name. - * @param name The possibly partial table name to resolve. Borrowed for the call only. - * @param desc On success, receives the owned description. Destroy via `duckdb_v2_table_description_destroy()`. + * @param info The update info handle. + * @param data Receives the user data pointer, or null if none was set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_describe_table(duckdb_v2_connection_handle conn, - duckdb_v2_qname_handle name, - duckdb_v2_table_description_handle *desc, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_update_get_user_data( + duckdb_v2_aggregate_function_update_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the resolved qualified name of the described table. - * - * Returns an owned copy of the fully resolved name: the catalog, schema, and table the lookup landed on, with the - * casing the table was created with, never an echo of the requested name. Rendering it produces SQL that pins the - * described table regardless of search path. + * Retrieves the bind data set by the function's bind callback. * * history: * - unstable: v2.0.0 * - * @param desc The description. - * @param name Receives the owned resolved name. Destroy via `duckdb_v2_qname_destroy()`. + * @param info The update info handle. + * @param data Receives the bind data pointer, or null if none was set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_description_get_qname(duckdb_v2_table_description_handle desc, - duckdb_v2_qname_handle *name, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_update_get_bind_data( + duckdb_v2_aggregate_function_update_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns whether the described table's catalog is read-only. - * - * True when the catalog the name resolved into was attached read-only, in which case no write to the table can succeed. - * False does not by itself prove a write will succeed; it clears the catalog-level check only. + * Returns how many input rows this invocation carries. This is the length of the argument vectors and of the state + * array: row i of every argument vector must be aggregated into state i. * * history: * - unstable: v2.0.0 * - * @param desc The description. - * @param readonly Receives whether the catalog is read-only. + * @param info The update info handle. + * @param count Receives the number of rows. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_description_is_readonly(duckdb_v2_table_description_handle desc, - bool *readonly, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_update_get_row_count( + duckdb_v2_aggregate_function_update_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of columns of the described table. + * Returns how many argument vectors this invocation carries, split into the four parts of the argument list. * - * Counts every column in declared order, generated columns included. Valid indices for - * `duckdb_v2_table_description_get_column()` are [0, count). + * The parts and their order are those the bind callback saw through `duckdb_v2_function_bind_get_arg_count()`, and the + * vectors are at the same indices. Valid indices for `duckdb_v2_aggregate_function_update_get_arg()` are [0, the sum of + * the four counts). Every out-parameter may be NULL, in which case nothing is written to it. * * history: * - unstable: v2.0.0 * - * @param desc The description. - * @param count Receives the column count. + * @param info The update info handle. + * @param positional_fixed Optional. Receives the number of positional-only and standard parameters. + * @param positional_variadic Optional. Receives the number of arguments `*args` received, 0 when the signature has + * none. + * @param named_fixed Optional. Receives the number of named-only parameters. + * @param named_variadic Optional. Receives the number of arguments `**kwargs` received, 0 when the signature has none. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_description_get_column_count(duckdb_v2_table_description_handle desc, - idx_t *count, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_update_get_arg_count( + duckdb_v2_aggregate_function_update_info_handle info, idx_t *positional_fixed, idx_t *positional_variadic, + idx_t *named_fixed, idx_t *named_variadic, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns an owned description of the column at index. + * Retrieves the argument vector at the given index. * - * Columns are numbered in declared order, generated columns included. An out-of-range index is rejected with - * `ERROR_INPUT_OUT_OF_RANGE`. + * The index is the one the bind callback used for the argument, e.g. the index + * `duckdb_v2_function_bind_get_arg_index()` found for a name. The vector holds the argument's values for the current + * batch; use `duckdb_v2_aggregate_function_update_get_row_count()` for the number of rows. Fails if the index is out of + * bounds. Borrowed; valid only for the duration of the callback. * * history: * - unstable: v2.0.0 * - * @param desc The description. - * @param index Zero-based column index. - * @param column Receives the owned column description. Destroy via `duckdb_v2_column_description_destroy()`. + * @param info The update info handle. + * @param index The index of the argument. + * @param vector Receives the borrowed argument vector. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_description_get_column(duckdb_v2_table_description_handle desc, - idx_t index, - duckdb_v2_column_description_handle *column, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR +duckdb_v2_aggregate_function_update_get_arg(duckdb_v2_aggregate_function_update_info_handle info, idx_t index, + duckdb_v2_vector_handle *vector, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys the table description, releasing its resources. - * - * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent - * double-destruction. Column descriptions obtained from it are independent and stay valid. + * Returns the array of aggregate states to update, one pointer per input row: row i of every argument vector must be + * aggregated into state i. Different rows may point to the same state. * * history: * - unstable: v2.0.0 * - * @param desc The description to destroy. + * @param info The update info handle. + * @param states Receives the array of aggregate state pointers. Borrowed; valid only for the duration of the callback. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_description_destroy(duckdb_v2_table_description_handle *desc); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_update_get_states( + duckdb_v2_aggregate_function_update_info_handle info, void ***states, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Borrows the name of the column. - * - * The name carries the casing the column was declared with. + * Retrieves the user data set via `duckdb_v2_aggregate_function_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param column The column description. - * @param name Receives a borrowed pointer to the column name. Valid until the column description is destroyed. - * @param name_length Receives the length of `*name` in bytes. `*name` is not guaranteed to be null-terminated. + * @param info The combine info handle. + * @param data Receives the user data pointer, or null if none was set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_description_get_name(duckdb_v2_column_description_handle column, - const char **name, idx_t *name_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_combine_get_user_data( + duckdb_v2_aggregate_function_combine_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Borrows the type of the column. + * Retrieves the bind data set by the function's bind callback. * * history: * - unstable: v2.0.0 * - * @param column The column description. - * @param type Receives the borrowed column type. Valid until the column description is destroyed; do not destroy it. + * @param info The combine info handle. + * @param data Receives the bind data pointer, or null if none was set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_description_get_type(duckdb_v2_column_description_handle column, - duckdb_v2_logical_type_handle *type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_combine_get_bind_data( + duckdb_v2_aggregate_function_combine_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns whether the column has a default value. - * - * True when the column declares a default expression; the engine evaluates it for rows that omit the column. Generated - * columns report false. + * Returns how many source/target state pairs this invocation must combine. This is the length of both the sources and + * the targets array. * * history: * - unstable: v2.0.0 * - * @param column The column description. - * @param has_default Receives whether the column has a default value. + * @param info The combine info handle. + * @param count Receives the number of state pairs. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_description_has_default(duckdb_v2_column_description_handle column, - bool *has_default, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_combine_get_state_count( + duckdb_v2_aggregate_function_combine_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns whether the column is generated. - * - * True when the column is a generated column, computed by the engine from a generation expression and not writable. + * Returns the array of source aggregate states, one pointer per pair. Source i must be combined into target i; the + * source must not be modified. * * history: * - unstable: v2.0.0 * - * @param column The column description. - * @param has_generated Receives whether the column is generated. + * @param info The combine info handle. + * @param states Receives the array of source aggregate state pointers. Borrowed; valid only for the duration of the + * callback. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_description_has_generated(duckdb_v2_column_description_handle column, - bool *has_generated, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_combine_get_sources( + duckdb_v2_aggregate_function_combine_info_handle info, void ***states, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys the column description, releasing its resources. - * - * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent - * double-destruction. Any name or type borrowed from it becomes dangling. + * Returns the array of target aggregate states, one pointer per pair. Source i must be combined into target i. * * history: * - unstable: v2.0.0 * - * @param column The column description to destroy. + * @param info The combine info handle. + * @param states Receives the array of target aggregate state pointers. Borrowed; valid only for the duration of the + * callback. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_description_destroy(duckdb_v2_column_description_handle *column); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_combine_get_targets( + duckdb_v2_aggregate_function_combine_info_handle info, void ***states, duckdb_v2_error_info_handle *err); #endif -/* --- Struct definitions for catalog --- */ - -/* ============================================================================ - * MODULE: custom_option - * ============================================================================ */ - -/* --- Enums for custom_option --- */ - -/* --- Struct forward declarations for custom_option --- */ - -/* --- Types for custom_option --- */ - -/*! - * An owned opaque handle to a custom option being built. Created with `duckdb_v2_custom_option_create()`, configured - * with the setter functions (e.g. `duckdb_v2_custom_option_set_name()`, `duckdb_v2_custom_option_set_type()`, etc.), - * made available with `duckdb_v2_connection_register_custom_option()` or - * `duckdb_v2_extension_register_custom_option()`, and destroyed with `duckdb_v2_custom_option_destroy()`. - */ -typedef struct _duckdb_v2_custom_option { - void *internal_ptr; -} * duckdb_v2_custom_option_handle; - -/*! - * A borrowed opaque handle to an update of a custom option, received by its update callback. It gives access to the new - * value, the scope it is written at and the user data, and can replace the value. - */ -typedef struct _duckdb_v2_custom_option_update_info { - void *internal_ptr; -} * duckdb_v2_custom_option_update_info_handle; - -/* --- Constants for custom_option --- */ - -/* --- Function pointer typedefs for custom_option --- */ - -typedef void (*duckdb_v2_custom_option_update_callback_fn)(duckdb_v2_custom_option_update_info_handle info, - duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); - -/* --- Functions for custom_option --- */ - #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a new custom option through a factory. - * - * The option starts out empty: configure it with the setter functions, then make it available with - * `duckdb_v2_connection_register_custom_option()` or `duckdb_v2_extension_register_custom_option()`. The caller owns - * the returned handle and must destroy it with `duckdb_v2_custom_option_destroy()`, also after registration. - * - * The custom option can only be registered on the instance the factory belongs to. + * Retrieves the user data set via `duckdb_v2_aggregate_function_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create the custom option through. - * @param option On success, receives the newly created custom option. Owned by the caller. + * @param info The finalize info handle. + * @param data Receives the user data pointer, or null if none was set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_create(duckdb_v2_factory_handle factory, - duckdb_v2_custom_option_handle *option, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_finalize_get_user_data( + duckdb_v2_aggregate_function_finalize_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the name of the custom option, as `SET` and the config functions refer to it. - * - * The name is borrowed and copied. Calling this again replaces the previous name. A name must be set before - * registration. + * Retrieves the bind data set by the function's bind callback. * * history: * - unstable: v2.0.0 * - * @param option The option to set the name of. - * @param name The name to set. Borrowed and copied. - * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be - * NULL only when this is 0. + * @param info The finalize info handle. + * @param data Receives the bind data pointer, or null if none was set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_name(duckdb_v2_custom_option_handle option, const char *name, - idx_t name_length, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_finalize_get_bind_data( + duckdb_v2_aggregate_function_finalize_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the type of the custom option. Every value written to the option is cast to it, as SQL `SET` does. - * - * The type is borrowed and copied. Optional when a default value is set, whose type the option then takes. + * Returns how many aggregate states this invocation must finalize. This is the length of the state array and the number + * of rows to write to the result vector. * * history: * - unstable: v2.0.0 * - * @param option The option to set the type of. - * @param type The type to set. Borrowed and copied. + * @param info The finalize info handle. + * @param count Receives the number of states. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_type(duckdb_v2_custom_option_handle option, - duckdb_v2_logical_type_handle type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_finalize_get_state_count( + duckdb_v2_aggregate_function_finalize_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the default value of the custom option: its value until it is set, and the value `RESET` restores. - * - * The value is borrowed and copied, and cast to the option's type at registration, which fails when the cast does. - * Without a default value the option reads as NULL until it is set. + * Returns the array of aggregate states to finalize, one pointer per state. State i must be finalized into result row + * offset + i. * * history: * - unstable: v2.0.0 * - * @param option The option to set the default value of. - * @param value The default value. Borrowed and copied. + * @param info The finalize info handle. + * @param states Receives the array of aggregate state pointers. Borrowed; valid only for the duration of the callback. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_default_value(duckdb_v2_custom_option_handle option, - duckdb_v2_value_handle value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_finalize_get_states( + duckdb_v2_aggregate_function_finalize_info_handle info, void ***states, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the description of the custom option, as `duckdb_v2_option_get_description()` and `duckdb_settings()` report it. + * Retrieves the result vector the finalize callback must write into. * - * The description is borrowed and copied. Calling this again replaces the previous description. + * State i must be finalized into result row offset + i, with the offset from + * `duckdb_v2_aggregate_function_finalize_get_result_offset()`. Borrowed; valid only for the duration of the callback. * * history: * - unstable: v2.0.0 * - * @param option The option to set the description of. - * @param description The description to set. Borrowed and copied. - * @param description_length The length of `description` in bytes. `description` need not be null-terminated and may be - * NULL only when this is 0. + * @param info The finalize info handle. + * @param vector Receives the borrowed result vector to write into. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_description(duckdb_v2_custom_option_handle option, - const char *description, idx_t description_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR +duckdb_v2_aggregate_function_finalize_get_result(duckdb_v2_aggregate_function_finalize_info_handle info, + duckdb_v2_vector_handle *vector, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the scope a write at `SETTING_SCOPE_DEFAULT` goes to, like SQL `SET name = value`. - * - * Must be GLOBAL or SESSION, and a scope the option supports. Defaults to SESSION, or to GLOBAL when the option does - * not support SESSION. + * Returns the offset in the result vector at which to start writing: state i must be finalized into result row offset + + * i. * * history: * - unstable: v2.0.0 * - * @param option The option to set the default scope of. - * @param scope The default scope, GLOBAL or SESSION. + * @param info The finalize info handle. + * @param offset Receives the result offset. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_default_scope(duckdb_v2_custom_option_handle option, - DUCKDB_V2_SETTING_SCOPE scope, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_finalize_get_result_offset( + duckdb_v2_aggregate_function_finalize_info_handle info, idx_t *offset, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets whether the custom option can be written at a scope, as `duckdb_v2_option_supports_scope()` reports it. - * - * A custom option supports both GLOBAL and SESSION unless told otherwise. A write at a scope it does not support fails, - * from SQL as from `duckdb_v2_config_set_option_value()`. Registration fails when the option supports neither scope. + * Retrieves the user data set via `duckdb_v2_aggregate_function_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param option The option to configure. - * @param scope The scope, GLOBAL or SESSION. - * @param supported Whether the option can be written at the scope. + * @param info The destroy info handle. + * @param data Receives the user data pointer, or null if none was set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_supports_scope(duckdb_v2_custom_option_handle option, - DUCKDB_V2_SETTING_SCOPE scope, bool supported, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_destroy_get_user_data( + duckdb_v2_aggregate_function_destroy_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets arbitrary user data on the custom option. - * - * Associates an opaque pointer with the option, retrievable from the update callback via - * `duckdb_v2_custom_option_update_get_user_data()`. The opaque handle bundles the pointer with an optional destructor, - * invoked when the data is no longer needed: once the custom option handle is destroyed and, if it was registered, the - * instance is too. + * Retrieves the bind data set by the function's bind callback. * * history: * - unstable: v2.0.0 * - * @param option The option to set the user data of. - * @param data Opaque handle bundling the user data pointer plus an optional destructor. + * @param info The destroy info handle. + * @param data Receives the bind data pointer, or null if none was set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_user_data(duckdb_v2_custom_option_handle option, - duckdb_v2_opaque *data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_destroy_get_bind_data( + duckdb_v2_aggregate_function_destroy_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional update callback of the custom option. - * - * The callback is invoked whenever the option is set or reset, from SQL as from `duckdb_v2_config_set_option_value()`, - * after the new value is cast to the option's type and before it is stored. It may replace the value with - * `duckdb_v2_custom_option_update_set_value()`, or refuse it by reporting an error. It is not invoked for the default - * value at registration, nor for a value given to the instance at startup. The callback must not write options itself. + * Returns how many aggregate states this invocation must destroy. This is the length of the state array. * * history: * - unstable: v2.0.0 * - * @param option The option to set the update callback of. - * @param callback The update callback to set. + * @param info The destroy info handle. + * @param count Receives the number of states. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_update_callback( - duckdb_v2_custom_option_handle option, duckdb_v2_custom_option_update_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_destroy_get_state_count( + duckdb_v2_aggregate_function_destroy_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_custom_option_set_user_data()`. + * Returns the array of aggregate states to destroy, one pointer per state. The callback must release any resources the + * states own. * * history: * - unstable: v2.0.0 * - * @param info The update info handle. - * @param data Receives the user data pointer, or null if none was set. + * @param info The destroy info handle. + * @param states Receives the array of aggregate state pointers. Borrowed; valid only for the duration of the callback. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_update_get_user_data( - duckdb_v2_custom_option_update_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_destroy_get_states( + duckdb_v2_aggregate_function_destroy_info_handle info, void ***states, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the value the option is updated to, already cast to the option's type. On a reset this is the default - * value, which may be NULL. The returned value is owned by the caller and must be destroyed via - * `duckdb_v2_value_destroy()`. + * Retrieves the user data set via `duckdb_v2_aggregate_function_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param info The update info handle. - * @param value Receives the new value. Owned by the caller; destroy via `duckdb_v2_value_destroy()`. + * @param info The stats info handle. + * @param data Receives the user data pointer, or null if none was set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_update_get_value(duckdb_v2_custom_option_update_info_handle info, - duckdb_v2_value_handle *value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_stats_get_user_data( + duckdb_v2_aggregate_function_stats_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Replaces the value the option is updated to, e.g. to normalize it. The value is borrowed and copied, and cast to the - * option's type, which fails when the cast does. + * Retrieves the bind data set by the function's bind callback. * * history: * - unstable: v2.0.0 * - * @param info The update info handle. - * @param value The value to store instead. Borrowed and copied. + * @param info The stats info handle. + * @param data Receives the bind data pointer, or null if none was set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_update_set_value(duckdb_v2_custom_option_update_info_handle info, - duckdb_v2_value_handle value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_stats_get_bind_data( + duckdb_v2_aggregate_function_stats_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the scope the value is written at: GLOBAL or SESSION, a DEFAULT write already resolved to the option's - * default scope. + * Returns how many arguments the call site has, split into the four parts of the argument list. + * + * The parts and their order are those the bind callback saw through `duckdb_v2_function_bind_get_arg_count()`, and the + * arguments are at the same indices. Valid indices for `duckdb_v2_aggregate_function_stats_get_arg_stats()` are [0, the + * sum of the four counts). Every out-parameter may be NULL, in which case nothing is written to it. * * history: * - unstable: v2.0.0 * - * @param info The update info handle. - * @param scope Receives the scope. + * @param info The stats info handle. + * @param positional_fixed Optional. Receives the number of positional-only and standard parameters. + * @param positional_variadic Optional. Receives the number of arguments `*args` received, 0 when the signature has + * none. + * @param named_fixed Optional. Receives the number of named-only parameters. + * @param named_variadic Optional. Receives the number of arguments `**kwargs` received, 0 when the signature has none. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_update_get_scope(duckdb_v2_custom_option_update_info_handle info, - DUCKDB_V2_SETTING_SCOPE *scope, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_stats_get_arg_count( + duckdb_v2_aggregate_function_stats_info_handle info, idx_t *positional_fixed, idx_t *positional_variadic, + idx_t *named_fixed, idx_t *named_variadic, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves whether the update is a reset to the default value, like SQL `RESET`. + * Retrieves the statistics of the argument at the given index. + * + * The index is the one the bind callback used for the argument. The statistics are read-only. Fails if the index is out + * of bounds. Borrowed; valid only for the duration of the callback. * * history: * - unstable: v2.0.0 * - * @param info The update info handle. - * @param is_reset Receives whether the update is a reset. + * @param info The stats info handle. + * @param index The index of the argument. + * @param stats Receives the borrowed, read-only statistics of the argument. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_update_is_reset(duckdb_v2_custom_option_update_info_handle info, - bool *is_reset, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR +duckdb_v2_aggregate_function_stats_get_arg_stats(duckdb_v2_aggregate_function_stats_info_handle info, idx_t index, + duckdb_v2_stats_handle *stats, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the custom option on the connection's instance, visible to every connection. - * - * Registration is not transactional: it takes effect at once, also inside an explicit transaction, and a rollback does - * not undo it. Registration requires a name and a type, or a default value to take the type from, and fails when an - * option of the same name already exists. A value given for the option at startup is picked up. The custom option must - * have been created through a factory of the same instance. The caller still owns the handle after registration and - * must destroy it with `duckdb_v2_custom_option_destroy()`, which does not affect the registered option. + * Retrieves the statistics of the call site's result, for the callback to narrow. * - * history: + * The statistics start out unknown, with every kind of value possible. They describe every result the aggregate + * produces, including the result of a group with no input rows, such as an ungrouped aggregate over an empty table. + * Borrowed; valid only for the duration of the callback. + * + * history: + * - unstable: v2.0.0 + * + * @param info The stats info handle. + * @param stats Receives the borrowed, writable statistics of the call site's result. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR +duckdb_v2_aggregate_function_stats_get_result_stats(duckdb_v2_aggregate_function_stats_info_handle info, + duckdb_v2_stats_handle *stats, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Registers the aggregate function, making it available for use in SQL queries. + * + * The function is registered on the connection's database, visible to every connection, in the connection's + * transaction: inside an explicit transaction, it is invisible to other connections until the transaction commits, and + * a rollback undoes it. Registration requires a name, the size, init, update, combine and finalize callbacks, and a + * signature with a complete return type; an ANY return type is accepted only together with a bind callback that sets + * the concrete type per call site. The aggregate function must have been created through a factory of the same + * database. The caller still owns the handle after registration and must destroy it with + * `duckdb_v2_aggregate_function_destroy()`, which does not affect the registered function. + * + * history: * - unstable: v2.0.0 * * @param conn The connection to register on. - * @param option The custom option to register. + * @param function The aggregate function to register. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_register_custom_option(duckdb_v2_connection_handle conn, - duckdb_v2_custom_option_handle option, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_register_aggregate_function( + duckdb_v2_connection_handle conn, duckdb_v2_aggregate_function_handle function, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the custom option on the loading extension's instance, visible to every connection. + * Registers the aggregate function, making it available for use in SQL queries. * - * Use this from the extension's load callback. Registration is not transactional, requires a name and a type, or a - * default value to take the type from, and fails when an option of the same name already exists. A value given for the - * option at startup is picked up. The custom option must have been created through a factory of the same instance. The - * caller still owns the handle after registration and must destroy it with `duckdb_v2_custom_option_destroy()`, which - * does not affect the registered option. + * The function is registered on the loading extension's database and attributed to the extension. Use this from the + * extension's load callback. Registration requires a name, the size, init, update, combine and finalize callbacks, and + * a signature with a complete return type; an ANY return type is accepted only together with a bind callback that sets + * the concrete type per call site. The aggregate function must have been created through a factory of the same + * database. The caller still owns the handle after registration and must destroy it with + * `duckdb_v2_aggregate_function_destroy()`, which does not affect the registered function. * * history: * - unstable: v2.0.0 * * @param extension The loading extension. - * @param option The custom option to register. + * @param function The aggregate function to register. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_custom_option(duckdb_v2_extension_handle extension, - duckdb_v2_custom_option_handle option, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_aggregate_function( + duckdb_v2_extension_handle extension, duckdb_v2_aggregate_function_handle function, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys the custom option, releasing its resources. + * Destroys the aggregate function, releasing its resources. * * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent - * double-destruction. Destroying the handle after registration does not affect the registered option. + * double-destruction. Destroying the handle after registration does not affect the registered function. * * history: * - unstable: v2.0.0 * - * @param option The option to destroy. + * @param function The function to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_destroy(duckdb_v2_custom_option_handle *option); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_aggregate_function_destroy(duckdb_v2_aggregate_function_handle *function); #endif -/* --- Struct definitions for custom_option --- */ +/* --- Struct definitions for aggregate --- */ /* ============================================================================ - * MODULE: expression + * MODULE: catalog * ============================================================================ */ -/* --- Enums for expression --- */ - -/*! - * The type of a bound expression node. The values mirror the engine's own expression types, restricted to the node - * types a filter predicate can contain; every other node type is reported as `EXPRESSION_TYPE_INVALID`. - * - * Comparisons, `BETWEEN` and casts are regular scalar function calls once bound: they have the function's children and - * name, and only their type tells them apart from any other function. A `CAST` therefore has one child, the value being - * cast, and its target type is the node's return type. - */ -typedef enum DUCKDB_V2_EXPRESSION_TYPE { - //! A node type this API does not model. Its children can still be walked. - DUCKDB_V2_EXPRESSION_TYPE_INVALID = 0, - - /*! - * A cast. One child; the target type is the node's return type and `duckdb_v2_expression_cast_get_mode()` tells a - * `TRY_CAST` apart. - */ - DUCKDB_V2_EXPRESSION_TYPE_OPERATOR_CAST = 12, - - //! Logical `NOT`. One child. - DUCKDB_V2_EXPRESSION_TYPE_OPERATOR_NOT = 13, - - //! `IS NULL`. One child. - DUCKDB_V2_EXPRESSION_TYPE_OPERATOR_IS_NULL = 14, - - //! `IS NOT NULL`. One child. - DUCKDB_V2_EXPRESSION_TYPE_OPERATOR_IS_NOT_NULL = 15, - - //! `=`. Two children. - DUCKDB_V2_EXPRESSION_TYPE_COMPARE_EQUAL = 25, - - //! `<>`. Two children. - DUCKDB_V2_EXPRESSION_TYPE_COMPARE_NOTEQUAL = 26, - - //! `<`. Two children. - DUCKDB_V2_EXPRESSION_TYPE_COMPARE_LESSTHAN = 27, - - //! `>`. Two children. - DUCKDB_V2_EXPRESSION_TYPE_COMPARE_GREATERTHAN = 28, - - //! `<=`. Two children. - DUCKDB_V2_EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO = 29, - - //! `>=`. Two children. - DUCKDB_V2_EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO = 30, - - //! `IN`. The first child is the value tested, the remaining children are the candidates. - DUCKDB_V2_EXPRESSION_TYPE_COMPARE_IN = 35, - - //! `NOT IN`. The first child is the value tested, the remaining children are the candidates. - DUCKDB_V2_EXPRESSION_TYPE_COMPARE_NOT_IN = 36, - - //! `IS DISTINCT FROM`. Two children. - DUCKDB_V2_EXPRESSION_TYPE_COMPARE_DISTINCT_FROM = 37, - - //! `BETWEEN`. Three children: the value tested, the lower bound and the upper bound. - DUCKDB_V2_EXPRESSION_TYPE_COMPARE_BETWEEN = 38, - - //! `IS NOT DISTINCT FROM`. Two children. - DUCKDB_V2_EXPRESSION_TYPE_COMPARE_NOT_DISTINCT_FROM = 40, - - //! Logical `AND`. Two or more children. - DUCKDB_V2_EXPRESSION_TYPE_CONJUNCTION_AND = 50, - - //! Logical `OR`. Two or more children. - DUCKDB_V2_EXPRESSION_TYPE_CONJUNCTION_OR = 51, - - //! A constant. No children; read it with `duckdb_v2_expression_constant_get_value()`. - DUCKDB_V2_EXPRESSION_TYPE_VALUE_CONSTANT = 75, - - //! A prepared statement parameter whose value is not known yet. No children. - DUCKDB_V2_EXPRESSION_TYPE_VALUE_PARAMETER = 76, - - /*! - * A call to a scalar function other than the ones listed above. The children are its arguments; read the name with - * `duckdb_v2_expression_function_get_name()`. - */ - DUCKDB_V2_EXPRESSION_TYPE_BOUND_FUNCTION = 141, - - //! A `CASE` expression. The children are each `WHEN` condition followed by its `THEN` result, then the `ELSE` - //! result. - DUCKDB_V2_EXPRESSION_TYPE_CASE_EXPR = 150, +/* --- Enums for catalog --- */ - //! `COALESCE`. One or more children. - DUCKDB_V2_EXPRESSION_TYPE_OPERATOR_COALESCE = 152, +/* --- Struct forward declarations for catalog --- */ - //! A reference to a column. No children; read it with `duckdb_v2_expression_column_ref_get_index()`. - DUCKDB_V2_EXPRESSION_TYPE_BOUND_COLUMN_REF = 228, - DUCKDB_V2_EXPRESSION_TYPE_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_EXPRESSION_TYPE; +/* --- Types for catalog --- */ /*! - * What checking a predicate against the statistics of its column found out (`FilterPropagateResult`): whether every row - * the statistics describe passes the predicate, none does, or the statistics do not tell. + * An owned snapshot of one base table taken at creation: where the name resolved, the table's columns, and per-column + * catalog facts. Later DDL does not update it. Create with `duckdb_v2_connection_describe_table()`, read the resolved + * location via `duckdb_v2_table_description_get_qname()`, and the columns via + * `duckdb_v2_table_description_get_column_count()` and `duckdb_v2_table_description_get_column()`. Destroy via + * `duckdb_v2_table_description_destroy()`. */ -typedef enum DUCKDB_V2_FILTER_PROPAGATE_RESULT { - //! The statistics do not decide the predicate. - DUCKDB_V2_FILTER_PROPAGATE_RESULT_NO_PRUNING_POSSIBLE = 0, - - //! Every row passes the predicate. - DUCKDB_V2_FILTER_PROPAGATE_RESULT_ALWAYS_TRUE = 1, - - //! No row passes the predicate. - DUCKDB_V2_FILTER_PROPAGATE_RESULT_ALWAYS_FALSE = 2, - - //! Every row passes the predicate or evaluates it to NULL. - DUCKDB_V2_FILTER_PROPAGATE_RESULT_TRUE_OR_NULL = 3, - - //! No row passes the predicate: each evaluates it to false or to NULL. - DUCKDB_V2_FILTER_PROPAGATE_RESULT_FALSE_OR_NULL = 4, - DUCKDB_V2_FILTER_PROPAGATE_RESULT_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_FILTER_PROPAGATE_RESULT; - -/* --- Struct forward declarations for expression --- */ - -/* --- Types for expression --- */ +typedef struct _duckdb_v2_table_description { + void *internal_ptr; +} * duckdb_v2_table_description_handle; /*! - * A borrowed opaque handle to a node of a bound expression tree. Read-only and owned by the engine: valid only for the - * duration of the callback that handed it out, and never destroyed by the caller. Child nodes borrowed via - * `duckdb_v2_expression_get_child()` share their parent's lifetime. + * An owned snapshot of one column of a described table: its name, type, and catalog facts. Obtain with + * `duckdb_v2_table_description_get_column()`, read with `duckdb_v2_column_description_get_name()`, + * `duckdb_v2_column_description_get_type()`, `duckdb_v2_column_description_has_default()` and + * `duckdb_v2_column_description_has_generated()`, and destroy with `duckdb_v2_column_description_destroy()`. */ -typedef struct _duckdb_v2_expression { +typedef struct _duckdb_v2_column_description { void *internal_ptr; -} * duckdb_v2_expression_handle; +} * duckdb_v2_column_description_handle; -/* --- Constants for expression --- */ +/* --- Constants for catalog --- */ -/* --- Function pointer typedefs for expression --- */ +/* --- Function pointer typedefs for catalog --- */ -/* --- Functions for expression --- */ +/* --- Functions for catalog --- */ #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the type of an expression node. + * Resolves a table name and snapshots its description. * - * The type decides which of the type-specific accessors apply, and what the node's children mean; see - * `EXPRESSION_TYPE`. A node of a type this API does not model reports `EXPRESSION_TYPE_INVALID`. + * Resolves name in the connection's catalogs and returns an owned description of the table it names. name may be + * partial: an unqualified or schema-qualified name resolves through the connection's search path, exactly as the same + * name resolves in SQL. A two-part name tries the first part as a schema and as an attached database, as SQL does, and + * is rejected when both readings exist. A name that resolves to nothing is rejected with the engine's missing-table + * error. A name that resolves to a view is rejected with the same error: a description snapshots a base table, and a + * view is not one, so it is reported as a table that does not exist. * * history: * - unstable: v2.0.0 * - * @param expression The expression node. - * @param type Receives the node type. + * @param conn The connection whose catalogs and search path resolve the name. + * @param name The possibly partial table name to resolve. Borrowed for the call only. + * @param desc On success, receives the owned description. Destroy via `duckdb_v2_table_description_destroy()`. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_get_type(duckdb_v2_expression_handle expression, - DUCKDB_V2_EXPRESSION_TYPE *type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_describe_table(duckdb_v2_connection_handle conn, + duckdb_v2_qname_handle name, + duckdb_v2_table_description_handle *desc, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the logical type the expression node evaluates to. + * Returns the resolved qualified name of the described table. * - * For a cast this is the target type. The returned type is owned by the caller and must be destroyed via - * `duckdb_v2_logical_type_destroy()`. + * Returns an owned copy of the fully resolved name: the catalog, schema, and table the lookup landed on, with the + * casing the table was created with, never an echo of the requested name. Rendering it produces SQL that pins the + * described table regardless of search path. * * history: * - unstable: v2.0.0 * - * @param expression The expression node. - * @param type Receives the owned logical type. + * @param desc The description. + * @param name Receives the owned resolved name. Destroy via `duckdb_v2_qname_destroy()`. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_get_return_type(duckdb_v2_expression_handle expression, - duckdb_v2_logical_type_handle *type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_description_get_qname(duckdb_v2_table_description_handle desc, + duckdb_v2_qname_handle *name, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of child nodes of an expression node. + * Returns whether the described table's catalog is read-only. * - * Works for every node type, including `EXPRESSION_TYPE_INVALID`. Constants, parameters and column references have no - * children. + * True when the catalog the name resolved into was attached read-only, in which case no write to the table can succeed. + * False does not by itself prove a write will succeed; it clears the catalog-level check only. * * history: * - unstable: v2.0.0 * - * @param expression The expression node. - * @param count Receives the number of children. + * @param desc The description. + * @param readonly Receives whether the catalog is read-only. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_get_child_count(duckdb_v2_expression_handle expression, idx_t *count, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_description_is_readonly(duckdb_v2_table_description_handle desc, + bool *readonly, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves a child node of an expression node by index. + * Returns the number of columns of the described table. * - * Fails if the index is out of bounds. Children are ordered as the node type describes (see `EXPRESSION_TYPE`). The - * child is borrowed and shares the lifetime of its parent. + * Counts every column in declared order, generated columns included. Valid indices for + * `duckdb_v2_table_description_get_column()` are [0, count). * * history: * - unstable: v2.0.0 * - * @param expression The expression node. - * @param index The index of the child to retrieve. - * @param child Receives the borrowed child node. + * @param desc The description. + * @param count Receives the column count. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_get_child(duckdb_v2_expression_handle expression, idx_t index, - duckdb_v2_expression_handle *child, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_description_get_column_count(duckdb_v2_table_description_handle desc, + idx_t *count, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value of a constant node. + * Returns an owned description of the column at index. * - * Fails if the node is not of type `EXPRESSION_TYPE_VALUE_CONSTANT`. The returned value is owned by the caller and must - * be destroyed via `duckdb_v2_value_destroy()`. + * Columns are numbered in declared order, generated columns included. An out-of-range index is rejected with + * `ERROR_INPUT_OUT_OF_RANGE`. * * history: * - unstable: v2.0.0 * - * @param expression The constant node. - * @param value Receives the owned constant value. + * @param desc The description. + * @param index Zero-based column index. + * @param column Receives the owned column description. Destroy via `duckdb_v2_column_description_destroy()`. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_constant_get_value(duckdb_v2_expression_handle expression, - duckdb_v2_value_handle *value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_description_get_column(duckdb_v2_table_description_handle desc, + idx_t index, + duckdb_v2_column_description_handle *column, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the column a column reference node points at. + * Destroys the table description, releasing its resources. * - * Fails if the node is not of type `EXPRESSION_TYPE_BOUND_COLUMN_REF`. The index counts the columns of the operator the - * predicate is evaluated against, which is not necessarily the full set of columns that operator can produce: a - * callback resolves it through whatever handed it the expression, e.g. - * `duckdb_v2_table_function_filter_pushdown_get_column_index()` for a filter offered to a table function. + * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent + * double-destruction. Column descriptions obtained from it are independent and stay valid. * * history: * - unstable: v2.0.0 * - * @param expression The column reference node. - * @param index Receives the column index. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param desc The description to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_column_ref_get_index(duckdb_v2_expression_handle expression, - idx_t *index, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_description_destroy(duckdb_v2_table_description_handle *desc); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the name of the scalar function a function node calls. + * Borrows the name of the column. * - * Applies to `EXPRESSION_TYPE_BOUND_FUNCTION` and to the node types that are function calls underneath: the - * comparisons, `EXPRESSION_TYPE_COMPARE_BETWEEN` and `EXPRESSION_TYPE_OPERATOR_CAST`. Fails for any other node type. - * For a comparison the name is its operator, e.g. `<`; for `BETWEEN` and casts it is an internal name, so dispatch on - * the type rather than the name for those. The name is borrowed and shares the lifetime of the node. + * The name carries the casing the column was declared with. * * history: * - unstable: v2.0.0 * - * @param expression The function node. - * @param name Receives a borrowed pointer to the function name. + * @param column The column description. + * @param name Receives a borrowed pointer to the column name. Valid until the column description is destroyed. * @param name_length Receives the length of `*name` in bytes. `*name` is not guaranteed to be null-terminated. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_function_get_name(duckdb_v2_expression_handle expression, - const char **name, idx_t *name_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_description_get_name(duckdb_v2_column_description_handle column, + const char **name, idx_t *name_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the qualified name of the scalar function a function node calls. - * - * Applies to the same node types as `duckdb_v2_expression_function_get_name()`, and fails for any other. The name is - * qualified with the catalog and schema the function was resolved in, where known. The returned name is owned by the - * caller and must be destroyed via `duckdb_v2_qname_destroy()`. + * Borrows the type of the column. * * history: * - unstable: v2.0.0 * - * @param expression The function node. - * @param name Receives the owned qualified name. + * @param column The column description. + * @param type Receives the borrowed column type. Valid until the column description is destroyed; do not destroy it. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_function_get_qname(duckdb_v2_expression_handle expression, - duckdb_v2_qname_handle *name, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_description_get_type(duckdb_v2_column_description_handle column, + duckdb_v2_logical_type_handle *type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns whether a cast node is a regular `CAST` or a `TRY_CAST`. + * Returns whether the column has a default value. * - * Fails if the node is not of type `EXPRESSION_TYPE_OPERATOR_CAST`. A `TRY_CAST` yields NULL for a value it cannot - * convert where a regular `CAST` would fail the query. + * True when the column declares a default expression; the engine evaluates it for rows that omit the column. Generated + * columns report false. * * history: * - unstable: v2.0.0 * - * @param expression The cast node. - * @param mode Receives the cast mode. + * @param column The column description. + * @param has_default Receives whether the column has a default value. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_cast_get_mode(duckdb_v2_expression_handle expression, - DUCKDB_V2_CAST_MODE *mode, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_description_has_default(duckdb_v2_column_description_handle column, + bool *has_default, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Checks a predicate over one column against the statistics of that column (`ExpressionFilter::CheckStatistics`): the - * statistics of the column are propagated through the expression - comparisons, conjunctions, IS NULL, IN, casts and - * the functions the engine knows the statistics of - to find out whether every row the statistics describe passes the - * predicate, none does, or nothing can be told. A table function uses it to skip a row group (or a file) whose - * statistics, built with `duckdb_v2_stats_create()`, make a pushed-down filter it did not take over false for every - * row. Every column reference of the predicate stands for the column described by `stats`. + * Returns whether the column is generated. + * + * True when the column is a generated column, computed by the engine from a generation expression and not writable. * * history: * - unstable: v2.0.0 * - * @param context The context of the query; the statistics of function calls in the predicate are derived through it. - * @param expression The predicate: a boolean expression over one column, referenced by its column references. - * @param stats The statistics of that column over the rows in question. - * @param result Receives what the statistics decide about the predicate. + * @param column The column description. + * @param has_generated Receives whether the column is generated. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_check_statistics(duckdb_v2_context_handle context, - duckdb_v2_expression_handle expression, - duckdb_v2_stats_handle stats, - DUCKDB_V2_FILTER_PROPAGATE_RESULT *result, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_description_has_generated(duckdb_v2_column_description_handle column, + bool *has_generated, + duckdb_v2_error_info_handle *err); #endif -/* --- Struct definitions for expression --- */ +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Destroys the column description, releasing its resources. + * + * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent + * double-destruction. Any name or type borrowed from it becomes dangling. + * + * history: + * - unstable: v2.0.0 + * + * @param column The column description to destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_column_description_destroy(duckdb_v2_column_description_handle *column); +#endif + +/* --- Struct definitions for catalog --- */ /* ============================================================================ - * MODULE: log sink + * MODULE: custom_option * ============================================================================ */ -/* --- Enums for log sink --- */ - -//! The scope a log entry was written in, which decides which of its ids are present. -typedef enum DUCKDB_V2_LOG_SCOPE { - //! Written for the database as a whole, carrying no connection, transaction or query id. - DUCKDB_V2_LOG_SCOPE_DATABASE = 10, - - //! Written by a connection, carrying its connection id and, inside one, the transaction and query ids. - DUCKDB_V2_LOG_SCOPE_CONNECTION = 20, - - //! Written by a thread executing a query, carrying the thread id next to the connection's ids. - DUCKDB_V2_LOG_SCOPE_THREAD = 30, - DUCKDB_V2_LOG_SCOPE_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_LOG_SCOPE; - -/* --- Struct forward declarations for log sink --- */ +/* --- Enums for custom_option --- */ -/* --- Types for log sink --- */ +/* --- Struct forward declarations for custom_option --- */ -/*! - * An owned opaque handle to a log sink being built. Created with `duckdb_v2_log_sink_create()`, configured with - * `duckdb_v2_log_sink_set_name()`, `duckdb_v2_log_sink_set_write_callback()` and the other setters, made available with - * `duckdb_v2_instance_register_log_sink()` or `duckdb_v2_extension_register_log_sink()`, and destroyed with - * `duckdb_v2_log_sink_destroy()`. - */ -typedef struct _duckdb_v2_log_sink { - void *internal_ptr; -} * duckdb_v2_log_sink_handle; +/* --- Types for custom_option --- */ /*! - * A borrowed opaque handle to the context of a log entry, received by a log sink's write callback next to the entry - * itself, and valid only for the duration of that call. Read the ids `duckdb_logs` reports for the entry through its - * getters, e.g. `duckdb_v2_log_sink_write_info_get_connection_id()`. + * An owned opaque handle to a custom option being built. Created with `duckdb_v2_custom_option_create()`, configured + * with the setter functions (e.g. `duckdb_v2_custom_option_set_name()`, `duckdb_v2_custom_option_set_type()`, etc.), + * made available with `duckdb_v2_connection_register_custom_option()` or + * `duckdb_v2_extension_register_custom_option()`, and destroyed with `duckdb_v2_custom_option_destroy()`. */ -typedef struct _duckdb_v2_log_sink_write_info { +typedef struct _duckdb_v2_custom_option { void *internal_ptr; -} * duckdb_v2_log_sink_write_info_handle; +} * duckdb_v2_custom_option_handle; /*! - * A borrowed opaque handle received by a log sink's flush callback, and valid only for the duration of that call. It - * carries nothing yet. + * A borrowed opaque handle to an update of a custom option, received by its update callback. It gives access to the new + * value, the scope it is written at and the user data, and can replace the value. */ -typedef struct _duckdb_v2_log_sink_flush_info { +typedef struct _duckdb_v2_custom_option_update_info { void *internal_ptr; -} * duckdb_v2_log_sink_flush_info_handle; - -/* --- Constants for log sink --- */ +} * duckdb_v2_custom_option_update_info_handle; -/* --- Function pointer typedefs for log sink --- */ +/* --- Constants for custom_option --- */ -typedef void (*duckdb_v2_log_sink_write_callback_fn)(duckdb_v2_log_sink_write_info_handle info, void *user_data, - int64_t timestamp, DUCKDB_V2_LOG_LEVEL level, - DUCKDB_V2_LOG_SCOPE scope, const char *type, idx_t type_length, - const char *message, idx_t message_length, - duckdb_v2_error_info_handle *err); +/* --- Function pointer typedefs for custom_option --- */ -typedef void (*duckdb_v2_log_sink_flush_callback_fn)(duckdb_v2_log_sink_flush_info_handle info, void *user_data, - duckdb_v2_error_info_handle *err); +typedef void (*duckdb_v2_custom_option_update_callback_fn)(duckdb_v2_custom_option_update_info_handle info, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); -/* --- Functions for log sink --- */ +/* --- Functions for custom_option --- */ #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a new log sink through a factory. + * Creates a new custom option through a factory. * - * The log sink starts out empty: configure it with the setter functions, then make it available with - * `duckdb_v2_instance_register_log_sink()` or `duckdb_v2_extension_register_log_sink()`. The caller owns the returned - * handle and must destroy it with `duckdb_v2_log_sink_destroy()`, also after registration. + * The option starts out empty: configure it with the setter functions, then make it available with + * `duckdb_v2_connection_register_custom_option()` or `duckdb_v2_extension_register_custom_option()`. The caller owns + * the returned handle and must destroy it with `duckdb_v2_custom_option_destroy()`, also after registration. * - * The log sink can only be registered on the instance the factory belongs to. + * The custom option can only be registered on the instance the factory belongs to. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create the log sink through. - * @param sink On success, receives the newly created log sink. Owned by the caller. + * @param factory The factory to create the custom option through. + * @param option On success, receives the newly created custom option. Owned by the caller. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_create(duckdb_v2_factory_handle factory, - duckdb_v2_log_sink_handle *sink, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_create(duckdb_v2_factory_handle factory, + duckdb_v2_custom_option_handle *option, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the name the logging configuration refers to the log sink by. + * Sets the name of the custom option, as `SET` and the config functions refer to it. * - * Names are matched case-insensitively. The name is borrowed and copied. Calling this again replaces the previous name. - * A name must be set before registration. + * The name is borrowed and copied. Calling this again replaces the previous name. A name must be set before + * registration. * * history: * - unstable: v2.0.0 * - * @param sink The log sink to set the name of. + * @param option The option to set the name of. * @param name The name to set. Borrowed and copied. * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be * NULL only when this is 0. @@ -10445,787 +9977,780 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_create(duckdb_v2_factory_handle * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_set_name(duckdb_v2_log_sink_handle sink, const char *name, - idx_t name_length, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_name(duckdb_v2_custom_option_handle option, const char *name, + idx_t name_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets arbitrary user data on the log sink. + * Sets the type of the custom option. Every value written to the option is cast to it, as SQL `SET` does. * - * Associates an opaque pointer with the sink, handed to its write and flush callbacks. The opaque handle bundles the - * pointer with an optional destructor, invoked when the data is no longer needed: when the instance is destroyed if the - * sink was registered, else when the log sink handle is. + * The type is borrowed and copied. Optional when a default value is set, whose type the option then takes. * * history: * - unstable: v2.0.0 * - * @param sink The log sink to set the user data of. - * @param data Opaque handle bundling the user data pointer plus an optional destructor. + * @param option The option to set the type of. + * @param type The type to set. Borrowed and copied. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_set_user_data(duckdb_v2_log_sink_handle sink, duckdb_v2_opaque *data, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_type(duckdb_v2_custom_option_handle option, + duckdb_v2_logical_type_handle type, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the write callback of the log sink, invoked for every entry the logging configuration directs to the sink. + * Sets the default value of the custom option: its value until it is set, and the value `RESET` restores. * - * The callback must return quickly, must be safe to run concurrently and on any thread, and must not log or change the - * logging configuration. A write callback must be set before registration. + * The value is borrowed and copied, and cast to the option's type at registration, which fails when the cast does. + * Without a default value the option reads as NULL until it is set. * * history: * - unstable: v2.0.0 * - * @param sink The log sink to set the write callback of. - * @param callback The write callback to set. + * @param option The option to set the default value of. + * @param value The default value. Borrowed and copied. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_set_write_callback(duckdb_v2_log_sink_handle sink, - duckdb_v2_log_sink_write_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_default_value(duckdb_v2_custom_option_handle option, + duckdb_v2_value_handle value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional flush callback of the log sink, invoked when DuckDB flushes its log, so entries the sink holds on - * to can be written out. When DuckDB flushes is up to DuckDB; entries still held when the instance is destroyed are for - * the user data's destructor to write out. + * Sets the description of the custom option, as `duckdb_v2_option_get_description()` and `duckdb_settings()` report it. * - * Like the write callback, it must be safe to run on any thread, and must not log or change the logging configuration. + * The description is borrowed and copied. Calling this again replaces the previous description. * * history: * - unstable: v2.0.0 * - * @param sink The log sink to set the flush callback of. - * @param callback The flush callback to set. + * @param option The option to set the description of. + * @param description The description to set. Borrowed and copied. + * @param description_length The length of `description` in bytes. `description` need not be null-terminated and may be + * NULL only when this is 0. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_set_flush_callback(duckdb_v2_log_sink_handle sink, - duckdb_v2_log_sink_flush_callback_fn callback, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_description(duckdb_v2_custom_option_handle option, + const char *description, idx_t description_length, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the scope a write at `SETTING_SCOPE_DEFAULT` goes to, like SQL `SET name = value`. + * + * Must be GLOBAL or SESSION, and a scope the option supports. Defaults to SESSION, or to GLOBAL when the option does + * not support SESSION. + * + * history: + * - unstable: v2.0.0 + * + * @param option The option to set the default scope of. + * @param scope The default scope, GLOBAL or SESSION. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_default_scope(duckdb_v2_custom_option_handle option, + DUCKDB_V2_SETTING_SCOPE scope, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets whether the custom option can be written at a scope, as `duckdb_v2_option_supports_scope()` reports it. + * + * A custom option supports both GLOBAL and SESSION unless told otherwise. A write at a scope it does not support fails, + * from SQL as from `duckdb_v2_config_set_option_value()`. Registration fails when the option supports neither scope. + * + * history: + * - unstable: v2.0.0 + * + * @param option The option to configure. + * @param scope The scope, GLOBAL or SESSION. + * @param supported Whether the option can be written at the scope. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_supports_scope(duckdb_v2_custom_option_handle option, + DUCKDB_V2_SETTING_SCOPE scope, bool supported, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets arbitrary user data on the custom option. + * + * Associates an opaque pointer with the option, retrievable from the update callback via + * `duckdb_v2_custom_option_update_get_user_data()`. The opaque handle bundles the pointer with an optional destructor, + * invoked when the data is no longer needed: once the custom option handle is destroyed and, if it was registered, the + * instance is too. + * + * history: + * - unstable: v2.0.0 + * + * @param option The option to set the user data of. + * @param data Opaque handle bundling the user data pointer plus an optional destructor. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_user_data(duckdb_v2_custom_option_handle option, + duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the id of the connection that wrote the entry, as `duckdb_logs` reports it. An entry written for the - * database as a whole has none: `present` then receives false and `id` is left untouched. + * Sets the optional update callback of the custom option. + * + * The callback is invoked whenever the option is set or reset, from SQL as from `duckdb_v2_config_set_option_value()`, + * after the new value is cast to the option's type and before it is stored. It may replace the value with + * `duckdb_v2_custom_option_update_set_value()`, or refuse it by reporting an error. It is not invoked for the default + * value at registration, nor for a value given to the instance at startup. The callback must not write options itself. * * history: * - unstable: v2.0.0 * - * @param info The write info handle of the entry. - * @param id Receives the connection id, if present. - * @param present Receives whether the entry has a connection id. + * @param option The option to set the update callback of. + * @param callback The update callback to set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_write_info_get_connection_id(duckdb_v2_log_sink_write_info_handle info, - idx_t *id, bool *present, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_set_update_callback( + duckdb_v2_custom_option_handle option, duckdb_v2_custom_option_update_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the id of the transaction the entry was written in, as `duckdb_logs` reports it. An entry written outside a - * transaction has none: `present` then receives false and `id` is left untouched. + * Retrieves the user data set via `duckdb_v2_custom_option_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param info The write info handle of the entry. - * @param id Receives the transaction id, if present. - * @param present Receives whether the entry has a transaction id. + * @param info The update info handle. + * @param data Receives the user data pointer, or null if none was set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_write_info_get_transaction_id(duckdb_v2_log_sink_write_info_handle info, - idx_t *id, bool *present, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_update_get_user_data( + duckdb_v2_custom_option_update_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the id of the query the entry was written for, as `duckdb_logs` reports it. An entry written outside a - * query has none: `present` then receives false and `id` is left untouched. + * Retrieves the value the option is updated to, already cast to the option's type. On a reset this is the default + * value, which may be NULL. The returned value is owned by the caller and must be destroyed via + * `duckdb_v2_value_destroy()`. * * history: * - unstable: v2.0.0 * - * @param info The write info handle of the entry. - * @param id Receives the query id, if present. - * @param present Receives whether the entry has a query id. + * @param info The update info handle. + * @param value Receives the new value. Owned by the caller; destroy via `duckdb_v2_value_destroy()`. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_write_info_get_query_id(duckdb_v2_log_sink_write_info_handle info, - idx_t *id, bool *present, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_update_get_value(duckdb_v2_custom_option_update_info_handle info, + duckdb_v2_value_handle *value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the id of the thread that wrote the entry, as `duckdb_logs` reports it. Only an entry written in the thread - * scope has one: otherwise `present` receives false and `id` is left untouched. The id identifies the thread that - * logged, which need not be the thread the write callback runs on. + * Replaces the value the option is updated to, e.g. to normalize it. The value is borrowed and copied, and cast to the + * option's type, which fails when the cast does. * * history: * - unstable: v2.0.0 * - * @param info The write info handle of the entry. - * @param id Receives the thread id, if present. - * @param present Receives whether the entry has a thread id. + * @param info The update info handle. + * @param value The value to store instead. Borrowed and copied. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_write_info_get_thread_id(duckdb_v2_log_sink_write_info_handle info, - idx_t *id, bool *present, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_update_set_value(duckdb_v2_custom_option_update_info_handle info, + duckdb_v2_value_handle value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the log sink on the instance, making it available to the logging configuration under its name. + * Retrieves the scope the value is written at: GLOBAL or SESSION, a DEFAULT write already resolved to the option's + * default scope. * - * Registering does not direct any entries to the sink by itself; the logging configuration does. Registration is not - * transactional, requires a name and a write callback, and fails when the name is taken: by a sink DuckDB provides - * itself, such as `memory`, `stdout` or `file`, or by a sink registered before. The log sink must have been created - * through a factory of the same instance. Its user data passes to the registered sink. The caller still owns the handle - * after registration and must destroy it with `duckdb_v2_log_sink_destroy()`, which does not affect the registered - * sink. + * history: + * - unstable: v2.0.0 + * + * @param info The update info handle. + * @param scope Receives the scope. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_update_get_scope(duckdb_v2_custom_option_update_info_handle info, + DUCKDB_V2_SETTING_SCOPE *scope, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves whether the update is a reset to the default value, like SQL `RESET`. * * history: * - unstable: v2.0.0 * - * @param instance The instance to register on. - * @param sink The log sink to register. + * @param info The update info handle. + * @param is_reset Receives whether the update is a reset. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_register_log_sink(duckdb_v2_instance_handle instance, - duckdb_v2_log_sink_handle sink, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_update_is_reset(duckdb_v2_custom_option_update_info_handle info, + bool *is_reset, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the log sink on the loading extension's instance, making it available to the logging configuration under - * its name. + * Registers the custom option on the connection's instance, visible to every connection. * - * Use this from the extension's load callback. Registration follows the rules of - * `duckdb_v2_instance_register_log_sink()`. + * Registration is not transactional: it takes effect at once, also inside an explicit transaction, and a rollback does + * not undo it. Registration requires a name and a type, or a default value to take the type from, and fails when an + * option of the same name already exists. A value given for the option at startup is picked up. The custom option must + * have been created through a factory of the same instance. The caller still owns the handle after registration and + * must destroy it with `duckdb_v2_custom_option_destroy()`, which does not affect the registered option. + * + * history: + * - unstable: v2.0.0 + * + * @param conn The connection to register on. + * @param option The custom option to register. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_register_custom_option(duckdb_v2_connection_handle conn, + duckdb_v2_custom_option_handle option, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Registers the custom option on the loading extension's instance, visible to every connection. + * + * Use this from the extension's load callback. Registration is not transactional, requires a name and a type, or a + * default value to take the type from, and fails when an option of the same name already exists. A value given for the + * option at startup is picked up. The custom option must have been created through a factory of the same instance. The + * caller still owns the handle after registration and must destroy it with `duckdb_v2_custom_option_destroy()`, which + * does not affect the registered option. * * history: * - unstable: v2.0.0 * * @param extension The loading extension. - * @param sink The log sink to register. + * @param option The custom option to register. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_log_sink(duckdb_v2_extension_handle extension, - duckdb_v2_log_sink_handle sink, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_custom_option(duckdb_v2_extension_handle extension, + duckdb_v2_custom_option_handle option, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys the log sink, releasing its resources. + * Destroys the custom option, releasing its resources. * * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent - * double-destruction. Destroying the handle after registration does not affect the registered sink. + * double-destruction. Destroying the handle after registration does not affect the registered option. * * history: * - unstable: v2.0.0 * - * @param sink The log sink to destroy. + * @param option The option to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_destroy(duckdb_v2_log_sink_handle *sink); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_custom_option_destroy(duckdb_v2_custom_option_handle *option); #endif -/* --- Struct definitions for log sink --- */ +/* --- Struct definitions for custom_option --- */ /* ============================================================================ - * MODULE: logical_type + * MODULE: expression * ============================================================================ */ -/* --- Enums for logical_type --- */ +/* --- Enums for expression --- */ /*! - * Logical type identifier. The values are the same integers DuckDB uses internally, so round-tripping is lossless. The - * bind- and UDF-only ids (UNKNOWN, ANY, TEMPLATE) appear here for completeness; they do not show up in result column - * types in practice. + * The type of a bound expression node. The values mirror the engine's own expression types, restricted to the node + * types a filter predicate can contain; every other node type is reported as `EXPRESSION_TYPE_INVALID`. + * + * Comparisons, `BETWEEN` and casts are regular scalar function calls once bound: they have the function's children and + * name, and only their type tells them apart from any other function. A `CAST` therefore has one child, the value being + * cast, and its target type is the node's return type. */ -typedef enum DUCKDB_V2_LOGICAL_TYPE_ID { - //! Invalid / unset. - DUCKDB_V2_LOGICAL_TYPE_ID_INVALID = 0, +typedef enum DUCKDB_V2_EXPRESSION_TYPE { + //! A node type this API does not model. Its children can still be walked. + DUCKDB_V2_EXPRESSION_TYPE_INVALID = 0, - //! NULL constant type. - DUCKDB_V2_LOGICAL_TYPE_ID_SQLNULL = 1, + /*! + * A cast. One child; the target type is the node's return type and `duckdb_v2_expression_cast_get_mode()` tells a + * `TRY_CAST` apart. + */ + DUCKDB_V2_EXPRESSION_TYPE_OPERATOR_CAST = 12, - //! Unknown — used for unresolved parameter expressions. - DUCKDB_V2_LOGICAL_TYPE_ID_UNKNOWN = 2, + //! Logical `NOT`. One child. + DUCKDB_V2_EXPRESSION_TYPE_OPERATOR_NOT = 13, - //! ANY — used for functions that accept any type. - DUCKDB_V2_LOGICAL_TYPE_ID_ANY = 3, + //! `IS NULL`. One child. + DUCKDB_V2_EXPRESSION_TYPE_OPERATOR_IS_NULL = 14, - //! A type carried as a value (type parameters). Values of this type are built via value_create_type. - DUCKDB_V2_LOGICAL_TYPE_ID_TYPE = 6, - DUCKDB_V2_LOGICAL_TYPE_ID_BOOLEAN = 10, - DUCKDB_V2_LOGICAL_TYPE_ID_TINYINT = 11, - DUCKDB_V2_LOGICAL_TYPE_ID_SMALLINT = 12, - DUCKDB_V2_LOGICAL_TYPE_ID_INTEGER = 13, - DUCKDB_V2_LOGICAL_TYPE_ID_BIGINT = 14, + //! `IS NOT NULL`. One child. + DUCKDB_V2_EXPRESSION_TYPE_OPERATOR_IS_NOT_NULL = 15, - //! 32-bit days since epoch. - DUCKDB_V2_LOGICAL_TYPE_ID_DATE = 15, + //! `=`. Two children. + DUCKDB_V2_EXPRESSION_TYPE_COMPARE_EQUAL = 25, - //! 64-bit microseconds since midnight. - DUCKDB_V2_LOGICAL_TYPE_ID_TIME = 16, + //! `<>`. Two children. + DUCKDB_V2_EXPRESSION_TYPE_COMPARE_NOTEQUAL = 26, - //! 64-bit seconds since epoch. - DUCKDB_V2_LOGICAL_TYPE_ID_TIMESTAMP_SEC = 17, + //! `<`. Two children. + DUCKDB_V2_EXPRESSION_TYPE_COMPARE_LESSTHAN = 27, - //! 64-bit milliseconds since epoch. - DUCKDB_V2_LOGICAL_TYPE_ID_TIMESTAMP_MS = 18, + //! `>`. Two children. + DUCKDB_V2_EXPRESSION_TYPE_COMPARE_GREATERTHAN = 28, - //! 64-bit microseconds since epoch. - DUCKDB_V2_LOGICAL_TYPE_ID_TIMESTAMP = 19, + //! `<=`. Two children. + DUCKDB_V2_EXPRESSION_TYPE_COMPARE_LESSTHANOREQUALTO = 29, - //! 64-bit nanoseconds since epoch. - DUCKDB_V2_LOGICAL_TYPE_ID_TIMESTAMP_NS = 20, + //! `>=`. Two children. + DUCKDB_V2_EXPRESSION_TYPE_COMPARE_GREATERTHANOREQUALTO = 30, - //! Decimal with width and scale parameters. - DUCKDB_V2_LOGICAL_TYPE_ID_DECIMAL = 21, - DUCKDB_V2_LOGICAL_TYPE_ID_FLOAT = 22, - DUCKDB_V2_LOGICAL_TYPE_ID_DOUBLE = 23, - DUCKDB_V2_LOGICAL_TYPE_ID_VARCHAR = 25, - DUCKDB_V2_LOGICAL_TYPE_ID_BLOB = 26, - DUCKDB_V2_LOGICAL_TYPE_ID_INTERVAL = 27, - DUCKDB_V2_LOGICAL_TYPE_ID_UTINYINT = 28, - DUCKDB_V2_LOGICAL_TYPE_ID_USMALLINT = 29, - DUCKDB_V2_LOGICAL_TYPE_ID_UINTEGER = 30, - DUCKDB_V2_LOGICAL_TYPE_ID_UBIGINT = 31, + //! `IN`. The first child is the value tested, the remaining children are the candidates. + DUCKDB_V2_EXPRESSION_TYPE_COMPARE_IN = 35, - //! 64-bit microseconds since epoch, timezone-aware. - DUCKDB_V2_LOGICAL_TYPE_ID_TIMESTAMP_TZ = 32, + //! `NOT IN`. The first child is the value tested, the remaining children are the candidates. + DUCKDB_V2_EXPRESSION_TYPE_COMPARE_NOT_IN = 36, - //! 64-bit nanoseconds since epoch, timezone-aware. - DUCKDB_V2_LOGICAL_TYPE_ID_TIMESTAMP_TZ_NS = 33, + //! `IS DISTINCT FROM`. Two children. + DUCKDB_V2_EXPRESSION_TYPE_COMPARE_DISTINCT_FROM = 37, - //! 64-bit microseconds since midnight + 32-bit offset. - DUCKDB_V2_LOGICAL_TYPE_ID_TIME_TZ = 34, + //! `BETWEEN`. Three children: the value tested, the lower bound and the upper bound. + DUCKDB_V2_EXPRESSION_TYPE_COMPARE_BETWEEN = 38, - //! 64-bit nanoseconds since midnight. - DUCKDB_V2_LOGICAL_TYPE_ID_TIME_NS = 35, - DUCKDB_V2_LOGICAL_TYPE_ID_BIT = 36, + //! `IS NOT DISTINCT FROM`. Two children. + DUCKDB_V2_EXPRESSION_TYPE_COMPARE_NOT_DISTINCT_FROM = 40, - //! Arbitrary-precision integer (VARINT-encoded). - DUCKDB_V2_LOGICAL_TYPE_ID_BIGNUM = 39, - DUCKDB_V2_LOGICAL_TYPE_ID_UHUGEINT = 49, - DUCKDB_V2_LOGICAL_TYPE_ID_HUGEINT = 50, - DUCKDB_V2_LOGICAL_TYPE_ID_UUID = 54, + //! Logical `AND`. Two or more children. + DUCKDB_V2_EXPRESSION_TYPE_CONJUNCTION_AND = 50, - //! Geometry (spatial extension). - DUCKDB_V2_LOGICAL_TYPE_ID_GEOMETRY = 60, + //! Logical `OR`. Two or more children. + DUCKDB_V2_EXPRESSION_TYPE_CONJUNCTION_OR = 51, - //! Geography (spatial extension); like GEOMETRY, but with spherical edges. - DUCKDB_V2_LOGICAL_TYPE_ID_GEOGRAPHY = 61, - DUCKDB_V2_LOGICAL_TYPE_ID_STRUCT = 100, - DUCKDB_V2_LOGICAL_TYPE_ID_LIST = 101, - DUCKDB_V2_LOGICAL_TYPE_ID_MAP = 102, - DUCKDB_V2_LOGICAL_TYPE_ID_ENUM = 104, - DUCKDB_V2_LOGICAL_TYPE_ID_UNION = 107, - DUCKDB_V2_LOGICAL_TYPE_ID_ARRAY = 108, - DUCKDB_V2_LOGICAL_TYPE_ID_VARIANT = 109, + //! A constant. No children; read it with `duckdb_v2_expression_constant_get_value()`. + DUCKDB_V2_EXPRESSION_TYPE_VALUE_CONSTANT = 75, - //! Unnamed struct; shares the physical representation of STRUCT. - DUCKDB_V2_LOGICAL_TYPE_ID_TUPLE = 110, - DUCKDB_V2_LOGICAL_TYPE_ID_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_LOGICAL_TYPE_ID; + //! A prepared statement parameter whose value is not known yet. No children. + DUCKDB_V2_EXPRESSION_TYPE_VALUE_PARAMETER = 76, -/* --- Struct forward declarations for logical_type --- */ + /*! + * A call to a scalar function other than the ones listed above. The children are its arguments; read the name with + * `duckdb_v2_expression_function_get_name()`. + */ + DUCKDB_V2_EXPRESSION_TYPE_BOUND_FUNCTION = 141, -/* --- Types for logical_type --- */ + //! A `CASE` expression. The children are each `WHEN` condition followed by its `THEN` result, then the `ELSE` + //! result. + DUCKDB_V2_EXPRESSION_TYPE_CASE_EXPR = 150, -/* --- Constants for logical_type --- */ + //! `COALESCE`. One or more children. + DUCKDB_V2_EXPRESSION_TYPE_OPERATOR_COALESCE = 152, -/* --- Function pointer typedefs for logical_type --- */ + //! A reference to a column. No children; read it with `duckdb_v2_expression_column_ref_get_index()`. + DUCKDB_V2_EXPRESSION_TYPE_BOUND_COLUMN_REF = 228, + DUCKDB_V2_EXPRESSION_TYPE_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_EXPRESSION_TYPE; -/* --- Functions for logical_type --- */ +/*! + * What checking a predicate against the statistics of its column found out (`FilterPropagateResult`): whether every row + * the statistics describe passes the predicate, none does, or the statistics do not tell. + */ +typedef enum DUCKDB_V2_FILTER_PROPAGATE_RESULT { + //! The statistics do not decide the predicate. + DUCKDB_V2_FILTER_PROPAGATE_RESULT_NO_PRUNING_POSSIBLE = 0, + + //! Every row passes the predicate. + DUCKDB_V2_FILTER_PROPAGATE_RESULT_ALWAYS_TRUE = 1, + + //! No row passes the predicate. + DUCKDB_V2_FILTER_PROPAGATE_RESULT_ALWAYS_FALSE = 2, + + //! Every row passes the predicate or evaluates it to NULL. + DUCKDB_V2_FILTER_PROPAGATE_RESULT_TRUE_OR_NULL = 3, + + //! No row passes the predicate: each evaluates it to false or to NULL. + DUCKDB_V2_FILTER_PROPAGATE_RESULT_FALSE_OR_NULL = 4, + DUCKDB_V2_FILTER_PROPAGATE_RESULT_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_FILTER_PROPAGATE_RESULT; + +/* --- Struct forward declarations for expression --- */ + +/* --- Types for expression --- */ + +/*! + * A borrowed opaque handle to a node of a bound expression tree. Read-only and owned by the engine: valid only for the + * duration of the callback that handed it out, and never destroyed by the caller. Child nodes borrowed via + * `duckdb_v2_expression_get_child()` share their parent's lifetime. + */ +typedef struct _duckdb_v2_expression { + void *internal_ptr; +} * duckdb_v2_expression_handle; + +/* --- Constants for expression --- */ + +/* --- Function pointer typedefs for expression --- */ + +/* --- Functions for expression --- */ #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a logical type from a type id plus value parameters. + * Returns the type of an expression node. * - * The id-keyed twin of factory_create_type_from_name: the type id names the kind, and the parameters bind it. With - * param_count 0 it instantiates a primitive directly, without touching the catalog: BOOLEAN, TINYINT..BIGINT, - * UTINYINT..UBIGINT, HUGEINT, UHUGEINT, FLOAT, DOUBLE, DATE, every TIME and TIMESTAMP variant, INTERVAL, VARCHAR, BLOB, - * BIT, BIGNUM, and UUID. ANY is accepted as well. + * The type decides which of the type-specific accessors apply, and what the node's children mean; see + * `EXPRESSION_TYPE`. A node of a type this API does not model reports `EXPRESSION_TYPE_INVALID`. * - * ANY is a function-signature wildcard, constructible here so it can be passed to the function parameter and varargs - * setters, as a fixed-arity ANY parameter or an ANY varargs type. Data-creating surfaces reject it: value and data - * chunk creation, scalar and aggregate return types, table function result columns, cast source and target types, and - * custom type registration. + * history: + * - unstable: v2.0.0 * - * With parameters, the id resolves to its canonical built-in type and binds through the same constructors as - * factory_create_type_from_name, so the parameterized kinds construct here too: decimal(width, scale); list(T); - * array(T, size); map(K, V); struct(fields); union(members); enum(entries); and varchar with a named "collation" - * parameter. Parameters are (name, value) pairs in two parallel arrays, exactly as for factory_create_type_from_name. + * @param expression The expression node. + * @param type Receives the node type. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_get_type(duckdb_v2_expression_handle expression, + DUCKDB_V2_EXPRESSION_TYPE *type, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Returns the logical type the expression node evaluates to. * - * Returns ERROR_INPUT_INVALID when param_count is 0 and the id needs parameters (DECIMAL, LIST, STRUCT, TUPLE, MAP, - * ARRAY, UNION, ENUM, VARIANT, GEOMETRY, GEOGRAPHY), for the bind-time-only ids (SQLNULL, UNKNOWN), for TYPE — - * construct that via factory_create_type_from_text — and for INVALID. + * For a cast this is the target type. The returned type is owned by the caller and must be destroyed via + * `duckdb_v2_logical_type_destroy()`. * * history: * - unstable: v2.0.0 * - * @param factory The factory to resolve the type in. - * @param type_id The type id to instantiate. - * @param param_names Optional. An array of param_count parameter names; an empty entry (NULL or zero length) is - * positional. Pass NULL for all-positional parameters. - * @param param_names_lengths Byte lengths of the entries in `param_names`; element i is the length of `param_names[i]`. - * May be NULL only when `param_names` is NULL. - * @param param_values An array of param_count parameter values. Borrowed (copied in). Pass NULL when param_count is 0. - * @param param_count The number of parameters. 0 instantiates a parameterless primitive. - * @param out_type Receives the new logical type handle. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param expression The expression node. + * @param type Receives the owned logical type. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_id( - duckdb_v2_factory_handle factory, DUCKDB_V2_LOGICAL_TYPE_ID type_id, const char *const *param_names, - const idx_t *param_names_lengths, const duckdb_v2_value_handle *param_values, idx_t param_count, - duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_get_return_type(duckdb_v2_expression_handle expression, + duckdb_v2_logical_type_handle *type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a logical type from a type name plus value parameters. + * Returns the number of child nodes of an expression node. * - * The generic constructor: resolves the name in the factory's catalog and binds it with the given parameters, exactly - * as SQL binds a type expression. Built-in parameterized kinds and registered extension types construct through this - * same call. + * Works for every node type, including `EXPRESSION_TYPE_INVALID`. Constants, parameters and column references have no + * children. * - * An unqualified name is resolved along the search path first and then in the system catalog, which is where the - * built-in kinds live. A qualified name is resolved exactly as written, with no system-catalog fallback, so it names - * the type in that catalog or schema or fails. + * history: + * - unstable: v2.0.0 * - * The width of a DECIMAL, also one nested in another type, is bounded by the max_decimal_width setting of the factory's - * connection, and by the default of that setting, 1000000, for an instance's factory, which has no settings: the time - * and memory a wide decimal takes grow with its width. A wider type returns ERROR_INPUT_INVALID; create it with the - * factory of a connection that raised the setting. factory_create_type_from_id and factory_create_type_from_text apply - * the same bound. - * - * Parameters are (name, value) pairs in two parallel arrays. param_names may be NULL to make every parameter - * positional, and an empty entry makes that one parameter positional. Child types cross as TYPE values, built with - * value_create_type. The built-in shapes are: decimal(width, scale); list(T); array(T, size); map(K, V); struct(fields, - * as named or all-positional TYPE values); union(members, as named TYPE values); enum(entries, as VARCHAR values); and - * varchar with a named "collation" VARCHAR parameter. - * - * A name that resolves to a type with no bind function takes no parameters, and passing any fails. Bind errors — - * unknown name, wrong parameter count or types — surface from the call. - * - * Resolves in the scope of the factory: a connection's or callback's factory reaches the catalog, an instance's factory - * knows only the built-in types. A connection's factory looks up catalog types in the connection's transaction, or in - * one of its own when none is open. Through an instance's factory, only an unqualified built-in name resolves. - * - * The returned logical type is caller-owned and must be destroyed via logical_type_destroy. A type resolved from the - * catalog shares database-owned storage, such as an ENUM dictionary, so destroy it before closing the database. This is - * the inverse of logical_type_get_param_count / logical_type_get_param. - * - * history: - * - unstable: v2.0.0 - * - * @param factory The factory to resolve the type in. - * @param name The type name to resolve. Parts are matched case-insensitively; qualify it to name a type in a particular - * catalog or schema. - * @param param_names Optional. An array of param_count parameter names; an empty entry (NULL or zero length) is - * positional. Pass NULL for all-positional parameters. - * @param param_names_lengths Byte lengths of the entries in `param_names`; element i is the length of `param_names[i]`. - * May be NULL only when `param_names` is NULL. - * @param param_values An array of param_count parameter values. Borrowed (copied in). Pass NULL when param_count is 0. - * @param param_count The number of parameters. - * @param out_type Receives the new logical type handle. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param expression The expression node. + * @param count Receives the number of children. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_name( - duckdb_v2_factory_handle factory, duckdb_v2_qname_handle name, const char *const *param_names, - const idx_t *param_names_lengths, const duckdb_v2_value_handle *param_values, idx_t param_count, - duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_get_child_count(duckdb_v2_expression_handle expression, idx_t *count, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a logical type by parsing SQL text. - * - * Parses a SQL type expression and returns the bound logical type. It accepts primitives ("INTEGER"), parameterized - * kinds ("DECIMAL(18,3)", "INTEGER[]", "STRUCT(a INTEGER, b VARCHAR)", "MAP(VARCHAR, INTEGER)", "INTEGER[3]", "UNION(i - * INTEGER, s VARCHAR)", "ENUM('a', 'b')"), and catalog-registered type names, both user-defined and from extensions. A - * catalog type name binds to its structural type, and the name is not preserved as an alias. Names are - * case-insensitive. Parse and bind errors surface from the call. - * - * Resolves in the scope of the factory: a connection's or callback's factory reaches the catalog, an instance's factory - * knows only the built-in types. A connection's factory looks up catalog types in the connection's transaction, or in - * one of its own when none is open. Text naming only built-in types never touches the catalog. + * Retrieves a child node of an expression node by index. * - * The returned logical type is caller-owned and must be destroyed via logical_type_destroy. A type resolved from the - * catalog shares database-owned storage, such as an ENUM dictionary, so destroy it before closing the database. This is - * the inverse of logical_type_to_text for every constructible kind. + * Fails if the index is out of bounds. Children are ordered as the node type describes (see `EXPRESSION_TYPE`). The + * child is borrowed and shares the lifetime of its parent. * * history: * - unstable: v2.0.0 * - * @param factory The factory to resolve the type in. - * @param text The SQL type expression to parse. - * @param text_length The length of `text` in bytes. `text` need not be null-terminated and may be NULL only when this - * is 0. - * @param out_type Receives the new logical type handle. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param expression The expression node. + * @param index The index of the child to retrieve. + * @param child Receives the borrowed child node. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_text(duckdb_v2_factory_handle factory, const char *text, - idx_t text_length, - duckdb_v2_logical_type_handle *out_type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_get_child(duckdb_v2_expression_handle expression, idx_t index, + duckdb_v2_expression_handle *child, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a copy of a logical type. + * Returns the value of a constant node. * - * On success, writes the new caller-owned handle into *out_type; destroy it via logical_type_destroy. + * Fails if the node is not of type `EXPRESSION_TYPE_VALUE_CONSTANT`. The returned value is owned by the caller and must + * be destroyed via `duckdb_v2_value_destroy()`. * * history: * - unstable: v2.0.0 * - * @param type The logical type to copy. - * @param out_type Receives the new logical type handle. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param expression The constant node. + * @param value Receives the owned constant value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_copy(duckdb_v2_logical_type_handle type, - duckdb_v2_logical_type_handle *out_type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_constant_get_value(duckdb_v2_expression_handle expression, + duckdb_v2_value_handle *value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys a logical type handle. + * Returns the column a column reference node points at. * - * Null-safe: passing nullptr or a slot already set to nullptr is a no-op. On success the slot is set to nullptr. + * Fails if the node is not of type `EXPRESSION_TYPE_BOUND_COLUMN_REF`. The index counts the columns of the operator the + * predicate is evaluated against, which is not necessarily the full set of columns that operator can produce: a + * callback resolves it through whatever handed it the expression, e.g. + * `duckdb_v2_table_function_filter_pushdown_get_column_index()` for a filter offered to a table function. * * history: * - unstable: v2.0.0 * - * @param type The logical type to destroy. + * @param expression The column reference node. + * @param index Receives the column index. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_destroy(duckdb_v2_logical_type_handle *type); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_column_ref_get_index(duckdb_v2_expression_handle expression, + idx_t *index, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Compares two logical types for deep equality. - * - * Two types are equal when they agree in kind and in every parameter, recursively. DECIMAL(10, 2) equals DECIMAL(10, - * 2), but not DECIMAL(10, 3) and not FLOAT; two STRUCTs are equal when they have the same field names in the same order - * and equal field types. - * - * history: - * - unstable: v2.0.0 + * Returns the name of the scalar function a function node calls. * - * @param left The first logical type. - * @param right The second logical type. - * @param result Receives the result of the comparison. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_is_equal(duckdb_v2_logical_type_handle left, - duckdb_v2_logical_type_handle right, bool *result, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Returns the logical type id. + * Applies to `EXPRESSION_TYPE_BOUND_FUNCTION` and to the node types that are function calls underneath: the + * comparisons, `EXPRESSION_TYPE_COMPARE_BETWEEN` and `EXPRESSION_TYPE_OPERATOR_CAST`. Fails for any other node type. + * For a comparison the name is its operator, e.g. `<`; for `BETWEEN` and casts it is an internal name, so dispatch on + * the type rather than the name for those. The name is borrowed and shares the lifetime of the node. * * history: * - unstable: v2.0.0 * - * @param type The logical type. - * @param out_id Receives the type id. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param expression The function node. + * @param name Receives a borrowed pointer to the function name. + * @param name_length Receives the length of `*name` in bytes. `*name` is not guaranteed to be null-terminated. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_get_id(duckdb_v2_logical_type_handle type, - DUCKDB_V2_LOGICAL_TYPE_ID *out_id, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_function_get_name(duckdb_v2_expression_handle expression, + const char **name, idx_t *name_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Borrows the logical type's name. + * Returns the qualified name of the scalar function a function node calls. * - * The alias when one is set — an extension or user-defined name such as "POINT_2D" — otherwise the canonical name of - * the type id, such as "INTEGER", "DECIMAL", or "TIMESTAMP WITH TIME ZONE". Never the empty view. This is exactly the - * name vocabulary create_type_from_name accepts. The view is valid until the logical type is destroyed; a canonical - * name points at static storage. + * Applies to the same node types as `duckdb_v2_expression_function_get_name()`, and fails for any other. The name is + * qualified with the catalog and schema the function was resolved in, where known. The returned name is owned by the + * caller and must be destroyed via `duckdb_v2_qname_destroy()`. * * history: * - unstable: v2.0.0 * - * @param type The logical type. - * @param out_name Receives a borrowed pointer to the name (alias when set, else the id's canonical name). - * @param out_name_length Receives the length of `*out_name` in bytes. `*out_name` is not guaranteed to be - * null-terminated. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param expression The function node. + * @param name Receives the owned qualified name. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_get_name(duckdb_v2_logical_type_handle type, const char **out_name, - idx_t *out_name_length, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_function_get_qname(duckdb_v2_expression_handle expression, + duckdb_v2_qname_handle *name, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Renders a logical type as SQL text. - * - * An aliased type renders as its alias, and create_type_from_text resolves that spelling only when the name is - * registered in the factory's catalog. The text round-trips through create_type_from_text for every constructible kind, - * with one exception: ANY renders as "ANY", but create_type_from_text cannot parse it back, since ANY is a signature - * wildcard rather than a parseable SQL type. - * - * Writes into a caller-supplied buffer, so nothing is allocated on the caller's behalf and nothing has to be freed. - * Pass out_text = NULL to size the buffer without rendering into it: out_length then receives the length, and - * out_capacity is ignored. With out_text != NULL, out_capacity must be at least out_length + 1, or the call returns - * ERROR_INPUT_OBJECT_SIZE with out_length set to the required length and out_text left untouched. + * Returns whether a cast node is a regular `CAST` or a `TRY_CAST`. * - * out_length never counts the terminator, but a successful write always appends one, so the buffer is usable as a C - * string. + * Fails if the node is not of type `EXPRESSION_TYPE_OPERATOR_CAST`. A `TRY_CAST` yields NULL for a value it cannot + * convert where a regular `CAST` would fail the query. * * history: * - unstable: v2.0.0 * - * @param type The logical type. - * @param out_text Caller-owned buffer receiving the text plus a null terminator, or NULL to only report the required - * length in out_length. - * @param out_capacity Bytes available in out_text, terminator included. Ignored when out_text is NULL. - * @param out_length Receives the text length excluding the null terminator — written on success and on - * ERROR_INPUT_OBJECT_SIZE. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param expression The cast node. + * @param mode Receives the cast mode. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_to_text(duckdb_v2_logical_type_handle type, char *out_text, - idx_t out_capacity, idx_t *out_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_cast_get_mode(duckdb_v2_expression_handle expression, + DUCKDB_V2_CAST_MODE *mode, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of value parameters of a logical type. - * - * The inspection dual of create_type_from_name: these are the parameters that reconstruct the type through it. Per - * kind: DECIMAL 2 (width, scale); LIST 1 (element type); ARRAY 2 (element type, size); MAP 2 (key type, value type); - * STRUCT and TUPLE one per field; UNION one per member; ENUM one per dictionary entry; VARCHAR 1 when a collation is - * set, else 0; GEOMETRY and GEOGRAPHY 1 when a coordinate system is set, else 0; everything else 0. A bound type - * reports only what it actually carries, so a bind-time modifier that is not retained — an ignored VARCHAR length, say - * — does not reappear. + * Checks a predicate over one column against the statistics of that column (`ExpressionFilter::CheckStatistics`): the + * statistics of the column are propagated through the expression - comparisons, conjunctions, IS NULL, IN, casts and + * the functions the engine knows the statistics of - to find out whether every row the statistics describe passes the + * predicate, none does, or nothing can be told. A table function uses it to skip a row group (or a file) whose + * statistics, built with `duckdb_v2_stats_create()`, make a pushed-down filter it did not take over false for every + * row. Every column reference of the predicate stands for the column described by `stats`. * * history: * - unstable: v2.0.0 * - * @param type The logical type. - * @param out_count Receives the number of parameters. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param context The context of the query; the statistics of function calls in the predicate are derived through it. + * @param expression The predicate: a boolean expression over one column, referenced by its column references. + * @param stats The statistics of that column over the rows in question. + * @param result Receives what the statistics decide about the predicate. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_get_param_count(duckdb_v2_logical_type_handle type, - idx_t *out_count, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_expression_check_statistics(duckdb_v2_context_handle context, + duckdb_v2_expression_handle expression, + duckdb_v2_stats_handle stats, + DUCKDB_V2_FILTER_PROPAGATE_RESULT *result, + duckdb_v2_error_info_handle *err); #endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Returns one value parameter of a logical type. - * - * out_name receives a borrowed view of the parameter name — a STRUCT field name, a UNION member name, "collation" — or - * an empty name for a positional parameter. A non-empty view is valid until the logical type is destroyed. out_value - * receives an owned value, destroyed via value_destroy: child types come back as TYPE values (unwrap them with - * value_get_type), DECIMAL width and scale as UINTEGER, ARRAY size as BIGINT, and ENUM dictionary entries and - * collations as VARCHAR. An out-of-range index returns ERROR_INPUT_INVALID. Each call allocates one owned value. - * - * history: - * - unstable: v2.0.0 - * - * @param type The logical type. - * @param index The parameter index, in [0, param_count). - * @param out_name Receives a borrowed pointer to the parameter name, or NULL with a zero length for a positional - * parameter. - * @param out_name_length Receives the length of `*out_name` in bytes. `*out_name` is not guaranteed to be - * null-terminated. - * @param out_value Receives the owned parameter value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_get_param(duckdb_v2_logical_type_handle type, idx_t index, - const char **out_name, idx_t *out_name_length, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); -#endif +/* --- Struct definitions for expression --- */ -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Creates a logical type that is an alias of another logical type. - * - * The alias keeps the base type's internal representation, so executing against it needs no special handling, while - * remaining logically distinct from the base type. Intended for custom type bind callbacks, where both the base type - * and the name come from the bind info. - * - * The alias is not registered anywhere, so this works through any factory. An empty alias name returns - * ERROR_INPUT_INVALID. - * - * history: - * - unstable: v2.0.0 - * - * @param factory The factory to resolve the type in. - * @param base_type The logical type to alias. Typically the base type supplied in the custom type bind info. - * @param alias_name The name for the resulting type. Typically the name of the custom type being constructed, also - * available from the bind info. - * @param alias_name_length The length of `alias_name` in bytes. `alias_name` must be valid UTF-8, need not be - * null-terminated, and may be NULL only when this is 0. - * @param out_type Receives the new type: the base type's internal representation under the given alias name. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_type_with_alias(duckdb_v2_factory_handle factory, - duckdb_v2_logical_type_handle base_type, - const char *alias_name, idx_t alias_name_length, - duckdb_v2_logical_type_handle *out_type, - duckdb_v2_error_info_handle *err); -#endif +/* ============================================================================ + * MODULE: log sink + * ============================================================================ */ -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Creates the common type of a set of logical types. - * - * The common type is the type every input implicitly casts to, resolved by the same rule a SQL list literal and - * value_create_list follow: INTEGER and BIGINT resolve to BIGINT, and DECIMAL(4,1) and DECIMAL(5,4) to DECIMAL(7,4). - * The types are combined pairwise from left to right, and the result is not guaranteed to be independent of their - * order. - * - * A connection's or a callback's factory also applies the casts that extensions registered, while an instance's factory - * knows only the built-in ones, so the two can resolve the same set differently. A single type resolves to a copy of - * itself. - * - * Returns ERROR_INPUT_INVALID for an empty set, for a NULL entry and for ANY, and ERROR_QUERY_NOT_IMPLEMENTED when the - * types have no common type. - * - * history: - * - unstable: v2.0.0 - * - * @param factory The factory to resolve the type in. - * @param types An array of type_count logical types. Borrowed. - * @param type_count The number of types. Must be at least 1. - * @param out_type Receives the new logical type handle. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_common_type(duckdb_v2_factory_handle factory, - const duckdb_v2_logical_type_handle *types, - idx_t type_count, - duckdb_v2_logical_type_handle *out_type, - duckdb_v2_error_info_handle *err); -#endif +/* --- Enums for log sink --- */ -/* --- Struct definitions for logical_type --- */ +//! The scope a log entry was written in, which decides which of its ids are present. +typedef enum DUCKDB_V2_LOG_SCOPE { + //! Written for the database as a whole, carrying no connection, transaction or query id. + DUCKDB_V2_LOG_SCOPE_DATABASE = 10, -/* ============================================================================ - * MODULE: macro - * ============================================================================ */ + //! Written by a connection, carrying its connection id and, inside one, the transaction and query ids. + DUCKDB_V2_LOG_SCOPE_CONNECTION = 20, -/* --- Enums for macro --- */ + //! Written by a thread executing a query, carrying the thread id next to the connection's ids. + DUCKDB_V2_LOG_SCOPE_THREAD = 30, + DUCKDB_V2_LOG_SCOPE_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_LOG_SCOPE; -//! The kind of a macro function, deciding how its body is read. Pass one to `duckdb_v2_macro_function_create()`. -typedef enum DUCKDB_V2_MACRO_FUNCTION_TYPE { - //! A scalar macro. The body is a single expression, and the macro is called like a scalar function. - DUCKDB_V2_MACRO_FUNCTION_TYPE_SCALAR = 0, +/* --- Struct forward declarations for log sink --- */ - //! A table macro. The body is a single SELECT query, and the macro is called like a table function. - DUCKDB_V2_MACRO_FUNCTION_TYPE_TABLE = 1, - DUCKDB_V2_MACRO_FUNCTION_TYPE_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_MACRO_FUNCTION_TYPE; +/* --- Types for log sink --- */ -/* --- Struct forward declarations for macro --- */ +/*! + * An owned opaque handle to a log sink being built. Created with `duckdb_v2_log_sink_create()`, configured with + * `duckdb_v2_log_sink_set_name()`, `duckdb_v2_log_sink_set_write_callback()` and the other setters, made available with + * `duckdb_v2_instance_register_log_sink()` or `duckdb_v2_extension_register_log_sink()`, and destroyed with + * `duckdb_v2_log_sink_destroy()`. + */ +typedef struct _duckdb_v2_log_sink { + void *internal_ptr; +} * duckdb_v2_log_sink_handle; -/* --- Types for macro --- */ +/*! + * A borrowed opaque handle to the context of a log entry, received by a log sink's write callback next to the entry + * itself, and valid only for the duration of that call. Read the ids `duckdb_logs` reports for the entry through its + * getters, e.g. `duckdb_v2_log_sink_write_info_get_connection_id()`. + */ +typedef struct _duckdb_v2_log_sink_write_info { + void *internal_ptr; +} * duckdb_v2_log_sink_write_info_handle; /*! - * An owned opaque handle to a macro function being built. Created with `duckdb_v2_macro_function_create()`, configured - * with `duckdb_v2_macro_function_set_name()`, `duckdb_v2_macro_function_set_body()` and the signature obtained via - * `duckdb_v2_macro_function_get_signature()`, made available with `duckdb_v2_extension_register_macro_function()`, and - * destroyed with `duckdb_v2_macro_function_destroy()`. + * A borrowed opaque handle received by a log sink's flush callback, and valid only for the duration of that call. It + * carries nothing yet. */ -typedef struct _duckdb_v2_macro_function { +typedef struct _duckdb_v2_log_sink_flush_info { void *internal_ptr; -} * duckdb_v2_macro_function_handle; +} * duckdb_v2_log_sink_flush_info_handle; -/* --- Constants for macro --- */ +/* --- Constants for log sink --- */ -/* --- Function pointer typedefs for macro --- */ +/* --- Function pointer typedefs for log sink --- */ -/* --- Functions for macro --- */ +typedef void (*duckdb_v2_log_sink_write_callback_fn)(duckdb_v2_log_sink_write_info_handle info, void *user_data, + int64_t timestamp, DUCKDB_V2_LOG_LEVEL level, + DUCKDB_V2_LOG_SCOPE scope, const char *type, idx_t type_length, + const char *message, idx_t message_length, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_log_sink_flush_callback_fn)(duckdb_v2_log_sink_flush_info_handle info, void *user_data, + duckdb_v2_error_info_handle *err); + +/* --- Functions for log sink --- */ #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a new macro function through a factory. + * Creates a new log sink through a factory. * - * The macro function starts out empty: configure it with the setter functions and the signature obtained via - * `duckdb_v2_macro_function_get_signature()`, then make it available with - * `duckdb_v2_extension_register_macro_function()`. The caller owns the returned handle and must destroy it with - * `duckdb_v2_macro_function_destroy()`, also after registration. + * The log sink starts out empty: configure it with the setter functions, then make it available with + * `duckdb_v2_instance_register_log_sink()` or `duckdb_v2_extension_register_log_sink()`. The caller owns the returned + * handle and must destroy it with `duckdb_v2_log_sink_destroy()`, also after registration. * - * The macro function can only be registered on the database the factory belongs to. + * The log sink can only be registered on the instance the factory belongs to. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create the macro function through. - * @param type Whether the macro is a scalar or a table macro. - * @param function On success, receives the newly created macro function. Owned by the caller. + * @param factory The factory to create the log sink through. + * @param sink On success, receives the newly created log sink. Owned by the caller. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_macro_function_create(duckdb_v2_factory_handle factory, - DUCKDB_V2_MACRO_FUNCTION_TYPE type, - duckdb_v2_macro_function_handle *function, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_create(duckdb_v2_factory_handle factory, + duckdb_v2_log_sink_handle *sink, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the name of the macro function, as SQL calls it. + * Sets the name the logging configuration refers to the log sink by. * - * The name is borrowed and copied. Calling this again replaces the previous name. A name must be set before - * registration. + * Names are matched case-insensitively. The name is borrowed and copied. Calling this again replaces the previous name. + * A name must be set before registration. * * history: * - unstable: v2.0.0 * - * @param function The macro function to set the name of. + * @param sink The log sink to set the name of. * @param name The name to set. Borrowed and copied. * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be * NULL only when this is 0. @@ -11233,379 +10758,1167 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_macro_function_create(duckdb_v2_factory_h * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_macro_function_set_name(duckdb_v2_macro_function_handle function, - const char *name, idx_t name_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_set_name(duckdb_v2_log_sink_handle sink, const char *name, + idx_t name_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the body of the macro function, as SQL text. + * Sets arbitrary user data on the log sink. * - * For a scalar macro the body is a single expression, for a table macro a single SELECT query. It refers to the - * parameters by name. The body is parsed at registration, which fails on a syntax error; names in it are resolved only - * when the macro is called, as with SQL `CREATE MACRO`. The body is borrowed and copied. Calling this again replaces - * the previous body. A body must be set before registration. + * Associates an opaque pointer with the sink, handed to its write and flush callbacks. The opaque handle bundles the + * pointer with an optional destructor, invoked when the data is no longer needed: when the instance is destroyed if the + * sink was registered, else when the log sink handle is. * * history: * - unstable: v2.0.0 * - * @param function The macro function to set the body of. - * @param body The SQL text of the body. Borrowed and copied. - * @param body_length The length of `body` in bytes. `body` need not be null-terminated and may be NULL only when this - * is 0. + * @param sink The log sink to set the user data of. + * @param data Opaque handle bundling the user data pointer plus an optional destructor. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_macro_function_set_body(duckdb_v2_macro_function_handle function, - const char *body, idx_t body_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_set_user_data(duckdb_v2_log_sink_handle sink, duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the macro function's signature so its parameters can be declared. + * Sets the write callback of the log sink, invoked for every entry the logging configuration directs to the sink. * - * Add parameters with `duckdb_v2_function_signature_add_parameter()`. A macro's parameters can always be passed by - * position or by name, so only `FUNCTION_PARAMETER_KIND_STANDARD` parameters are accepted; a macro has no variadic - * parameters. A parameter of type ANY is untyped, and a parameter with a default value can be omitted by a caller. A - * macro's result is decided by its body, so the signature cannot set a return type. Registration fails on a signature - * that does not follow these rules. The signature is modified in place. + * The callback must return quickly, must be safe to run concurrently and on any thread, and must not log or change the + * logging configuration. A write callback must be set before registration. * * history: * - unstable: v2.0.0 * - * @param function The macro function to get the signature of. - * @param sig The returned signature. Borrowed and valid for the lifetime of the macro function handle. + * @param sink The log sink to set the write callback of. + * @param callback The write callback to set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_macro_function_get_signature(duckdb_v2_macro_function_handle function, - duckdb_v2_function_signature_handle *sig, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_set_write_callback(duckdb_v2_log_sink_handle sink, + duckdb_v2_log_sink_write_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the documentation of the macro function so it can be filled in. + * Sets the optional flush callback of the log sink, invoked when DuckDB flushes its log, so entries the sink holds on + * to can be written out. When DuckDB flushes is up to DuckDB; entries still held when the instance is destroyed are for + * the user data's destructor to write out. * - * Set a description with `duckdb_v2_function_docs_set_description()`, and add examples and categories with - * `duckdb_v2_function_docs_add_example()` and `duckdb_v2_function_docs_add_category()`. The documentation is modified - * in place and registered with the macro function. Optional. + * Like the write callback, it must be safe to run on any thread, and must not log or change the logging configuration. * * history: * - unstable: v2.0.0 * - * @param function The macro function to get the documentation of. - * @param docs The returned documentation. Borrowed and valid for the lifetime of the macro function handle. + * @param sink The log sink to set the flush callback of. + * @param callback The flush callback to set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_macro_function_get_docs(duckdb_v2_macro_function_handle function, - duckdb_v2_function_docs_handle *docs, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_set_flush_callback(duckdb_v2_log_sink_handle sink, + duckdb_v2_log_sink_flush_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the macro function, making it available for use in SQL queries. - * - * The macro function is registered on the loading extension's database and attributed to the extension. Use this from - * the extension's load callback. Registration requires a name and a body that parses, and a signature that follows the - * rules of `duckdb_v2_macro_function_get_signature()`. It fails when a function of the same name already exists: a - * macro function has a single overload. The macro function must have been created through a factory of the same - * database. The caller still owns the handle after registration and must destroy it with - * `duckdb_v2_macro_function_destroy()`, which does not affect the registered macro function. + * Retrieves the id of the connection that wrote the entry, as `duckdb_logs` reports it. An entry written for the + * database as a whole has none: `present` then receives false and `id` is left untouched. * * history: * - unstable: v2.0.0 * - * @param extension The loading extension. - * @param function The macro function to register. + * @param info The write info handle of the entry. + * @param id Receives the connection id, if present. + * @param present Receives whether the entry has a connection id. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_macro_function(duckdb_v2_extension_handle extension, - duckdb_v2_macro_function_handle function, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Destroys the macro function, releasing its resources. - * - * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent - * double-destruction. Destroying the handle after registration does not affect the registered macro function. - * - * history: - * - unstable: v2.0.0 - * - * @param function The macro function to destroy. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_macro_function_destroy(duckdb_v2_macro_function_handle *function); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_write_info_get_connection_id(duckdb_v2_log_sink_write_info_handle info, + idx_t *id, bool *present, + duckdb_v2_error_info_handle *err); #endif -/* --- Struct definitions for macro --- */ - -/* ============================================================================ - * MODULE: pragma - * ============================================================================ */ - -/* --- Enums for pragma --- */ - -/* --- Struct forward declarations for pragma --- */ - -/* --- Types for pragma --- */ - -/*! - * An owned opaque handle to a custom pragma function being built. Created with `duckdb_v2_pragma_function_create()`, - * configured with the setter functions (e.g. `duckdb_v2_pragma_function_set_name()`, - * `duckdb_v2_pragma_function_set_query_callback()`, etc.) and the signature obtained via - * `duckdb_v2_pragma_function_get_signature()`, made available with `duckdb_v2_connection_register_pragma_function()` or - * `duckdb_v2_extension_register_pragma_function()`, and destroyed with `duckdb_v2_pragma_function_destroy()`. - */ -typedef struct _duckdb_v2_pragma_function { - void *internal_ptr; -} * duckdb_v2_pragma_function_handle; - -/*! - * A borrowed opaque handle to the result of a pragma function's "query" callback. The query callback receives this - * handle next to a `duckdb_v2_function_bind_info_handle`, which gives access to the arguments and the user data, and - * uses it to set the query to run in place of the `PRAGMA` statement. - */ -typedef struct _duckdb_v2_pragma_function_query_info { - void *internal_ptr; -} * duckdb_v2_pragma_function_query_info_handle; - -/* --- Constants for pragma --- */ - -/* --- Function pointer typedefs for pragma --- */ - -typedef void (*duckdb_v2_pragma_function_query_callback_fn)(duckdb_v2_function_bind_info_handle info, - duckdb_v2_pragma_function_query_info_handle result, - duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_pragma_function_exec_callback_fn)(duckdb_v2_function_bind_info_handle info, - duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); - -/* --- Functions for pragma --- */ - #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a new pragma function through a factory. - * - * The function starts out empty: configure it with the setter functions (e.g. `duckdb_v2_pragma_function_set_name()`, - * `duckdb_v2_pragma_function_set_query_callback()`, etc.) and the signature obtained via - * `duckdb_v2_pragma_function_get_signature()`, then make it available with - * `duckdb_v2_connection_register_pragma_function()` or `duckdb_v2_extension_register_pragma_function()`. The caller - * owns the returned handle and must destroy it with `duckdb_v2_pragma_function_destroy()`, also after registration. - * - * The pragma function can only be registered on the database the factory belongs to. + * Retrieves the id of the transaction the entry was written in, as `duckdb_logs` reports it. An entry written outside a + * transaction has none: `present` then receives false and `id` is left untouched. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create the pragma function through. - * @param function On success, receives the newly created pragma function. Owned by the caller. + * @param info The write info handle of the entry. + * @param id Receives the transaction id, if present. + * @param present Receives whether the entry has a transaction id. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_create(duckdb_v2_factory_handle factory, - duckdb_v2_pragma_function_handle *function, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_write_info_get_transaction_id(duckdb_v2_log_sink_write_info_handle info, + idx_t *id, bool *present, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the name of the pragma function, as the `PRAGMA` statement calls it. - * - * The name is borrowed and copied. Calling this again replaces the previous name. A name must be set before - * registration. + * Retrieves the id of the query the entry was written for, as `duckdb_logs` reports it. An entry written outside a + * query has none: `present` then receives false and `id` is left untouched. * * history: * - unstable: v2.0.0 * - * @param function The function to set the name of. - * @param name The name to set. Borrowed and copied. - * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be - * NULL only when this is 0. + * @param info The write info handle of the entry. + * @param id Receives the query id, if present. + * @param present Receives whether the entry has a query id. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_set_name(duckdb_v2_pragma_function_handle function, - const char *name, idx_t name_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_write_info_get_query_id(duckdb_v2_log_sink_write_info_handle info, + idx_t *id, bool *present, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the documentation of the function so it can be filled in. - * - * Set a description with `duckdb_v2_function_docs_set_description()`, and add examples and categories with - * `duckdb_v2_function_docs_add_example()` and `duckdb_v2_function_docs_add_category()`. The documentation is modified - * in place and registered with the function. Optional. + * Retrieves the id of the thread that wrote the entry, as `duckdb_logs` reports it. Only an entry written in the thread + * scope has one: otherwise `present` receives false and `id` is left untouched. The id identifies the thread that + * logged, which need not be the thread the write callback runs on. * * history: * - unstable: v2.0.0 * - * @param function The function to get the documentation of. - * @param docs The returned documentation. Borrowed and valid for the lifetime of the function handle. + * @param info The write info handle of the entry. + * @param id Receives the thread id, if present. + * @param present Receives whether the entry has a thread id. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_get_docs(duckdb_v2_pragma_function_handle function, - duckdb_v2_function_docs_handle *docs, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_write_info_get_thread_id(duckdb_v2_log_sink_write_info_handle info, + idx_t *id, bool *present, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the function's signature so it can be configured. + * Registers the log sink on the instance, making it available to the logging configuration under its name. * - * Add parameters with `duckdb_v2_function_signature_add_parameter()`. A pragma produces no value, so its signature - * cannot set a return type. A signature without parameters makes a pragma called as `PRAGMA name`. The signature is - * modified in place. + * Registering does not direct any entries to the sink by itself; the logging configuration does. Registration is not + * transactional, requires a name and a write callback, and fails when the name is taken: by a sink DuckDB provides + * itself, such as `memory`, `stdout` or `file`, or by a sink registered before. The log sink must have been created + * through a factory of the same instance. Its user data passes to the registered sink. The caller still owns the handle + * after registration and must destroy it with `duckdb_v2_log_sink_destroy()`, which does not affect the registered + * sink. * * history: * - unstable: v2.0.0 * - * @param function The function to get the signature of. - * @param sig The returned signature. Borrowed and valid for the lifetime of the function handle. + * @param instance The instance to register on. + * @param sink The log sink to register. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_get_signature(duckdb_v2_pragma_function_handle function, - duckdb_v2_function_signature_handle *sig, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_instance_register_log_sink(duckdb_v2_instance_handle instance, + duckdb_v2_log_sink_handle sink, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets arbitrary user data on the pragma function. + * Registers the log sink on the loading extension's instance, making it available to the logging configuration under + * its name. * - * Associates an opaque pointer with the function, retrievable from the callbacks via - * `duckdb_v2_function_bind_get_user_data()`. The opaque handle bundles the pointer with an optional destructor, invoked - * when the data is no longer needed. + * Use this from the extension's load callback. Registration follows the rules of + * `duckdb_v2_instance_register_log_sink()`. * * history: * - unstable: v2.0.0 * - * @param function The function to set the user data of. - * @param data Opaque handle bundling the user data pointer plus an optional destructor. + * @param extension The loading extension. + * @param sink The log sink to register. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_set_user_data(duckdb_v2_pragma_function_handle function, - duckdb_v2_opaque *data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_log_sink(duckdb_v2_extension_handle extension, + duckdb_v2_log_sink_handle sink, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the query callback of the pragma function, making it a query pragma. + * Destroys the log sink, releasing its resources. * - * The query callback is invoked before the `PRAGMA` statement is bound, and must set a SQL string through - * `duckdb_v2_pragma_function_query_set_query()`. The string is parsed and its statements run in place of the `PRAGMA` - * statement. A pragma function has either a query callback or an exec callback; registration fails when both or neither - * are set. + * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent + * double-destruction. Destroying the handle after registration does not affect the registered sink. * * history: * - unstable: v2.0.0 * - * @param function The function to set the query callback of. - * @param callback The query callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param sink The log sink to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_set_query_callback( - duckdb_v2_pragma_function_handle function, duckdb_v2_pragma_function_query_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_log_sink_destroy(duckdb_v2_log_sink_handle *sink); #endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Sets the exec callback of the pragma function, making it an exec pragma. - * - * The exec callback is invoked when the `PRAGMA` statement executes, and runs for its side effects: the statement - * produces no rows. A pragma function has either a query callback or an exec callback; registration fails when both or - * neither are set. - * - * history: - * - unstable: v2.0.0 - * - * @param function The function to set the exec callback of. - * @param callback The exec callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_set_exec_callback( - duckdb_v2_pragma_function_handle function, duckdb_v2_pragma_function_exec_callback_fn callback, - duckdb_v2_error_info_handle *err); -#endif +/* --- Struct definitions for log sink --- */ -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Sets the SQL to run in place of the `PRAGMA` statement. - * - * The query may hold several statements, separated by semicolons. It is borrowed and copied. Calling this again - * replaces the previous query. The query callback must set a query. - * - * history: - * - unstable: v2.0.0 - * - * @param info The query info handle. - * @param query The SQL to run. Borrowed and copied. - * @param query_length The length of `query` in bytes. `query` need not be null-terminated and may be NULL only when - * this is 0. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_query_set_query(duckdb_v2_pragma_function_query_info_handle info, - const char *query, idx_t query_length, - duckdb_v2_error_info_handle *err); -#endif +/* ============================================================================ + * MODULE: logical_type + * ============================================================================ */ -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Registers the pragma function, making it available to the `PRAGMA` statement. - * - * The function is registered on the connection's database, visible to every connection, in the connection's - * transaction: inside an explicit transaction, it is invisible to other connections until the transaction commits, and - * a rollback undoes it. Registration requires a name and exactly one of a query callback or an exec callback, and fails - * when a pragma of the same name already exists. The pragma function must have been created through a factory of the - * same database. The caller still owns the handle after registration and must destroy it with - * `duckdb_v2_pragma_function_destroy()`, which does not affect the registered function. - * - * history: - * - unstable: v2.0.0 - * - * @param conn The connection to register on. - * @param function The pragma function to register. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_register_pragma_function(duckdb_v2_connection_handle conn, - duckdb_v2_pragma_function_handle function, - duckdb_v2_error_info_handle *err); -#endif +/* --- Enums for logical_type --- */ -#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Logical type identifier. The values are the same integers DuckDB uses internally, so round-tripping is lossless. The + * bind- and UDF-only ids (UNKNOWN, ANY, TEMPLATE) appear here for completeness; they do not show up in result column + * types in practice. + */ +typedef enum DUCKDB_V2_LOGICAL_TYPE_ID { + //! Invalid / unset. + DUCKDB_V2_LOGICAL_TYPE_ID_INVALID = 0, + + //! NULL constant type. + DUCKDB_V2_LOGICAL_TYPE_ID_SQLNULL = 1, + + //! Unknown — used for unresolved parameter expressions. + DUCKDB_V2_LOGICAL_TYPE_ID_UNKNOWN = 2, + + //! ANY — used for functions that accept any type. + DUCKDB_V2_LOGICAL_TYPE_ID_ANY = 3, + + //! A type carried as a value (type parameters). Values of this type are built via value_create_type. + DUCKDB_V2_LOGICAL_TYPE_ID_TYPE = 6, + DUCKDB_V2_LOGICAL_TYPE_ID_BOOLEAN = 10, + DUCKDB_V2_LOGICAL_TYPE_ID_TINYINT = 11, + DUCKDB_V2_LOGICAL_TYPE_ID_SMALLINT = 12, + DUCKDB_V2_LOGICAL_TYPE_ID_INTEGER = 13, + DUCKDB_V2_LOGICAL_TYPE_ID_BIGINT = 14, + + //! 32-bit days since epoch. + DUCKDB_V2_LOGICAL_TYPE_ID_DATE = 15, + + //! 64-bit microseconds since midnight. + DUCKDB_V2_LOGICAL_TYPE_ID_TIME = 16, + + //! 64-bit seconds since epoch. + DUCKDB_V2_LOGICAL_TYPE_ID_TIMESTAMP_SEC = 17, + + //! 64-bit milliseconds since epoch. + DUCKDB_V2_LOGICAL_TYPE_ID_TIMESTAMP_MS = 18, + + //! 64-bit microseconds since epoch. + DUCKDB_V2_LOGICAL_TYPE_ID_TIMESTAMP = 19, + + //! 64-bit nanoseconds since epoch. + DUCKDB_V2_LOGICAL_TYPE_ID_TIMESTAMP_NS = 20, + + //! Decimal with width and scale parameters. + DUCKDB_V2_LOGICAL_TYPE_ID_DECIMAL = 21, + DUCKDB_V2_LOGICAL_TYPE_ID_FLOAT = 22, + DUCKDB_V2_LOGICAL_TYPE_ID_DOUBLE = 23, + DUCKDB_V2_LOGICAL_TYPE_ID_VARCHAR = 25, + DUCKDB_V2_LOGICAL_TYPE_ID_BLOB = 26, + DUCKDB_V2_LOGICAL_TYPE_ID_INTERVAL = 27, + DUCKDB_V2_LOGICAL_TYPE_ID_UTINYINT = 28, + DUCKDB_V2_LOGICAL_TYPE_ID_USMALLINT = 29, + DUCKDB_V2_LOGICAL_TYPE_ID_UINTEGER = 30, + DUCKDB_V2_LOGICAL_TYPE_ID_UBIGINT = 31, + + //! 64-bit microseconds since epoch, timezone-aware. + DUCKDB_V2_LOGICAL_TYPE_ID_TIMESTAMP_TZ = 32, + + //! 64-bit nanoseconds since epoch, timezone-aware. + DUCKDB_V2_LOGICAL_TYPE_ID_TIMESTAMP_TZ_NS = 33, + + //! 64-bit microseconds since midnight + 32-bit offset. + DUCKDB_V2_LOGICAL_TYPE_ID_TIME_TZ = 34, + + //! 64-bit nanoseconds since midnight. + DUCKDB_V2_LOGICAL_TYPE_ID_TIME_NS = 35, + DUCKDB_V2_LOGICAL_TYPE_ID_BIT = 36, + + //! Arbitrary-precision integer (VARINT-encoded). + DUCKDB_V2_LOGICAL_TYPE_ID_BIGNUM = 39, + DUCKDB_V2_LOGICAL_TYPE_ID_UHUGEINT = 49, + DUCKDB_V2_LOGICAL_TYPE_ID_HUGEINT = 50, + DUCKDB_V2_LOGICAL_TYPE_ID_UUID = 54, + + //! Geometry (spatial extension). + DUCKDB_V2_LOGICAL_TYPE_ID_GEOMETRY = 60, + + //! Geography (spatial extension); like GEOMETRY, but with spherical edges. + DUCKDB_V2_LOGICAL_TYPE_ID_GEOGRAPHY = 61, + DUCKDB_V2_LOGICAL_TYPE_ID_STRUCT = 100, + DUCKDB_V2_LOGICAL_TYPE_ID_LIST = 101, + DUCKDB_V2_LOGICAL_TYPE_ID_MAP = 102, + DUCKDB_V2_LOGICAL_TYPE_ID_ENUM = 104, + DUCKDB_V2_LOGICAL_TYPE_ID_UNION = 107, + DUCKDB_V2_LOGICAL_TYPE_ID_ARRAY = 108, + DUCKDB_V2_LOGICAL_TYPE_ID_VARIANT = 109, + + //! Unnamed struct; shares the physical representation of STRUCT. + DUCKDB_V2_LOGICAL_TYPE_ID_TUPLE = 110, + DUCKDB_V2_LOGICAL_TYPE_ID_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_LOGICAL_TYPE_ID; + +/* --- Struct forward declarations for logical_type --- */ + +/* --- Types for logical_type --- */ + +/* --- Constants for logical_type --- */ + +/* --- Function pointer typedefs for logical_type --- */ + +/* --- Functions for logical_type --- */ + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Creates a logical type from a type id plus value parameters. + * + * The id-keyed twin of factory_create_type_from_name: the type id names the kind, and the parameters bind it. With + * param_count 0 it instantiates a primitive directly, without touching the catalog: BOOLEAN, TINYINT..BIGINT, + * UTINYINT..UBIGINT, HUGEINT, UHUGEINT, FLOAT, DOUBLE, DATE, every TIME and TIMESTAMP variant, INTERVAL, VARCHAR, BLOB, + * BIT, BIGNUM, and UUID. ANY is accepted as well. + * + * ANY is a function-signature wildcard, constructible here so it can be passed to the function parameter and varargs + * setters, as a fixed-arity ANY parameter or an ANY varargs type. Data-creating surfaces reject it: value and data + * chunk creation, scalar and aggregate return types, table function result columns, cast source and target types, and + * custom type registration. + * + * With parameters, the id resolves to its canonical built-in type and binds through the same constructors as + * factory_create_type_from_name, so the parameterized kinds construct here too: decimal(width, scale); list(T); + * array(T, size); map(K, V); struct(fields); union(members); enum(entries); and varchar with a named "collation" + * parameter. Parameters are (name, value) pairs in two parallel arrays, exactly as for factory_create_type_from_name. + * + * Returns ERROR_INPUT_INVALID when param_count is 0 and the id needs parameters (DECIMAL, LIST, STRUCT, TUPLE, MAP, + * ARRAY, UNION, ENUM, VARIANT, GEOMETRY, GEOGRAPHY), for the bind-time-only ids (SQLNULL, UNKNOWN), for TYPE — + * construct that via factory_create_type_from_text — and for INVALID. + * + * history: + * - unstable: v2.0.0 + * + * @param factory The factory to resolve the type in. + * @param type_id The type id to instantiate. + * @param param_names Optional. An array of param_count parameter names; an empty entry (NULL or zero length) is + * positional. Pass NULL for all-positional parameters. + * @param param_names_lengths Byte lengths of the entries in `param_names`; element i is the length of `param_names[i]`. + * May be NULL only when `param_names` is NULL. + * @param param_values An array of param_count parameter values. Borrowed (copied in). Pass NULL when param_count is 0. + * @param param_count The number of parameters. 0 instantiates a parameterless primitive. + * @param out_type Receives the new logical type handle. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_id( + duckdb_v2_factory_handle factory, DUCKDB_V2_LOGICAL_TYPE_ID type_id, const char *const *param_names, + const idx_t *param_names_lengths, const duckdb_v2_value_handle *param_values, idx_t param_count, + duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Creates a logical type from a type name plus value parameters. + * + * The generic constructor: resolves the name in the factory's catalog and binds it with the given parameters, exactly + * as SQL binds a type expression. Built-in parameterized kinds and registered extension types construct through this + * same call. + * + * An unqualified name is resolved along the search path first and then in the system catalog, which is where the + * built-in kinds live. A qualified name is resolved exactly as written, with no system-catalog fallback, so it names + * the type in that catalog or schema or fails. + * + * The width of a DECIMAL, also one nested in another type, is bounded by the max_decimal_width setting of the factory's + * connection, and by the default of that setting, 1000000, for an instance's factory, which has no settings: the time + * and memory a wide decimal takes grow with its width. A wider type returns ERROR_INPUT_INVALID; create it with the + * factory of a connection that raised the setting. factory_create_type_from_id and factory_create_type_from_text apply + * the same bound. + * + * Parameters are (name, value) pairs in two parallel arrays. param_names may be NULL to make every parameter + * positional, and an empty entry makes that one parameter positional. Child types cross as TYPE values, built with + * value_create_type. The built-in shapes are: decimal(width, scale); list(T); array(T, size); map(K, V); struct(fields, + * as named or all-positional TYPE values); union(members, as named TYPE values); enum(entries, as VARCHAR values); and + * varchar with a named "collation" VARCHAR parameter. + * + * A name that resolves to a type with no bind function takes no parameters, and passing any fails. Bind errors — + * unknown name, wrong parameter count or types — surface from the call. + * + * Resolves in the scope of the factory: a connection's or callback's factory reaches the catalog, an instance's factory + * knows only the built-in types. A connection's factory looks up catalog types in the connection's transaction, or in + * one of its own when none is open. Through an instance's factory, only an unqualified built-in name resolves. + * + * The returned logical type is caller-owned and must be destroyed via logical_type_destroy. A type resolved from the + * catalog shares database-owned storage, such as an ENUM dictionary, so destroy it before closing the database. This is + * the inverse of logical_type_get_param_count / logical_type_get_param. + * + * history: + * - unstable: v2.0.0 + * + * @param factory The factory to resolve the type in. + * @param name The type name to resolve. Parts are matched case-insensitively; qualify it to name a type in a particular + * catalog or schema. + * @param param_names Optional. An array of param_count parameter names; an empty entry (NULL or zero length) is + * positional. Pass NULL for all-positional parameters. + * @param param_names_lengths Byte lengths of the entries in `param_names`; element i is the length of `param_names[i]`. + * May be NULL only when `param_names` is NULL. + * @param param_values An array of param_count parameter values. Borrowed (copied in). Pass NULL when param_count is 0. + * @param param_count The number of parameters. + * @param out_type Receives the new logical type handle. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_name( + duckdb_v2_factory_handle factory, duckdb_v2_qname_handle name, const char *const *param_names, + const idx_t *param_names_lengths, const duckdb_v2_value_handle *param_values, idx_t param_count, + duckdb_v2_logical_type_handle *out_type, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Creates a logical type by parsing SQL text. + * + * Parses a SQL type expression and returns the bound logical type. It accepts primitives ("INTEGER"), parameterized + * kinds ("DECIMAL(18,3)", "INTEGER[]", "STRUCT(a INTEGER, b VARCHAR)", "MAP(VARCHAR, INTEGER)", "INTEGER[3]", "UNION(i + * INTEGER, s VARCHAR)", "ENUM('a', 'b')"), and catalog-registered type names, both user-defined and from extensions. A + * catalog type name binds to its structural type, and the name is not preserved as an alias. Names are + * case-insensitive. Parse and bind errors surface from the call. + * + * Resolves in the scope of the factory: a connection's or callback's factory reaches the catalog, an instance's factory + * knows only the built-in types. A connection's factory looks up catalog types in the connection's transaction, or in + * one of its own when none is open. Text naming only built-in types never touches the catalog. + * + * The returned logical type is caller-owned and must be destroyed via logical_type_destroy. A type resolved from the + * catalog shares database-owned storage, such as an ENUM dictionary, so destroy it before closing the database. This is + * the inverse of logical_type_to_text for every constructible kind. + * + * history: + * - unstable: v2.0.0 + * + * @param factory The factory to resolve the type in. + * @param text The SQL type expression to parse. + * @param text_length The length of `text` in bytes. `text` need not be null-terminated and may be NULL only when this + * is 0. + * @param out_type Receives the new logical type handle. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_type_from_text(duckdb_v2_factory_handle factory, const char *text, + idx_t text_length, + duckdb_v2_logical_type_handle *out_type, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Creates a copy of a logical type. + * + * On success, writes the new caller-owned handle into *out_type; destroy it via logical_type_destroy. + * + * history: + * - unstable: v2.0.0 + * + * @param type The logical type to copy. + * @param out_type Receives the new logical type handle. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_copy(duckdb_v2_logical_type_handle type, + duckdb_v2_logical_type_handle *out_type, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Destroys a logical type handle. + * + * Null-safe: passing nullptr or a slot already set to nullptr is a no-op. On success the slot is set to nullptr. + * + * history: + * - unstable: v2.0.0 + * + * @param type The logical type to destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_destroy(duckdb_v2_logical_type_handle *type); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Compares two logical types for deep equality. + * + * Two types are equal when they agree in kind and in every parameter, recursively. DECIMAL(10, 2) equals DECIMAL(10, + * 2), but not DECIMAL(10, 3) and not FLOAT; two STRUCTs are equal when they have the same field names in the same order + * and equal field types. + * + * history: + * - unstable: v2.0.0 + * + * @param left The first logical type. + * @param right The second logical type. + * @param result Receives the result of the comparison. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_is_equal(duckdb_v2_logical_type_handle left, + duckdb_v2_logical_type_handle right, bool *result, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Returns the logical type id. + * + * history: + * - unstable: v2.0.0 + * + * @param type The logical type. + * @param out_id Receives the type id. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_get_id(duckdb_v2_logical_type_handle type, + DUCKDB_V2_LOGICAL_TYPE_ID *out_id, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Borrows the logical type's name. + * + * The alias when one is set — an extension or user-defined name such as "POINT_2D" — otherwise the canonical name of + * the type id, such as "INTEGER", "DECIMAL", or "TIMESTAMP WITH TIME ZONE". Never the empty view. This is exactly the + * name vocabulary create_type_from_name accepts. The view is valid until the logical type is destroyed; a canonical + * name points at static storage. + * + * history: + * - unstable: v2.0.0 + * + * @param type The logical type. + * @param out_name Receives a borrowed pointer to the name (alias when set, else the id's canonical name). + * @param out_name_length Receives the length of `*out_name` in bytes. `*out_name` is not guaranteed to be + * null-terminated. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_get_name(duckdb_v2_logical_type_handle type, const char **out_name, + idx_t *out_name_length, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Renders a logical type as SQL text. + * + * An aliased type renders as its alias, and create_type_from_text resolves that spelling only when the name is + * registered in the factory's catalog. The text round-trips through create_type_from_text for every constructible kind, + * with one exception: ANY renders as "ANY", but create_type_from_text cannot parse it back, since ANY is a signature + * wildcard rather than a parseable SQL type. + * + * Writes into a caller-supplied buffer, so nothing is allocated on the caller's behalf and nothing has to be freed. + * Pass out_text = NULL to size the buffer without rendering into it: out_length then receives the length, and + * out_capacity is ignored. With out_text != NULL, out_capacity must be at least out_length + 1, or the call returns + * ERROR_INPUT_OBJECT_SIZE with out_length set to the required length and out_text left untouched. + * + * out_length never counts the terminator, but a successful write always appends one, so the buffer is usable as a C + * string. + * + * history: + * - unstable: v2.0.0 + * + * @param type The logical type. + * @param out_text Caller-owned buffer receiving the text plus a null terminator, or NULL to only report the required + * length in out_length. + * @param out_capacity Bytes available in out_text, terminator included. Ignored when out_text is NULL. + * @param out_length Receives the text length excluding the null terminator — written on success and on + * ERROR_INPUT_OBJECT_SIZE. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_to_text(duckdb_v2_logical_type_handle type, char *out_text, + idx_t out_capacity, idx_t *out_length, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Returns the number of value parameters of a logical type. + * + * The inspection dual of create_type_from_name: these are the parameters that reconstruct the type through it. Per + * kind: DECIMAL 2 (width, scale); LIST 1 (element type); ARRAY 2 (element type, size); MAP 2 (key type, value type); + * STRUCT and TUPLE one per field; UNION one per member; ENUM one per dictionary entry; VARCHAR 1 when a collation is + * set, else 0; GEOMETRY and GEOGRAPHY 1 when a coordinate system is set, else 0; everything else 0. A bound type + * reports only what it actually carries, so a bind-time modifier that is not retained — an ignored VARCHAR length, say + * — does not reappear. + * + * history: + * - unstable: v2.0.0 + * + * @param type The logical type. + * @param out_count Receives the number of parameters. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_get_param_count(duckdb_v2_logical_type_handle type, + idx_t *out_count, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Returns one value parameter of a logical type. + * + * out_name receives a borrowed view of the parameter name — a STRUCT field name, a UNION member name, "collation" — or + * an empty name for a positional parameter. A non-empty view is valid until the logical type is destroyed. out_value + * receives an owned value, destroyed via value_destroy: child types come back as TYPE values (unwrap them with + * value_get_type), DECIMAL width and scale as UINTEGER, ARRAY size as BIGINT, and ENUM dictionary entries and + * collations as VARCHAR. An out-of-range index returns ERROR_INPUT_INVALID. Each call allocates one owned value. + * + * history: + * - unstable: v2.0.0 + * + * @param type The logical type. + * @param index The parameter index, in [0, param_count). + * @param out_name Receives a borrowed pointer to the parameter name, or NULL with a zero length for a positional + * parameter. + * @param out_name_length Receives the length of `*out_name` in bytes. `*out_name` is not guaranteed to be + * null-terminated. + * @param out_value Receives the owned parameter value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_logical_type_get_param(duckdb_v2_logical_type_handle type, idx_t index, + const char **out_name, idx_t *out_name_length, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Creates a logical type that is an alias of another logical type. + * + * The alias keeps the base type's internal representation, so executing against it needs no special handling, while + * remaining logically distinct from the base type. Intended for custom type bind callbacks, where both the base type + * and the name come from the bind info. + * + * The alias is not registered anywhere, so this works through any factory. An empty alias name returns + * ERROR_INPUT_INVALID. + * + * history: + * - unstable: v2.0.0 + * + * @param factory The factory to resolve the type in. + * @param base_type The logical type to alias. Typically the base type supplied in the custom type bind info. + * @param alias_name The name for the resulting type. Typically the name of the custom type being constructed, also + * available from the bind info. + * @param alias_name_length The length of `alias_name` in bytes. `alias_name` must be valid UTF-8, need not be + * null-terminated, and may be NULL only when this is 0. + * @param out_type Receives the new type: the base type's internal representation under the given alias name. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_type_with_alias(duckdb_v2_factory_handle factory, + duckdb_v2_logical_type_handle base_type, + const char *alias_name, idx_t alias_name_length, + duckdb_v2_logical_type_handle *out_type, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Creates the common type of a set of logical types. + * + * The common type is the type every input implicitly casts to, resolved by the same rule a SQL list literal and + * value_create_list follow: INTEGER and BIGINT resolve to BIGINT, and DECIMAL(4,1) and DECIMAL(5,4) to DECIMAL(7,4). + * The types are combined pairwise from left to right, and the result is not guaranteed to be independent of their + * order. + * + * A connection's or a callback's factory also applies the casts that extensions registered, while an instance's factory + * knows only the built-in ones, so the two can resolve the same set differently. A single type resolves to a copy of + * itself. + * + * Returns ERROR_INPUT_INVALID for an empty set, for a NULL entry and for ANY, and ERROR_QUERY_NOT_IMPLEMENTED when the + * types have no common type. + * + * history: + * - unstable: v2.0.0 + * + * @param factory The factory to resolve the type in. + * @param types An array of type_count logical types. Borrowed. + * @param type_count The number of types. Must be at least 1. + * @param out_type Receives the new logical type handle. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_factory_create_common_type(duckdb_v2_factory_handle factory, + const duckdb_v2_logical_type_handle *types, + idx_t type_count, + duckdb_v2_logical_type_handle *out_type, + duckdb_v2_error_info_handle *err); +#endif + +/* --- Struct definitions for logical_type --- */ + +/* ============================================================================ + * MODULE: macro + * ============================================================================ */ + +/* --- Enums for macro --- */ + +//! The kind of a macro function, deciding how its body is read. Pass one to `duckdb_v2_macro_function_create()`. +typedef enum DUCKDB_V2_MACRO_FUNCTION_TYPE { + //! A scalar macro. The body is a single expression, and the macro is called like a scalar function. + DUCKDB_V2_MACRO_FUNCTION_TYPE_SCALAR = 0, + + //! A table macro. The body is a single SELECT query, and the macro is called like a table function. + DUCKDB_V2_MACRO_FUNCTION_TYPE_TABLE = 1, + DUCKDB_V2_MACRO_FUNCTION_TYPE_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_MACRO_FUNCTION_TYPE; + +/* --- Struct forward declarations for macro --- */ + +/* --- Types for macro --- */ + +/*! + * An owned opaque handle to a macro function being built. Created with `duckdb_v2_macro_function_create()`, configured + * with `duckdb_v2_macro_function_set_name()`, `duckdb_v2_macro_function_set_body()` and the signature obtained via + * `duckdb_v2_macro_function_get_signature()`, made available with `duckdb_v2_extension_register_macro_function()`, and + * destroyed with `duckdb_v2_macro_function_destroy()`. + */ +typedef struct _duckdb_v2_macro_function { + void *internal_ptr; +} * duckdb_v2_macro_function_handle; + +/* --- Constants for macro --- */ + +/* --- Function pointer typedefs for macro --- */ + +/* --- Functions for macro --- */ + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Creates a new macro function through a factory. + * + * The macro function starts out empty: configure it with the setter functions and the signature obtained via + * `duckdb_v2_macro_function_get_signature()`, then make it available with + * `duckdb_v2_extension_register_macro_function()`. The caller owns the returned handle and must destroy it with + * `duckdb_v2_macro_function_destroy()`, also after registration. + * + * The macro function can only be registered on the database the factory belongs to. + * + * history: + * - unstable: v2.0.0 + * + * @param factory The factory to create the macro function through. + * @param type Whether the macro is a scalar or a table macro. + * @param function On success, receives the newly created macro function. Owned by the caller. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_macro_function_create(duckdb_v2_factory_handle factory, + DUCKDB_V2_MACRO_FUNCTION_TYPE type, + duckdb_v2_macro_function_handle *function, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the name of the macro function, as SQL calls it. + * + * The name is borrowed and copied. Calling this again replaces the previous name. A name must be set before + * registration. + * + * history: + * - unstable: v2.0.0 + * + * @param function The macro function to set the name of. + * @param name The name to set. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_macro_function_set_name(duckdb_v2_macro_function_handle function, + const char *name, idx_t name_length, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the body of the macro function, as SQL text. + * + * For a scalar macro the body is a single expression, for a table macro a single SELECT query. It refers to the + * parameters by name. The body is parsed at registration, which fails on a syntax error; names in it are resolved only + * when the macro is called, as with SQL `CREATE MACRO`. The body is borrowed and copied. Calling this again replaces + * the previous body. A body must be set before registration. + * + * history: + * - unstable: v2.0.0 + * + * @param function The macro function to set the body of. + * @param body The SQL text of the body. Borrowed and copied. + * @param body_length The length of `body` in bytes. `body` need not be null-terminated and may be NULL only when this + * is 0. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_macro_function_set_body(duckdb_v2_macro_function_handle function, + const char *body, idx_t body_length, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Returns the macro function's signature so its parameters can be declared. + * + * Add parameters with `duckdb_v2_function_signature_add_parameter()`. A macro's parameters can always be passed by + * position or by name, so only `FUNCTION_PARAMETER_KIND_STANDARD` parameters are accepted; a macro has no variadic + * parameters. A parameter of type ANY is untyped, and a parameter with a default value can be omitted by a caller. A + * macro's result is decided by its body, so the signature cannot set a return type. Registration fails on a signature + * that does not follow these rules. The signature is modified in place. + * + * history: + * - unstable: v2.0.0 + * + * @param function The macro function to get the signature of. + * @param sig The returned signature. Borrowed and valid for the lifetime of the macro function handle. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_macro_function_get_signature(duckdb_v2_macro_function_handle function, + duckdb_v2_function_signature_handle *sig, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Returns the documentation of the macro function so it can be filled in. + * + * Set a description with `duckdb_v2_function_docs_set_description()`, and add examples and categories with + * `duckdb_v2_function_docs_add_example()` and `duckdb_v2_function_docs_add_category()`. The documentation is modified + * in place and registered with the macro function. Optional. + * + * history: + * - unstable: v2.0.0 + * + * @param function The macro function to get the documentation of. + * @param docs The returned documentation. Borrowed and valid for the lifetime of the macro function handle. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_macro_function_get_docs(duckdb_v2_macro_function_handle function, + duckdb_v2_function_docs_handle *docs, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Registers the macro function, making it available for use in SQL queries. + * + * The macro function is registered on the loading extension's database and attributed to the extension. Use this from + * the extension's load callback. Registration requires a name and a body that parses, and a signature that follows the + * rules of `duckdb_v2_macro_function_get_signature()`. It fails when a function of the same name already exists: a + * macro function has a single overload. The macro function must have been created through a factory of the same + * database. The caller still owns the handle after registration and must destroy it with + * `duckdb_v2_macro_function_destroy()`, which does not affect the registered macro function. + * + * history: + * - unstable: v2.0.0 + * + * @param extension The loading extension. + * @param function The macro function to register. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_macro_function(duckdb_v2_extension_handle extension, + duckdb_v2_macro_function_handle function, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Destroys the macro function, releasing its resources. + * + * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent + * double-destruction. Destroying the handle after registration does not affect the registered macro function. + * + * history: + * - unstable: v2.0.0 + * + * @param function The macro function to destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_macro_function_destroy(duckdb_v2_macro_function_handle *function); +#endif + +/* --- Struct definitions for macro --- */ + +/* ============================================================================ + * MODULE: pragma + * ============================================================================ */ + +/* --- Enums for pragma --- */ + +/* --- Struct forward declarations for pragma --- */ + +/* --- Types for pragma --- */ + +/*! + * An owned opaque handle to a custom pragma function being built. Created with `duckdb_v2_pragma_function_create()`, + * configured with the setter functions (e.g. `duckdb_v2_pragma_function_set_name()`, + * `duckdb_v2_pragma_function_set_query_callback()`, etc.) and the signature obtained via + * `duckdb_v2_pragma_function_get_signature()`, made available with `duckdb_v2_connection_register_pragma_function()` or + * `duckdb_v2_extension_register_pragma_function()`, and destroyed with `duckdb_v2_pragma_function_destroy()`. + */ +typedef struct _duckdb_v2_pragma_function { + void *internal_ptr; +} * duckdb_v2_pragma_function_handle; + +/*! + * A borrowed opaque handle to the result of a pragma function's "query" callback. The query callback receives this + * handle next to a `duckdb_v2_function_bind_info_handle`, which gives access to the arguments and the user data, and + * uses it to set the query to run in place of the `PRAGMA` statement. + */ +typedef struct _duckdb_v2_pragma_function_query_info { + void *internal_ptr; +} * duckdb_v2_pragma_function_query_info_handle; + +/* --- Constants for pragma --- */ + +/* --- Function pointer typedefs for pragma --- */ + +typedef void (*duckdb_v2_pragma_function_query_callback_fn)(duckdb_v2_function_bind_info_handle info, + duckdb_v2_pragma_function_query_info_handle result, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_pragma_function_exec_callback_fn)(duckdb_v2_function_bind_info_handle info, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +/* --- Functions for pragma --- */ + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Creates a new pragma function through a factory. + * + * The function starts out empty: configure it with the setter functions (e.g. `duckdb_v2_pragma_function_set_name()`, + * `duckdb_v2_pragma_function_set_query_callback()`, etc.) and the signature obtained via + * `duckdb_v2_pragma_function_get_signature()`, then make it available with + * `duckdb_v2_connection_register_pragma_function()` or `duckdb_v2_extension_register_pragma_function()`. The caller + * owns the returned handle and must destroy it with `duckdb_v2_pragma_function_destroy()`, also after registration. + * + * The pragma function can only be registered on the database the factory belongs to. + * + * history: + * - unstable: v2.0.0 + * + * @param factory The factory to create the pragma function through. + * @param function On success, receives the newly created pragma function. Owned by the caller. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_create(duckdb_v2_factory_handle factory, + duckdb_v2_pragma_function_handle *function, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the name of the pragma function, as the `PRAGMA` statement calls it. + * + * The name is borrowed and copied. Calling this again replaces the previous name. A name must be set before + * registration. + * + * history: + * - unstable: v2.0.0 + * + * @param function The function to set the name of. + * @param name The name to set. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_set_name(duckdb_v2_pragma_function_handle function, + const char *name, idx_t name_length, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Returns the documentation of the function so it can be filled in. + * + * Set a description with `duckdb_v2_function_docs_set_description()`, and add examples and categories with + * `duckdb_v2_function_docs_add_example()` and `duckdb_v2_function_docs_add_category()`. The documentation is modified + * in place and registered with the function. Optional. + * + * history: + * - unstable: v2.0.0 + * + * @param function The function to get the documentation of. + * @param docs The returned documentation. Borrowed and valid for the lifetime of the function handle. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_get_docs(duckdb_v2_pragma_function_handle function, + duckdb_v2_function_docs_handle *docs, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Returns the function's signature so it can be configured. + * + * Add parameters with `duckdb_v2_function_signature_add_parameter()`. A pragma produces no value, so its signature + * cannot set a return type. A signature without parameters makes a pragma called as `PRAGMA name`. The signature is + * modified in place. + * + * history: + * - unstable: v2.0.0 + * + * @param function The function to get the signature of. + * @param sig The returned signature. Borrowed and valid for the lifetime of the function handle. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_get_signature(duckdb_v2_pragma_function_handle function, + duckdb_v2_function_signature_handle *sig, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets arbitrary user data on the pragma function. + * + * Associates an opaque pointer with the function, retrievable from the callbacks via + * `duckdb_v2_function_bind_get_user_data()`. The opaque handle bundles the pointer with an optional destructor, invoked + * when the data is no longer needed. + * + * history: + * - unstable: v2.0.0 + * + * @param function The function to set the user data of. + * @param data Opaque handle bundling the user data pointer plus an optional destructor. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_set_user_data(duckdb_v2_pragma_function_handle function, + duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the query callback of the pragma function, making it a query pragma. + * + * The query callback is invoked before the `PRAGMA` statement is bound, and must set a SQL string through + * `duckdb_v2_pragma_function_query_set_query()`. The string is parsed and its statements run in place of the `PRAGMA` + * statement. A pragma function has either a query callback or an exec callback; registration fails when both or neither + * are set. + * + * history: + * - unstable: v2.0.0 + * + * @param function The function to set the query callback of. + * @param callback The query callback to set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_set_query_callback( + duckdb_v2_pragma_function_handle function, duckdb_v2_pragma_function_query_callback_fn callback, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the exec callback of the pragma function, making it an exec pragma. + * + * The exec callback is invoked when the `PRAGMA` statement executes, and runs for its side effects: the statement + * produces no rows. A pragma function has either a query callback or an exec callback; registration fails when both or + * neither are set. + * + * history: + * - unstable: v2.0.0 + * + * @param function The function to set the exec callback of. + * @param callback The exec callback to set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_set_exec_callback( + duckdb_v2_pragma_function_handle function, duckdb_v2_pragma_function_exec_callback_fn callback, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Sets the SQL to run in place of the `PRAGMA` statement. + * + * The query may hold several statements, separated by semicolons. It is borrowed and copied. Calling this again + * replaces the previous query. The query callback must set a query. + * + * history: + * - unstable: v2.0.0 + * + * @param info The query info handle. + * @param query The SQL to run. Borrowed and copied. + * @param query_length The length of `query` in bytes. `query` need not be null-terminated and may be NULL only when + * this is 0. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_pragma_function_query_set_query(duckdb_v2_pragma_function_query_info_handle info, + const char *query, idx_t query_length, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Registers the pragma function, making it available to the `PRAGMA` statement. + * + * The function is registered on the connection's database, visible to every connection, in the connection's + * transaction: inside an explicit transaction, it is invisible to other connections until the transaction commits, and + * a rollback undoes it. Registration requires a name and exactly one of a query callback or an exec callback, and fails + * when a pragma of the same name already exists. The pragma function must have been created through a factory of the + * same database. The caller still owns the handle after registration and must destroy it with + * `duckdb_v2_pragma_function_destroy()`, which does not affect the registered function. + * + * history: + * - unstable: v2.0.0 + * + * @param conn The connection to register on. + * @param function The pragma function to register. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_register_pragma_function(duckdb_v2_connection_handle conn, + duckdb_v2_pragma_function_handle function, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! * Registers the pragma function, making it available to the `PRAGMA` statement. * @@ -12376,6 +12689,31 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_get_generic_property(duck duckdb_v2_error_info_handle *err); #endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Declares how the function's result changes with one of its arguments, see `DUCKDB_V2_FUNCTION_MONOTONICITY`. + * + * The optimizer relies on the declaration: a filter on the result of a non-decreasing function of a column, for + * example, can skip the row groups whose statistics rule the argument out. Declaring a monotonicity the function does + * not have produces wrong query results. A call can withdraw or change the declaration for itself from the bind + * callback with `duckdb_v2_scalar_function_bind_set_argument_monotonicity()`. Defaults to + * `FUNCTION_MONOTONICITY_UNKNOWN` for every argument. + * + * history: + * - unstable: v2.0.0 + * + * @param function The function to declare the monotonicity of. + * @param index The index of the argument, in the order the arguments are passed. + * @param monotonicity How the result changes with the argument. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_argument_monotonicity( + duckdb_v2_scalar_function_handle function, idx_t index, DUCKDB_V2_FUNCTION_MONOTONICITY monotonicity, + duckdb_v2_error_info_handle *err); +#endif + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! * Sets the optional resolve types callback of the scalar function. @@ -12414,5065 +12752,4772 @@ DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_resolve_types_callbac * - unstable: v2.0.0 * * @param function The function to set the bind callback of. - * @param callback The bind callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_bind_callback( - duckdb_v2_scalar_function_handle function, duckdb_v2_scalar_function_bind_callback_fn callback, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Sets the optional init callback of the scalar function. - * - * The init callback is invoked at the start of execution for each thread that will execute the function. It can set - * worker-local "init data", retrievable from the exec callback, to keep mutable state across invocations of the - * function. - * - * history: - * - unstable: v2.0.0 - * - * @param function The function to set the init callback of. - * @param callback The init callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_init_callback( - duckdb_v2_scalar_function_handle function, duckdb_v2_scalar_function_init_callback_fn callback, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Sets the exec callback of the scalar function. - * - * The exec callback implements the function's logic: it is invoked during query execution with a batch of input rows - * and must fill the result vector. An exec callback must be set before registration. - * - * history: - * - unstable: v2.0.0 - * - * @param function The function to set the exec callback of. - * @param callback The exec callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_exec_callback( - duckdb_v2_scalar_function_handle function, duckdb_v2_scalar_function_exec_callback_fn callback, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Sets the optional stats callback of the scalar function. - * - * The stats callback is invoked during query optimization for each call site of the function, after it has been bound. - * Through its `duckdb_v2_scalar_function_stats_info_handle` it reads the statistics of the arguments and narrows the - * statistics of the result, which the engine then uses to simplify the query. A function without a stats callback gives - * the engine no statistics for its result. - * - * history: - * - unstable: v2.0.0 - * - * @param function The function to set the stats callback of. - * @param callback The stats callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_stats_callback( - duckdb_v2_scalar_function_handle function, duckdb_v2_scalar_function_stats_callback_fn callback, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Sets the concrete return type of the call site being bound. - * - * Overrides the return type declared in the signature. Register the function with an ANY return type and set the - * concrete type here, derived from the argument types, to build a function whose result type depends on its input. The - * type is borrowed and copied. - * - * history: - * - unstable: v2.0.0 - * - * @param info The resolve types info handle. - * @param return_type The return type to set. Borrowed for the call only. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_resolve_types_set_return_type( - duckdb_v2_scalar_function_resolve_types_info_handle info, duckdb_v2_logical_type_handle return_type, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Sets the function's "bind data" from the bind callback. - * - * The bind data is stored with the bound call site and retrievable from the init and exec callbacks. The opaque handle - * bundles the pointer with an optional destructor, invoked when the bind data is no longer needed, and an optional - * equality callback used when comparing two bound call sites; without one, pointer equality is used. Scalar functions - * set their bind data through this function, `duckdb_v2_function_bind_set_bind_data()` is not available to them. - * - * history: - * - unstable: v2.0.0 - * - * @param info The bind info handle. - * @param data Opaque handle bundling the bind data pointer plus optional destructor and equality callbacks. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_bind_set_bind_data( - duckdb_v2_scalar_function_bind_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Retrieves the user data set via `duckdb_v2_scalar_function_set_user_data()`. - * - * history: - * - unstable: v2.0.0 - * - * @param info The init info handle. - * @param data Receives the user data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_init_get_user_data( - duckdb_v2_scalar_function_init_info_handle info, void **data, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Retrieves the bind data set by the function's bind callback. - * - * history: - * - unstable: v2.0.0 - * - * @param info The init info handle. - * @param data Receives the bind data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_init_get_bind_data( - duckdb_v2_scalar_function_init_info_handle info, void **data, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Sets the function's worker-local "init data" from the init callback. - * - * The init data is associated with the executing thread for the duration of the query and retrievable from the exec - * callback via `duckdb_v2_scalar_function_exec_get_init_data()`. The opaque handle bundles the pointer with an optional - * destructor, invoked when the init data is no longer needed. - * - * history: - * - unstable: v2.0.0 - * - * @param info The init info handle. - * @param data Opaque handle bundling the init data pointer plus an optional destructor. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_init_set_init_data( - duckdb_v2_scalar_function_init_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Retrieves the user data set via `duckdb_v2_scalar_function_set_user_data()`. - * - * history: - * - unstable: v2.0.0 - * - * @param info The exec info handle. - * @param data Receives the user data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_exec_get_user_data( - duckdb_v2_scalar_function_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Retrieves the bind data set by the function's bind callback. - * - * history: - * - unstable: v2.0.0 - * - * @param info The exec info handle. - * @param data Receives the bind data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_exec_get_bind_data( - duckdb_v2_scalar_function_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Retrieves the worker-local init data set by the function's init callback. - * - * history: - * - unstable: v2.0.0 - * - * @param info The exec info handle. - * @param data Receives the init data pointer for the executing thread, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_exec_get_init_data( - duckdb_v2_scalar_function_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Returns how many rows this execution must produce. The exec callback must write exactly this many rows to the result - * vector. Note that this may be less than a full vector: with all-constant arguments the function is invoked for a - * single row and the result is expanded by the engine. - * - * history: - * - unstable: v2.0.0 - * - * @param info The exec info handle. - * @param count Receives the number of rows. + * @param callback The bind callback to set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_exec_get_row_count( - duckdb_v2_scalar_function_exec_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_bind_callback( + duckdb_v2_scalar_function_handle function, duckdb_v2_scalar_function_bind_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns how many argument vectors this invocation carries, split into the four parts of the argument list. + * Sets the optional init callback of the scalar function. * - * The parts and their order are those the bind callback saw through `duckdb_v2_function_bind_get_arg_count()`, and the - * vectors are at the same indices. Valid indices for `duckdb_v2_scalar_function_exec_get_arg()` are [0, the sum of the - * four counts). Every out-parameter may be NULL, in which case nothing is written to it. + * The init callback is invoked at the start of execution for each thread that will execute the function. It can set + * worker-local "init data", retrievable from the exec callback, to keep mutable state across invocations of the + * function. * * history: * - unstable: v2.0.0 * - * @param info The exec info handle. - * @param positional_fixed Optional. Receives the number of positional-only and standard parameters. - * @param positional_variadic Optional. Receives the number of arguments `*args` received, 0 when the signature has - * none. - * @param named_fixed Optional. Receives the number of named-only parameters. - * @param named_variadic Optional. Receives the number of arguments `**kwargs` received, 0 when the signature has none. + * @param function The function to set the init callback of. + * @param callback The init callback to set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_exec_get_arg_count( - duckdb_v2_scalar_function_exec_info_handle info, idx_t *positional_fixed, idx_t *positional_variadic, - idx_t *named_fixed, idx_t *named_variadic, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_init_callback( + duckdb_v2_scalar_function_handle function, duckdb_v2_scalar_function_init_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the argument vector at the given index. + * Sets the exec callback of the scalar function. * - * The index is the one the bind callback used for the argument, e.g. the index - * `duckdb_v2_function_bind_get_arg_index()` found for a name. The vector holds the argument's values for the current - * batch; use `duckdb_v2_scalar_function_exec_get_row_count()` for the number of rows. Fails if the index is out of - * bounds. Borrowed; valid only for the duration of the callback. + * The exec callback implements the function's logic: it is invoked during query execution with a batch of input rows + * and must fill the result vector. An exec callback must be set before registration. * * history: * - unstable: v2.0.0 * - * @param info The exec info handle. - * @param index The index of the argument. - * @param vector Receives the borrowed argument vector. + * @param function The function to set the exec callback of. + * @param callback The exec callback to set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_exec_get_arg(duckdb_v2_scalar_function_exec_info_handle info, - idx_t index, duckdb_v2_vector_handle *vector, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_exec_callback( + duckdb_v2_scalar_function_handle function, duckdb_v2_scalar_function_exec_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the result vector the exec callback must write into. + * Sets the optional stats callback of the scalar function. * - * The callback must write one entry per input row; use `duckdb_v2_scalar_function_exec_get_row_count()` for the number - * of rows. Borrowed; valid only for the duration of the callback. + * The stats callback is invoked during query optimization for each call site of the function, after it has been bound. + * Through its `duckdb_v2_scalar_function_stats_info_handle` it reads the statistics of the arguments and narrows the + * statistics of the result, which the engine then uses to simplify the query. A function without a stats callback gives + * the engine no statistics for its result. * * history: * - unstable: v2.0.0 * - * @param info The exec info handle. - * @param vector Receives the borrowed result vector to write into. + * @param function The function to set the stats callback of. + * @param callback The stats callback to set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_exec_get_result(duckdb_v2_scalar_function_exec_info_handle info, - duckdb_v2_vector_handle *vector, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_stats_callback( + duckdb_v2_scalar_function_handle function, duckdb_v2_scalar_function_stats_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_scalar_function_set_user_data()`. + * Sets the concrete return type of the call site being bound. + * + * Overrides the return type declared in the signature. Register the function with an ANY return type and set the + * concrete type here, derived from the argument types, to build a function whose result type depends on its input. The + * type is borrowed and copied. * * history: * - unstable: v2.0.0 * - * @param info The stats info handle. - * @param data Receives the user data pointer, or null if none was set. + * @param info The resolve types info handle. + * @param return_type The return type to set. Borrowed for the call only. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_stats_get_user_data( - duckdb_v2_scalar_function_stats_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_resolve_types_set_return_type( + duckdb_v2_scalar_function_resolve_types_info_handle info, duckdb_v2_logical_type_handle return_type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's bind callback. + * Sets the function's "bind data" from the bind callback. + * + * The bind data is stored with the bound call site and retrievable from the init and exec callbacks. The opaque handle + * bundles the pointer with an optional destructor, invoked when the bind data is no longer needed, and an optional + * equality callback used when comparing two bound call sites; without one, pointer equality is used. Scalar functions + * set their bind data through this function, `duckdb_v2_function_bind_set_bind_data()` is not available to them. * * history: * - unstable: v2.0.0 * - * @param info The stats info handle. - * @param data Receives the bind data pointer, or null if none was set. + * @param info The bind info handle. + * @param data Opaque handle bundling the bind data pointer plus optional destructor and equality callbacks. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_stats_get_bind_data( - duckdb_v2_scalar_function_stats_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_bind_set_bind_data( + duckdb_v2_scalar_function_bind_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns how many arguments the call site has, split into the four parts of the argument list. + * Sets a property of the call being bound, overriding the one the function was registered with + * (`duckdb_v2_scalar_function_set_property()`) for this call only. * - * The parts and their order are those the bind callback saw through `duckdb_v2_function_bind_get_arg_count()`, and the - * arguments are at the same indices. Valid indices for `duckdb_v2_scalar_function_stats_get_arg_stats()` are [0, the - * sum of the four counts). Every out-parameter may be NULL, in which case nothing is written to it. + * Only `FUNCTION_PROPERTY_STABILITY` can be set: a function whose result depends on a setting for some arguments only, + * e.g. on the time zone for some formats, declares `FUNCTION_PROPERTY_STABILITY_CONSISTENT` at registration and + * `FUNCTION_PROPERTY_STABILITY_CONSISTENT_WITHIN_QUERY` for the calls that read the setting, or the other way around. + * Any other key, or a value that does not belong to the key, results in an error. * * history: * - unstable: v2.0.0 * - * @param info The stats info handle. - * @param positional_fixed Optional. Receives the number of positional-only and standard parameters. - * @param positional_variadic Optional. Receives the number of arguments `*args` received, 0 when the signature has - * none. - * @param named_fixed Optional. Receives the number of named-only parameters. - * @param named_variadic Optional. Receives the number of arguments `**kwargs` received, 0 when the signature has none. + * @param info The bind info handle. + * @param key The property to set. Must be `FUNCTION_PROPERTY_STABILITY`. + * @param value The value to set for the property. Must belong to `key`. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_stats_get_arg_count( - duckdb_v2_scalar_function_stats_info_handle info, idx_t *positional_fixed, idx_t *positional_variadic, - idx_t *named_fixed, idx_t *named_variadic, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_bind_set_property( + duckdb_v2_scalar_function_bind_info_handle info, DUCKDB_V2_FUNCTION_PROPERTY_KEY key, + DUCKDB_V2_FUNCTION_PROPERTY_VALUE value, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the statistics of the argument at the given index. + * Changes the monotonicity of the call being bound in one of its arguments, overriding the declaration of + * `duckdb_v2_scalar_function_set_argument_monotonicity()` for this call only. * - * The index is the one the bind callback used for the argument. The statistics are read-only. Fails if the index is out - * of bounds. Borrowed; valid only for the duration of the callback. + * A function that is monotone for most of its constant arguments declares the monotonicity at registration, and + * withdraws it with `FUNCTION_MONOTONICITY_UNKNOWN` for the calls whose constant arguments make it not monotone. * * history: * - unstable: v2.0.0 * - * @param info The stats info handle. - * @param index The index of the argument. - * @param stats Receives the borrowed, read-only statistics of the argument. + * @param info The bind info handle. + * @param index The index of the argument, in the order the arguments are passed. + * @param monotonicity How the result changes with the argument in this call. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR -duckdb_v2_scalar_function_stats_get_arg_stats(duckdb_v2_scalar_function_stats_info_handle info, idx_t index, - duckdb_v2_stats_handle *stats, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_bind_set_argument_monotonicity( + duckdb_v2_scalar_function_bind_info_handle info, idx_t index, DUCKDB_V2_FUNCTION_MONOTONICITY monotonicity, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the statistics of the call site's result, for the callback to narrow. + * Replaces the call being bound with a call of another scalar function, on some of its arguments. * - * The statistics start out unknown, with every kind of value possible. Borrowed; valid only for the duration of the - * callback. + * Once the bind callback returns, the engine binds the function named `name`, from the schema the function being bound + * was registered in, to the arguments at `arg_indices`, in that order, and the query runs that call in place of this + * one: its return type, bind data, properties and statistics are the replacement's. A function with one constant + * argument that selects a cheaper or better described function uses it, e.g. `date_part` with a constant part replacing + * itself with the function of that part. The bind data the callback set is discarded. + * + * The replacement is bound like a call written in SQL, so its overload is chosen by the types of the arguments, and it + * may itself replace its call. Binding it fails like such a call when no function of that name takes those arguments. * * history: * - unstable: v2.0.0 * - * @param info The stats info handle. - * @param stats Receives the borrowed, writable statistics of the call site's result. + * @param info The bind info handle. + * @param name The name of the function to call instead. Not necessarily null-terminated. + * @param name_length The length of `name` in bytes. + * @param arg_indices The indices of the arguments of the call being bound to pass to the replacement, in order. May be + * null when `arg_count` is 0. + * @param arg_count The number of entries in `arg_indices`. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_stats_get_result_stats( - duckdb_v2_scalar_function_stats_info_handle info, duckdb_v2_stats_handle *stats, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_bind_replace_call( + duckdb_v2_scalar_function_bind_info_handle info, const char *name, idx_t name_length, const idx_t *arg_indices, + idx_t arg_count, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the scalar function, making it available for use in SQL queries. - * - * The function is registered on the connection's database, visible to every connection, in the connection's - * transaction: inside an explicit transaction, it is invisible to other connections until the transaction commits, and - * a rollback undoes it. Registration requires a name, an exec callback, and a signature with a complete return type; an - * ANY return type is accepted only together with a resolve types callback that sets the concrete type per call site. - * The scalar function must have been created through a factory of the same database. The caller still owns the handle - * after registration and must destroy it with `duckdb_v2_scalar_function_destroy()`, which does not affect the - * registered function. + * Retrieves the user data set via `duckdb_v2_scalar_function_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param conn The connection to register on. - * @param function The scalar function to register. + * @param info The init info handle. + * @param data Receives the user data pointer, or null if none was set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_register_scalar_function(duckdb_v2_connection_handle conn, - duckdb_v2_scalar_function_handle function, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_init_get_user_data( + duckdb_v2_scalar_function_init_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the scalar function, making it available for use in SQL queries. - * - * The function is registered on the loading extension's database and attributed to the extension. Use this from the - * extension's load callback. Registration requires a name, an exec callback, and a signature with a complete return - * type; an ANY return type is accepted only together with a resolve types callback that sets the concrete type per call - * site. The scalar function must have been created through a factory of the same database. The caller still owns the - * handle after registration and must destroy it with `duckdb_v2_scalar_function_destroy()`, which does not affect the - * registered function. + * Retrieves the bind data set by the function's bind callback. * * history: * - unstable: v2.0.0 * - * @param extension The loading extension. - * @param function The scalar function to register. + * @param info The init info handle. + * @param data Receives the bind data pointer, or null if none was set. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_scalar_function(duckdb_v2_extension_handle extension, - duckdb_v2_scalar_function_handle function, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_init_get_bind_data( + duckdb_v2_scalar_function_init_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys the scalar function, releasing its resources. + * Sets the function's worker-local "init data" from the init callback. * - * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent - * double-destruction. Destroying the handle after registration does not affect the registered function. + * The init data is associated with the executing thread for the duration of the query and retrievable from the exec + * callback via `duckdb_v2_scalar_function_exec_get_init_data()`. The opaque handle bundles the pointer with an optional + * destructor, invoked when the init data is no longer needed. * * history: * - unstable: v2.0.0 * - * @param function The function to destroy. + * @param info The init info handle. + * @param data Opaque handle bundling the init data pointer plus an optional destructor. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_destroy(duckdb_v2_scalar_function_handle *function); -#endif - -/* --- Struct definitions for scalar --- */ - -/* ============================================================================ - * MODULE: sql_statement - * ============================================================================ */ - -/* --- Enums for sql_statement --- */ - -//! SQL statement type of a parsed statement or an executed query. -typedef enum DUCKDB_V2_STATEMENT_TYPE { - DUCKDB_V2_STATEMENT_TYPE_INVALID = 0, - DUCKDB_V2_STATEMENT_TYPE_SELECT = 1, - DUCKDB_V2_STATEMENT_TYPE_INSERT = 2, - DUCKDB_V2_STATEMENT_TYPE_UPDATE = 3, - DUCKDB_V2_STATEMENT_TYPE_CREATE = 4, - DUCKDB_V2_STATEMENT_TYPE_DELETE = 5, - DUCKDB_V2_STATEMENT_TYPE_PREPARE = 6, - DUCKDB_V2_STATEMENT_TYPE_EXECUTE = 7, - DUCKDB_V2_STATEMENT_TYPE_ALTER = 8, - DUCKDB_V2_STATEMENT_TYPE_TRANSACTION = 9, - DUCKDB_V2_STATEMENT_TYPE_COPY = 10, - DUCKDB_V2_STATEMENT_TYPE_ANALYZE = 11, - DUCKDB_V2_STATEMENT_TYPE_VARIABLE_SET = 12, - DUCKDB_V2_STATEMENT_TYPE_CREATE_FUNC = 13, - DUCKDB_V2_STATEMENT_TYPE_EXPLAIN = 14, - DUCKDB_V2_STATEMENT_TYPE_DROP = 15, - DUCKDB_V2_STATEMENT_TYPE_EXPORT = 16, - DUCKDB_V2_STATEMENT_TYPE_PRAGMA = 17, - DUCKDB_V2_STATEMENT_TYPE_VACUUM = 18, - DUCKDB_V2_STATEMENT_TYPE_CALL = 19, - DUCKDB_V2_STATEMENT_TYPE_SET = 20, - DUCKDB_V2_STATEMENT_TYPE_LOAD = 21, - DUCKDB_V2_STATEMENT_TYPE_RELATION = 22, - DUCKDB_V2_STATEMENT_TYPE_EXTENSION = 23, - DUCKDB_V2_STATEMENT_TYPE_LOGICAL_PLAN = 24, - DUCKDB_V2_STATEMENT_TYPE_ATTACH = 25, - DUCKDB_V2_STATEMENT_TYPE_DETACH = 26, - DUCKDB_V2_STATEMENT_TYPE_MULTI = 27, - DUCKDB_V2_STATEMENT_TYPE_COPY_DATABASE = 28, - DUCKDB_V2_STATEMENT_TYPE_UPDATE_EXTENSIONS = 29, - DUCKDB_V2_STATEMENT_TYPE_MERGE_INTO = 30, - DUCKDB_V2_STATEMENT_TYPE_CONNECT = 31, - DUCKDB_V2_STATEMENT_TYPE_DISCONNECT = 32, - DUCKDB_V2_STATEMENT_TYPE_EXTERNAL_RESOURCE = 33, - DUCKDB_V2_STATEMENT_TYPE_PASSTHROUGH = 34, - DUCKDB_V2_STATEMENT_TYPE_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_STATEMENT_TYPE; - -/* --- Struct forward declarations for sql_statement --- */ - -/* --- Types for sql_statement --- */ - -/*! - * An opaque, owned handle to a single parsed SQL statement, produced by statement_iterator_next. statement_execute runs - * it without consuming it; the caller always destroys it via sql_statement_destroy. - */ -typedef struct _duckdb_v2_sql_statement { - void *internal_ptr; -} * duckdb_v2_sql_statement_handle; - -/*! - * An opaque, owned handle to an iterator over the statements of a SQL string, produced by parse_sql. Destroy it via - * statement_iterator_destroy; statements it already yielded are independently owned and unaffected. - */ -typedef struct _duckdb_v2_statement_iterator { - void *internal_ptr; -} * duckdb_v2_statement_iterator_handle; - -/* --- Constants for sql_statement --- */ - -/* --- Function pointer typedefs for sql_statement --- */ - -/* --- Functions for sql_statement --- */ + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_init_set_init_data( + duckdb_v2_scalar_function_init_info_handle info, duckdb_v2_opaque *data, duckdb_v2_error_info_handle *err); +#endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Parses a SQL string into an iterator over its statements. - * - * Parses and nothing more: no binding and no catalog access. The connection supplies the parser options and parser - * extensions. With apply_invalidation_policy, a parse error invalidates the connection's active transaction according - * to the transaction invalidation policy, like an error from running the statement would; pass that when the statements - * are parsed to be run. Without it, a parse error leaves the transaction usable, for callers that only inspect the - * statements, for example with `duckdb_v2_statement_bind()`. Statements are raw parser output; statement-level rewrites - * happen inside statement_execute. The SQL string is copied, so the caller may free it once this call returns. An input - * with no statements — empty, whitespace, or separators only — yields an iterator that is immediately exhausted. + * Retrieves the user data set via `duckdb_v2_scalar_function_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param conn The connection supplying the parser configuration. - * @param sql The SQL text, `sql_length` bytes long; may contain any number of statements. Need not be null-terminated. - * May be NULL only when `sql_length` is 0. - * @param sql_length The length of `sql` in bytes. - * @param apply_invalidation_policy Whether a parse error invalidates the active transaction, according to the - * transaction invalidation policy. - * @param out_iterator Receives the new iterator handle. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The exec info handle. + * @param data Receives the user data pointer, or null if none was set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_parse_sql(duckdb_v2_connection_handle conn, const char *sql, idx_t sql_length, - bool apply_invalidation_policy, - duckdb_v2_statement_iterator_handle *out_iterator, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_exec_get_user_data( + duckdb_v2_scalar_function_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Yields the next statement, or NULL when exhausted. - * - * On success *out_statement receives the next owned statement, or NULL once the iterator is exhausted — repeatedly, so - * calling again is harmless. A parse error within the input surfaces no later than the call that reaches the failing - * statement: an implementation that parses eagerly reports it from parse_sql instead and yields no statements at all, - * while an incremental one yields the statements ahead of the failure first. On failure *out_statement is set to NULL. + * Retrieves the bind data set by the function's bind callback. * * history: * - unstable: v2.0.0 * - * @param iterator The iterator to advance. - * @param out_statement Receives an owned statement, or NULL when the iterator is exhausted. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The exec info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_iterator_next(duckdb_v2_statement_iterator_handle iterator, - duckdb_v2_sql_statement_handle *out_statement, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_exec_get_bind_data( + duckdb_v2_scalar_function_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Binds a parsed statement without executing, yielding its schema signature. - * - * Preprocesses and binds the statement exactly as execution would, but runs nothing: the result is the statement's - * signature as two schemas, not a query result. The statement is borrowed, not consumed, so it can be bound as often as - * you like and executed later. out_schema receives the output schema (result columns) and is never empty, since a - * non-SELECT reports a single status column: a BIGINT changed-rows count, or a BOOLEAN success. out_parameters, when - * non-NULL, receives the input schema (parameter types, ordered by binding index). Both are owned; destroy them via - * schema_destroy. + * Retrieves the worker-local init data set by the function's init callback. * - * Binding is read-only and does not disturb a live result: it begins no query, claims no cursor, reuses an active - * transaction read-only, and runs alongside a paused stream. It is single-consumer like the stepping functions, so bind - * concurrently only on a second connection. Errors of the bind itself (catalog lookups, type resolution, preprocessing) - * surface here; errors of the planning after the bind (the plan depth limit, a correlated subquery or trigger body that - * decorrelation refuses) may surface only when the statement is executed. A statement that expands into a group (a - * dynamic PIVOT, or statement-expanding DDL such as ALTER ADD COLUMN with a non-constant DEFAULT) has a schema known - * only at execution, and is reported with ERROR_INPUT_METADATA_DEFERRED; execute it instead. + * history: + * - unstable: v2.0.0 * - * *out_schema and *out_parameters are set to NULL on failure. + * @param info The exec info handle. + * @param data Receives the init data pointer for the executing thread, or null if none was set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_exec_get_init_data( + duckdb_v2_scalar_function_exec_info_handle info, void **data, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Returns how many rows this execution must produce. The exec callback must write exactly this many rows to the result + * vector. Note that this may be less than a full vector: with all-constant arguments the function is invoked for a + * single row and the result is expanded by the engine. * * history: * - unstable: v2.0.0 * - * @param conn The connection supplying the catalog, transaction, and parser configuration. - * @param statement The statement to bind. Borrowed; not consumed. - * @param out_schema Receives the owned output schema (result columns). Destroy via schema_destroy. - * @param out_parameters Optional. When non-NULL, receives the owned input schema (parameter types, ordered by binding - * index). Destroy via schema_destroy. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The exec info handle. + * @param count Receives the number of rows. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_bind(duckdb_v2_connection_handle conn, - duckdb_v2_sql_statement_handle statement, - duckdb_v2_schema_handle *out_schema, - duckdb_v2_schema_handle *out_parameters, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_exec_get_row_count( + duckdb_v2_scalar_function_exec_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Binds a column data collection to the statement under a name. + * Returns how many argument vectors this invocation carries, split into the four parts of the argument list. * - * Makes the collection visible to the statement as a table named `name`, by adding a common table expression to the - * parsed statement. The statement can then be bound, prepared or executed as usual; each execution reads the - * collection's contents at that moment, so a prepared statement can be executed again after the collection was cleared - * and refilled. Supported statement types are SELECT, INSERT, UPDATE, DELETE and MERGE INTO; any other type is rejected - * with `ERROR_INPUT_INVALID`. + * The parts and their order are those the bind callback saw through `duckdb_v2_function_bind_get_arg_count()`, and the + * vectors are at the same indices. Valid indices for `duckdb_v2_scalar_function_exec_get_arg()` are [0, the sum of the + * four counts). Every out-parameter may be NULL, in which case nothing is written to it. * - * A name the statement already defines as a common table expression, in its SQL text or by a prior call, is rejected - * with `ERROR_INPUT_INVALID`. The binding shadows any catalog table named `name`, as a common table expression does. + * history: + * - unstable: v2.0.0 * - * By default the collection's columns are named col1..colN. Pass `column_names` to name them instead; when supplied, - * `column_count` must equal the collection's column count. Pass NULL and 0 for the default names. + * @param info The exec info handle. + * @param positional_fixed Optional. Receives the number of positional-only and standard parameters. + * @param positional_variadic Optional. Receives the number of arguments `*args` received, 0 when the signature has + * none. + * @param named_fixed Optional. Receives the number of named-only parameters. + * @param named_variadic Optional. Receives the number of arguments `**kwargs` received, 0 when the signature has none. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_exec_get_arg_count( + duckdb_v2_scalar_function_exec_info_handle info, idx_t *positional_fixed, idx_t *positional_variadic, + idx_t *named_fixed, idx_t *named_variadic, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Retrieves the argument vector at the given index. * - * The collection is borrowed: the caller keeps ownership and must keep it alive, and must not clear, reset or destroy - * it, for as long as the statement, any statement copied or prepared from it, or any result executing it is live. An - * empty collection is a valid binding. Several collections can be bound under distinct names. + * The index is the one the bind callback used for the argument, e.g. the index + * `duckdb_v2_function_bind_get_arg_index()` found for a name. The vector holds the argument's values for the current + * batch; use `duckdb_v2_scalar_function_exec_get_row_count()` for the number of rows. Fails if the index is out of + * bounds. Borrowed; valid only for the duration of the callback. * * history: * - unstable: v2.0.0 * - * @param statement The statement to bind the collection to. Modified in place. - * @param name The non-empty name the statement refers to the collection by. Borrowed and copied. - * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be - * NULL only when this is 0. - * @param collection The collection to bind. Borrowed; the caller keeps ownership and must keep it alive. - * @param column_names Optional. An array of `column_count` names for the collection's columns, in order. Pass NULL for - * col1..colN. - * @param column_names_lengths Byte lengths of the entries in `column_names`; element i is the length of - * `column_names[i]`. May be NULL only when `column_names` is NULL. - * @param column_count The number of names in `column_names`. 0 for the default names; otherwise the collection's column - * count. + * @param info The exec info handle. + * @param index The index of the argument. + * @param vector Receives the borrowed argument vector. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_add_collection(duckdb_v2_sql_statement_handle statement, - const char *name, idx_t name_length, - duckdb_v2_column_data_collection_handle collection, - const char *const *column_names, - const idx_t *column_names_lengths, idx_t column_count, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_exec_get_arg(duckdb_v2_scalar_function_exec_info_handle info, + idx_t index, duckdb_v2_vector_handle *vector, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the statement's type as classified by the parser. + * Retrieves the result vector the exec callback must write into. * - * This gives the type before the statement-level rewrites that `duckdb_v2_statement_execute()` applies, if any. So a - * PRAGMA reports PRAGMA even where execution rewrites it into a SELECT or a CALL. - * `duckdb_v2_result_get_statement_type()` on the executed result reports the rewritten type of a statement that - * rewrites into one. A statement the parser expands into a group reports MULTI, here and on its result. Its parts are - * not visible here, and statement_bind reports ERROR_INPUT_METADATA_DEFERRED for it. + * The callback must write one entry per input row; use `duckdb_v2_scalar_function_exec_get_row_count()` for the number + * of rows. Borrowed; valid only for the duration of the callback. * * history: * - unstable: v2.0.0 * - * @param statement The statement. - * @param out_type Receives the statement type. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The exec info handle. + * @param vector Receives the borrowed result vector to write into. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_sql_statement_get_type(duckdb_v2_sql_statement_handle statement, - DUCKDB_V2_STATEMENT_TYPE *out_type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_exec_get_result(duckdb_v2_scalar_function_exec_info_handle info, + duckdb_v2_vector_handle *vector, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Borrows the statement's own SQL text. - * - * The slice of the parsed string that belongs to this statement. A trailing terminator and the whitespace after it are - * included, whitespace and comments before the first token are not. The statement holds its own copy, so the view - * outlives the SQL string passed to parse_sql and the iterator, and stays valid until the statement is destroyed. A - * statement produced by a parser extension that overrides parsing carries whatever text the extension recorded. + * Retrieves the user data set via `duckdb_v2_scalar_function_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param statement The statement. - * @param out_text Receives a borrowed pointer to the statement text, valid until the statement is destroyed. - * @param out_text_length Receives the length of `*out_text` in bytes. `*out_text` is not guaranteed to be - * null-terminated. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The stats info handle. + * @param data Receives the user data pointer, or null if none was set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_sql_statement_get_text(duckdb_v2_sql_statement_handle statement, - const char **out_text, idx_t *out_text_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_stats_get_user_data( + duckdb_v2_scalar_function_stats_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of distinct parameters the statement declares. - * - * This counts the parameters the parser found ($1, ?, $name, ...), so it needs no catalog and no binding; only the - * parameter types wait for `duckdb_v2_statement_bind()`. Repeated uses of one parameter count once. + * Retrieves the bind data set by the function's bind callback. * * history: * - unstable: v2.0.0 * - * @param statement The statement. - * @param out_count Receives the number of distinct parameters. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The stats info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_sql_statement_get_parameter_count(duckdb_v2_sql_statement_handle statement, - idx_t *out_count, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_stats_get_bind_data( + duckdb_v2_scalar_function_stats_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Borrows the name of one parameter, in binding order. + * Returns how many arguments the call site has, split into the four parts of the argument list. * - * Parse-time metadata. Positions follow the parameters' binding indices, the order of `duckdb_v2_statement_bind()`'s - * parameter schema, so position i here names field i there. The name is the binding key that - * `duckdb_v2_statement_execute()` accepts: "1", "2", ... for a positional parameter ($1 or ?), the identifier for a - * named one ($name). Positional indices may be gapped ($1 and $3 without $2), in which case the names are "1" and "3" - * at positions 0 and 1. The view is valid until the statement is destroyed. An index outside [0, count) is rejected - * with ERROR_INPUT_OUT_OF_RANGE. + * The parts and their order are those the bind callback saw through `duckdb_v2_function_bind_get_arg_count()`, and the + * arguments are at the same indices. Valid indices for `duckdb_v2_scalar_function_stats_get_arg_stats()` are [0, the + * sum of the four counts). Every out-parameter may be NULL, in which case nothing is written to it. * * history: * - unstable: v2.0.0 * - * @param statement The statement. - * @param index Zero-based position in binding order. - * @param out_name Receives a borrowed pointer to the parameter name, valid until the statement is destroyed. - * @param out_name_length Receives the length of `*out_name` in bytes. `*out_name` is not guaranteed to be - * null-terminated. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The stats info handle. + * @param positional_fixed Optional. Receives the number of positional-only and standard parameters. + * @param positional_variadic Optional. Receives the number of arguments `*args` received, 0 when the signature has + * none. + * @param named_fixed Optional. Receives the number of named-only parameters. + * @param named_variadic Optional. Receives the number of arguments `**kwargs` received, 0 when the signature has none. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_sql_statement_get_parameter_name(duckdb_v2_sql_statement_handle statement, - idx_t index, const char **out_name, - idx_t *out_name_length, - duckdb_v2_error_info_handle *err); + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_stats_get_arg_count( + duckdb_v2_scalar_function_stats_info_handle info, idx_t *positional_fixed, idx_t *positional_variadic, + idx_t *named_fixed, idx_t *named_variadic, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys a statement handle. + * Retrieves the statistics of the argument at the given index. * - * Null-safe: passing nullptr or a slot already set to nullptr is a no-op. statement_execute does not consume a - * statement, so every statement is destroyed here once it is no longer needed. On success the slot is set to nullptr. + * The index is the one the bind callback used for the argument. The statistics are read-only. Fails if the index is out + * of bounds. Borrowed; valid only for the duration of the callback. * * history: * - unstable: v2.0.0 * - * @param statement The statement to destroy. + * @param info The stats info handle. + * @param index The index of the argument. + * @param stats Receives the borrowed, read-only statistics of the argument. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_sql_statement_destroy(duckdb_v2_sql_statement_handle *statement); +DUCKDB_C_API DUCKDB_V2_ERROR +duckdb_v2_scalar_function_stats_get_arg_stats(duckdb_v2_scalar_function_stats_info_handle info, idx_t index, + duckdb_v2_stats_handle *stats, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys a statement iterator handle. + * Retrieves the statistics of the call site's result, for the callback to narrow. * - * Null-safe: passing nullptr or a slot already set to nullptr is a no-op. Statements already yielded are independently - * owned and stay valid. On success the slot is set to nullptr. + * The statistics start out unknown, with every kind of value possible. Borrowed; valid only for the duration of the + * callback. * * history: * - unstable: v2.0.0 * - * @param iterator The iterator to destroy. + * @param info The stats info handle. + * @param stats Receives the borrowed, writable statistics of the call site's result. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_iterator_destroy(duckdb_v2_statement_iterator_handle *iterator); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_stats_get_result_stats( + duckdb_v2_scalar_function_stats_info_handle info, duckdb_v2_stats_handle *stats, duckdb_v2_error_info_handle *err); #endif -/* --- Struct definitions for sql_statement --- */ - -/* ============================================================================ - * MODULE: vector - * ============================================================================ */ - -/* --- Enums for vector --- */ - -/*! - * Internal representation of a vector, with FSST / SEQUENCE / SHREDDED collapsed into OTHER: the view getter rejects - * those and requires an explicit vector_flatten first. OTHER is the 0-value, so a zero-initialized out-param reads as - * "unspecified, needs flatten" rather than silently looking like FLAT. - */ -typedef enum DUCKDB_V2_VECTOR_TYPE { - //! Default for zero-init. Covers FSST / SEQUENCE / SHREDDED — call vector_flatten first. - DUCKDB_V2_VECTOR_TYPE_OTHER = 0, - - //! Standard per-row storage. - DUCKDB_V2_VECTOR_TYPE_FLAT = 1, - - //! A single value applies to every row in the vector. - DUCKDB_V2_VECTOR_TYPE_CONSTANT = 2, - - //! Data + selection vector indirection into another vector. - DUCKDB_V2_VECTOR_TYPE_DICTIONARY = 3, - DUCKDB_V2_VECTOR_TYPE_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_VECTOR_TYPE; - -/* --- Struct forward declarations for vector --- */ - -typedef struct duckdb_v2_vector_view duckdb_v2_vector_view; - -typedef struct duckdb_v2_list_entry duckdb_v2_list_entry; - -typedef struct duckdb_v2_hugeint_t duckdb_v2_hugeint_t; - -typedef struct duckdb_v2_uhugeint_t duckdb_v2_uhugeint_t; - -typedef struct duckdb_v2_interval_t duckdb_v2_interval_t; - -/* --- Types for vector --- */ - -/* --- Constants for vector --- */ - -/* --- Function pointer typedefs for vector --- */ - -/* --- Functions for vector --- */ - #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the internal representation kind: flat, constant, or dictionary. + * Registers the scalar function, making it available for use in SQL queries. * - * Reports VECTOR_TYPE_OTHER for FSST / SEQUENCE / SHREDDED vectors, which must be passed through vector_flatten before - * vector_get_view will read them. + * The function is registered on the connection's database, visible to every connection, in the connection's + * transaction: inside an explicit transaction, it is invisible to other connections until the transaction commits, and + * a rollback undoes it. Registration requires a name, an exec callback, and a signature with a complete return type; an + * ANY return type is accepted only together with a resolve types callback that sets the concrete type per call site. + * The scalar function must have been created through a factory of the same database. The caller still owns the handle + * after registration and must destroy it with `duckdb_v2_scalar_function_destroy()`, which does not affect the + * registered function. * * history: * - unstable: v2.0.0 * - * @param vector The vector. - * @param out_type Receives the representation kind. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param conn The connection to register on. + * @param function The scalar function to register. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_get_vector_type(duckdb_v2_vector_handle vector, - DUCKDB_V2_VECTOR_TYPE *out_type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_register_scalar_function(duckdb_v2_connection_handle conn, + duckdb_v2_scalar_function_handle function, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the vector's logical type. + * Registers the scalar function, making it available for use in SQL queries. * - * The returned logical type is the same type that was passed to vector_reference, or the type that was set on creation. - * It is caller-owned; destroy it via logical_type_destroy. + * The function is registered on the loading extension's database and attributed to the extension. Use this from the + * extension's load callback. Registration requires a name, an exec callback, and a signature with a complete return + * type; an ANY return type is accepted only together with a resolve types callback that sets the concrete type per call + * site. The scalar function must have been created through a factory of the same database. The caller still owns the + * handle after registration and must destroy it with `duckdb_v2_scalar_function_destroy()`, which does not affect the + * registered function. * * history: * - unstable: v2.0.0 * - * @param vector The vector. - * @param out_type Receives the caller-owned logical type handle. Destroy via logical_type_destroy. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param extension The loading extension. + * @param function The scalar function to register. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_get_logical_type(duckdb_v2_vector_handle vector, - duckdb_v2_logical_type_handle *out_type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_scalar_function(duckdb_v2_extension_handle extension, + duckdb_v2_scalar_function_handle function, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Reads a vector as a unified view of data, validity, selection, and count. - * - * Populates out_view with borrowed pointers, valid until the owning chunk is destroyed. view.data addresses the - * vector's elements, to be cast to the layout its logical type implies: a typed leaf array for the primitives, - * hugeint_t / uhugeint_t / interval_t for those kinds, bytes for VARCHAR / BLOB / BIT / BIGNUM, list_entry for LIST and - * MAP, and nothing at all for ARRAY / STRUCT / UNION, whose data lives in their children. - * - * DECIMAL and ENUM are typed leaf arrays too, over a storage tier that follows from the type; both mappings are - * contract. A DECIMAL of width <= 4 stores int16, <= 9 int32, <= 18 int64, and <= 38 int128, boundaries inclusive, with - * the width and scale available from logical_type_get_param. An ENUM stores its dictionary indices as uint8 for a - * dictionary of at most 255 entries, uint16 for at most 65535, and uint32 beyond that, boundaries inclusive and an - * empty dictionary uint8; logical_type_get_param resolves an index to its entry. - * - * Rejects VECTOR_TYPE_OTHER; call vector_flatten first. + * Destroys the scalar function, releasing its resources. * - * Reading a DICTIONARY vector has one side effect: the dictionary's underlying child is flattened in place if it is not - * already FLAT. The parent vector stays DICTIONARY, and only the child's storage shape changes, but any pointer - * previously borrowed into that child — from an earlier vector_get_view on a vector aliasing the same buffer, say — is - * invalidated. This is the only mutation vector_get_view performs; compare vector_flatten, which materializes the whole - * vector to FLAT. + * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent + * double-destruction. Destroying the handle after registration does not affect the registered function. * * history: * - unstable: v2.0.0 * - * @param vector The vector to read. - * @param out_view Receives the view. Its pointers are borrowed and valid until the owning chunk is destroyed. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_get_view(duckdb_v2_vector_handle vector, duckdb_v2_vector_view *out_view, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_scalar_function_destroy(duckdb_v2_scalar_function_handle *function); #endif +/* --- Struct definitions for scalar --- */ + +/* ============================================================================ + * MODULE: sql_statement + * ============================================================================ */ + +/* --- Enums for sql_statement --- */ + +//! SQL statement type of a parsed statement or an executed query. +typedef enum DUCKDB_V2_STATEMENT_TYPE { + DUCKDB_V2_STATEMENT_TYPE_INVALID = 0, + DUCKDB_V2_STATEMENT_TYPE_SELECT = 1, + DUCKDB_V2_STATEMENT_TYPE_INSERT = 2, + DUCKDB_V2_STATEMENT_TYPE_UPDATE = 3, + DUCKDB_V2_STATEMENT_TYPE_CREATE = 4, + DUCKDB_V2_STATEMENT_TYPE_DELETE = 5, + DUCKDB_V2_STATEMENT_TYPE_PREPARE = 6, + DUCKDB_V2_STATEMENT_TYPE_EXECUTE = 7, + DUCKDB_V2_STATEMENT_TYPE_ALTER = 8, + DUCKDB_V2_STATEMENT_TYPE_TRANSACTION = 9, + DUCKDB_V2_STATEMENT_TYPE_COPY = 10, + DUCKDB_V2_STATEMENT_TYPE_ANALYZE = 11, + DUCKDB_V2_STATEMENT_TYPE_VARIABLE_SET = 12, + DUCKDB_V2_STATEMENT_TYPE_CREATE_FUNC = 13, + DUCKDB_V2_STATEMENT_TYPE_EXPLAIN = 14, + DUCKDB_V2_STATEMENT_TYPE_DROP = 15, + DUCKDB_V2_STATEMENT_TYPE_EXPORT = 16, + DUCKDB_V2_STATEMENT_TYPE_PRAGMA = 17, + DUCKDB_V2_STATEMENT_TYPE_VACUUM = 18, + DUCKDB_V2_STATEMENT_TYPE_CALL = 19, + DUCKDB_V2_STATEMENT_TYPE_SET = 20, + DUCKDB_V2_STATEMENT_TYPE_LOAD = 21, + DUCKDB_V2_STATEMENT_TYPE_RELATION = 22, + DUCKDB_V2_STATEMENT_TYPE_EXTENSION = 23, + DUCKDB_V2_STATEMENT_TYPE_LOGICAL_PLAN = 24, + DUCKDB_V2_STATEMENT_TYPE_ATTACH = 25, + DUCKDB_V2_STATEMENT_TYPE_DETACH = 26, + DUCKDB_V2_STATEMENT_TYPE_MULTI = 27, + DUCKDB_V2_STATEMENT_TYPE_COPY_DATABASE = 28, + DUCKDB_V2_STATEMENT_TYPE_UPDATE_EXTENSIONS = 29, + DUCKDB_V2_STATEMENT_TYPE_MERGE_INTO = 30, + DUCKDB_V2_STATEMENT_TYPE_CONNECT = 31, + DUCKDB_V2_STATEMENT_TYPE_DISCONNECT = 32, + DUCKDB_V2_STATEMENT_TYPE_EXTERNAL_RESOURCE = 33, + DUCKDB_V2_STATEMENT_TYPE_PASSTHROUGH = 34, + DUCKDB_V2_STATEMENT_TYPE_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_STATEMENT_TYPE; + +/* --- Struct forward declarations for sql_statement --- */ + +/* --- Types for sql_statement --- */ + +/*! + * An opaque, owned handle to a single parsed SQL statement, produced by statement_iterator_next. statement_execute runs + * it without consuming it; the caller always destroys it via sql_statement_destroy. + */ +typedef struct _duckdb_v2_sql_statement { + void *internal_ptr; +} * duckdb_v2_sql_statement_handle; + +/*! + * An opaque, owned handle to an iterator over the statements of a SQL string, produced by parse_sql. Destroy it via + * statement_iterator_destroy; statements it already yielded are independently owned and unaffected. + */ +typedef struct _duckdb_v2_statement_iterator { + void *internal_ptr; +} * duckdb_v2_statement_iterator_handle; + +/* --- Constants for sql_statement --- */ + +/* --- Function pointer typedefs for sql_statement --- */ + +/* --- Functions for sql_statement --- */ + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of elements in the vector. + * Parses a SQL string into an iterator over its statements. * - * The size is the number of logical elements the vector represents, which for a nested kind can differ from the size of - * its children. An ARRAY vector of size 10 whose array size is 3, for instance, has 10 logical elements while its - * single child vector has 30. + * Parses and nothing more: no binding and no catalog access. The connection supplies the parser options and parser + * extensions. With apply_invalidation_policy, a parse error invalidates the connection's active transaction according + * to the transaction invalidation policy, like an error from running the statement would; pass that when the statements + * are parsed to be run. Without it, a parse error leaves the transaction usable, for callers that only inspect the + * statements, for example with `duckdb_v2_statement_bind()`. Statements are raw parser output; statement-level rewrites + * happen inside statement_execute. The SQL string is copied, so the caller may free it once this call returns. An input + * with no statements — empty, whitespace, or separators only — yields an iterator that is immediately exhausted. * * history: * - unstable: v2.0.0 * - * @param vector The vector. - * @param out_size Receives the number of elements. + * @param conn The connection supplying the parser configuration. + * @param sql The SQL text, `sql_length` bytes long; may contain any number of statements. Need not be null-terminated. + * May be NULL only when `sql_length` is 0. + * @param sql_length The length of `sql` in bytes. + * @param apply_invalidation_policy Whether a parse error invalidates the active transaction, according to the + * transaction invalidation policy. + * @param out_iterator Receives the new iterator handle. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_get_size(duckdb_v2_vector_handle vector, idx_t *out_size, - duckdb_v2_error_info_handle *err); + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_parse_sql(duckdb_v2_connection_handle conn, const char *sql, idx_t sql_length, + bool apply_invalidation_policy, + duckdb_v2_statement_iterator_handle *out_iterator, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the number of elements in the vector. + * Yields the next statement, or NULL when exhausted. * - * The counterpart of vector_get_size: it declares how many logical elements the vector now holds. It reserves enough - * space for size logical elements. + * On success *out_statement receives the next owned statement, or NULL once the iterator is exhausted — repeatedly, so + * calling again is harmless. A parse error within the input surfaces no later than the call that reaches the failing + * statement: an implementation that parses eagerly reports it from parse_sql instead and yields no statements at all, + * while an incremental one yields the statements ahead of the failure first. On failure *out_statement is set to NULL. * * history: * - unstable: v2.0.0 * - * @param vector The vector. - * @param size The new number of logical elements. + * @param iterator The iterator to advance. + * @param out_statement Receives an owned statement, or NULL when the iterator is exhausted. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_set_size(duckdb_v2_vector_handle vector, idx_t size, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_iterator_next(duckdb_v2_statement_iterator_handle iterator, + duckdb_v2_sql_statement_handle *out_statement, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Reads one cell of a vector as an owned value. + * Binds a parsed statement without executing, yielding its schema signature. * - * The total fallback reader. It reads any logical row of any vector representation without flattening — FLAT, CONSTANT, - * DICTIONARY, and the compressed kinds the view getter rejects — and covers every type kind, including those with no - * committed view layout (today VARIANT and GEOMETRY), where it is the only way to reach a cell. + * Preprocesses and binds the statement exactly as execution would, but runs nothing: the result is the statement's + * signature as two schemas, not a query result. The statement is borrowed, not consumed, so it can be bound as often as + * you like and executed later. out_schema receives the output schema (result columns) and is never empty, since a + * non-SELECT reports a single status column: a BIGINT changed-rows count, or a BOOLEAN success. out_parameters, when + * non-NULL, receives the input schema (parameter types, ordered by binding index). Both are owned; destroy them via + * schema_destroy. * - * Each call allocates one owned value, which makes this a single-cell bridge rather than a per-row loop primitive; use - * vector_get_view on hot paths. The row index is logical and bounds-checked against vector_get_size. The returned value - * is caller-owned; destroy it via value_destroy. + * Binding is read-only and does not disturb a live result: it begins no query, claims no cursor, reuses an active + * transaction read-only, and runs alongside a paused stream. It is single-consumer like the stepping functions, so bind + * concurrently only on a second connection. Errors of the bind itself (catalog lookups, type resolution, preprocessing) + * surface here; errors of the planning after the bind (the plan depth limit, a correlated subquery or trigger body that + * decorrelation refuses) may surface only when the statement is executed. A statement that expands into a group (a + * dynamic PIVOT, or statement-expanding DDL such as ALTER ADD COLUMN with a non-constant DEFAULT) has a schema known + * only at execution, and is reported with ERROR_INPUT_METADATA_DEFERRED; execute it instead. + * + * *out_schema and *out_parameters are set to NULL on failure. * * history: * - unstable: v2.0.0 * - * @param vector The vector to read from. - * @param row The logical row index, in [0, vector_get_size). - * @param out_value Receives the owned cell value. + * @param conn The connection supplying the catalog, transaction, and parser configuration. + * @param statement The statement to bind. Borrowed; not consumed. + * @param out_schema Receives the owned output schema (result columns). Destroy via schema_destroy. + * @param out_parameters Optional. When non-NULL, receives the owned input schema (parameter types, ordered by binding + * index). Destroy via schema_destroy. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_get_value(duckdb_v2_vector_handle vector, idx_t row, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_bind(duckdb_v2_connection_handle conn, + duckdb_v2_sql_statement_handle statement, + duckdb_v2_schema_handle *out_schema, + duckdb_v2_schema_handle *out_parameters, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Writes one cell of a FLAT vector from a value. + * Binds a column data collection to the statement under a name. * - * The total fallback writer. It covers every type kind, including those with no committed view layout (today VARIANT - * and GEOMETRY), where it is the only way to write a cell. The value is borrowed and copied in, then cast to the - * vector's type through the non-strict default cast; a cast failure surfaces from the call. A NULL value clears the - * row's validity. + * Makes the collection visible to the statement as a table named `name`, by adding a common table expression to the + * parsed statement. The statement can then be bound, prepared or executed as usual; each execution reads the + * collection's contents at that moment, so a prepared statement can be executed again after the collection was cleared + * and refilled. Supported statement types are SELECT, INSERT, UPDATE, DELETE and MERGE INTO; any other type is rejected + * with `ERROR_INPUT_INVALID`. * - * Requires a FLAT vector: constant, dictionary, and compressed representations are not row-addressable, so call - * vector_flatten first. Each call performs one value write, which makes this a single-cell bridge rather than a per-row - * loop primitive; use the typed mutable-data paths on hot paths. The row index is logical and bounds-checked against - * vector_get_size. + * A name the statement already defines as a common table expression, in its SQL text or by a prior call, is rejected + * with `ERROR_INPUT_INVALID`. The binding shadows any catalog table named `name`, as a common table expression does. + * + * By default the collection's columns are named col1..colN. Pass `column_names` to name them instead; when supplied, + * `column_count` must equal the collection's column count. Pass NULL and 0 for the default names. + * + * The collection is borrowed: the caller keeps ownership and must keep it alive, and must not clear, reset or destroy + * it, for as long as the statement, any statement copied or prepared from it, or any result executing it is live. An + * empty collection is a valid binding. Several collections can be bound under distinct names. * * history: * - unstable: v2.0.0 * - * @param vector The vector to write to. - * @param row The logical row index, in [0, vector_get_size). - * @param value The borrowed value to write. Copied in; cast to the vector's type. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param statement The statement to bind the collection to. Modified in place. + * @param name The non-empty name the statement refers to the collection by. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param collection The collection to bind. Borrowed; the caller keeps ownership and must keep it alive. + * @param column_names Optional. An array of `column_count` names for the collection's columns, in order. Pass NULL for + * col1..colN. + * @param column_names_lengths Byte lengths of the entries in `column_names`; element i is the length of + * `column_names[i]`. May be NULL only when `column_names` is NULL. + * @param column_count The number of names in `column_names`. 0 for the default names; otherwise the collection's column + * count. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_set_value(duckdb_v2_vector_handle vector, idx_t row, - duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_add_collection(duckdb_v2_sql_statement_handle statement, + const char *name, idx_t name_length, + duckdb_v2_column_data_collection_handle collection, + const char *const *column_names, + const idx_t *column_names_lengths, idx_t column_count, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns a mutable pointer to the data of a FLAT or CONSTANT vector. - * - * Any other representation returns ERROR_INPUT_INVALID. The pointer is valid until the owning chunk is destroyed, and - * the vector's storage shape must not change — through a flatten, say — while it is in use. + * Returns the statement's type as classified by the parser. * - * When writing VARCHAR values, the caller must ensure that the bytes contain valid UTF-8. + * This gives the type before the statement-level rewrites that `duckdb_v2_statement_execute()` applies, if any. So a + * PRAGMA reports PRAGMA even where execution rewrites it into a SELECT or a CALL. + * `duckdb_v2_result_get_statement_type()` on the executed result reports the rewritten type of a statement that + * rewrites into one. A statement the parser expands into a group reports MULTI, here and on its result. Its parts are + * not visible here, and statement_bind reports ERROR_INPUT_METADATA_DEFERRED for it. * * history: * - unstable: v2.0.0 * - * @param vector The vector. - * @param out_data Receives a mutable pointer to the data. + * @param statement The statement. + * @param out_type Receives the statement type. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_get_data_mutable(duckdb_v2_vector_handle vector, void **out_data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_sql_statement_get_type(duckdb_v2_sql_statement_handle statement, + DUCKDB_V2_STATEMENT_TYPE *out_type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Forces a vector into FLAT representation, in place. + * Borrows the statement's own SQL text. * - * A no-op for a vector that is already FLAT. For a CONSTANT, DICTIONARY, FSST, SEQUENCE, or SHREDDED vector it - * materializes the per-row data and switches the representation to FLAT. Call it before vector_get_view if you would - * rather not handle CONSTANT and DICTIONARY semantics in the view; it is required for any vector reporting - * VECTOR_TYPE_OTHER. + * The slice of the parsed string that belongs to this statement. A trailing terminator and the whitespace after it are + * included, whitespace and comments before the first token are not. The statement holds its own copy, so the view + * outlives the SQL string passed to parse_sql and the iterator, and stays valid until the statement is destroyed. A + * statement produced by a parser extension that overrides parsing carries whatever text the extension recorded. * * history: * - unstable: v2.0.0 * - * @param vector The vector to flatten. + * @param statement The statement. + * @param out_text Receives a borrowed pointer to the statement text, valid until the statement is destroyed. + * @param out_text_length Receives the length of `*out_text` in bytes. `*out_text` is not guaranteed to be + * null-terminated. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_flatten(duckdb_v2_vector_handle vector, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_sql_statement_get_text(duckdb_v2_sql_statement_handle statement, + const char **out_text, idx_t *out_text_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Casts every row of a vector into another vector, using a factory. - * - * The conversion is the one SQL `CAST` / `TRY_CAST` performs, registered custom casts included, from the type of - * `source` to the type of `target`. It covers as many rows as `source` holds (`duckdb_v2_vector_get_size()`), of any - * representation. `target` is replaced by the result, as `duckdb_v2_vector_reference()` would, taking its size: data - * and views taken from it beforehand do not survive the call, and nothing it held before carries over. In - * CAST_MODE_NORMAL a row that does not convert fails the call with the engine's conversion error, and the contents of - * `target` are unspecified. In CAST_MODE_TRY such rows are NULL in `target` instead and the call succeeds; compare the - * validity of `source` and `target` to find them. `cast_err` then receives the conversion error of one of them, e.g. to - * report why the cast did not convert every row. + * Returns the number of distinct parameters the statement declares. * - * A connection's or callback's factory casts with that client's cast functions and settings (e.g. TimeZone). An - * instance's factory supports only the built-in casts, with default settings. `source` and `target` must be different - * vectors; `target` is typically a vector of a data chunk created by the caller, or the result vector of a callback. + * This counts the parameters the parser found ($1, ?, $name, ...), so it needs no catalog and no binding; only the + * parameter types wait for `duckdb_v2_statement_bind()`. Repeated uses of one parameter count once. * * history: * - unstable: v2.0.0 * - * @param factory The factory supplying the cast functions. - * @param source The vector to cast. Borrowed for the call only. - * @param target The vector to write the cast rows into. Its logical type is the target type. - * @param mode Whether a row that does not convert fails the call, or becomes NULL. - * @param out_converted Optional. Receives whether every row converted. Always true when a CAST_MODE_NORMAL cast - * succeeds. - * @param cast_err Optional. When a CAST_MODE_TRY cast succeeds without converting every row, receives an opaque info - * handle with the conversion error of one row that did not convert, which the caller must destroy via - * error_info_destroy. Otherwise receives NULL. + * @param statement The statement. + * @param out_count Receives the number of distinct parameters. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_cast(duckdb_v2_factory_handle factory, duckdb_v2_vector_handle source, - duckdb_v2_vector_handle target, DUCKDB_V2_CAST_MODE mode, - bool *out_converted, duckdb_v2_error_info_handle *cast_err, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_sql_statement_get_parameter_count(duckdb_v2_sql_statement_handle statement, + idx_t *out_count, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Repoints a vector at another vector's data, without copying. + * Borrows the name of one parameter, in binding order. * - * `vector` takes on the storage of `source`: no data moves, and the two alias the same buffers until one of them is - * reset or re-referenced. Works for any type, including nested types. The source's logical type must equal the - * vector's; a mismatch returns ERROR_INPUT_INVALID. The source's data must outlive every read of `vector`. Use it to - * hand an already-materialized vector straight to an output vector without a per-row copy. + * Parse-time metadata. Positions follow the parameters' binding indices, the order of `duckdb_v2_statement_bind()`'s + * parameter schema, so position i here names field i there. The name is the binding key that + * `duckdb_v2_statement_execute()` accepts: "1", "2", ... for a positional parameter ($1 or ?), the identifier for a + * named one ($name). Positional indices may be gapped ($1 and $3 without $2), in which case the names are "1" and "3" + * at positions 0 and 1. The view is valid until the statement is destroyed. An index outside [0, count) is rejected + * with ERROR_INPUT_OUT_OF_RANGE. * * history: * - unstable: v2.0.0 * - * @param vector The vector to repoint at the source's data. - * @param source The vector whose data to reference. Its logical type must equal the vector's. + * @param statement The statement. + * @param index Zero-based position in binding order. + * @param out_name Receives a borrowed pointer to the parameter name, valid until the statement is destroyed. + * @param out_name_length Receives the length of `*out_name` in bytes. `*out_name` is not guaranteed to be + * null-terminated. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_reference(duckdb_v2_vector_handle vector, duckdb_v2_vector_handle source, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_sql_statement_get_parameter_name(duckdb_v2_sql_statement_handle statement, + idx_t index, const char **out_name, + idx_t *out_name_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Turns the vector into a CONSTANT vector holding the given value. + * Destroys a statement handle. * - * Afterwards the vector holds a single element that applies to every logical row; write it through - * vector_get_data_mutable, which returns a pointer to that one element. For a STRUCT vector the change propagates to - * every child. The value's logical type must equal the vector's; a mismatch returns ERROR_INPUT_INVALID. + * Null-safe: passing nullptr or a slot already set to nullptr is a no-op. statement_execute does not consume a + * statement, so every statement is destroyed here once it is no longer needed. On success the slot is set to nullptr. * * history: * - unstable: v2.0.0 * - * @param vector The vector to make constant. - * @param value The value every row takes. Its logical type must equal the vector's. - * @param count The number of elements in the vector. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param statement The statement to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_make_constant(duckdb_v2_vector_handle vector, - duckdb_v2_value_handle value, idx_t count, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_sql_statement_destroy(duckdb_v2_sql_statement_handle *statement); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets a vector to a SEQUENCE representation. + * Destroys a statement iterator handle. * - * Afterwards the vector represents the arithmetic sequence start, start+increment, start+2*increment, ... over count - * elements. No data pointer is involved; the three parameters describe the sequence completely. + * Null-safe: passing nullptr or a slot already set to nullptr is a no-op. Statements already yielded are independently + * owned and stay valid. On success the slot is set to nullptr. * * history: * - unstable: v2.0.0 * - * @param vector The vector to turn into a sequence. - * @param start The first value of the sequence. - * @param increment The step between consecutive values. - * @param count The number of elements in the sequence. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param iterator The iterator to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_make_sequence(duckdb_v2_vector_handle vector, int64_t start, - int64_t increment, idx_t count, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_iterator_destroy(duckdb_v2_statement_iterator_handle *iterator); #endif +/* --- Struct definitions for sql_statement --- */ + +/* ============================================================================ + * MODULE: value + * ============================================================================ */ + +/* --- Enums for value --- */ + +/* --- Struct forward declarations for value --- */ + +/* --- Types for value --- */ + +/* --- Constants for value --- */ + +/* --- Function pointer typedefs for value --- */ + +/* --- Functions for value --- */ + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets one row of a FLAT vector to NULL, nested children included. - * - * Clears the row's validity and broadcasts the NULL recursively to every descendant element under that row — STRUCT - * fields, and ARRAY elements strided by the array size — maintaining DuckDB's nested NULL invariant: when a STRUCT or - * ARRAY row is NULL, every descendant element under it must be NULL too. LIST children are left untouched, since their - * consumers gate on the list's own validity. Which kinds propagate is normative DuckDB behavior that evolves with the - * type system, which makes this the total NULL write path: equivalent to vector_set_value with a NULL value, without - * the per-call value allocation. + * Destroys a value handle. * - * Requires a FLAT vector: constant, dictionary, and compressed representations are not row-addressable, so call - * vector_flatten first. The row index is logical and bounds-checked against vector_get_size. + * Null-safe: passing nullptr or a slot already set to nullptr is a no-op. On success the slot is set to nullptr. * * history: * - unstable: v2.0.0 * - * @param vector The vector to write to. - * @param row The logical row index, in [0, vector_get_size). - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param value The value to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_set_null(duckdb_v2_vector_handle vector, idx_t row, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_destroy(duckdb_v2_value_handle *value); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns a mutable pointer to the validity mask of a FLAT vector. - * - * Allocates the mask on first use, so the returned pointer is always non-null. Each uint64_t word covers 64 rows: bit N - * of word W is row W*64+N. A set bit means valid; a cleared bit means NULL. + * Returns the value as a BOOLEAN. * - * A raw mask write marks only this vector's rows. Clearing a STRUCT or ARRAY parent bit leaves the descendant elements - * untouched, which violates DuckDB's nested NULL invariant — a NULL STRUCT or ARRAY row requires NULL descendants — so - * set nested rows NULL through vector_set_null instead. When writing nested masks raw anyway, invalidate the child - * masks up front and mark elements valid as the values are written. + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param vector The vector. - * @param out_validity Receives a mutable pointer to the validity mask. + * @param value The value to read. + * @param out Receives the payload as a bool. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_flat_get_validity_mutable(duckdb_v2_vector_handle vector, - uint64_t **out_validity, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_bool(duckdb_v2_value_handle value, bool *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the validity of a CONSTANT vector. + * Returns the value as a UTINYINT. * - * A constant vector holds a single element, so one flag decides whether every row reads as the value or as NULL. + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param vector The constant vector. - * @param validity True to mark the vector's single element valid, false to mark it NULL. + * @param value The value to read. + * @param out Receives the payload as a uint8_t. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_constant_set_valid(duckdb_v2_vector_handle vector, bool validity, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_utinyint(duckdb_v2_value_handle value, uint8_t *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Borrows a string-backed vector's arena for writing. + * Returns the value as a USMALLINT. * - * Allocates the arena on first use. Valid for VARCHAR, BLOB, BIT, and BIGNUM vectors, and returns ERROR_INPUT_INVALID - * for anything else. This call is the single string-ness check, which is why arena_allocate itself performs none. The - * arena is borrowed — never destroy it — and stays valid until the vector is flattened, reallocated, or destroyed. + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param vector The string-backed vector whose arena to borrow. - * @param out_arena Receives the borrowed arena handle. + * @param value The value to read. + * @param out Receives the payload as a uint16_t. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_get_arena(duckdb_v2_vector_handle vector, - duckdb_v2_arena_handle *out_arena, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_usmallint(duckdb_v2_value_handle value, uint16_t *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of child vectors a nested vector exposes. + * Returns the value as a UINTEGER. * - * 1 for LIST, MAP and ARRAY; the field count for STRUCT; member_count + 1 for UNION, the tag plus the members; and 0 - * for any non-nested kind. vector_get_child documents what each index addresses. + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param vector The vector. - * @param out_count Receives the number of child vectors. + * @param value The value to read. + * @param out Receives the payload as a uint32_t. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_get_child_count(duckdb_v2_vector_handle vector, idx_t *out_count, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_uint(duckdb_v2_value_handle value, uint32_t *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Borrows a child vector by index. - * - * What each index addresses, by kind: LIST and ARRAY expose [0] = the elements; MAP [0] = the entries, a STRUCT(key, - * value) whose children are the keys and the values; STRUCT and TUPLE [i] = field i; and UNION [0] = the tag with - * [1..N] = the members. Note that value_get_child diverges on UNION, exposing only the active member. + * Returns the value as a UBIGINT. * - * The returned child is borrowed and lives as long as the owning chunk. Returns ERROR_INPUT_INVALID if the vector has - * no children, or if the index is out of range. + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param vector The nested vector to descend into. - * @param index The child index, in [0, vector_get_child_count). - * @param out_child Receives the borrowed child vector. + * @param value The value to read. + * @param out Receives the payload as a uint64_t. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_vector_get_child(duckdb_v2_vector_handle vector, idx_t index, - duckdb_v2_vector_handle *out_child, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_ubigint(duckdb_v2_value_handle value, uint64_t *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Decodes BIGNUM storage bytes into a caller-supplied magnitude buffer + sign flag. - * - * in_data and in_length are the value's raw storage bytes, exactly as they sit in a vector's bignum payload or as - * value_get_blob reports them for a BIGNUM value. Those bytes are opaque: the storage encoding is not a committed part - * of this API, and this function is the only thing that interprets them. - * - * Writes the big-endian magnitude bytes into out_data and the sign flag into out_is_negative; reconstruct the integer - * as (-1)**out_is_negative * unsigned_big_endian(out_data[0..out_length]). Materializing the bytes is unavoidable, - * since a negative bignum stores its magnitude bit-inverted, but the buffer belongs to the caller: this function never - * allocates and hands back nothing to free. - * - * Pass out_data = NULL to size the buffer without decoding. out_length then receives the exact number of magnitude - * bytes and out_is_negative the sign, and out_capacity is ignored. The size comes straight out of the storage header, - * so the query is O(1) and exact — a size call followed by a decode call never needs a retry loop. - * - * With out_data != NULL, out_capacity must be at least out_length bytes, or the call returns ERROR_INPUT_OBJECT_SIZE - * with out_length set to the required size and out_data left untouched. On success exactly out_length bytes are - * written, and the rest of the buffer is not modified. + * Returns the value as a UHUGEINT. * - * Returns ERROR_INPUT_INVALID if in_data is NULL, or if in_length is too short to hold a bignum header. + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param in_data The value's raw BIGNUM storage bytes. - * @param in_length Size of in_data in bytes. - * @param out_data Caller-owned buffer receiving the magnitude bytes, or NULL to only report the required size in - * out_length. - * @param out_capacity Bytes available in out_data. Ignored when out_data is NULL. - * @param out_length Receives the magnitude size in bytes, written on success and on ERROR_INPUT_OBJECT_SIZE. - * @param out_is_negative Receives true if the value is negative, false otherwise. + * @param value The value to read. + * @param out Receives the payload as a uint128_t. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_bignum_decode(const uint8_t *in_data, idx_t in_length, uint8_t *out_data, - idx_t out_capacity, idx_t *out_length, bool *out_is_negative, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_uhugeint(duckdb_v2_value_handle value, duckdb_v2_uhugeint_t *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Encodes a magnitude + sign flag into BIGNUM storage bytes. - * - * The inverse of bignum_decode. in_data and in_length are the big-endian magnitude bytes and is_negative the sign; - * out_data receives the raw storage bytes for that integer, in the form a BIGNUM vector payload expects. Those bytes - * are opaque: the storage encoding is not a committed part of this API. - * - * Pass out_data = NULL to size the buffer without encoding. out_length then receives the exact number of storage bytes, - * and out_capacity is ignored. The size is a fixed function of in_length, so the query is O(1) and exact. - * - * With out_data != NULL, out_capacity must be at least out_length bytes, or the call returns ERROR_INPUT_OBJECT_SIZE - * with out_length set to the required size and out_data left untouched. On success exactly out_length bytes are - * written, and the rest of the buffer is not modified. + * Returns the value as a TINYINT. * - * The magnitude must be canonical, matching what bignum_decode produces: in_length >= 1 with no leading zero bytes, so - * the value zero is the single byte 0x00 with is_negative = false. A NULL in_data, an in_length of 0, a leading zero - * byte, or a negative zero returns ERROR_INPUT_INVALID; a magnitude beyond the maximum bignum width returns - * ERROR_INPUT_OUT_OF_RANGE. + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param in_data Big-endian magnitude bytes, with no leading zero bytes. - * @param in_length Size of in_data in bytes. Must be >= 1. - * @param is_negative True to encode a negative value. - * @param out_data Caller-owned buffer receiving the storage bytes, or NULL to only report the required size in - * out_length. - * @param out_capacity Bytes available in out_data. Ignored when out_data is NULL. - * @param out_length Receives the storage size in bytes — written on success and on ERROR_INPUT_OBJECT_SIZE. + * @param value The value to read. + * @param out Receives the payload as an int8_t. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_bignum_encode(const uint8_t *in_data, idx_t in_length, bool is_negative, - uint8_t *out_data, idx_t out_capacity, idx_t *out_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_tinyint(duckdb_v2_value_handle value, int8_t *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Validates all `text_length` bytes of `text` as UTF-8, including bytes after embedded NUL characters. - * - * Returns ERROR_INPUT_INVALID if any of: - * - text is NULL and text_length is nonzero. - * - The input contains malformed UTF-8. + * Returns the value as a SMALLINT. * - * A NULL text with a zero length is valid. + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param text The bytes to validate. - * @param text_length The length of `text` in bytes. `text` need not be null-terminated and may be NULL only when this - * is 0. + * @param value The value to read. + * @param out Receives the payload as an int16_t. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_validate_utf8(const char *text, idx_t text_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_smallint(duckdb_v2_value_handle value, int16_t *out, + duckdb_v2_error_info_handle *err); #endif -/* --- Struct definitions for vector --- */ - -struct duckdb_v2_vector_view { - const void *data; - const uint64_t *validity; - const duckdb_v2_sel_t *sel; - idx_t count; -}; - -struct duckdb_v2_list_entry { - idx_t offset; - idx_t length; -}; - -struct duckdb_v2_hugeint_t { - uint64_t lower; - int64_t upper; -}; - -struct duckdb_v2_uhugeint_t { - uint64_t lower; - uint64_t upper; -}; - -struct duckdb_v2_interval_t { - int32_t months; - int32_t days; - int64_t micros; -}; - -/* ============================================================================ - * MODULE: prepared_statement - * ============================================================================ */ - -/* --- Enums for prepared_statement --- */ - -/* --- Struct forward declarations for prepared_statement --- */ - -/* --- Types for prepared_statement --- */ - +#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * An owned handle to a statement bound and planned once, executable repeatedly via - * `duckdb_v2_prepared_statement_execute()`. Construct with `duckdb_v2_prepared_statement_create()` and destroy with - * `duckdb_v2_prepared_statement_destroy()`. It keeps its connection's session alive, so it stays usable across - * executions and even after the connection is disconnected. - */ -typedef struct _duckdb_v2_prepared_statement { - void *internal_ptr; -} * duckdb_v2_prepared_statement_handle; - -/* --- Constants for prepared_statement --- */ - -/* --- Function pointer typedefs for prepared_statement --- */ - -/* --- Functions for prepared_statement --- */ + * Returns the value as an INTEGER. + * + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * + * history: + * - unstable: v2.0.0 + * + * @param value The value to read. + * @param out Receives the payload as an int32_t. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_int(duckdb_v2_value_handle value, int32_t *out, + duckdb_v2_error_info_handle *err); +#endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Prepares a parsed statement into a reusable handle. Non-consuming. + * Returns the value as a BIGINT. * - * Copies the statement's AST, then binds and plans it once. Binder and catalog errors surface here, exactly as they - * would from `duckdb_v2_statement_execute()`. The statement is borrowed rather than consumed, since a copy is what gets - * prepared, so it can be prepared again or executed directly; the caller destroys it with - * `duckdb_v2_sql_statement_destroy()`. + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * - * By default this succeeds for any preparable statement, whether or not its plan will be reused; ask - * `duckdb_v2_prepared_statement_reuses_plan()` which one you got. Setting `require_cacheable` instead fails with - * `ERROR_INPUT_INVALID` when the plan would not be reused, so a caller who wants the handle only for the speedup finds - * out here rather than after silently taking the slow path. + * history: + * - unstable: v2.0.0 * - * A statement that DuckDB expands into several, such as a dynamic PIVOT, is kept as written and expanded again at each - * execution, in the transaction state of that execution. It runs nothing here, its plan is never reused, and its - * result's metadata is deferred as for `duckdb_v2_statement_execute()`. Parameters on such a statement are refused with - * `ERROR_INPUT_INVALID`. + * @param value The value to read. + * @param out Receives the payload as an int64_t. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_bigint(duckdb_v2_value_handle value, int64_t *out, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Returns the value as a HUGEINT. * - * Refuses with `ERROR_RESOURCE_IN_USE` while a statement on the connection is still running. Drain, destroy, or - * interrupt that result first, or prepare on another connection. `*out_prepared` is set to NULL on failure. + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param conn The connection supplying the catalog, transaction, and parser state. The prepared statement belongs to - * it. - * @param statement The statement to prepare. Borrowed and copied, not consumed; destroy it with - * `duckdb_v2_sql_statement_destroy()`. - * @param require_cacheable When true, fail with `ERROR_INPUT_INVALID` unless the prepared plan will be reused across - * executions, as `duckdb_v2_prepared_statement_reuses_plan()` would report it. - * @param out_prepared On success, receives the new prepared statement. Owned by the caller; destroy via - * `duckdb_v2_prepared_statement_destroy()`. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out Receives the payload as an int128_t. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_prepared_statement_create(duckdb_v2_connection_handle conn, - duckdb_v2_sql_statement_handle statement, - bool require_cacheable, - duckdb_v2_prepared_statement_handle *out_prepared, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_hugeint(duckdb_v2_value_handle value, duckdb_v2_hugeint_t *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Executes a prepared statement, streaming its result. Non-consuming. + * Returns the value as a VARCHAR. * - * Returns a result without executing anything: execution happens incrementally as the result is stepped or drained, - * exactly as with `duckdb_v2_statement_execute()`. The handle returned is an ordinary result, with identical behaviour - * throughout -- streaming, draining, the changed-row count of a DML statement, the output schema, the statement type, - * and the result type. + * The string is borrowed from the value and stays valid until the value is destroyed. That borrow is why this getter + * does not convert: a converted copy would not outlive the call. A value of any other type id, and a NULL value, return + * ERROR_INPUT_INVALID. * - * `parameter_values` binds the statement's parameters as constants for this execution. Binding is positional by default - * ($1 = element 0); supply `parameter_names` to bind by name instead, where a non-empty entry binds its value to that - * named parameter ($name, matched case-insensitively) and an empty entry stays positional. Pass NULL for both arrays, - * or a count of 0, for a statement without parameters. Both arrays are borrowed and copied in, so the caller still owns - * and destroys them. A key set that does not match the statement's parameters is rejected with `ERROR_INPUT_INVALID`, - * with one exception: a named parameter left without a value reads the session variable of the same name (`SET - * VARIABLE`) when one exists. + * history: + * - unstable: v2.0.0 * - * Not consumed: execute the same handle again, with the same values or different ones, as often as you like. Values are - * bound per execution and nothing carries over between them. A catalog change since the statement was prepared, or a - * parameter type that differs from the one the cached plan assumed, triggers a re-bind that is invisible apart from its - * cost. + * @param value The value to read. + * @param out Receives the payload as a UTF-8 string. The returned string is borrowed and valid until the value handle + * is destroyed. + * @param out_length Receives the length of `*out` in bytes. `*out` is not guaranteed to be null-terminated. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_varchar(duckdb_v2_value_handle value, const char **out, + idx_t *out_length, duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Returns the value as a byte string: a BLOB, or the storage bytes of a BIT, a BIGNUM, or a DECIMAL wider than 38 + * digits (the BIGNUM storage of its unscaled value, for bignum_decode). * - * Refuses with `ERROR_RESOURCE_IN_USE` while a statement on the connection is still running; drain, destroy, or - * interrupt that result first, or execute on another connection. A failed execution, at any stage, leaves the prepared - * statement usable. `*out_result` is set to NULL on failure. + * The string is borrowed from the value and stays valid until the value is destroyed. That borrow is why this getter + * does not convert: a converted copy would not outlive the call. A value of any other type id, and a NULL value, return + * ERROR_INPUT_INVALID. * * history: * - unstable: v2.0.0 * - * @param prepared The prepared statement to execute. Borrowed; not consumed. - * @param parameter_names Optional. An array of `parameter_count` parameter names; a non-empty entry binds its value to - * the named parameter ($name, case-insensitive), an empty entry (NULL or zero length) keeps it positional ($1 = element - * 0). Pass NULL to bind everything positionally. - * @param parameter_names_lengths Byte lengths of the entries in `parameter_names`; element i is the length of - * `parameter_names[i]`. May be NULL only when `parameter_names` is NULL. - * @param parameter_values Optional. An array of `parameter_count` values. Each binds by name when `parameter_names` - * supplies one, and positionally ($1 = element 0) otherwise. Borrowed and copied in. Pass NULL for a statement without - * parameters. - * @param parameter_count The number of entries in `parameter_names` and `parameter_values`. Pass 0 for a statement - * without parameters. - * @param out_result On success, receives the new result. Owned by the caller; destroy via `duckdb_v2_result_destroy()`. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out Receives the payload as a byte string. The returned string is borrowed and valid until the value handle is + * destroyed. + * @param out_length Receives the length of `*out` in bytes. `*out` is not guaranteed to be null-terminated. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_prepared_statement_execute( - duckdb_v2_prepared_statement_handle prepared, const char *const *parameter_names, - const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, - duckdb_v2_result_handle *out_result, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_blob(duckdb_v2_value_handle value, const char **out, idx_t *out_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Reports whether the prepared statement reuses its compiled plan across executions. - * - * True when executions reuse the plan built at prepare time, provided the supplied values match the planned parameter - * types and nothing the plan depends on has changed; false when the statement re-binds on every execution, making it no - * faster than `duckdb_v2_statement_execute()`. A plan is reused only when all parameter types were resolved at prepare - * time and the plan is cacheable: `SELECT 42` reuses, `SELECT $1::INTEGER + 1` reuses, a statement reading a base table - * does not (it re-binds so a catalog change is picked up), and `SELECT $1 + $2` does not (the types are unknown until - * values arrive). + * Returns the value as a FLOAT. * - * A static property of the built plan, fixed when the statement was prepared and independent of the values later passed - * to `duckdb_v2_prepared_statement_execute()`. + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param prepared The prepared statement to inspect. - * @param out_reuses Receives true when the compiled plan is reused across executions, false when the statement re-binds - * each time. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out Receives the payload as a float. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_prepared_statement_reuses_plan(duckdb_v2_prepared_statement_handle prepared, - bool *out_reuses, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_float(duckdb_v2_value_handle value, float *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys a prepared statement. + * Returns the value as a DOUBLE. * - * Null-safe: passing NULL, or a slot already set to NULL, is a no-op. A result produced by - * `duckdb_v2_prepared_statement_execute()` is independently owned and keeps the session alive itself, so the prepared - * statement may be destroyed while results made from it are still live. On success the slot is set to NULL. + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param prepared The prepared statement to destroy. + * @param value The value to read. + * @param out Receives the payload as a double. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_prepared_statement_destroy(duckdb_v2_prepared_statement_handle *prepared); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_double(duckdb_v2_value_handle value, double *out, + duckdb_v2_error_info_handle *err); #endif -/* --- Struct definitions for prepared_statement --- */ - -/* ============================================================================ - * MODULE: query_result - * ============================================================================ */ - -/* --- Enums for query_result --- */ - +#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Shape of a query result. QUERY_RESULT carries rows and columns; CHANGED_ROWS carries an affected row count, as an - * INSERT, UPDATE, or DELETE without RETURNING produces; NOTHING covers DDL and other statements with no row output. + * Returns the value as a DATE. + * + * The payload is days since 1970-01-01, the same unit a vector of this type exposes. + * + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * + * history: + * - unstable: v2.0.0 + * + * @param value The value to read. + * @param out Receives the payload. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR */ -typedef enum DUCKDB_V2_RESULT_TYPE { - DUCKDB_V2_RESULT_TYPE_QUERY_RESULT = 0, - DUCKDB_V2_RESULT_TYPE_CHANGED_ROWS = 1, - DUCKDB_V2_RESULT_TYPE_NOTHING = 2, - DUCKDB_V2_RESULT_TYPE_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_RESULT_TYPE; +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_date(duckdb_v2_value_handle value, int32_t *out, + duckdb_v2_error_info_handle *err); +#endif +#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Outcome of a result_step call. WAITING is the 0-value, so a zero-initialized out-param reads as "no work product yet" - * rather than CHUNK, the same convention VECTOR_TYPE_OTHER follows. The four states are the ones a consumer acts on; - * they are deliberately not a projection of any internal enum. + * Returns the value as a TIME. + * + * The payload is microseconds since midnight, the same unit a vector of this type exposes. + * + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * + * history: + * - unstable: v2.0.0 + * + * @param value The value to read. + * @param out Receives the payload. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR */ -typedef enum DUCKDB_V2_RESULT_STEP_STATUS { - //! No chunk yet; step again, or block in result_wait. - DUCKDB_V2_RESULT_STEP_STATUS_WAITING = 0, - - //! A caller-owned chunk was written to *out_chunk, or an array to *out_array. - DUCKDB_V2_RESULT_STEP_STATUS_CHUNK = 1, - - //! Stream exhausted. Sticky. - DUCKDB_V2_RESULT_STEP_STATUS_FINISHED = 2, - - //! Query was interrupted. Sticky. - DUCKDB_V2_RESULT_STEP_STATUS_CANCELLED = 3, - DUCKDB_V2_RESULT_STEP_STATUS_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_RESULT_STEP_STATUS; - -/* --- Struct forward declarations for query_result --- */ - -/* --- Types for query_result --- */ - -/* --- Constants for query_result --- */ - -/* --- Function pointer typedefs for query_result --- */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_time(duckdb_v2_value_handle value, int64_t *out, + duckdb_v2_error_info_handle *err); +#endif -/* --- Functions for query_result --- */ +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Returns the value as a TIME_NS. + * + * The payload is nanoseconds since midnight, the same unit a vector of this type exposes. + * + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * + * history: + * - unstable: v2.0.0 + * + * @param value The value to read. + * @param out Receives the payload. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_time_ns(duckdb_v2_value_handle value, int64_t *out, + duckdb_v2_error_info_handle *err); +#endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Executes a parsed statement on the connection, streaming its result. Non-consuming. - * - * Takes a statement produced by the sql_statement module (parse_sql / statement_iterator_next), preprocesses and - * prepares it, and returns a result handle without executing anything: execution happens incrementally as the result is - * stepped (result_step) or drained (result_fetch_chunk). This call reports only the errors detectable at prepare time — - * binder, catalog, pragma preprocessing — while errors raised during execution surface from the stepping functions. + * Returns the value as a TIME_TZ. * - * The statement is borrowed, not consumed, since a copy is what executes. It can be executed again, for example with a - * different set of values, and the caller destroys it with sql_statement_destroy. + * The payload packs the time of day and the UTC offset into one integer, in the committed layout: micros in the high 40 + * bits, a biased offset in the low 24. The same form a vector of this type exposes. * - * parameter_values binds the statement's parameters as constants for this execution. Binding is positional by default: - * the i-th value binds $(i+1), matching SQL's own convention, so dense $1..$N and ? placeholders work directly. Supply - * parameter_names to bind by name instead — a non-empty name binds its value to that named parameter ($name, matched - * case-insensitively), while an empty entry leaves that value positional. The parameter schema from statement_bind - * lists the names to use. Both arrays are borrowed and copied in; the caller still owns and destroys them. Pass NULL - * for both, or a count of 0, for an unparameterized statement. A key set that does not match the statement's parameters - * — names for a positional statement, or the reverse — is rejected with ERROR_INPUT_INVALID, and named and positional - * parameters cannot be mixed within one statement. Parameters and statement expansion are mutually exclusive: passing - * values for a statement that preprocesses into a group is rejected with ERROR_INPUT_INVALID. + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * - * DuckDB can expand one statement into a group: a dynamic PIVOT, or statement-expanding DDL such as ALTER ... ADD - * COLUMN with a non-constant DEFAULT. The group executes as one result through the same steps, and the stream surfaces - * the rows of the first row-producing statement of the group. A row-producing statement followed by another cannot be - * served as a single result and reports ERROR_QUERY_NOT_IMPLEMENTED; no known expansion produces one. + * history: + * - unstable: v2.0.0 * - * One running statement per connection: this refuses with ERROR_RESOURCE_IN_USE while a statement on the connection is - * still running. Drain, destroy, or interrupt that result first, or open another connection. + * @param value The value to read. + * @param out Receives the payload. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_time_tz(duckdb_v2_value_handle value, uint64_t *out, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Returns the value as a TIMESTAMP. * - * Schema metadata — result type, statement type, column count, names, logical types — is available on the returned - * handle immediately, before the first step. + * The payload is microseconds since 1970-01-01, the same unit a vector of this type exposes. * - * *out_result is set to nullptr on failure. + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param conn The connection on which to execute the statement. - * @param statement The statement to execute. Borrowed and copied; not consumed. Destroy it with sql_statement_destroy. - * @param parameter_names Optional. An array of parameter_count parameter names; a non-empty entry binds its value to - * the named parameter ($name, case-insensitive), an empty entry (NULL or zero length) keeps it positional ($1 = element - * 0). Pass NULL for all-positional binding. Named and positional parameters cannot be mixed within one statement. - * @param parameter_names_lengths Byte lengths of the entries in `parameter_names`; element i is the length of - * `parameter_names[i]`. May be NULL only when `parameter_names` is NULL. - * @param parameter_values Optional. An array of parameter_count value handles. Each binds by name when parameter_names - * supplies one, otherwise positionally ($1 = element 0). Borrowed (copied in). Pass NULL for an unparameterized - * statement. - * @param parameter_count The number of parameters in parameter_names and parameter_values. Pass 0 for an - * unparameterized statement. - * @param out_result Receives the new result handle. + * @param value The value to read. + * @param out Receives the payload. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_execute( - duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, const char *const *parameter_names, - const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, - duckdb_v2_result_handle *out_result, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_timestamp(duckdb_v2_value_handle value, int64_t *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys a result handle. + * Returns the value as a TIMESTAMP_SEC. * - * Null-safe: passing nullptr or a slot already set to nullptr is a no-op. Frees the memory the result owns and releases - * the connection for its next query. Safe at any point in the stream's life. Destroying a result before its statement - * ended (drained, or stepped to FINISHED) aborts the statement. On autocommit, its writes are rolled back. Inside a - * transaction, a statement that may write invalidates the transaction, and a read-only statement just stops. Chunks - * already fetched are caller-owned and stay valid. On success the slot is set to nullptr. + * The payload is seconds since 1970-01-01, the same unit a vector of this type exposes. + * + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param result The result to destroy. + * @param value The value to read. + * @param out Receives the payload. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_destroy(duckdb_v2_result_handle *result); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_timestamp_sec(duckdb_v2_value_handle value, int64_t *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Runs one bounded unit of query execution and returns without blocking. - * - * The streaming primitive: a step does a bounded amount of execution work, mostly without blocking, and returns control - * to the caller, so an event loop stays responsive and can interleave other work between steps. The conveniences — - * result_wait, result_fetch_chunk, result_drain — block, and are for synchronous callers. out_status reports the - * outcome: + * Returns the value as a TIMESTAMP_MS. * - * - CHUNK: *out_chunk receives a caller-owned chunk (destroy via data_chunk_destroy). Written only for this status; - * nullptr otherwise. - * - WAITING: no chunk yet, but work was done. Transient: keep stepping and it resolves to CHUNK, FINISHED, CANCELLED, - * or an error. Block in result_wait rather than busy-stepping. - * - FINISHED: stream exhausted. Sticky. - * - CANCELLED: query interrupted via connection_interrupt. Sticky. Cancellation is a status here, not an error; - * result_fetch_chunk, which has no status out-param, reports it as ERROR_RUNTIME_INTERRUPT. + * The payload is milliseconds since 1970-01-01, the same unit a vector of this type exposes. * - * Execution errors come back as the return code plus err, never as a status; out_status is then unspecified and - * *out_chunk is nullptr. Errors are sticky, so later steps report the same code. + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param result The result to step. - * @param out_chunk Receives an owned chunk if *out_status is CHUNK; set to nullptr otherwise. - * @param out_status Receives the step status. + * @param value The value to read. + * @param out Receives the payload. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_step(duckdb_v2_result_handle result, - duckdb_v2_data_chunk_handle *out_chunk, - DUCKDB_V2_RESULT_STEP_STATUS *out_status, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_timestamp_ms(duckdb_v2_value_handle value, int64_t *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Blocks until the next chunk is available and returns it. - * - * A convenience over result_step: blocks until a chunk is produced or the stream ends. On success *out_chunk receives a - * caller-owned chunk (destroy via data_chunk_destroy), or nullptr at end-of-stream. End-of-stream is sticky, so later - * calls keep succeeding with *out_chunk set to nullptr. + * Returns the value as a TIMESTAMP_NS. * - * An interrupted query returns ERROR_RUNTIME_INTERRUPT — the same event result_step reports as status CANCELLED, - * carried on the error channel because this function has no status out-param. + * The payload is nanoseconds since 1970-01-01, the same unit a vector of this type exposes. * - * On failure *out_chunk is set to nullptr. Errors are sticky, so later calls report the same code. + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param result The result to fetch from. - * @param out_chunk Receives an owned chunk, or nullptr at end-of-stream. + * @param value The value to read. + * @param out Receives the payload. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_fetch_chunk(duckdb_v2_result_handle result, - duckdb_v2_data_chunk_handle *out_chunk, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_timestamp_ns(duckdb_v2_value_handle value, int64_t *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Blocks until result_step can make progress. + * Returns the value as a TIMESTAMP_TZ. * - * A convenience over result_step: blocks until a step is worth issuing again, that is, until a unit of execution work - * can run on the calling thread. Never produces or consumes chunks. Waiting on a terminal result — FINISHED, CANCELLED, - * or a sticky error — returns immediately; it is a no-op, never an error. + * The payload is microseconds since 1970-01-01, in UTC, the same unit a vector of this type exposes. + * + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param result The result to wait on. + * @param value The value to read. + * @param out Receives the payload. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_wait(duckdb_v2_result_handle result, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_timestamp_tz(duckdb_v2_value_handle value, int64_t *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Renders the result as a box table, consuming it. + * Returns the value as a TIMESTAMP_TZ_NS. * - * Drains the result into a column data collection and renders it with the same renderer the DuckDB CLI uses, so every - * client displays results identically without reimplementing table formatting. The result is consumed by transfer: the - * slot is set to NULL on success and on failure alike. A partially consumed result is accepted, and the remainder is - * what gets rendered. + * The payload is nanoseconds since 1970-01-01, in UTC, the same unit a vector of this type exposes. * - * The whole remaining result materializes in memory before rendering. max_rows bounds what is DISPLAYED, not what is - * read, so with limit 0 the footer's row count is exact. A caller who cannot afford full materialization should bound - * the query itself (e.g. LIMIT n) and pass n as limit; the footer then renders "? rows" whenever the result fills that - * bound, since the true total is unknown at that point. + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * - * Zero selects the renderer default for each sizing knob: max_rows 20, max_width the probed terminal width or 80 when - * that is unavailable, max_col_width 20. An empty null_value renders NULL cells as the default "NULL" text. + * history: + * - unstable: v2.0.0 * - * The rendered text goes to sink rather than being returned: a box can be large, and this way nothing allocates a - * buffer the caller has to free. The sink is called exactly once with the whole box, so its view carries the full - * length — write it straight to a stream, or copy it into your own string. sink must not be NULL. + * @param value The value to read. + * @param out Receives the payload. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_timestamp_tz_ns(duckdb_v2_value_handle value, int64_t *out, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Returns the value as an INTERVAL. + * + * The payload is the (months, days, micros) triple, the same unit a vector of this type exposes. + * + * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. + * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. * * history: * - unstable: v2.0.0 * - * @param result The result to render; consumed and set to NULL. Left intact only when the call rejects null arguments. - * @param max_rows Maximum rows displayed; 0 selects the renderer default (20). - * @param max_width Maximum total width in characters; 0 selects the renderer default. - * @param max_col_width Maximum width of one column; 0 selects the renderer default (20). - * @param null_value Text rendered for NULL cells; empty selects "NULL". - * @param null_value_length The length of `null_value` in bytes. `null_value` need not be null-terminated and may be - * NULL only when this is 0. - * @param render_mode 0 renders rows (records down the page); 1 renders columns; other values are rejected with - * INVALID_INPUT. - * @param limit The row limit the caller applied to the query before rendering; 0 means none. When the materialized - * result holds exactly this many rows the true total is unknown, so the footer renders "? rows" instead of an exact - * count. - * @param sink Receives the whole rendered box in a single call. Borrowed for the duration of that call; see text_sink - * for the full contract. - * @param user_data Opaque pointer passed through to sink untouched. May be NULL. + * @param value The value to read. + * @param out Receives the payload. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_render_box(duckdb_v2_result_handle *result, idx_t max_rows, - idx_t max_width, idx_t max_col_width, const char *null_value, - idx_t null_value_length, idx_t render_mode, idx_t limit, - duckdb_v2_text_sink_fn sink, void *user_data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_interval(duckdb_v2_value_handle value, duckdb_v2_interval_t *out, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Runs the result to completion and reports the changed-row count. + * Returns the value as a UUID, in its internal 128-bit form. * - * A convenience over result_step: blocks until the stream is fully consumed, so every side effect is applied. Rows of a - * row-producing result are discarded. For a CHANGED_ROWS result *out_rows_changed receives the affected row count; for - * every other result type, and for a stream whose Count chunk was already consumed, it receives 0. + * The dual of value_create_uuid: the storage form a vector element holds, with the high bit flipped so the integer + * sorts, rather than the canonical byte order. A value of any other type id, and a NULL value, return + * ERROR_INPUT_INVALID. * - * The result type (result_get_result_type) is prepare-time metadata, so a caller can choose between consuming rows and - * draining without inspecting the SQL. Draining an already FINISHED result succeeds. Cancellation surfaces as - * ERROR_RUNTIME_INTERRUPT; errors are sticky, and on failure *out_rows_changed is unspecified. + * history: + * - unstable: v2.0.0 + * + * @param value The value to read. + * @param out Receives the internal 128-bit storage form. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_uuid(duckdb_v2_value_handle value, duckdb_v2_hugeint_t *out, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Returns the value as a DECIMAL: its backing integer plus the width and scale of its type. + * + * The integer is the value scaled by 10^scale — the dual of value_create_decimal — widened to 128 bits from whatever + * storage tier the width selects. The integer getters convert, so a DECIMAL read through value_get_bigint is its + * numeric value with the fraction dropped; this one always reports storage instead, together with the scale needed to + * interpret it. A value of any other type id, and a NULL value, return ERROR_INPUT_INVALID. A DECIMAL wider than 38 + * digits (stored as BIGNUM) is reported the same way, whatever its width, as long as its backing integer fits in 128 + * bits. Beyond that the call fails, and the exact backing integer is read without a conversion: value_get_blob hands + * back the BIGNUM storage bytes, bignum_decode turns them into a sign and a big-endian magnitude, and the width and + * scale come from the value's logical type (value_get_logical_type and logical_type_get_param). * * history: * - unstable: v2.0.0 * - * @param result The result to drain. - * @param out_rows_changed Receives the affected row count for CHANGED_ROWS results, 0 otherwise. + * @param value The value to read. + * @param out Receives the backing integer, scaled by 10^scale. + * @param out_width Receives the total digit count of the value's type. + * @param out_scale Receives the digits after the decimal point. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_drain(duckdb_v2_result_handle result, idx_t *out_rows_changed, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_decimal(duckdb_v2_value_handle value, duckdb_v2_hugeint_t *out, + uint32_t *out_width, uint32_t *out_scale, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the shape of the result: query, changed rows, or nothing. - * - * QUERY_RESULT for statements that produce rows (SELECT, RETURNING, EXPLAIN), CHANGED_ROWS for an INSERT, UPDATE, or - * DELETE without RETURNING, NOTHING for DDL and other statements with no row output. + * Unwraps the logical type carried by a TYPE value. * - * Prepare-time metadata: available from statement_execute on, except for a statement that expands into a group, where - * it fails with ERROR_INPUT_METADATA_DEFERRED until stepping has bound the row-producing statement, or the group ended - * without one. + * Returns ERROR_INPUT_INVALID unless the value is a non-NULL TYPE value. The returned logical type is caller-owned and + * must be destroyed via logical_type_destroy. * * history: * - unstable: v2.0.0 * - * @param result The result. - * @param out_type Receives the result shape. + * @param value The value to read. + * @param out_type Receives the owned logical type. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_get_result_type(duckdb_v2_result_handle result, - DUCKDB_V2_RESULT_TYPE *out_type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_type(duckdb_v2_value_handle value, + duckdb_v2_logical_type_handle *out_type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the SQL statement type that produced the result. + * Creates a NULL value of the given logical type. * - * Prepare-time metadata: available from statement_execute on. A statement that expands into a group reports its type as - * written: MULTI, or PRAGMA for a pragma such as IMPORT DATABASE. + * The logical type is borrowed and copied into the value, so the caller can destroy it independently. * * history: * - unstable: v2.0.0 * - * @param result The result. - * @param out_type Receives the statement type. + * @param factory The factory to create with. + * @param type The borrowed logical type to attach to the NULL value. + * @param out_value Receives the new NULL value. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_get_statement_type(duckdb_v2_result_handle result, - DUCKDB_V2_STATEMENT_TYPE *out_type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_null(duckdb_v2_factory_handle factory, + duckdb_v2_logical_type_handle type, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the result's output schema as a single schema handle. - * - * Builds an owned schema of the result's column names and types into *out_schema; destroy it via schema_destroy. - * Prepare-time metadata, available before the first step, or for an expanding statement once stepping has bound the - * row-producing statement (before that it fails with ERROR_INPUT_METADATA_DEFERRED). Never empty: a non-SELECT reports - * a single status column, either a BIGINT changed-rows count or a BOOLEAN success. - * - * This schema is the authoritative source for the column types of the chunks the result produces; vectors do not carry - * their own type. + * Creates a BOOLEAN value from a bool. * - * *out_schema is set to NULL on failure. + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param result The result. - * @param out_schema Receives the owned output schema. Destroy via schema_destroy. + * @param factory The factory to create with. + * @param in_value The bool to wrap. + * @param out_value Receives the new BOOLEAN value. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_get_schema(duckdb_v2_result_handle result, - duckdb_v2_schema_handle *out_schema, - duckdb_v2_error_info_handle *err); -#endif - -/* --- Struct definitions for query_result --- */ - -/* ============================================================================ - * MODULE: table - * ============================================================================ */ - -/* --- Enums for table --- */ - -/*! - * Whether a table function's scan is partitioned by a given set of columns, and how. Reported by - * `duckdb_v2_table_function_set_partitioning_callback()` via - * `duckdb_v2_table_function_partitioning_set_partition_info()`. - */ -typedef enum DUCKDB_V2_TABLE_PARTITION_INFO { - //! The scan is not known to be partitioned by the requested columns. - DUCKDB_V2_TABLE_PARTITION_INFO_NOT_PARTITIONED = 0, - - //! Each partition the scan produces carries exactly one distinct value for the requested columns. - DUCKDB_V2_TABLE_PARTITION_INFO_SINGLE_VALUE_PARTITIONS = 1, - - //! The partitions the scan produces overlap only at their boundaries. - DUCKDB_V2_TABLE_PARTITION_INFO_OVERLAPPING_PARTITIONS = 2, - - //! The partitions the scan produces are disjoint ranges. - DUCKDB_V2_TABLE_PARTITION_INFO_DISJOINT_PARTITIONS = 3, - DUCKDB_V2_TABLE_PARTITION_INFO_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_TABLE_PARTITION_INFO; - -/*! - * A column a table function can produce next to the columns it declares in bind. A query asks for it by name, but it is - * not part of the function's result columns. Declared with `duckdb_v2_table_function_add_virtual_column()`. In the - * column lists of the scan (e.g. `duckdb_v2_data_source_exec_get_column_index()`), a virtual column is identified by - * 2^63 plus its value in this enum. - */ -typedef enum DUCKDB_V2_TABLE_VIRTUAL_COLUMN { - /*! - * `file_row_number`, a BIGINT holding the position of the row within the file it was read from, counting from 0. A - * function that reads a single file produces it when it is wrapped in a multi-file function (see - * `duckdb_v2_multi_file_function_create()`), which is where the name of the file comes from. - */ - DUCKDB_V2_TABLE_VIRTUAL_COLUMN_FILE_ROW_NUMBER = 0, - DUCKDB_V2_TABLE_VIRTUAL_COLUMN_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_TABLE_VIRTUAL_COLUMN; - -/*! - * Where the input of a table function's operator comes from: what the rows of the input chunks the operator receives - * are. Chosen with `duckdb_v2_table_function_set_operator()`. - */ -typedef enum DUCKDB_V2_TABLE_OPERATOR_INPUT { - /*! - * The positional arguments of a call of the function are the columns of the operator's input, one row per set of - * arguments. Called with constant arguments, e.g. `f(1, 'a')`, the operator receives a single input row. Called - * with arguments that reference the columns of a table that precedes the call in the `FROM` clause, e.g. `FROM t, - * f(t.x)` (an implicit `LATERAL` join), it receives one input row per row of that table, one at a time, and every - * row it produces is joined to the row of `t` it was produced for. - */ - DUCKDB_V2_TABLE_OPERATOR_INPUT_ARGUMENTS = 0, - - /*! - * The function takes a table as its first argument, written as a subquery, e.g. `f((SELECT * FROM t))`, and the - * operator receives the rows of that table as its input, chunk by chunk, possibly on several threads. The columns - * of its input are the columns of the table. - */ - DUCKDB_V2_TABLE_OPERATOR_INPUT_TABLE = 1, - DUCKDB_V2_TABLE_OPERATOR_INPUT_MAX_ENUM = 0x7FFFFFFF, -} DUCKDB_V2_TABLE_OPERATOR_INPUT; - -/* --- Struct forward declarations for table --- */ - -/* --- Types for table --- */ - -/*! - * An owned opaque handle to a custom table function being built. Created with `duckdb_v2_table_function_create()`, - * configured with the setter functions (e.g. `duckdb_v2_table_function_set_name()`, - * `duckdb_v2_table_function_set_data_source()`, etc.) and the signature obtained via - * `duckdb_v2_table_function_get_signature()`, made available with `duckdb_v2_connection_register_table_function()` or - * `duckdb_v2_extension_register_table_function()`, and destroyed with `duckdb_v2_table_function_destroy()`. - */ -typedef struct _duckdb_v2_table_function { - void *internal_ptr; -} * duckdb_v2_table_function_handle; - -/*! - * A borrowed opaque handle to the result of a table function's "bind" phase. The "bind" callback receives this handle - * next to a `duckdb_v2_function_bind_info_handle`, which gives access to the arguments, the user data and the bind - * data. It must use this handle to declare the columns the function returns, and can use it to hint at the number of - * rows the scan will produce. - */ -typedef struct _duckdb_v2_table_function_bind_info { - void *internal_ptr; -} * duckdb_v2_table_function_bind_info_handle; - -/*! - * A borrowed opaque handle to the arguments supplied to a table function during the "filter pushdown" phase of query - * optimization. The "filter pushdown" callback receives this handle and can use it to inspect the filter predicates the - * query applies to the function's rows, and to accept the ones it will apply itself. - */ -typedef struct _duckdb_v2_table_function_filter_pushdown_info { - void *internal_ptr; -} * duckdb_v2_table_function_filter_pushdown_info_handle; - -/*! - * A borrowed opaque handle to the arguments supplied to a table function during the "stats" phase of query - * optimization. The engine invokes the callback once per column the query reads, and the callback can use the handle to - * find out which column is asked about and to report what it knows about the column's values (its minimum and maximum, - * whether it holds NULLs, ...) by narrowing the statistics of that column. - */ -typedef struct _duckdb_v2_table_function_stats_info { - void *internal_ptr; -} * duckdb_v2_table_function_stats_info_handle; - -/*! - * A borrowed opaque handle to the arguments supplied to a table function during the "partitioning" phase of query - * optimization. The engine invokes the callback once per candidate `GROUP BY` column set, before execution starts, to - * decide whether the scan can feed a partitioned aggregate directly instead of hashing. - */ -typedef struct _duckdb_v2_table_function_partitioning_info { - void *internal_ptr; -} * duckdb_v2_table_function_partitioning_info_handle; - -/*! - * A borrowed opaque handle to the arguments supplied to a table function when the engine asks it to describe a bound - * call. The "get bind info" callback receives this handle, and can use it to describe the call in more detail than its - * columns: with identifiers of its columns (e.g. field ids), and with options - key-value facts about what the call - * reads. - */ -typedef struct _duckdb_v2_table_function_get_bind_info_info { - void *internal_ptr; -} * duckdb_v2_table_function_get_bind_info_info_handle; - -/*! - * A borrowed opaque handle to the arguments supplied to a table function when the engine describes a bound call of it - * in a query plan, e.g. for `EXPLAIN`. The "to string" callback receives this handle and can use it to report the - * key-value pairs the plan shows for the scan. - */ -typedef struct _duckdb_v2_table_function_to_string_info { - void *internal_ptr; -} * duckdb_v2_table_function_to_string_info_handle; - -/*! - * An owned opaque handle to a multi-file table function being built. A multi-file function wraps an already registered - * table function that reads a single file, and adds everything that is needed to read many files at once on top of it: - * globbing, lists of files, hive partitioning, the `filename` column, `union_by_name` and the like. Created with - * `duckdb_v2_multi_file_function_create()`, configured with the setter functions (e.g. - * `duckdb_v2_multi_file_function_set_name()`, `duckdb_v2_multi_file_function_set_single_file_function()`), made - * available with `duckdb_v2_connection_register_multi_file_function()` or - * `duckdb_v2_extension_register_multi_file_function()`, and destroyed with `duckdb_v2_multi_file_function_destroy()`. - */ -typedef struct _duckdb_v2_multi_file_function { - void *internal_ptr; -} * duckdb_v2_multi_file_function_handle; - -/* --- Constants for table --- */ - -/* --- Function pointer typedefs for table --- */ - -typedef void (*duckdb_v2_table_function_bind_callback_fn)(duckdb_v2_function_bind_info_handle info, - duckdb_v2_table_function_bind_info_handle result, - duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_table_function_filter_pushdown_callback_fn)( - duckdb_v2_table_function_filter_pushdown_info_handle info, duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_table_function_partitioning_callback_fn)( - duckdb_v2_table_function_partitioning_info_handle info, duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_table_function_get_bind_info_callback_fn)( - duckdb_v2_table_function_get_bind_info_info_handle info, duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_table_function_stats_callback_fn)(duckdb_v2_table_function_stats_info_handle info, - duckdb_v2_context_handle context, - duckdb_v2_error_info_handle *err); - -typedef void (*duckdb_v2_table_function_to_string_callback_fn)(duckdb_v2_table_function_to_string_info_handle info, - duckdb_v2_error_info_handle *err); - -/* --- Functions for table --- */ + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_bool(duckdb_v2_factory_handle factory, bool in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); +#endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a new table function through a factory. - * - * The function starts out empty: configure it with the setter functions (e.g. `duckdb_v2_table_function_set_name()`, - * `duckdb_v2_table_function_set_data_source()`, etc.) and the signature obtained via - * `duckdb_v2_table_function_get_signature()`, then make it available with - * `duckdb_v2_connection_register_table_function()` or `duckdb_v2_extension_register_table_function()`. The caller owns - * the returned handle and must destroy it with `duckdb_v2_table_function_destroy()`, also after registration. + * Creates a UTINYINT value from a uint8_t. * - * The table function can only be registered on the database the factory belongs to. + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create the table function through. - * @param function On success, receives the newly created table function. Owned by the caller. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The uint8_t to wrap. + * @param out_value Receives the new UTINYINT value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_create(duckdb_v2_factory_handle factory, - duckdb_v2_table_function_handle *function, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_utinyint(duckdb_v2_factory_handle factory, uint8_t in_value, + duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the name of the table function. + * Creates a USMALLINT value from a uint16_t. * - * The name is borrowed and copied. Calling this again replaces the previous name. A name must be set before - * registration. + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param function The function to set the name of. - * @param name The name to set. Borrowed and copied. - * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be - * NULL only when this is 0. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The uint16_t to wrap. + * @param out_value Receives the new USMALLINT value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_name(duckdb_v2_table_function_handle function, - const char *name, idx_t name_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_usmallint(duckdb_v2_factory_handle factory, uint16_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the documentation of the function so it can be filled in. + * Creates a UINTEGER value from a uint32_t. * - * Set a description with `duckdb_v2_function_docs_set_description()`, and add examples and categories with - * `duckdb_v2_function_docs_add_example()` and `duckdb_v2_function_docs_add_category()`. The documentation is modified - * in place, describes this overload only, and is registered with the function. Optional. + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param function The function to get the documentation of. - * @param docs The returned documentation. Borrowed and valid for the lifetime of the function handle. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The uint32_t to wrap. + * @param out_value Receives the new UINTEGER value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_get_docs(duckdb_v2_table_function_handle function, - duckdb_v2_function_docs_handle *docs, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_uint(duckdb_v2_factory_handle factory, uint32_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the function's signature so it can be configured. + * Creates a UBIGINT value from a uint64_t. * - * Add parameters with `duckdb_v2_function_signature_add_parameter()`. The signature is modified in place. A table - * function declares the columns it returns from its bind callback instead of through a return type, so registration - * rejects a signature whose return type was set with `duckdb_v2_function_signature_set_return_type()`. + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param function The function to get the signature of. - * @param sig The returned signature. Borrowed and valid for the lifetime of the function handle. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The uint64_t to wrap. + * @param out_value Receives the new UBIGINT value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_get_signature(duckdb_v2_table_function_handle function, - duckdb_v2_function_signature_handle *sig, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_ubigint(duckdb_v2_factory_handle factory, uint64_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets a property on the table function. + * Creates a UHUGEINT value from a uint128_t. * - * Only `FUNCTION_PROPERTY_STABILITY` is supported for table functions; any other key, a key that is not valid for table - * functions, or a value that does not belong to `key` results in an error. A table function defaults to - * `FUNCTION_PROPERTY_STABILITY_VOLATILE`. Declaring `FUNCTION_PROPERTY_STABILITY_CONSISTENT_WITHIN_QUERY` promises that - * repeated executions with the same bound data and input rows return equivalent rows within one query and have no - * observable side effects, which allows the optimizer to share identical scans. + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param function The function to set the property of. - * @param key The property to set. - * @param value The value to set for the property. Must belong to `key`. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The uint128_t to wrap. + * @param out_value Receives the new UHUGEINT value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_property(duckdb_v2_table_function_handle function, - DUCKDB_V2_FUNCTION_PROPERTY_KEY key, - DUCKDB_V2_FUNCTION_PROPERTY_VALUE value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_uhugeint(duckdb_v2_factory_handle factory, + const duckdb_v2_uhugeint_t *in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets arbitrary user data on the table function. + * Creates a TINYINT value from an int8_t. * - * Associates an opaque pointer with the function, retrievable from the callbacks via - * `duckdb_v2_function_bind_get_user_data()`, `duckdb_v2_data_source_init_global_get_user_data()`, - * `duckdb_v2_data_source_exec_get_user_data()` and their counterparts on the other phases. The opaque handle bundles - * the pointer with an optional destructor, invoked when the data is no longer needed. + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param function The function to set the user data of. - * @param data Opaque handle bundling the user data pointer plus an optional destructor. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The int8_t to wrap. + * @param out_value Receives the new TINYINT value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_user_data(duckdb_v2_table_function_handle function, - duckdb_v2_opaque *data, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_tinyint(duckdb_v2_factory_handle factory, int8_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the bind callback of the table function. + * Creates a SMALLINT value from an int16_t. * - * The bind callback is invoked during query planning for each call site of the function. It must declare the columns - * the function returns via `duckdb_v2_table_function_bind_add_result_column()`. Through its - * `duckdb_v2_function_bind_info_handle` it can also inspect the constant argument values and set "bind data" that is - * shared with all later callbacks. A bind callback must be set before registration. + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param function The function to set the bind callback of. - * @param callback The bind callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The int16_t to wrap. + * @param out_value Receives the new SMALLINT value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_bind_callback( - duckdb_v2_table_function_handle function, duckdb_v2_table_function_bind_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_smallint(duckdb_v2_factory_handle factory, int16_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets whether the table function supports projection pushdown. Defaults to false. + * Creates an INTEGER value from an int32_t. * - * With projection pushdown, the engine asks the function for only the columns a query actually uses: the exec - * callback's output chunk holds one vector per requested column rather than one per column declared in bind, and the - * global init, local init and exec callbacks can look up which declared column each vector stands for via e.g. - * `duckdb_v2_data_source_exec_get_column_index()`. Without it the output chunk always holds every declared column, and - * the engine drops the unused ones itself. + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param function The function to configure. - * @param enable Whether the function supports projection pushdown. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The int32_t to wrap. + * @param out_value Receives the new INTEGER value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_projection_pushdown(duckdb_v2_table_function_handle function, - bool enable, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_int(duckdb_v2_factory_handle factory, int32_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Declares that the table function can produce the given virtual column. + * Creates a BIGINT value from an int64_t. * - * A virtual column is not one of the columns declared in bind: the query asks for it by name, and the function only - * produces it when it is asked for. It then takes up a vector of the exec callback's output chunk, like any other - * column the scan produces. This requires projection pushdown (see - * `duckdb_v2_table_function_set_projection_pushdown()`), which is what lets the engine ask for it. The global init, - * local init and exec callbacks recognize the vector by its column index, which is 2^63 plus the value of the - * `DUCKDB_V2_TABLE_VIRTUAL_COLUMN` (see e.g. `duckdb_v2_data_source_exec_get_column_index()`). + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param function The function to configure. - * @param column The virtual column the function can produce. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The int64_t to wrap. + * @param out_value Receives the new BIGINT value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_add_virtual_column(duckdb_v2_table_function_handle function, - DUCKDB_V2_TABLE_VIRTUAL_COLUMN column, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_bigint(duckdb_v2_factory_handle factory, int64_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional filter pushdown callback of the table function. + * Creates a HUGEINT value from an int128_t. * - * The filter pushdown callback is invoked while the query is optimized, after the bind callback and before any init - * callback, with the filter predicates the query applies to the function's rows. Each predicate is a bound expression - * the callback can inspect with the `expression` functions; the callback accepts the predicates it will apply itself - * via `duckdb_v2_table_function_filter_pushdown_accept()`, typically after recording what they select in the bind data. - * The engine then stops applying the accepted predicates and keeps applying the rest above the scan, so accepting a - * predicate is a promise to filter the rows exactly as it would have. The optimizer may invoke the callback more than - * once for the same query, each time with the predicates not yet accepted; it is not invoked when there are none. + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * - * A function that also has projection pushdown (see `duckdb_v2_table_function_set_projection_pushdown()`) is offered - * the predicates that apply to a single column of it once more when a scan starts, just before the global init - * callback, in the same form, with the column references resolved by - * `duckdb_v2_table_function_filter_pushdown_get_column_index()` as at optimization time. This is how the callback of a - * function wrapped in a multi-file function sees the predicates, which the optimizer only offers to the wrapper. The - * engine applies these predicates to the rows the function produces itself, so the function may use them to skip what - * the query can never use but does not have to understand them, and accepting one has no effect. The scan keeps the - * columns the predicates are applied to. + * history: + * - unstable: v2.0.0 + * + * @param factory The factory to create with. + * @param in_value The int128_t to wrap. + * @param out_value Receives the new HUGEINT value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @return DUCKDB_V2_ERROR + */ +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_hugeint(duckdb_v2_factory_handle factory, + const duckdb_v2_hugeint_t *in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); +#endif + +#if DUCKDB_V2_API_ALLOW_UNSTABLE +/*! + * Creates a VARCHAR value from a UTF-8 string. + * + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param function The function to set the filter pushdown callback of. - * @param callback The filter pushdown callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The UTF-8 string to wrap. + * @param in_value_length The length of `in_value` in bytes. `in_value` need not be null-terminated and may be NULL only + * when this is 0. + * @param out_value Receives the new VARCHAR value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_filter_pushdown_callback( - duckdb_v2_table_function_handle function, duckdb_v2_table_function_filter_pushdown_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_varchar(duckdb_v2_factory_handle factory, const char *in_value, + idx_t in_value_length, duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional "partitioning" callback of the table function. + * Creates a BLOB value from a byte string. * - * The callback tells the query optimizer, for a candidate `GROUP BY` column set, whether every partition the scan - * produces carries exactly one distinct value for those columns; only `TABLE_PARTITION_INFO_SINGLE_VALUE_PARTITIONS` - * unlocks the partitioned aggregate optimization; any other result, or leaving this callback unset, keeps the regular - * hash aggregate. It runs on the planning thread, before execution starts, and must be deterministic for a given column - * set since it may be called on a plan the optimizer later discards. Registration fails unless - * `duckdb_v2_data_source_set_partition_data_callback()` is set too, since the engine asks that callback for the - * partitioning column values once this one claims single-value partitions. + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param function The function to set the partitioning callback of. - * @param callback The partitioning callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The byte string to wrap. + * @param in_value_length The length of `in_value` in bytes. `in_value` need not be null-terminated and may be NULL only + * when this is 0. + * @param out_value Receives the new BLOB value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_partitioning_callback( - duckdb_v2_table_function_handle function, duckdb_v2_table_function_partitioning_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_blob(duckdb_v2_factory_handle factory, const char *in_value, + idx_t in_value_length, duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional stats callback of the table function. + * Creates a FLOAT value from a float. * - * The stats callback is invoked during query optimization once for each declared column the query reads, when the - * engine wants to know about the column's values without reading them - e.g. to prune a scan whose filter no value can - * satisfy, to answer `min()` / `max()` from the statistics, or to estimate the selectivity of a filter. Through its - * `duckdb_v2_table_function_stats_info_handle` the callback narrows the statistics of that column (see - * `duckdb_v2_table_function_stats_get_result_stats()`): its minimum and maximum, whether it holds NULLs, the statistics - * of the children of a nested column, ... Leaving the statistics unchanged tells the engine nothing about the column. - * The statistics must hold for every row the call produces: a bound that excludes a value the scan then produces leads - * to wrong results. A function without a stats callback gives the engine no statistics for its columns. The callback is - * only asked about whole declared columns, never about virtual columns or about fields extracted from a column. + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param function The function to set the stats callback of. - * @param callback The stats callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The float to wrap. + * @param out_value Receives the new FLOAT value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_stats_callback( - duckdb_v2_table_function_handle function, duckdb_v2_table_function_stats_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_float(duckdb_v2_factory_handle factory, float in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Declares one of the columns the function returns. + * Creates a DOUBLE value from a double. * - * Call this once per column, in order: the columns declared here are the columns of the table the function produces, - * and the vectors of the output chunk the exec callback fills follow the same order. At least one column must be - * declared. The type must be a fully defined concrete type; ANY is rejected, as a result column carries data. The name - * and type are borrowed and copied. + * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. - * @param name The name of the column. Borrowed and copied. - * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be - * NULL only when this is 0. - * @param type The type of the column. Borrowed and copied. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The double to wrap. + * @param out_value Receives the new DOUBLE value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_bind_add_result_column( - duckdb_v2_table_function_bind_info_handle info, const char *name, idx_t name_length, - duckdb_v2_logical_type_handle type, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_double(duckdb_v2_factory_handle factory, double in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the estimated number of rows the scan will produce. + * Creates a TYPE value from a logical type. * - * The estimate is a hint for the optimizer, not a limit: producing a different number of rows is not an error. Without - * it, the optimizer falls back on its own defaults. + * The logical type is borrowed and copied into the value, so the caller can destroy it independently. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. - * @param cardinality The estimated number of rows. - * @param is_exact Whether the estimate is exact, which also makes it an upper bound on the row count. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_type The borrowed logical type to wrap. + * @param out_value Receives the new TYPE value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_bind_set_cardinality( - duckdb_v2_table_function_bind_info_handle info, idx_t cardinality, bool is_exact, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_type(duckdb_v2_factory_handle factory, + duckdb_v2_logical_type_handle in_type, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the order guarantee of the rows this call of the function produces. Defaults to - * `ORDER_PRESERVATION_INSERTION_ORDER`. + * Creates a DATE value. * - * With `ORDER_PRESERVATION_NO_ORDER`, a scan that reports more than one thread via - * `duckdb_v2_data_source_init_global_set_max_threads()` runs in parallel into query results, INSERT and COPY without a - * `duckdb_v2_data_source_set_partition_data_callback()`, and the rows arrive in no particular order. With insertion - * order kept, those consumers need the partition data callback to run in parallel. Fails with `ERROR_INPUT_INVALID` - * when order is not one of the enum's declared values. + * The payload is days since 1970-01-01, the same unit value_get_date reports. It is not range-checked here; value_cast + * is the validating path. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. - * @param order The order guarantee of the produced rows. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The payload to wrap. + * @param out_value Receives the new DATE value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_bind_set_order_preservation( - duckdb_v2_table_function_bind_info_handle info, DUCKDB_V2_ORDER_PRESERVATION order, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_date(duckdb_v2_factory_handle factory, int32_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`, or null if none was set. + * Creates a TIME value. + * + * The payload is microseconds since midnight, the same unit value_get_time reports. It is not range-checked here; + * value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The filter pushdown info handle. - * @param data Receives the user data pointer. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The payload to wrap. + * @param out_value Receives the new TIME value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_filter_pushdown_get_user_data( - duckdb_v2_table_function_filter_pushdown_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_time(duckdb_v2_factory_handle factory, int64_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set via `duckdb_v2_function_bind_set_bind_data()`, or null if none was set. + * Creates a TIME_NS value. * - * This is the same object the init and exec callbacks later receive, so a predicate the callback accepts can be - * recorded in it for the scan to apply. + * The payload is nanoseconds since midnight, the same unit value_get_time_ns reports. It is not range-checked here; + * value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The filter pushdown info handle. - * @param data Receives the bind data pointer. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The payload to wrap. + * @param out_value Receives the new TIME_NS value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_filter_pushdown_get_bind_data( - duckdb_v2_table_function_filter_pushdown_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_time_ns(duckdb_v2_factory_handle factory, int64_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of filter predicates offered to the function. + * Creates a TIME_TZ value. * - * The predicates are combined with `AND`: every row the scan produces must satisfy all of them. Valid indices for - * `duckdb_v2_table_function_filter_pushdown_get_filter()` and `duckdb_v2_table_function_filter_pushdown_accept()` are - * `0` up to (but excluding) this count. + * The payload packs the time of day and the UTC offset into one integer, in the committed layout: micros in the high 40 + * bits, a biased offset in the low 24. The same form value_get_time_tz reports. It is not range-checked here; + * value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The filter pushdown info handle. - * @param count Receives the number of predicates. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The payload to wrap. + * @param out_value Receives the new TIME_TZ value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_filter_pushdown_get_filter_count( - duckdb_v2_table_function_filter_pushdown_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_time_tz(duckdb_v2_factory_handle factory, uint64_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the filter predicate at the given index. + * Creates a TIMESTAMP value. * - * Fails if the index is out of bounds. The predicate is a bound expression evaluating to `BOOLEAN`; inspect it with - * `duckdb_v2_expression_get_type()` and the other `expression` functions, and resolve the column references it contains - * via `duckdb_v2_table_function_filter_pushdown_get_column_index()`. Borrowed; valid only for the duration of the - * callback. + * The payload is microseconds since 1970-01-01, the same unit value_get_timestamp reports. It is not range-checked + * here; value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The filter pushdown info handle. - * @param index The index of the predicate to retrieve. - * @param filter Receives the borrowed predicate. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The payload to wrap. + * @param out_value Receives the new TIMESTAMP value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_filter_pushdown_get_filter( - duckdb_v2_table_function_filter_pushdown_info_handle info, idx_t index, duckdb_v2_expression_handle *filter, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_timestamp(duckdb_v2_factory_handle factory, int64_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Accepts the filter predicate at the given index: the function will apply it itself. + * Creates a TIMESTAMP_SEC value. * - * The engine stops applying an accepted predicate, so the scan must produce only rows that satisfy it, or the query - * returns rows it should not. Predicates left unaccepted are applied by the engine as usual, so a callback that - * recognizes nothing can simply return. Fails if the index is out of bounds. + * The payload is seconds since 1970-01-01, the same unit value_get_timestamp_sec reports. It is not range-checked here; + * value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The filter pushdown info handle. - * @param index The index of the predicate to accept. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The payload to wrap. + * @param out_value Receives the new TIMESTAMP_SEC value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_filter_pushdown_accept( - duckdb_v2_table_function_filter_pushdown_info_handle info, idx_t index, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_timestamp_sec(duckdb_v2_factory_handle factory, int64_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of columns the predicates can refer to. + * Creates a TIMESTAMP_MS value. * - * A column reference inside a predicate (`duckdb_v2_expression_column_ref_get_index()`) indexes the columns the query - * reads from the function, not the columns declared in bind. Valid indices for - * `duckdb_v2_table_function_filter_pushdown_get_column_index()` are `0` up to (but excluding) this count. + * The payload is milliseconds since 1970-01-01, the same unit value_get_timestamp_ms reports. It is not range-checked + * here; value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The filter pushdown info handle. - * @param count Receives the number of referable columns. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The payload to wrap. + * @param out_value Receives the new TIMESTAMP_MS value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_filter_pushdown_get_column_count( - duckdb_v2_table_function_filter_pushdown_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_timestamp_ms(duckdb_v2_factory_handle factory, int64_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Resolves a column reference found in a predicate to the declared column it refers to. + * Creates a TIMESTAMP_NS value. * - * Takes the index a `EXPRESSION_TYPE_BOUND_COLUMN_REF` node reports and returns the index of the column among the ones - * declared with `duckdb_v2_table_function_bind_add_result_column()`, in declaration order. Fails if the index is out of - * bounds. + * The payload is nanoseconds since 1970-01-01, the same unit value_get_timestamp_ns reports. It is not range-checked + * here; value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The filter pushdown info handle. - * @param index The column index reported by a column reference node. - * @param column_index Receives the index of the declared column. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The payload to wrap. + * @param out_value Receives the new TIMESTAMP_NS value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_filter_pushdown_get_column_index( - duckdb_v2_table_function_filter_pushdown_info_handle info, idx_t index, idx_t *column_index, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_timestamp_ns(duckdb_v2_factory_handle factory, int64_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`. + * Creates a TIMESTAMP_TZ value. + * + * The payload is microseconds since 1970-01-01, in UTC, the same unit value_get_timestamp_tz reports. It is not + * range-checked here; value_cast is the validating path. The returned value is caller-owned; destroy it via + * value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The partitioning info handle. - * @param data Receives the user data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The payload to wrap. + * @param out_value Receives the new TIMESTAMP_TZ value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_partitioning_get_user_data( - duckdb_v2_table_function_partitioning_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_timestamp_tz(duckdb_v2_factory_handle factory, int64_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's bind callback. + * Creates a TIMESTAMP_TZ_NS value. + * + * The payload is nanoseconds since 1970-01-01, in UTC, the same unit value_get_timestamp_tz_ns reports. It is not + * range-checked here; value_cast is the validating path. The returned value is caller-owned; destroy it via + * value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The partitioning info handle. - * @param data Receives the bind data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The payload to wrap. + * @param out_value Receives the new TIMESTAMP_TZ_NS value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_partitioning_get_bind_data( - duckdb_v2_table_function_partitioning_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_timestamp_tz_ns(duckdb_v2_factory_handle factory, int64_t in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of columns the optimizer is asking about: the candidate `GROUP BY` column set. + * Creates a INTERVAL value. * - * Valid indices for `duckdb_v2_table_function_partitioning_get_partition_column_index()` are `0` up to (but excluding) - * this count. + * The payload is the (months, days, micros) triple, the same unit value_get_interval reports. It is not range-checked + * here; value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param info The partitioning info handle. - * @param count Receives the number of columns in the candidate set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The payload to wrap. + * @param out_value Receives the new INTERVAL value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_partitioning_get_partition_column_count( - duckdb_v2_table_function_partitioning_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_interval(duckdb_v2_factory_handle factory, + const duckdb_v2_interval_t *in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns which declared column the candidate `GROUP BY` column at the given index stands for. + * Creates a DECIMAL value from its backing integer. * - * The result indexes the columns declared with `duckdb_v2_table_function_bind_add_result_column()`, in declaration - * order. Fails if the index is out of bounds. + * The value is scaled by 10^scale, so (18500, 18, 3) is 18.500. width is the total digit count and must be at least 1; + * scale is the number of digits after the point and must not exceed width. Violating either returns + * ERROR_INPUT_INVALID, as does a value that does not fit in width digits. Widths above 38 build a wide decimal stored + * as BIGNUM, for which the 128-bit backing integer always fits; a wide decimal whose backing integer needs more than + * 128 bits is built through value_cast. + * + * The width is bounded like the width of a DECIMAL type the factory creates (see factory_create_type_from_name): by the + * max_decimal_width setting of the factory's connection, and by the default of that setting, 1000000, for an instance's + * factory. A wider width returns ERROR_INPUT_INVALID; use the factory of a connection that raised the setting. * * history: * - unstable: v2.0.0 * - * @param info The partitioning info handle. - * @param index The index of the candidate column. - * @param column_index Receives the index of the declared column. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The backing integer, scaled by 10^scale. + * @param width Total digit count, at least 1 and at most the factory's maximum DECIMAL width; widths above 38 are wide + * decimals. + * @param scale Digits after the decimal point; must not exceed width. + * @param out_value Receives the new DECIMAL value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_partitioning_get_partition_column_index( - duckdb_v2_table_function_partitioning_info_handle info, idx_t index, idx_t *column_index, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_decimal(duckdb_v2_factory_handle factory, + const duckdb_v2_hugeint_t *in_value, uint32_t width, + uint32_t scale, duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Reports whether every partition the scan produces carries exactly one distinct value for the candidate `GROUP BY` - * column set. + * Creates a UUID value from its internal 128-bit form. * - * Only `TABLE_PARTITION_INFO_SINGLE_VALUE_PARTITIONS` unlocks the partitioned aggregate optimization; any other value - * keeps the regular hash aggregate. A callback that never calls this is treated as reporting - * `TABLE_PARTITION_INFO_NOT_PARTITIONED`. Fails with `ERROR_INPUT_INVALID` when partition_info is not one of the enum's - * declared values. + * The payload is the storage form a vector element holds, not the canonical byte order: the high bit is flipped so the + * integer sorts. To build one from canonical text, cast a VARCHAR with value_cast instead, which is also how a UUID + * renders back. * * history: * - unstable: v2.0.0 * - * @param info The partitioning info handle. - * @param partition_info Whether, and how, the scan is partitioned by the candidate column set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The internal 128-bit storage form. + * @param out_value Receives the new UUID value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_partitioning_set_partition_info( - duckdb_v2_table_function_partitioning_info_handle info, DUCKDB_V2_TABLE_PARTITION_INFO partition_info, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_uuid(duckdb_v2_factory_handle factory, + const duckdb_v2_hugeint_t *in_value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of columns of the input of the function's operator (see - * `duckdb_v2_table_function_set_operator()`). + * Creates a BIT value from its wire bytes. * - * These are the vectors of the input chunks the operator's execute callback receives: the positional arguments of the - * call for `TABLE_OPERATOR_INPUT_ARGUMENTS`, or the columns of the table argument for `TABLE_OPERATOR_INPUT_TABLE`. A - * bind callback typically derives the function's result columns from them. Unlike - * `duckdb_v2_function_bind_get_arg_value()`, this also describes arguments that are not constant. 0 for a function - * without an operator. + * The wire form is a mandatory padding-header byte — the count of leading bits in the first data byte that are not part + * of the bit string — followed by the data bytes, so the input must be at least 1 byte. These are the same bytes + * value_get_blob reports back. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. - * @param count Receives the number of input columns. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The wire bytes, a padding header byte followed by data. Must be at least 1 byte. + * @param in_value_length The length of `in_value` in bytes. `in_value` need not be null-terminated and may be NULL only + * when this is 0. + * @param out_value Receives the new BIT value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_bind_get_input_column_count( - duckdb_v2_table_function_bind_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_bit(duckdb_v2_factory_handle factory, const char *in_value, + idx_t in_value_length, duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the type of the operator's input column at the given index (see - * `duckdb_v2_table_function_bind_get_input_column_count()`). + * Creates a BIGNUM value from its storage bytes. * - * Fails if the index is out of bounds. The returned type is owned by the caller and must be destroyed via - * `duckdb_v2_logical_type_destroy()`. + * The bytes are opaque storage, as produced by bignum_encode from a magnitude and a sign flag; a negative is stored + * bit-inverted behind a header, so these are not the magnitude bytes. The header plus at least one magnitude byte means + * the input must exceed 3 bytes. These are the same bytes value_get_blob reports back, for bignum_decode to translate. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. - * @param index The index of the input column. - * @param type Receives the column type. Owned by the caller; destroy via `duckdb_v2_logical_type_destroy()`. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param in_value The opaque storage bytes from bignum_encode. Must exceed 3 bytes. + * @param in_value_length The length of `in_value` in bytes. `in_value` need not be null-terminated and may be NULL only + * when this is 0. + * @param out_value Receives the new BIGNUM value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_bind_get_input_column_type( - duckdb_v2_table_function_bind_info_handle info, idx_t index, duckdb_v2_logical_type_handle *type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_bignum(duckdb_v2_factory_handle factory, const char *in_value, + idx_t in_value_length, duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the name of the operator's input column at the given index (see - * `duckdb_v2_table_function_bind_get_input_column_count()`). + * Creates a LIST value from its elements. * - * For `TABLE_OPERATOR_INPUT_TABLE` this is the name of the column of the table argument. The arguments of - * `TABLE_OPERATOR_INPUT_ARGUMENTS` have no names, and yield an empty name. Fails if the index is out of bounds. The - * name is borrowed and valid only for the duration of the callback. + * The child type is the common type of the elements, resolved by the same rule a SQL list literal follows, and every + * element is cast to it; a set with no common type surfaces the cast error. Pass child_type to name the type instead, + * which is also how an empty list is built: with child_type NULL, an empty element array has no type to resolve and + * returns ERROR_INPUT_INVALID. + * + * The elements are borrowed and copied in, and a NULL element becomes a typed NULL. The type is rebuilt from its child, + * so an alias on the outer LIST type is not preserved; value_cast is the alias-preserving path. * * history: * - unstable: v2.0.0 * - * @param info The bind info handle. - * @param index The index of the input column. - * @param name Receives a borrowed pointer to the column name. Valid only for the duration of the callback. - * @param name_length Receives the length of `*name` in bytes. `*name` is not guaranteed to be null-terminated. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param child_type Optional. The element type. Pass NULL to resolve it from the elements. + * @param children An array of child_count elements. Borrowed (copied in). Pass NULL when child_count is 0. + * @param child_count The number of elements. + * @param out_value Receives the new composite value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_bind_get_input_column_name( - duckdb_v2_table_function_bind_info_handle info, idx_t index, const char **name, idx_t *name_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_list(duckdb_v2_factory_handle factory, + duckdb_v2_logical_type_handle child_type, + const duckdb_v2_value_handle *children, idx_t child_count, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`. + * Creates an ARRAY value from its elements, sized by their count. + * + * The child type is resolved exactly as for value_create_list, and child_type names it explicitly the same way. The + * minimum array size is 1, so an empty element array returns ERROR_INPUT_INVALID whether or not child_type is given. + * + * The elements are borrowed and copied in, and a NULL element becomes a typed NULL. * * history: * - unstable: v2.0.0 * - * @param info The stats info handle. - * @param data Receives the user data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param child_type Optional. The element type. Pass NULL to resolve it from the elements. + * @param children An array of child_count elements. Borrowed (copied in). Pass NULL when child_count is 0. + * @param child_count The number of elements. + * @param out_value Receives the new composite value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_stats_get_user_data( - duckdb_v2_table_function_stats_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_array(duckdb_v2_factory_handle factory, + duckdb_v2_logical_type_handle child_type, + const duckdb_v2_value_handle *children, idx_t child_count, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data set by the function's bind callback. + * Creates a STRUCT value from named fields, in order. + * + * Each field keeps its own child's type, so there is nothing to resolve across them; names and children are parallel + * arrays of field_count entries. An empty field list builds the empty struct, which is a real type. + * + * The names and children are borrowed and copied in, and a NULL child becomes a typed NULL. Duplicate field names are + * rejected. * * history: * - unstable: v2.0.0 * - * @param info The stats info handle. - * @param data Receives the bind data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param names An array of field_count field names. Pass NULL when field_count is 0. + * @param names_lengths Byte lengths of the entries in `names`; element i is the length of `names[i]`. May be NULL only + * when `names` is NULL. + * @param children An array of field_count field values. Borrowed (copied in). Pass NULL when field_count is 0. + * @param field_count The number of fields. + * @param out_value Receives the new composite value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_stats_get_bind_data( - duckdb_v2_table_function_stats_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_struct(duckdb_v2_factory_handle factory, const char *const *names, + const idx_t *names_lengths, + const duckdb_v2_value_handle *children, idx_t field_count, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns which declared column the statistics describe. + * Creates a TUPLE value from positional fields. * - * The result indexes the columns declared with `duckdb_v2_table_function_bind_add_result_column()`, in declaration - * order. It is never the index of a virtual column or of a field extracted from a column; the callback is not asked - * about those. + * TUPLE is the unnamed struct: the same positional children as value_create_struct, under a distinct type id and with + * no names. Each field keeps its own child's type. An empty field list builds the empty tuple, which is a real type. + * + * The children are borrowed and copied in, and a NULL child becomes a typed NULL. * * history: * - unstable: v2.0.0 * - * @param info The stats info handle. - * @param column_index Receives the index of the declared column. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param children An array of field_count field values. Borrowed (copied in). Pass NULL when field_count is 0. + * @param field_count The number of fields. + * @param out_value Receives the new composite value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_stats_get_column_index( - duckdb_v2_table_function_stats_info_handle info, idx_t *column_index, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_tuple(duckdb_v2_factory_handle factory, + const duckdb_v2_value_handle *children, idx_t field_count, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the statistics of the column, for the callback to narrow. + * Creates a MAP value from parallel key and value arrays. * - * The statistics start out unknown, with every kind of value possible, and are of the column's type as the bind - * callback declared it. The callback narrows them with `duckdb_v2_stats_set_value()`, from a STRUCT value in the shape - * `duckdb_v2_stats_get_value()` returns - e.g. `{'min': 20, 'max': 30, 'has_null': false}` for an INTEGER column, or - * the statistics of the fields of a STRUCT column under `child_stats` - and with `duckdb_v2_stats_set_can_have_null()` - * / `duckdb_v2_stats_set_can_have_valid()`. Statistics built with `duckdb_v2_stats_create()`, e.g. combined from the - * files of a scan with `duckdb_v2_stats_merge()`, are copied in with `duckdb_v2_stats_assign()`. They describe every - * value the scan produces for the column. Borrowed; valid only for the duration of the callback. + * The key and value types are the common types of the keys and of the values, resolved as for value_create_list, and + * every entry is cast to them. Pass key_type and value_type to name them instead, which is also how an empty map is + * built: with both NULL, empty key and value arrays have no types to resolve and return ERROR_INPUT_INVALID. + * + * Keys and values are borrowed and copied in, and the two arrays must be the same length. Keys must be non-NULL and + * unique; both are enforced. * * history: * - unstable: v2.0.0 * - * @param info The stats info handle. - * @param stats Receives the borrowed, writable statistics of the column. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory to create with. + * @param key_type Optional. The key type. Pass NULL to resolve it from the keys. + * @param value_type Optional. The value type. Pass NULL to resolve it from the values. + * @param keys An array of entry_count keys. Borrowed (copied in). Pass NULL when entry_count is 0. + * @param values An array of entry_count values, parallel to keys. Borrowed (copied in). Pass NULL when entry_count is + * 0. + * @param entry_count The number of entries. + * @param out_value Receives the new composite value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_stats_get_result_stats( - duckdb_v2_table_function_stats_info_handle info, duckdb_v2_stats_handle *stats, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_map( + duckdb_v2_factory_handle factory, duckdb_v2_logical_type_handle key_type, duckdb_v2_logical_type_handle value_type, + const duckdb_v2_value_handle *keys, const duckdb_v2_value_handle *values, idx_t entry_count, + duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the table function, making it available for use in SQL queries. + * Returns the number of child values of a value. * - * The function is registered on the connection's database, visible to every connection, in the connection's - * transaction: inside an explicit transaction, it is invisible to other connections until the transaction commits, and - * a rollback undoes it. Registration requires a name, a bind callback and either a data source or an operator (see - * `duckdb_v2_table_function_set_operator()`), and rejects a signature that declares a return type, since a table - * function declares the columns it returns from its bind callback. The table function must have been created through a - * factory of the same database. The caller still owns the handle after registration and must destroy it with - * `duckdb_v2_table_function_destroy()`, which does not affect the registered function. + * Per type kind: the element count for LIST and ARRAY; the field count for STRUCT and TUPLE; twice the entry count for + * MAP, whose children alternate key, value; and 2 for UNION, the tag plus the active member. Everything else reports 0, + * NULL values of any nested type included. * * history: * - unstable: v2.0.0 * - * @param conn The connection to register on. - * @param function The table function to register. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out_count Receives the number of children. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_register_table_function(duckdb_v2_connection_handle conn, - duckdb_v2_table_function_handle function, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_child_count(duckdb_v2_value_handle value, idx_t *out_count, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the table function, making it available for use in SQL queries. + * Returns one child of a composite value as an owned copy. * - * The function is registered on the loading extension's database and attributed to the extension. Use this from the - * extension's load callback. Registration requires a name, a bind callback and either a data source or an operator (see - * `duckdb_v2_table_function_set_operator()`), and rejects a signature that declares a return type, since a table - * function declares the columns it returns from its bind callback. The table function must have been created through a - * factory of the same database. The caller still owns the handle after registration and must destroy it with - * `duckdb_v2_table_function_destroy()`, which does not affect the registered function. + * LIST and ARRAY children are the elements. STRUCT and TUPLE children are the fields in declared order, and a STRUCT's + * field names come from its type, via logical_type_get_param. MAP children alternate key, value, symmetric with + * value_create_map. UNION children are [0] the tag, as a UTINYINT value, and [1] the active member, because a union + * value holds only that one member. + * + * Note the divergence from vector_get_child, which descends structurally and so exposes [0] = tag and [1..N] = ALL + * members. Code written to descend generically over both must account for that difference. + * + * An out-of-range index returns ERROR_INPUT_INVALID, as does any index on a non-composite or NULL value. The returned + * value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param extension The loading extension. - * @param function The table function to register. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param index The child index, in [0, child_count). + * @param out_child Receives the owned child value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_table_function(duckdb_v2_extension_handle extension, - duckdb_v2_table_function_handle function, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_child(duckdb_v2_value_handle value, idx_t index, + duckdb_v2_value_handle *out_child, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys the table function, releasing its resources. + * Returns the value that a VARIANT value holds, as a value of its own type. * - * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent - * double-destruction. Destroying the handle after registration does not affect the registered function. + * A VARIANT holds a value of any other type, e.g. a TINYINT, a VARCHAR or a LIST of STRUCTs, that is only known per + * value: this reads it back, with the type that it was stored with. The value is built with the content of the variant, + * so a stored list gives a LIST with its elements, and a stored object a STRUCT with its fields. The elements of a list + * that were stored with different types, which a LIST cannot hold, stay VARIANT values: a LIST of VARIANT. Convert + * those with this function in turn. A NULL VARIANT gives a NULL value. A value that is not a VARIANT returns + * ERROR_INPUT_INVALID. The inverse is value_cast to a VARIANT type, which factory_create_type_from_text gives. The + * returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param function The function to destroy. + * @param value The VARIANT value to convert. + * @param out_value Receives the owned value. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_destroy(duckdb_v2_table_function_handle *function); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_variant_to_value(duckdb_v2_value_handle value, + duckdb_v2_value_handle *out_value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional "get bind info" callback of the table function. + * Casts a value to a target type, using a factory. * - * The engine invokes the callback with the bind data of a bound call when it needs to know more about the call than its - * columns. E.g. a multi-file function registered with `duckdb_v2_connection_register_multi_file_function()` or - * `duckdb_v2_extension_register_multi_file_function()` asks the function it wraps for every file it binds: it maps the - * columns of the files onto the columns of its scan by the identifiers the callback reports, and exposes the options it - * reports as the metadata of the reader of the file. The callback may be invoked more than once for the same bind data, - * so it should only report what the bind already determined. + * The conversion is the SQL-faithful, non-strict one, registered custom casts included, and a cast failure surfaces + * from the call. Together with a VARCHAR built through value_create_varchar, this constructs any value from text, + * extension values included; casting a member value to a union type, or a VARCHAR to an enum type, is the sanctioned + * way to build UNION and ENUM values. + * + * A connection's or callback's factory casts with that client's cast functions and settings (e.g. TimeZone). An + * instance's factory supports only the built-in casts, with default settings. + * + * The input value and target type are borrowed. The returned value is caller-owned; destroy it via value_destroy. * * history: * - unstable: v2.0.0 * - * @param function The function to set the callback of. - * @param callback The "get bind info" callback to set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param factory The factory supplying the cast functions. + * @param value The borrowed value to cast. + * @param target_type The borrowed target logical type. + * @param out_value Receives the owned cast result. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_get_bind_info_callback( - duckdb_v2_table_function_handle function, duckdb_v2_table_function_get_bind_info_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_cast(duckdb_v2_factory_handle factory, duckdb_v2_value_handle value, + duckdb_v2_logical_type_handle target_type, + duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`. + * Returns whether the value is NULL. * * history: * - unstable: v2.0.0 * - * @param info The get bind info handle. - * @param data Receives the user data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out_is_null Receives true if the value is NULL, false otherwise. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_get_bind_info_get_user_data( - duckdb_v2_table_function_get_bind_info_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_is_null(duckdb_v2_value_handle value, bool *out_is_null, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data the function's bind callback set for the bound call being described. + * Returns the logical type of the value. + * + * The returned logical type is caller-owned; destroy it via logical_type_destroy. * * history: * - unstable: v2.0.0 * - * @param info The get bind info handle. - * @param data Receives the bind data pointer, or null if none was set. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out_type Receives the owned logical type. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_get_bind_info_get_bind_data( - duckdb_v2_table_function_get_bind_info_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_logical_type(duckdb_v2_value_handle value, + duckdb_v2_logical_type_handle *out_type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Attaches an identifier to a result column of the bound call, or to a field nested inside one. + * Renders the value as a human-readable string. Diagnostic only. * - * A multi-file reader can then map the columns of every file onto the columns of its scan by identifier rather than by - * name - e.g. by the field ids of a file format that carries them, so that renamed columns and fields are still found. - * An identifier is an INTEGER field id or a VARCHAR name. + * Writes into a caller-supplied buffer, so nothing is allocated on the caller's behalf and nothing has to be freed. * - * The nested field is addressed by a path of child indexes, starting at the result column at `column_index`: a STRUCT - * field by its index, the elements of a LIST or ARRAY by `0`, the keys of a MAP by `0` and its values by `1`, and a - * UNION member by its index. An empty path addresses the result column itself. Setting an identifier again for the same - * column or field replaces it. Fails with `ERROR_INPUT_INVALID` when the column index is out of range, or the path does - * not address a nested field of the column's type. + * Pass out_string = NULL to size the buffer without rendering into it: out_length then receives the length, and + * out_capacity is ignored. With out_string != NULL, out_capacity must be at least out_length + 1, or the call returns + * ERROR_INPUT_OBJECT_SIZE with out_length set to the required length and out_string left untouched. + * + * out_length never counts the terminator, but a successful write always appends one, so the buffer is usable as a C + * string. * * history: * - unstable: v2.0.0 * - * @param info The get bind info handle. - * @param column_index The index of the result column, in the order the bind callback declared the columns. - * @param child_path The path of child indexes addressing the nested field, or null for the column itself. - * @param child_path_length The number of entries in the path, 0 for the column itself. - * @param identifier The identifier, an INTEGER or VARCHAR value. Borrowed and copied. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param value The value to read. + * @param out_string Caller-owned buffer receiving the text plus a null terminator, or NULL to only report the required + * length in out_length. + * @param out_capacity Bytes available in out_string, terminator included. Ignored when out_string is NULL. + * @param out_length Receives the text length excluding the null terminator — written on success and on + * ERROR_INPUT_OBJECT_SIZE. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_get_bind_info_set_column_identifier( - duckdb_v2_table_function_get_bind_info_info_handle info, idx_t column_index, const idx_t *child_path, - idx_t child_path_length, duckdb_v2_value_handle identifier, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_to_string(duckdb_v2_value_handle value, char *out_string, + idx_t out_capacity, idx_t *out_length, + duckdb_v2_error_info_handle *err); #endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Sets an option describing the bound call: a key-value fact about what the call reads, e.g. a property of the file it - * reads. Setting a key again replaces its value. - * - * A multi-file function registered with `duckdb_v2_connection_register_multi_file_function()` or - * `duckdb_v2_extension_register_multi_file_function()` exposes the options of the function it wraps as the metadata of - * the reader of each file, e.g. to a custom multi-file reader of another extension. - * - * history: - * - unstable: v2.0.0 - * - * @param info The get bind info handle. - * @param key The key of the option. Borrowed and copied. - * @param key_length The length of `key` in bytes. `key` need not be null-terminated and may be NULL only when this is - * 0. - * @param value The value of the option. Borrowed and copied. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. - * @return DUCKDB_V2_ERROR +/* --- Struct definitions for value --- */ + +/* ============================================================================ + * MODULE: cast + * ============================================================================ */ + +/* --- Enums for cast --- */ + +/* --- Struct forward declarations for cast --- */ + +/* --- Types for cast --- */ + +/*! + * An owned opaque handle to a cast function being built. Created with `duckdb_v2_cast_function_create()`, configured + * with the setter functions (e.g. `duckdb_v2_cast_function_set_source_type()`, + * `duckdb_v2_cast_function_set_function()`, etc.), made available with `duckdb_v2_connection_register_cast_function()` + * or `duckdb_v2_extension_register_cast_function()`, and destroyed with `duckdb_v2_cast_function_destroy()`. */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_get_bind_info_set_option( - duckdb_v2_table_function_get_bind_info_info_handle info, const char *key, idx_t key_length, - duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err); -#endif +typedef struct _duckdb_v2_cast_function { + void *internal_ptr; +} * duckdb_v2_cast_function_handle; + +/* --- Constants for cast --- */ + +/* --- Function pointer typedefs for cast --- */ + +/* --- Functions for cast --- */ #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the optional "to string" callback of the table function. + * Creates a new cast function through a factory. * - * The engine invokes the callback with the bind data of a bound call when it renders a query plan that scans the - * function, e.g. for `EXPLAIN`, `EXPLAIN ANALYZE` and the profiler, both for the logical and for the physical plan. The - * callback reports what the plan shows for the scan as key-value pairs with `duckdb_v2_table_function_to_string_set()`, - * e.g. the file or the remote table it reads. Without the callback the physical plan shows the name of the function - * under the key `Function`; with it, the plan shows what the callback reports instead, so a callback that wants the - * name shown reports it itself. The engine shows the projections, filters and estimated cardinality of the scan next to - * them either way. The callback may be invoked more than once for the same bind data, and is not invoked with the - * global state of a scan, so it should only report what the bind already determined. A function wrapped in a multi-file - * function is not asked: the plan describes the multi-file scan. + * The function starts out empty: configure it with the setter functions (e.g. + * `duckdb_v2_cast_function_set_source_type()`, `duckdb_v2_cast_function_set_function()`, etc.), then make it available + * with `duckdb_v2_connection_register_cast_function()` or `duckdb_v2_extension_register_cast_function()`. The caller + * owns the returned handle and must destroy it with `duckdb_v2_cast_function_destroy()`, also after registration. * - * With profiling enabled (including `EXPLAIN ANALYZE`), the engine also invokes the callback while the query executes, - * once per worker thread that scans the function. Calls can therefore run concurrently with the same bind data and user - * data, so the callback must not modify them without synchronization, and an error it reports there fails the query. - * Builds with assertions enabled also invoke it while executing queries without profiling. + * The cast function can only be registered on the database the factory belongs to. * * history: * - unstable: v2.0.0 * - * @param function The function to set the callback of. - * @param callback The "to string" callback to set. + * @param factory The factory to create the cast function through. + * @param function On success, receives the newly created cast function. Owned by the caller. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_to_string_callback( - duckdb_v2_table_function_handle function, duckdb_v2_table_function_to_string_callback_fn callback, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_cast_function_create(duckdb_v2_factory_handle factory, + duckdb_v2_cast_function_handle *function, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`. + * Sets the type the cast converts from. + * + * The type is borrowed and copied. Calling this again replaces the previous source type. A source type must be set + * before registration, and it must be a fully defined concrete type. * * history: * - unstable: v2.0.0 * - * @param info The to string info handle. - * @param data Receives the user data pointer, or null if none was set. + * @param function The function to set the source type of. + * @param source_type The type to cast from. Borrowed for the call only. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_to_string_get_user_data( - duckdb_v2_table_function_to_string_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_cast_function_set_source_type(duckdb_v2_cast_function_handle function, + duckdb_v2_logical_type_handle source_type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Retrieves the bind data the function's bind callback set for the bound call being described. + * Sets the type the cast converts to. + * + * The type is borrowed and copied. Calling this again replaces the previous target type. A target type must be set + * before registration, and it must be a fully defined concrete type. * * history: * - unstable: v2.0.0 * - * @param info The to string info handle. - * @param data Receives the bind data pointer, or null if none was set. + * @param function The function to set the target type of. + * @param target_type The type to cast to. Borrowed for the call only. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_to_string_get_bind_data( - duckdb_v2_table_function_to_string_info_handle info, void **data, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_cast_function_set_target_type(duckdb_v2_cast_function_handle function, + duckdb_v2_logical_type_handle target_type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Reports a key-value pair the query plan shows for the scan, e.g. `File` and the path of the file it reads. The plan - * shows the pairs in the order they were first reported; setting a key again replaces its value in place. Fails with - * `ERROR_INPUT_INVALID` when the key is empty. + * Sets what it costs to apply this cast implicitly. + * + * The binder uses the cost to choose between candidate implicit casts: a lower non-negative cost makes the cast more + * likely to be picked, a higher one less likely. Built-in widening casts sit in the [0, 20] range, so a cost above 100 + * effectively puts this cast last. A negative cost -- the default -- means the cast is never applied implicitly and is + * reached only through an explicit CAST or TRY_CAST. * * history: * - unstable: v2.0.0 * - * @param info The to string info handle. - * @param key The key. Borrowed and copied. - * @param key_length The length of `key` in bytes. `key` need not be null-terminated. - * @param value The value. Borrowed and copied. May span several lines. - * @param value_length The length of `value` in bytes. `value` need not be null-terminated and may be NULL only when - * this is 0. + * @param function The function to set the implicit cast cost of. + * @param cost The cost. Negative disables implicit casting. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_to_string_set(duckdb_v2_table_function_to_string_info_handle info, - const char *key, idx_t key_length, - const char *value, idx_t value_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_cast_function_set_implicit_cast_cost(duckdb_v2_cast_function_handle function, + int64_t cost, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Makes the table function a table in-out function, whose rows the given operator produces from an input. - * - * Instead of producing its rows from nothing by scanning a data source, the function then transforms an input into its - * rows: the operator's execute callback receives the input chunk by chunk, and writes the function's rows into its - * output chunk, which holds the columns declared by the bind callback. Where the input comes from is set by `input`, - * see `DUCKDB_V2_TABLE_OPERATOR_INPUT`. The bind callback still runs first, declares the result columns, and can - * inspect the input columns with `duckdb_v2_table_function_bind_get_input_column_count()` and its siblings; the - * operator reaches the bind data via e.g. `duckdb_v2_operator_execute_get_bind_data()`. - * - * The operator's configuration is copied, so the caller still owns `op` and must destroy it with - * `duckdb_v2_operator_destroy()`; it may be handed to several functions. Calling this again replaces the operator. + * Sets the scalar function that implements CAST. * - * Registration rejects a function with an operator that also has a data source, or a callback that is part of scanning: - * init global, init local, progress, metrics, filter pushdown, partition data, partitioning and claim batch callbacks, - * projection pushdown and virtual columns. The operator itself carries the init and finalize callbacks. For - * `TABLE_OPERATOR_INPUT_TABLE`, the signature must not declare positional parameters, since the table is the only - * positional argument; registration adds it. It may declare named parameters, which are constant arguments of the call - * as usual. Such a function cannot be overloaded, and its operator cannot have a finalize callback when it is called - * with a table that is correlated with an outer query. For `TABLE_OPERATOR_INPUT_ARGUMENTS`, the operator cannot have a - * finalize callback. + * The cast executes by calling this scalar function, so the bind, init and exec callbacks, the bind and init data, the + * user data and the stability of the scalar function all apply to the cast. The scalar function must take exactly one + * standard parameter whose type is the source type of the cast, and return the target type of the cast; it must have no + * resolve types callback, and it cannot declare a collation handling other than the default + * `FUNCTION_PROPERTY_COLLATION_HANDLING_PROPAGATE`, as a cast converts its input as it is. The function reports a row + * it cannot convert as an error, which aborts the query. Its bind callback cannot replace the call with + * `duckdb_v2_scalar_function_bind_replace_call()`: binding the cast then fails. It is copied: the caller still owns the + * handle and later changes to it do not affect the cast. The scalar function must have been created through a factory + * of the same database as the cast function. Its name is only used in messages. A cast needs a client context to be + * bound, but not to run: when it converts without one, for example while an index key is evaluated, the init and exec + * callbacks of the scalar function receive no context, as those of a scalar function in an index key do. A scalar + * function is required before registration. * * history: * - unstable: v2.0.0 * - * @param function The function to set the operator of. - * @param op The operator producing the function's rows. Borrowed; its configuration is copied. - * @param input Where the operator's input comes from. + * @param function The cast function to set the CAST function of. + * @param scalar_function The scalar function to use. Borrowed for the call only; it is copied, so later changes to it + * do not affect the cast. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_operator(duckdb_v2_table_function_handle function, - duckdb_v2_operator_handle op, - DUCKDB_V2_TABLE_OPERATOR_INPUT input, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_cast_function_set_function(duckdb_v2_cast_function_handle function, + duckdb_v2_scalar_function_handle scalar_function, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a new multi-file function through a factory. + * Sets the scalar function that implements TRY_CAST. * - * The function starts out empty: give it a name with `duckdb_v2_multi_file_function_set_name()` and the single-file - * function it wraps with `duckdb_v2_multi_file_function_set_single_file_function()`, then make it available with - * `duckdb_v2_connection_register_multi_file_function()` or `duckdb_v2_extension_register_multi_file_function()`. The - * caller owns the returned handle and must destroy it with `duckdb_v2_multi_file_function_destroy()`, also after + * It must have the same shape as the function of `duckdb_v2_cast_function_set_function()`. For each row that does not + * convert it writes a NULL into the result vector, and it reports the error through the error slot once the batch is + * written: the engine swallows the error, keeps the rows the callback wrote, and reports that not every row converted, + * which callers that probe a cast, such as the CSV sniffer, rely on. The function runs once per batch, also when it + * reports an error. A row it has not written when it reports the error holds the zero value of the result type: zero + * for the numeric, temporal and UUID types and a DECIMAL of up to 38 digits, an empty VARCHAR, BLOB, LIST or MAP, a BIT + * or BIGNUM of 0, the first member of a non-empty ENUM, an empty point for a GEOMETRY, a VARIANT holding INTEGER 0, or + * a UNION holding the zero value of its first member with its other members NULL, recursively for the fields of a + * STRUCT and the elements of an ARRAY. Every other type, such as a wider DECIMAL, GEOGRAPHY, TYPE or an ENUM without + * members, starts out NULL, and the function marks each row of it it writes valid. Write NULL into each row that does + * not convert. A callback that leaves a row NULL without reporting an error tells the engine the row converted. The + * function can share its exec callback with the function of CAST. A try scalar function is required before * registration. * - * The multi-file function can only be registered on the database the factory belongs to. - * * history: * - unstable: v2.0.0 * - * @param factory The factory to create the multi-file function through. - * @param function On success, receives the newly created multi-file function. Owned by the caller. + * @param function The cast function to set the TRY_CAST function of. + * @param scalar_function The scalar function to use. Borrowed for the call only; it is copied, so later changes to it + * do not affect the cast. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_multi_file_function_create(duckdb_v2_factory_handle factory, - duckdb_v2_multi_file_function_handle *function, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_cast_function_set_try_function(duckdb_v2_cast_function_handle function, + duckdb_v2_scalar_function_handle scalar_function, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the name of the multi-file function, as SQL will call it. + * Registers the cast function, making it available to CAST and TRY_CAST. * - * The name is borrowed and copied. Calling this again replaces the previous name. A name must be set before - * registration. + * The cast is registered on the connection's database and takes effect immediately for every connection; it is not part + * of the connection's transaction, so a rollback does not undo it. Registration requires a source type, a target type, + * and the scalar functions of CAST and TRY_CAST; both types must be fully defined concrete types and the scalar + * functions must convert between them. When a pair already has a cast, the first registration wins and registering + * again changes nothing. The cast function must have been created through a factory of the same database. The caller + * still owns the handle after registration and must destroy it with `duckdb_v2_cast_function_destroy()`, which does not + * affect the registered function. * * history: * - unstable: v2.0.0 * - * @param function The function to set the name of. - * @param name The name to set. Borrowed and copied. - * @param name_length The length of `name` in bytes. `name` need not be null-terminated and may be NULL only when this - * is 0. + * @param conn The connection to register on. + * @param function The cast function to register. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_multi_file_function_set_name(duckdb_v2_multi_file_function_handle function, - const char *name, idx_t name_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_register_cast_function(duckdb_v2_connection_handle conn, + duckdb_v2_cast_function_handle function, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the name of the table function that reads a single file, which the multi-file function wraps. + * Registers the cast function, making it available to CAST and TRY_CAST. * - * The single-file function must be registered before the multi-file function is, and must take the file to read as its - * only positional parameter, of type ANY. It is bound once for every file that is read, and receives the file the way a - * multi-file function takes one: as the VARCHAR path of the file when there is nothing more to know about it, and - * otherwise as a STRUCT holding the path in its `filename` field and the options to open the file with in its other - * fields - e.g. the size of the file, as a file system reported it while globbing, or the options a caller passed along - * with the file (`read_x([{'filename': 'f.x', 'file_size': 42}])`). Opening the file with those options, set with - * `duckdb_v2_file_open_options_set_value()`, lets the file system skip work it would otherwise repeat, such as asking a - * remote store for the size of the file. A single-file function that takes a VARCHAR parameter instead is still - * accepted, and only receives the path. Every named parameter the single-file function declares is also a named - * parameter of the multi-file function, forwarded to it as given. Everything that involves several files - globbing, - * lists of files, hive partitioning, the `filename` column, `union_by_name` and the like - is provided by the - * multi-file function on top of it. The name is borrowed and copied. A single-file function must be set before - * registration. + * The cast is registered on the loading extension's database. Use this from the extension's load callback. Registration + * requires a source type, a target type, and the scalar functions of CAST and TRY_CAST; both types must be fully + * defined concrete types and the scalar functions must convert between them. When a pair already has a cast, the first + * registration wins and registering again changes nothing. The cast function must have been created through a factory + * of the same database. The caller still owns the handle after registration and must destroy it with + * `duckdb_v2_cast_function_destroy()`, which does not affect the registered function. * * history: * - unstable: v2.0.0 * - * @param function The function to set the single-file function of. - * @param name The name of the registered single-file table function. Borrowed and copied. - * @param name_length The length of `name` in bytes. `name` need not be null-terminated and may be NULL only when this - * is 0. + * @param extension The loading extension. + * @param function The cast function to register. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR -duckdb_v2_multi_file_function_set_single_file_function(duckdb_v2_multi_file_function_handle function, const char *name, - idx_t name_length, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_cast_function(duckdb_v2_extension_handle extension, + duckdb_v2_cast_function_handle function, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets how the files the function reads are referred to in messages, e.g. "Avro" or "JSON". + * Destroys the cast function, releasing its resources. * - * Optional: without it, the files are referred to by the name of the multi-file function. The name is borrowed and - * copied. + * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent + * double-destruction. Destroying the handle after registration does not affect the registered function. * * history: * - unstable: v2.0.0 * - * @param function The function to set the reader type of. - * @param reader_type The reader type. Borrowed and copied. - * @param reader_type_length The length of `reader_type` in bytes. `reader_type` need not be null-terminated and may be - * NULL only when this is 0. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via - * `duckdb_v2_error_info_destroy()`. + * @param function The function to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR -duckdb_v2_multi_file_function_set_reader_type(duckdb_v2_multi_file_function_handle function, const char *reader_type, - idx_t reader_type_length, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_cast_function_destroy(duckdb_v2_cast_function_handle *function); #endif +/* --- Struct definitions for cast --- */ + +/* ============================================================================ + * MODULE: prepared_statement + * ============================================================================ */ + +/* --- Enums for prepared_statement --- */ + +/* --- Struct forward declarations for prepared_statement --- */ + +/* --- Types for prepared_statement --- */ + +/*! + * An owned handle to a statement bound and planned once, executable repeatedly via + * `duckdb_v2_prepared_statement_execute()`. Construct with `duckdb_v2_prepared_statement_create()` and destroy with + * `duckdb_v2_prepared_statement_destroy()`. It keeps its connection's session alive, so it stays usable across + * executions and even after the connection is disconnected. + */ +typedef struct _duckdb_v2_prepared_statement { + void *internal_ptr; +} * duckdb_v2_prepared_statement_handle; + +/* --- Constants for prepared_statement --- */ + +/* --- Function pointer typedefs for prepared_statement --- */ + +/* --- Functions for prepared_statement --- */ + #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Sets the file extension of the files the function reads, e.g. "avro". + * Prepares a parsed statement into a reusable handle. Non-consuming. * - * Optional. With a file extension, a path that names a directory rather than a file reads the files with that extension - * inside it. Without one, the paths passed to the function must match at least one file. The extension is given without - * a leading dot, and is borrowed and copied. + * Copies the statement's AST, then binds and plans it once. Binder and catalog errors surface here, exactly as they + * would from `duckdb_v2_statement_execute()`. The statement is borrowed rather than consumed, since a copy is what gets + * prepared, so it can be prepared again or executed directly; the caller destroys it with + * `duckdb_v2_sql_statement_destroy()`. + * + * By default this succeeds for any preparable statement, whether or not its plan will be reused; ask + * `duckdb_v2_prepared_statement_reuses_plan()` which one you got. Setting `require_cacheable` instead fails with + * `ERROR_INPUT_INVALID` when the plan would not be reused, so a caller who wants the handle only for the speedup finds + * out here rather than after silently taking the slow path. + * + * A statement that DuckDB expands into several, such as a dynamic PIVOT, is kept as written and expanded again at each + * execution, in the transaction state of that execution. It runs nothing here, its plan is never reused, and its + * result's metadata is deferred as for `duckdb_v2_statement_execute()`. Parameters on such a statement are refused with + * `ERROR_INPUT_INVALID`. + * + * Refuses with `ERROR_RESOURCE_IN_USE` while a statement on the connection is still running. Drain, destroy, or + * interrupt that result first, or prepare on another connection. `*out_prepared` is set to NULL on failure. * * history: * - unstable: v2.0.0 * - * @param function The function to set the file extension of. - * @param extension The file extension, without a leading dot. Borrowed and copied. - * @param extension_length The length of `extension` in bytes. `extension` need not be null-terminated and may be NULL - * only when this is 0. + * @param conn The connection supplying the catalog, transaction, and parser state. The prepared statement belongs to + * it. + * @param statement The statement to prepare. Borrowed and copied, not consumed; destroy it with + * `duckdb_v2_sql_statement_destroy()`. + * @param require_cacheable When true, fail with `ERROR_INPUT_INVALID` unless the prepared plan will be reused across + * executions, as `duckdb_v2_prepared_statement_reuses_plan()` would report it. + * @param out_prepared On success, receives the new prepared statement. Owned by the caller; destroy via + * `duckdb_v2_prepared_statement_destroy()`. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR -duckdb_v2_multi_file_function_set_file_extension(duckdb_v2_multi_file_function_handle function, const char *extension, - idx_t extension_length, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_prepared_statement_create(duckdb_v2_connection_handle conn, + duckdb_v2_sql_statement_handle statement, + bool require_cacheable, + duckdb_v2_prepared_statement_handle *out_prepared, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the multi-file function, making it available for use in SQL queries. + * Executes a prepared statement, streaming its result. Non-consuming. * - * The function is registered on the connection's database, visible to every connection, in the connection's - * transaction: inside an explicit transaction, it is invisible to other connections until the transaction commits, and - * a rollback undoes it. It can then be called with the path of a single file, a glob pattern, or a list of either, and - * accepts the options every multi-file function accepts (e.g. `filename`, `hive_partitioning`, `union_by_name`) next to - * the named parameters of the single-file function. Registration requires a name and a single-file function, and fails - * when no table function by that name is registered or it does not take the path of the file to read as its only - * positional parameter (see `duckdb_v2_multi_file_function_set_single_file_function()`). The multi-file function must - * have been created through a factory of the same database. The caller still owns the handle after registration and - * must destroy it with `duckdb_v2_multi_file_function_destroy()`, which does not affect the registered function. + * Returns a result without executing anything: execution happens incrementally as the result is stepped or drained, + * exactly as with `duckdb_v2_statement_execute()`. The handle returned is an ordinary result, with identical behaviour + * throughout -- streaming, draining, the changed-row count of a DML statement, the output schema, the statement type, + * and the result type. + * + * `parameter_values` binds the statement's parameters as constants for this execution. Binding is positional by default + * ($1 = element 0); supply `parameter_names` to bind by name instead, where a non-empty entry binds its value to that + * named parameter ($name, matched case-insensitively) and an empty entry stays positional. Pass NULL for both arrays, + * or a count of 0, for a statement without parameters. Both arrays are borrowed and copied in, so the caller still owns + * and destroys them. A key set that does not match the statement's parameters is rejected with `ERROR_INPUT_INVALID`, + * with one exception: a named parameter left without a value reads the session variable of the same name (`SET + * VARIABLE`) when one exists. + * + * Not consumed: execute the same handle again, with the same values or different ones, as often as you like. Values are + * bound per execution and nothing carries over between them. A catalog change since the statement was prepared, or a + * parameter type that differs from the one the cached plan assumed, triggers a re-bind that is invisible apart from its + * cost. + * + * Refuses with `ERROR_RESOURCE_IN_USE` while a statement on the connection is still running; drain, destroy, or + * interrupt that result first, or execute on another connection. A failed execution, at any stage, leaves the prepared + * statement usable. `*out_result` is set to NULL on failure. * * history: * - unstable: v2.0.0 * - * @param conn The connection to register on. - * @param function The multi-file function to register. + * @param prepared The prepared statement to execute. Borrowed; not consumed. + * @param parameter_names Optional. An array of `parameter_count` parameter names; a non-empty entry binds its value to + * the named parameter ($name, case-insensitive), an empty entry (NULL or zero length) keeps it positional ($1 = element + * 0). Pass NULL to bind everything positionally. + * @param parameter_names_lengths Byte lengths of the entries in `parameter_names`; element i is the length of + * `parameter_names[i]`. May be NULL only when `parameter_names` is NULL. + * @param parameter_values Optional. An array of `parameter_count` values. Each binds by name when `parameter_names` + * supplies one, and positionally ($1 = element 0) otherwise. Borrowed and copied in. Pass NULL for a statement without + * parameters. + * @param parameter_count The number of entries in `parameter_names` and `parameter_values`. Pass 0 for a statement + * without parameters. + * @param out_result On success, receives the new result. Owned by the caller; destroy via `duckdb_v2_result_destroy()`. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_register_multi_file_function( - duckdb_v2_connection_handle conn, duckdb_v2_multi_file_function_handle function, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_prepared_statement_execute( + duckdb_v2_prepared_statement_handle prepared, const char *const *parameter_names, + const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, + duckdb_v2_result_handle *out_result, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Registers the multi-file function, making it available for use in SQL queries. + * Reports whether the prepared statement reuses its compiled plan across executions. * - * The function is registered on the loading extension's database and attributed to the extension. Use this from the - * extension's load callback. It can then be called with the path of a single file, a glob pattern, or a list of either, - * and accepts the options every multi-file function accepts (e.g. `filename`, `hive_partitioning`, `union_by_name`) - * next to the named parameters of the single-file function. Registration requires a name and a single-file function, - * and fails when no table function by that name is registered or it does not take the path of the file to read as its - * only positional parameter (see `duckdb_v2_multi_file_function_set_single_file_function()`). The multi-file function - * must have been created through a factory of the same database. The caller still owns the handle after registration - * and must destroy it with `duckdb_v2_multi_file_function_destroy()`, which does not affect the registered function. + * True when executions reuse the plan built at prepare time, provided the supplied values match the planned parameter + * types and nothing the plan depends on has changed; false when the statement re-binds on every execution, making it no + * faster than `duckdb_v2_statement_execute()`. A plan is reused only when all parameter types were resolved at prepare + * time and the plan is cacheable: `SELECT 42` reuses, `SELECT $1::INTEGER + 1` reuses, a statement reading a base table + * does not (it re-binds so a catalog change is picked up), and `SELECT $1 + $2` does not (the types are unknown until + * values arrive). + * + * A static property of the built plan, fixed when the statement was prepared and independent of the values later passed + * to `duckdb_v2_prepared_statement_execute()`. * * history: * - unstable: v2.0.0 * - * @param extension The loading extension. - * @param function The multi-file function to register. + * @param prepared The prepared statement to inspect. + * @param out_reuses Receives true when the compiled plan is reused across executions, false when the statement re-binds + * each time. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_multi_file_function( - duckdb_v2_extension_handle extension, duckdb_v2_multi_file_function_handle function, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_prepared_statement_reuses_plan(duckdb_v2_prepared_statement_handle prepared, + bool *out_reuses, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys the multi-file function, releasing its resources. + * Destroys a prepared statement. * - * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent - * double-destruction. Destroying the handle after registration does not affect the registered function. + * Null-safe: passing NULL, or a slot already set to NULL, is a no-op. A result produced by + * `duckdb_v2_prepared_statement_execute()` is independently owned and keeps the session alive itself, so the prepared + * statement may be destroyed while results made from it are still live. On success the slot is set to NULL. * * history: * - unstable: v2.0.0 * - * @param function The function to destroy. + * @param prepared The prepared statement to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_multi_file_function_destroy(duckdb_v2_multi_file_function_handle *function); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_prepared_statement_destroy(duckdb_v2_prepared_statement_handle *prepared); #endif -/* --- Struct definitions for table --- */ +/* --- Struct definitions for prepared_statement --- */ /* ============================================================================ - * MODULE: value + * MODULE: query_result * ============================================================================ */ -/* --- Enums for value --- */ +/* --- Enums for query_result --- */ -/* --- Struct forward declarations for value --- */ +/*! + * Shape of a query result. QUERY_RESULT carries rows and columns; CHANGED_ROWS carries an affected row count, as an + * INSERT, UPDATE, or DELETE without RETURNING produces; NOTHING covers DDL and other statements with no row output. + */ +typedef enum DUCKDB_V2_RESULT_TYPE { + DUCKDB_V2_RESULT_TYPE_QUERY_RESULT = 0, + DUCKDB_V2_RESULT_TYPE_CHANGED_ROWS = 1, + DUCKDB_V2_RESULT_TYPE_NOTHING = 2, + DUCKDB_V2_RESULT_TYPE_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_RESULT_TYPE; -/* --- Types for value --- */ +/*! + * Outcome of a result_step call. WAITING is the 0-value, so a zero-initialized out-param reads as "no work product yet" + * rather than CHUNK, the same convention VECTOR_TYPE_OTHER follows. The four states are the ones a consumer acts on; + * they are deliberately not a projection of any internal enum. + */ +typedef enum DUCKDB_V2_RESULT_STEP_STATUS { + //! No chunk yet; step again, or block in result_wait. + DUCKDB_V2_RESULT_STEP_STATUS_WAITING = 0, -/* --- Constants for value --- */ + //! A caller-owned chunk was written to *out_chunk, or an array to *out_array. + DUCKDB_V2_RESULT_STEP_STATUS_CHUNK = 1, -/* --- Function pointer typedefs for value --- */ + //! Stream exhausted. Sticky. + DUCKDB_V2_RESULT_STEP_STATUS_FINISHED = 2, -/* --- Functions for value --- */ + //! Query was interrupted. Sticky. + DUCKDB_V2_RESULT_STEP_STATUS_CANCELLED = 3, + DUCKDB_V2_RESULT_STEP_STATUS_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_RESULT_STEP_STATUS; + +/* --- Struct forward declarations for query_result --- */ + +/* --- Types for query_result --- */ + +/* --- Constants for query_result --- */ + +/* --- Function pointer typedefs for query_result --- */ + +/* --- Functions for query_result --- */ #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Destroys a value handle. + * Executes a parsed statement on the connection, streaming its result. Non-consuming. * - * Null-safe: passing nullptr or a slot already set to nullptr is a no-op. On success the slot is set to nullptr. + * Takes a statement produced by the sql_statement module (parse_sql / statement_iterator_next), preprocesses and + * prepares it, and returns a result handle without executing anything: execution happens incrementally as the result is + * stepped (result_step) or drained (result_fetch_chunk). This call reports only the errors detectable at prepare time — + * binder, catalog, pragma preprocessing — while errors raised during execution surface from the stepping functions. * - * history: - * - unstable: v2.0.0 + * The statement is borrowed, not consumed, since a copy is what executes. It can be executed again, for example with a + * different set of values, and the caller destroys it with sql_statement_destroy. * - * @param value The value to destroy. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_destroy(duckdb_v2_value_handle *value); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Returns the value as a BOOLEAN. + * parameter_values binds the statement's parameters as constants for this execution. Binding is positional by default: + * the i-th value binds $(i+1), matching SQL's own convention, so dense $1..$N and ? placeholders work directly. Supply + * parameter_names to bind by name instead — a non-empty name binds its value to that named parameter ($name, matched + * case-insensitively), while an empty entry leaves that value positional. The parameter schema from statement_bind + * lists the names to use. Both arrays are borrowed and copied in; the caller still owns and destroys them. Pass NULL + * for both, or a count of 0, for an unparameterized statement. A key set that does not match the statement's parameters + * — names for a positional statement, or the reverse — is rejected with ERROR_INPUT_INVALID, and named and positional + * parameters cannot be mixed within one statement. Parameters and statement expansion are mutually exclusive: passing + * values for a statement that preprocesses into a group is rejected with ERROR_INPUT_INVALID. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * DuckDB can expand one statement into a group: a dynamic PIVOT, or statement-expanding DDL such as ALTER ... ADD + * COLUMN with a non-constant DEFAULT. The group executes as one result through the same steps, and the stream surfaces + * the rows of the first row-producing statement of the group. A row-producing statement followed by another cannot be + * served as a single result and reports ERROR_QUERY_NOT_IMPLEMENTED; no known expansion produces one. + * + * One running statement per connection: this refuses with ERROR_RESOURCE_IN_USE while a statement on the connection is + * still running. Drain, destroy, or interrupt that result first, or open another connection. + * + * Schema metadata — result type, statement type, column count, names, logical types — is available on the returned + * handle immediately, before the first step. + * + * *out_result is set to nullptr on failure. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload as a bool. + * @param conn The connection on which to execute the statement. + * @param statement The statement to execute. Borrowed and copied; not consumed. Destroy it with sql_statement_destroy. + * @param parameter_names Optional. An array of parameter_count parameter names; a non-empty entry binds its value to + * the named parameter ($name, case-insensitive), an empty entry (NULL or zero length) keeps it positional ($1 = element + * 0). Pass NULL for all-positional binding. Named and positional parameters cannot be mixed within one statement. + * @param parameter_names_lengths Byte lengths of the entries in `parameter_names`; element i is the length of + * `parameter_names[i]`. May be NULL only when `parameter_names` is NULL. + * @param parameter_values Optional. An array of parameter_count value handles. Each binds by name when parameter_names + * supplies one, otherwise positionally ($1 = element 0). Borrowed (copied in). Pass NULL for an unparameterized + * statement. + * @param parameter_count The number of parameters in parameter_names and parameter_values. Pass 0 for an + * unparameterized statement. + * @param out_result Receives the new result handle. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_bool(duckdb_v2_value_handle value, bool *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_statement_execute( + duckdb_v2_connection_handle conn, duckdb_v2_sql_statement_handle statement, const char *const *parameter_names, + const idx_t *parameter_names_lengths, const duckdb_v2_value_handle *parameter_values, idx_t parameter_count, + duckdb_v2_result_handle *out_result, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a UTINYINT. + * Destroys a result handle. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * Null-safe: passing nullptr or a slot already set to nullptr is a no-op. Frees the memory the result owns and releases + * the connection for its next query. Safe at any point in the stream's life. Destroying a result before its statement + * ended (drained, or stepped to FINISHED) aborts the statement. On autocommit, its writes are rolled back. Inside a + * transaction, a statement that may write invalidates the transaction, and a read-only statement just stops. Chunks + * already fetched are caller-owned and stay valid. On success the slot is set to nullptr. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload as a uint8_t. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param result The result to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_utinyint(duckdb_v2_value_handle value, uint8_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_destroy(duckdb_v2_result_handle *result); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a USMALLINT. + * Runs one bounded unit of query execution and returns without blocking. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * The streaming primitive: a step does a bounded amount of execution work, mostly without blocking, and returns control + * to the caller, so an event loop stays responsive and can interleave other work between steps. The conveniences — + * result_wait, result_fetch_chunk, result_drain — block, and are for synchronous callers. out_status reports the + * outcome: + * + * - CHUNK: *out_chunk receives a caller-owned chunk (destroy via data_chunk_destroy). Written only for this status; + * nullptr otherwise. + * - WAITING: no chunk yet, but work was done. Transient: keep stepping and it resolves to CHUNK, FINISHED, CANCELLED, + * or an error. Block in result_wait rather than busy-stepping. + * - FINISHED: stream exhausted. Sticky. + * - CANCELLED: query interrupted via connection_interrupt. Sticky. Cancellation is a status here, not an error; + * result_fetch_chunk, which has no status out-param, reports it as ERROR_RUNTIME_INTERRUPT. + * + * Execution errors come back as the return code plus err, never as a status; out_status is then unspecified and + * *out_chunk is nullptr. Errors are sticky, so later steps report the same code. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload as a uint16_t. + * @param result The result to step. + * @param out_chunk Receives an owned chunk if *out_status is CHUNK; set to nullptr otherwise. + * @param out_status Receives the step status. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_usmallint(duckdb_v2_value_handle value, uint16_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_step(duckdb_v2_result_handle result, + duckdb_v2_data_chunk_handle *out_chunk, + DUCKDB_V2_RESULT_STEP_STATUS *out_status, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a UINTEGER. + * Blocks until the next chunk is available and returns it. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * A convenience over result_step: blocks until a chunk is produced or the stream ends. On success *out_chunk receives a + * caller-owned chunk (destroy via data_chunk_destroy), or nullptr at end-of-stream. End-of-stream is sticky, so later + * calls keep succeeding with *out_chunk set to nullptr. + * + * An interrupted query returns ERROR_RUNTIME_INTERRUPT — the same event result_step reports as status CANCELLED, + * carried on the error channel because this function has no status out-param. + * + * On failure *out_chunk is set to nullptr. Errors are sticky, so later calls report the same code. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload as a uint32_t. + * @param result The result to fetch from. + * @param out_chunk Receives an owned chunk, or nullptr at end-of-stream. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_uint(duckdb_v2_value_handle value, uint32_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_fetch_chunk(duckdb_v2_result_handle result, + duckdb_v2_data_chunk_handle *out_chunk, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a UBIGINT. + * Blocks until result_step can make progress. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * A convenience over result_step: blocks until a step is worth issuing again, that is, until a unit of execution work + * can run on the calling thread. Never produces or consumes chunks. Waiting on a terminal result — FINISHED, CANCELLED, + * or a sticky error — returns immediately; it is a no-op, never an error. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload as a uint64_t. + * @param result The result to wait on. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_ubigint(duckdb_v2_value_handle value, uint64_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_wait(duckdb_v2_result_handle result, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a UHUGEINT. + * Renders the result as a box table, consuming it. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * Drains the result into a column data collection and renders it with the same renderer the DuckDB CLI uses, so every + * client displays results identically without reimplementing table formatting. The result is consumed by transfer: the + * slot is set to NULL on success and on failure alike. A partially consumed result is accepted, and the remainder is + * what gets rendered. * - * history: - * - unstable: v2.0.0 + * The whole remaining result materializes in memory before rendering. max_rows bounds what is DISPLAYED, not what is + * read, so with limit 0 the footer's row count is exact. A caller who cannot afford full materialization should bound + * the query itself (e.g. LIMIT n) and pass n as limit; the footer then renders "? rows" whenever the result fills that + * bound, since the true total is unknown at that point. * - * @param value The value to read. - * @param out Receives the payload as a uint128_t. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. - * @return DUCKDB_V2_ERROR - */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_uhugeint(duckdb_v2_value_handle value, duckdb_v2_uhugeint_t *out, - duckdb_v2_error_info_handle *err); -#endif - -#if DUCKDB_V2_API_ALLOW_UNSTABLE -/*! - * Returns the value as a TINYINT. + * Zero selects the renderer default for each sizing knob: max_rows 20, max_width the probed terminal width or 80 when + * that is unavailable, max_col_width 20. An empty null_value renders NULL cells as the default "NULL" text. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * The rendered text goes to sink rather than being returned: a box can be large, and this way nothing allocates a + * buffer the caller has to free. The sink is called exactly once with the whole box, so its view carries the full + * length — write it straight to a stream, or copy it into your own string. sink must not be NULL. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload as an int8_t. + * @param result The result to render; consumed and set to NULL. Left intact only when the call rejects null arguments. + * @param max_rows Maximum rows displayed; 0 selects the renderer default (20). + * @param max_width Maximum total width in characters; 0 selects the renderer default. + * @param max_col_width Maximum width of one column; 0 selects the renderer default (20). + * @param null_value Text rendered for NULL cells; empty selects "NULL". + * @param null_value_length The length of `null_value` in bytes. `null_value` need not be null-terminated and may be + * NULL only when this is 0. + * @param render_mode 0 renders rows (records down the page); 1 renders columns; other values are rejected with + * INVALID_INPUT. + * @param limit The row limit the caller applied to the query before rendering; 0 means none. When the materialized + * result holds exactly this many rows the true total is unknown, so the footer renders "? rows" instead of an exact + * count. + * @param sink Receives the whole rendered box in a single call. Borrowed for the duration of that call; see text_sink + * for the full contract. + * @param user_data Opaque pointer passed through to sink untouched. May be NULL. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_tinyint(duckdb_v2_value_handle value, int8_t *out, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_render_box(duckdb_v2_result_handle *result, idx_t max_rows, + idx_t max_width, idx_t max_col_width, const char *null_value, + idx_t null_value_length, idx_t render_mode, idx_t limit, + duckdb_v2_text_sink_fn sink, void *user_data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a SMALLINT. + * Runs the result to completion and reports the changed-row count. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * A convenience over result_step: blocks until the stream is fully consumed, so every side effect is applied. Rows of a + * row-producing result are discarded. For a CHANGED_ROWS result *out_rows_changed receives the affected row count; for + * every other result type, and for a stream whose Count chunk was already consumed, it receives 0. + * + * The result type (result_get_result_type) is prepare-time metadata, so a caller can choose between consuming rows and + * draining without inspecting the SQL. Draining an already FINISHED result succeeds. Cancellation surfaces as + * ERROR_RUNTIME_INTERRUPT; errors are sticky, and on failure *out_rows_changed is unspecified. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload as an int16_t. + * @param result The result to drain. + * @param out_rows_changed Receives the affected row count for CHANGED_ROWS results, 0 otherwise. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_smallint(duckdb_v2_value_handle value, int16_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_drain(duckdb_v2_result_handle result, idx_t *out_rows_changed, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as an INTEGER. + * Returns the shape of the result: query, changed rows, or nothing. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * QUERY_RESULT for statements that produce rows (SELECT, RETURNING, EXPLAIN), CHANGED_ROWS for an INSERT, UPDATE, or + * DELETE without RETURNING, NOTHING for DDL and other statements with no row output. + * + * Prepare-time metadata: available from statement_execute on, except for a statement that expands into a group, where + * it fails with ERROR_INPUT_METADATA_DEFERRED until stepping has bound the row-producing statement, or the group ended + * without one. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload as an int32_t. + * @param result The result. + * @param out_type Receives the result shape. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_int(duckdb_v2_value_handle value, int32_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_get_result_type(duckdb_v2_result_handle result, + DUCKDB_V2_RESULT_TYPE *out_type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a BIGINT. + * Returns the SQL statement type that produced the result. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * Prepare-time metadata: available from statement_execute on. A statement that expands into a group reports its type as + * written: MULTI, or PRAGMA for a pragma such as IMPORT DATABASE. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload as an int64_t. + * @param result The result. + * @param out_type Receives the statement type. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_bigint(duckdb_v2_value_handle value, int64_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_get_statement_type(duckdb_v2_result_handle result, + DUCKDB_V2_STATEMENT_TYPE *out_type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a HUGEINT. + * Returns the result's output schema as a single schema handle. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * Builds an owned schema of the result's column names and types into *out_schema; destroy it via schema_destroy. + * Prepare-time metadata, available before the first step, or for an expanding statement once stepping has bound the + * row-producing statement (before that it fails with ERROR_INPUT_METADATA_DEFERRED). Never empty: a non-SELECT reports + * a single status column, either a BIGINT changed-rows count or a BOOLEAN success. + * + * This schema is the authoritative source for the column types of the chunks the result produces; vectors do not carry + * their own type. + * + * *out_schema is set to NULL on failure. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload as an int128_t. + * @param result The result. + * @param out_schema Receives the owned output schema. Destroy via schema_destroy. * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_hugeint(duckdb_v2_value_handle value, duckdb_v2_hugeint_t *out, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_result_get_schema(duckdb_v2_result_handle result, + duckdb_v2_schema_handle *out_schema, duckdb_v2_error_info_handle *err); #endif -#if DUCKDB_V2_API_ALLOW_UNSTABLE +/* --- Struct definitions for query_result --- */ + +/* ============================================================================ + * MODULE: table + * ============================================================================ */ + +/* --- Enums for table --- */ + +/*! + * Whether a table function's scan is partitioned by a given set of columns, and how. Reported by + * `duckdb_v2_table_function_set_partitioning_callback()` via + * `duckdb_v2_table_function_partitioning_set_partition_info()`. + */ +typedef enum DUCKDB_V2_TABLE_PARTITION_INFO { + //! The scan is not known to be partitioned by the requested columns. + DUCKDB_V2_TABLE_PARTITION_INFO_NOT_PARTITIONED = 0, + + //! Each partition the scan produces carries exactly one distinct value for the requested columns. + DUCKDB_V2_TABLE_PARTITION_INFO_SINGLE_VALUE_PARTITIONS = 1, + + //! The partitions the scan produces overlap only at their boundaries. + DUCKDB_V2_TABLE_PARTITION_INFO_OVERLAPPING_PARTITIONS = 2, + + //! The partitions the scan produces are disjoint ranges. + DUCKDB_V2_TABLE_PARTITION_INFO_DISJOINT_PARTITIONS = 3, + DUCKDB_V2_TABLE_PARTITION_INFO_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_TABLE_PARTITION_INFO; + +/*! + * A column a table function can produce next to the columns it declares in bind. A query asks for it by name, but it is + * not part of the function's result columns. Declared with `duckdb_v2_table_function_add_virtual_column()`. In the + * column lists of the scan (e.g. `duckdb_v2_data_source_exec_get_column_index()`), a virtual column is identified by + * 2^63 plus its value in this enum. + */ +typedef enum DUCKDB_V2_TABLE_VIRTUAL_COLUMN { + /*! + * `file_row_number`, a BIGINT holding the position of the row within the file it was read from, counting from 0. A + * function that reads a single file produces it when it is wrapped in a multi-file function (see + * `duckdb_v2_multi_file_function_create()`), which is where the name of the file comes from. + */ + DUCKDB_V2_TABLE_VIRTUAL_COLUMN_FILE_ROW_NUMBER = 0, + DUCKDB_V2_TABLE_VIRTUAL_COLUMN_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_TABLE_VIRTUAL_COLUMN; + +/*! + * Where the input of a table function's operator comes from: what the rows of the input chunks the operator receives + * are. Chosen with `duckdb_v2_table_function_set_operator()`. + */ +typedef enum DUCKDB_V2_TABLE_OPERATOR_INPUT { + /*! + * The positional arguments of a call of the function are the columns of the operator's input, one row per set of + * arguments. Called with constant arguments, e.g. `f(1, 'a')`, the operator receives a single input row. Called + * with arguments that reference the columns of a table that precedes the call in the `FROM` clause, e.g. `FROM t, + * f(t.x)` (an implicit `LATERAL` join), it receives one input row per row of that table, one at a time, and every + * row it produces is joined to the row of `t` it was produced for. + */ + DUCKDB_V2_TABLE_OPERATOR_INPUT_ARGUMENTS = 0, + + /*! + * The function takes a table as its first argument, written as a subquery, e.g. `f((SELECT * FROM t))`, and the + * operator receives the rows of that table as its input, chunk by chunk, possibly on several threads. The columns + * of its input are the columns of the table. + */ + DUCKDB_V2_TABLE_OPERATOR_INPUT_TABLE = 1, + DUCKDB_V2_TABLE_OPERATOR_INPUT_MAX_ENUM = 0x7FFFFFFF, +} DUCKDB_V2_TABLE_OPERATOR_INPUT; + +/* --- Struct forward declarations for table --- */ + +/* --- Types for table --- */ + +/*! + * An owned opaque handle to a custom table function being built. Created with `duckdb_v2_table_function_create()`, + * configured with the setter functions (e.g. `duckdb_v2_table_function_set_name()`, + * `duckdb_v2_table_function_set_data_source()`, etc.) and the signature obtained via + * `duckdb_v2_table_function_get_signature()`, made available with `duckdb_v2_connection_register_table_function()` or + * `duckdb_v2_extension_register_table_function()`, and destroyed with `duckdb_v2_table_function_destroy()`. + */ +typedef struct _duckdb_v2_table_function { + void *internal_ptr; +} * duckdb_v2_table_function_handle; + /*! - * Returns the value as a VARCHAR. - * - * The string is borrowed from the value and stays valid until the value is destroyed. That borrow is why this getter - * does not convert: a converted copy would not outlive the call. A value of any other type id, and a NULL value, return - * ERROR_INPUT_INVALID. - * - * history: - * - unstable: v2.0.0 - * - * @param value The value to read. - * @param out Receives the payload as a UTF-8 string. The returned string is borrowed and valid until the value handle - * is destroyed. - * @param out_length Receives the length of `*out` in bytes. `*out` is not guaranteed to be null-terminated. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. - * @return DUCKDB_V2_ERROR + * A borrowed opaque handle to the result of a table function's "bind" phase. The "bind" callback receives this handle + * next to a `duckdb_v2_function_bind_info_handle`, which gives access to the arguments, the user data and the bind + * data. It must use this handle to declare the columns the function returns, and can use it to hint at the number of + * rows the scan will produce. */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_varchar(duckdb_v2_value_handle value, const char **out, - idx_t *out_length, duckdb_v2_error_info_handle *err); -#endif +typedef struct _duckdb_v2_table_function_bind_info { + void *internal_ptr; +} * duckdb_v2_table_function_bind_info_handle; -#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a byte string: a BLOB, or the storage bytes of a BIT, a BIGNUM, or a DECIMAL wider than 38 - * digits (the BIGNUM storage of its unscaled value, for bignum_decode). - * - * The string is borrowed from the value and stays valid until the value is destroyed. That borrow is why this getter - * does not convert: a converted copy would not outlive the call. A value of any other type id, and a NULL value, return - * ERROR_INPUT_INVALID. - * - * history: - * - unstable: v2.0.0 - * - * @param value The value to read. - * @param out Receives the payload as a byte string. The returned string is borrowed and valid until the value handle is - * destroyed. - * @param out_length Receives the length of `*out` in bytes. `*out` is not guaranteed to be null-terminated. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. - * @return DUCKDB_V2_ERROR + * A borrowed opaque handle to the arguments supplied to a table function during the "filter pushdown" phase of query + * optimization. The "filter pushdown" callback receives this handle and can use it to inspect the filter predicates the + * query applies to the function's rows, and to accept the ones it will apply itself. */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_blob(duckdb_v2_value_handle value, const char **out, idx_t *out_length, - duckdb_v2_error_info_handle *err); -#endif +typedef struct _duckdb_v2_table_function_filter_pushdown_info { + void *internal_ptr; +} * duckdb_v2_table_function_filter_pushdown_info_handle; -#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a FLOAT. - * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. - * - * history: - * - unstable: v2.0.0 - * - * @param value The value to read. - * @param out Receives the payload as a float. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. - * @return DUCKDB_V2_ERROR + * A borrowed opaque handle to the arguments supplied to a table function during the "stats" phase of query + * optimization. The engine invokes the callback once per column the query reads, and the callback can use the handle to + * find out which column is asked about and to report what it knows about the column's values (its minimum and maximum, + * whether it holds NULLs, ...) by narrowing the statistics of that column. */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_float(duckdb_v2_value_handle value, float *out, - duckdb_v2_error_info_handle *err); -#endif +typedef struct _duckdb_v2_table_function_stats_info { + void *internal_ptr; +} * duckdb_v2_table_function_stats_info_handle; -#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a DOUBLE. - * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. - * - * history: - * - unstable: v2.0.0 - * - * @param value The value to read. - * @param out Receives the payload as a double. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. - * @return DUCKDB_V2_ERROR + * A borrowed opaque handle to the arguments supplied to a table function during the "partitioning" phase of query + * optimization. The engine invokes the callback once per candidate `GROUP BY` column set, before execution starts, to + * decide whether the scan can feed a partitioned aggregate directly instead of hashing. */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_double(duckdb_v2_value_handle value, double *out, - duckdb_v2_error_info_handle *err); -#endif +typedef struct _duckdb_v2_table_function_partitioning_info { + void *internal_ptr; +} * duckdb_v2_table_function_partitioning_info_handle; -#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a DATE. - * - * The payload is days since 1970-01-01, the same unit a vector of this type exposes. - * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. - * - * history: - * - unstable: v2.0.0 - * - * @param value The value to read. - * @param out Receives the payload. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. - * @return DUCKDB_V2_ERROR + * A borrowed opaque handle to the arguments supplied to a table function when the engine asks it to describe a bound + * call. The "get bind info" callback receives this handle, and can use it to describe the call in more detail than its + * columns: with identifiers of its columns (e.g. field ids), and with options - key-value facts about what the call + * reads. */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_date(duckdb_v2_value_handle value, int32_t *out, - duckdb_v2_error_info_handle *err); -#endif +typedef struct _duckdb_v2_table_function_get_bind_info_info { + void *internal_ptr; +} * duckdb_v2_table_function_get_bind_info_info_handle; -#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a TIME. - * - * The payload is microseconds since midnight, the same unit a vector of this type exposes. - * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. - * - * history: - * - unstable: v2.0.0 - * - * @param value The value to read. - * @param out Receives the payload. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. - * @return DUCKDB_V2_ERROR + * A borrowed opaque handle to the arguments supplied to a table function when the engine describes a bound call of it + * in a query plan, e.g. for `EXPLAIN`. The "to string" callback receives this handle and can use it to report the + * key-value pairs the plan shows for the scan. */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_time(duckdb_v2_value_handle value, int64_t *out, - duckdb_v2_error_info_handle *err); -#endif +typedef struct _duckdb_v2_table_function_to_string_info { + void *internal_ptr; +} * duckdb_v2_table_function_to_string_info_handle; -#if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a TIME_NS. - * - * The payload is nanoseconds since midnight, the same unit a vector of this type exposes. - * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. - * - * history: - * - unstable: v2.0.0 - * - * @param value The value to read. - * @param out Receives the payload. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. - * @return DUCKDB_V2_ERROR + * An owned opaque handle to a multi-file table function being built. A multi-file function wraps an already registered + * table function that reads a single file, and adds everything that is needed to read many files at once on top of it: + * globbing, lists of files, hive partitioning, the `filename` column, `union_by_name` and the like. Created with + * `duckdb_v2_multi_file_function_create()`, configured with the setter functions (e.g. + * `duckdb_v2_multi_file_function_set_name()`, `duckdb_v2_multi_file_function_set_single_file_function()`), made + * available with `duckdb_v2_connection_register_multi_file_function()` or + * `duckdb_v2_extension_register_multi_file_function()`, and destroyed with `duckdb_v2_multi_file_function_destroy()`. */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_time_ns(duckdb_v2_value_handle value, int64_t *out, - duckdb_v2_error_info_handle *err); -#endif +typedef struct _duckdb_v2_multi_file_function { + void *internal_ptr; +} * duckdb_v2_multi_file_function_handle; + +/* --- Constants for table --- */ + +/* --- Function pointer typedefs for table --- */ + +typedef void (*duckdb_v2_table_function_bind_callback_fn)(duckdb_v2_function_bind_info_handle info, + duckdb_v2_table_function_bind_info_handle result, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_table_function_filter_pushdown_callback_fn)( + duckdb_v2_table_function_filter_pushdown_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_table_function_partitioning_callback_fn)( + duckdb_v2_table_function_partitioning_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_table_function_get_bind_info_callback_fn)( + duckdb_v2_table_function_get_bind_info_info_handle info, duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_table_function_stats_callback_fn)(duckdb_v2_table_function_stats_info_handle info, + duckdb_v2_context_handle context, + duckdb_v2_error_info_handle *err); + +typedef void (*duckdb_v2_table_function_to_string_callback_fn)(duckdb_v2_table_function_to_string_info_handle info, + duckdb_v2_error_info_handle *err); + +/* --- Functions for table --- */ #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a TIME_TZ. + * Creates a new table function through a factory. * - * The payload packs the time of day and the UTC offset into one integer, in the committed layout: micros in the high 40 - * bits, a biased offset in the low 24. The same form a vector of this type exposes. + * The function starts out empty: configure it with the setter functions (e.g. `duckdb_v2_table_function_set_name()`, + * `duckdb_v2_table_function_set_data_source()`, etc.) and the signature obtained via + * `duckdb_v2_table_function_get_signature()`, then make it available with + * `duckdb_v2_connection_register_table_function()` or `duckdb_v2_extension_register_table_function()`. The caller owns + * the returned handle and must destroy it with `duckdb_v2_table_function_destroy()`, also after registration. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * The table function can only be registered on the database the factory belongs to. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param factory The factory to create the table function through. + * @param function On success, receives the newly created table function. Owned by the caller. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_time_tz(duckdb_v2_value_handle value, uint64_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_create(duckdb_v2_factory_handle factory, + duckdb_v2_table_function_handle *function, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a TIMESTAMP. - * - * The payload is microseconds since 1970-01-01, the same unit a vector of this type exposes. + * Sets the name of the table function. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * The name is borrowed and copied. Calling this again replaces the previous name. A name must be set before + * registration. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the name of. + * @param name The name to set. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_timestamp(duckdb_v2_value_handle value, int64_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_name(duckdb_v2_table_function_handle function, + const char *name, idx_t name_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a TIMESTAMP_SEC. - * - * The payload is seconds since 1970-01-01, the same unit a vector of this type exposes. + * Returns the documentation of the function so it can be filled in. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * Set a description with `duckdb_v2_function_docs_set_description()`, and add examples and categories with + * `duckdb_v2_function_docs_add_example()` and `duckdb_v2_function_docs_add_category()`. The documentation is modified + * in place, describes this overload only, and is registered with the function. Optional. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to get the documentation of. + * @param docs The returned documentation. Borrowed and valid for the lifetime of the function handle. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_timestamp_sec(duckdb_v2_value_handle value, int64_t *out, +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_get_docs(duckdb_v2_table_function_handle function, + duckdb_v2_function_docs_handle *docs, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a TIMESTAMP_MS. - * - * The payload is milliseconds since 1970-01-01, the same unit a vector of this type exposes. + * Returns the function's signature so it can be configured. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * Add parameters with `duckdb_v2_function_signature_add_parameter()`. The signature is modified in place. A table + * function declares the columns it returns from its bind callback instead of through a return type, so registration + * rejects a signature whose return type was set with `duckdb_v2_function_signature_set_return_type()`. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to get the signature of. + * @param sig The returned signature. Borrowed and valid for the lifetime of the function handle. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_timestamp_ms(duckdb_v2_value_handle value, int64_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_get_signature(duckdb_v2_table_function_handle function, + duckdb_v2_function_signature_handle *sig, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a TIMESTAMP_NS. - * - * The payload is nanoseconds since 1970-01-01, the same unit a vector of this type exposes. + * Sets a property on the table function. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * Only `FUNCTION_PROPERTY_STABILITY` is supported for table functions; any other key, a key that is not valid for table + * functions, or a value that does not belong to `key` results in an error. A table function defaults to + * `FUNCTION_PROPERTY_STABILITY_VOLATILE`. Declaring `FUNCTION_PROPERTY_STABILITY_CONSISTENT_WITHIN_QUERY` promises that + * repeated executions with the same bound data and input rows return equivalent rows within one query and have no + * observable side effects, which allows the optimizer to share identical scans. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the property of. + * @param key The property to set. + * @param value The value to set for the property. Must belong to `key`. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_timestamp_ns(duckdb_v2_value_handle value, int64_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_property(duckdb_v2_table_function_handle function, + DUCKDB_V2_FUNCTION_PROPERTY_KEY key, + DUCKDB_V2_FUNCTION_PROPERTY_VALUE value, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a TIMESTAMP_TZ. - * - * The payload is microseconds since 1970-01-01, in UTC, the same unit a vector of this type exposes. + * Sets arbitrary user data on the table function. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * Associates an opaque pointer with the function, retrievable from the callbacks via + * `duckdb_v2_function_bind_get_user_data()`, `duckdb_v2_data_source_init_global_get_user_data()`, + * `duckdb_v2_data_source_exec_get_user_data()` and their counterparts on the other phases. The opaque handle bundles + * the pointer with an optional destructor, invoked when the data is no longer needed. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the user data of. + * @param data Opaque handle bundling the user data pointer plus an optional destructor. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_timestamp_tz(duckdb_v2_value_handle value, int64_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_user_data(duckdb_v2_table_function_handle function, + duckdb_v2_opaque *data, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a TIMESTAMP_TZ_NS. - * - * The payload is nanoseconds since 1970-01-01, in UTC, the same unit a vector of this type exposes. + * Sets the bind callback of the table function. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * The bind callback is invoked during query planning for each call site of the function. It must declare the columns + * the function returns via `duckdb_v2_table_function_bind_add_result_column()`. Through its + * `duckdb_v2_function_bind_info_handle` it can also inspect the constant argument values and set "bind data" that is + * shared with all later callbacks. A bind callback must be set before registration. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the bind callback of. + * @param callback The bind callback to set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_timestamp_tz_ns(duckdb_v2_value_handle value, int64_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_bind_callback( + duckdb_v2_table_function_handle function, duckdb_v2_table_function_bind_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as an INTERVAL. - * - * The payload is the (months, days, micros) triple, the same unit a vector of this type exposes. + * Sets whether the table function supports projection pushdown. Defaults to false. * - * A value of a different type is converted through the default cast set, on a copy, so reading never alters the value. - * An unsupported conversion returns ERROR_INPUT_INVALID, as does a NULL value. + * With projection pushdown, the engine asks the function for only the columns a query actually uses: the exec + * callback's output chunk holds one vector per requested column rather than one per column declared in bind, and the + * global init, local init and exec callbacks can look up which declared column each vector stands for via e.g. + * `duckdb_v2_data_source_exec_get_column_index()`. Without it the output chunk always holds every declared column, and + * the engine drops the unused ones itself. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the payload. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to configure. + * @param enable Whether the function supports projection pushdown. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_interval(duckdb_v2_value_handle value, duckdb_v2_interval_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_projection_pushdown(duckdb_v2_table_function_handle function, + bool enable, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a UUID, in its internal 128-bit form. + * Declares that the table function can produce the given virtual column. * - * The dual of value_create_uuid: the storage form a vector element holds, with the high bit flipped so the integer - * sorts, rather than the canonical byte order. A value of any other type id, and a NULL value, return - * ERROR_INPUT_INVALID. + * A virtual column is not one of the columns declared in bind: the query asks for it by name, and the function only + * produces it when it is asked for. It then takes up a vector of the exec callback's output chunk, like any other + * column the scan produces. This requires projection pushdown (see + * `duckdb_v2_table_function_set_projection_pushdown()`), which is what lets the engine ask for it. The global init, + * local init and exec callbacks recognize the vector by its column index, which is 2^63 plus the value of the + * `DUCKDB_V2_TABLE_VIRTUAL_COLUMN` (see e.g. `duckdb_v2_data_source_exec_get_column_index()`). * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the internal 128-bit storage form. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to configure. + * @param column The virtual column the function can produce. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_uuid(duckdb_v2_value_handle value, duckdb_v2_hugeint_t *out, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_add_virtual_column(duckdb_v2_table_function_handle function, + DUCKDB_V2_TABLE_VIRTUAL_COLUMN column, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value as a DECIMAL: its backing integer plus the width and scale of its type. + * Sets the optional filter pushdown callback of the table function. * - * The integer is the value scaled by 10^scale — the dual of value_create_decimal — widened to 128 bits from whatever - * storage tier the width selects. The integer getters convert, so a DECIMAL read through value_get_bigint is its - * numeric value with the fraction dropped; this one always reports storage instead, together with the scale needed to - * interpret it. A value of any other type id, and a NULL value, return ERROR_INPUT_INVALID. A DECIMAL wider than 38 - * digits (stored as BIGNUM) is reported the same way, whatever its width, as long as its backing integer fits in 128 - * bits. Beyond that the call fails, and the exact backing integer is read without a conversion: value_get_blob hands - * back the BIGNUM storage bytes, bignum_decode turns them into a sign and a big-endian magnitude, and the width and - * scale come from the value's logical type (value_get_logical_type and logical_type_get_param). + * The filter pushdown callback is invoked while the query is optimized, after the bind callback and before any init + * callback, with the filter predicates the query applies to the function's rows. Each predicate is a bound expression + * the callback can inspect with the `expression` functions; the callback accepts the predicates it will apply itself + * via `duckdb_v2_table_function_filter_pushdown_accept()`, typically after recording what they select in the bind data. + * The engine then stops applying the accepted predicates and keeps applying the rest above the scan, so accepting a + * predicate is a promise to filter the rows exactly as it would have. The optimizer may invoke the callback more than + * once for the same query, each time with the predicates not yet accepted; it is not invoked when there are none. + * + * A function that also has projection pushdown (see `duckdb_v2_table_function_set_projection_pushdown()`) is offered + * the predicates that apply to a single column of it once more when a scan starts, just before the global init + * callback, in the same form, with the column references resolved by + * `duckdb_v2_table_function_filter_pushdown_get_column_index()` as at optimization time. This is how the callback of a + * function wrapped in a multi-file function sees the predicates, which the optimizer only offers to the wrapper. The + * engine applies these predicates to the rows the function produces itself, so the function may use them to skip what + * the query can never use but does not have to understand them, and accepting one has no effect. The scan keeps the + * columns the predicates are applied to. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out Receives the backing integer, scaled by 10^scale. - * @param out_width Receives the total digit count of the value's type. - * @param out_scale Receives the digits after the decimal point. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the filter pushdown callback of. + * @param callback The filter pushdown callback to set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_decimal(duckdb_v2_value_handle value, duckdb_v2_hugeint_t *out, - uint32_t *out_width, uint32_t *out_scale, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_filter_pushdown_callback( + duckdb_v2_table_function_handle function, duckdb_v2_table_function_filter_pushdown_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Unwraps the logical type carried by a TYPE value. + * Sets the optional "partitioning" callback of the table function. * - * Returns ERROR_INPUT_INVALID unless the value is a non-NULL TYPE value. The returned logical type is caller-owned and - * must be destroyed via logical_type_destroy. + * The callback tells the query optimizer, for a candidate `GROUP BY` column set, whether every partition the scan + * produces carries exactly one distinct value for those columns; only `TABLE_PARTITION_INFO_SINGLE_VALUE_PARTITIONS` + * unlocks the partitioned aggregate optimization; any other result, or leaving this callback unset, keeps the regular + * hash aggregate. It runs on the planning thread, before execution starts, and must be deterministic for a given column + * set since it may be called on a plan the optimizer later discards. Registration fails unless + * `duckdb_v2_data_source_set_partition_data_callback()` is set too, since the engine asks that callback for the + * partitioning column values once this one claims single-value partitions. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out_type Receives the owned logical type. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the partitioning callback of. + * @param callback The partitioning callback to set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_type(duckdb_v2_value_handle value, - duckdb_v2_logical_type_handle *out_type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_partitioning_callback( + duckdb_v2_table_function_handle function, duckdb_v2_table_function_partitioning_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a NULL value of the given logical type. + * Sets the optional stats callback of the table function. * - * The logical type is borrowed and copied into the value, so the caller can destroy it independently. + * The stats callback is invoked during query optimization once for each declared column the query reads, when the + * engine wants to know about the column's values without reading them - e.g. to prune a scan whose filter no value can + * satisfy, to answer `min()` / `max()` from the statistics, or to estimate the selectivity of a filter. Through its + * `duckdb_v2_table_function_stats_info_handle` the callback narrows the statistics of that column (see + * `duckdb_v2_table_function_stats_get_result_stats()`): its minimum and maximum, whether it holds NULLs, the statistics + * of the children of a nested column, ... Leaving the statistics unchanged tells the engine nothing about the column. + * The statistics must hold for every row the call produces: a bound that excludes a value the scan then produces leads + * to wrong results. A function without a stats callback gives the engine no statistics for its columns. The callback is + * only asked about whole declared columns, never about virtual columns or about fields extracted from a column. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param type The borrowed logical type to attach to the NULL value. - * @param out_value Receives the new NULL value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the stats callback of. + * @param callback The stats callback to set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_null(duckdb_v2_factory_handle factory, - duckdb_v2_logical_type_handle type, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_stats_callback( + duckdb_v2_table_function_handle function, duckdb_v2_table_function_stats_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a BOOLEAN value from a bool. + * Declares one of the columns the function returns. * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * Call this once per column, in order: the columns declared here are the columns of the table the function produces, + * and the vectors of the output chunk the exec callback fills follow the same order. At least one column must be + * declared. The type must be a fully defined concrete type; ANY is rejected, as a result column carries data. The name + * and type are borrowed and copied. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The bool to wrap. - * @param out_value Receives the new BOOLEAN value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The bind info handle. + * @param name The name of the column. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` must be valid UTF-8, need not be null-terminated, and may be + * NULL only when this is 0. + * @param type The type of the column. Borrowed and copied. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_bool(duckdb_v2_factory_handle factory, bool in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_bind_add_result_column( + duckdb_v2_table_function_bind_info_handle info, const char *name, idx_t name_length, + duckdb_v2_logical_type_handle type, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a UTINYINT value from a uint8_t. + * Sets the estimated number of rows the scan will produce. * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * The estimate is a hint for the optimizer, not a limit: producing a different number of rows is not an error. Without + * it, the optimizer falls back on its own defaults. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The uint8_t to wrap. - * @param out_value Receives the new UTINYINT value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The bind info handle. + * @param cardinality The estimated number of rows. + * @param is_exact Whether the estimate is exact, which also makes it an upper bound on the row count. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_utinyint(duckdb_v2_factory_handle factory, uint8_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_bind_set_cardinality( + duckdb_v2_table_function_bind_info_handle info, idx_t cardinality, bool is_exact, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a USMALLINT value from a uint16_t. + * Sets the order guarantee of the rows this call of the function produces. Defaults to + * `ORDER_PRESERVATION_INSERTION_ORDER`. * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * With `ORDER_PRESERVATION_NO_ORDER`, a scan that reports more than one thread via + * `duckdb_v2_data_source_init_global_set_max_threads()` runs in parallel into query results, INSERT and COPY without a + * `duckdb_v2_data_source_set_partition_data_callback()`, and the rows arrive in no particular order. With insertion + * order kept, those consumers need the partition data callback to run in parallel. Fails with `ERROR_INPUT_INVALID` + * when order is not one of the enum's declared values. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The uint16_t to wrap. - * @param out_value Receives the new USMALLINT value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The bind info handle. + * @param order The order guarantee of the produced rows. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_usmallint(duckdb_v2_factory_handle factory, uint16_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_bind_set_order_preservation( + duckdb_v2_table_function_bind_info_handle info, DUCKDB_V2_ORDER_PRESERVATION order, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a UINTEGER value from a uint32_t. - * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`, or null if none was set. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The uint32_t to wrap. - * @param out_value Receives the new UINTEGER value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The filter pushdown info handle. + * @param data Receives the user data pointer. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_uint(duckdb_v2_factory_handle factory, uint32_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_filter_pushdown_get_user_data( + duckdb_v2_table_function_filter_pushdown_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a UBIGINT value from a uint64_t. + * Retrieves the bind data set via `duckdb_v2_function_bind_set_bind_data()`, or null if none was set. * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * This is the same object the init and exec callbacks later receive, so a predicate the callback accepts can be + * recorded in it for the scan to apply. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The uint64_t to wrap. - * @param out_value Receives the new UBIGINT value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The filter pushdown info handle. + * @param data Receives the bind data pointer. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_ubigint(duckdb_v2_factory_handle factory, uint64_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_filter_pushdown_get_bind_data( + duckdb_v2_table_function_filter_pushdown_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a UHUGEINT value from a uint128_t. + * Returns the number of filter predicates offered to the function. * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * The predicates are combined with `AND`: every row the scan produces must satisfy all of them. Valid indices for + * `duckdb_v2_table_function_filter_pushdown_get_filter()` and `duckdb_v2_table_function_filter_pushdown_accept()` are + * `0` up to (but excluding) this count. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The uint128_t to wrap. - * @param out_value Receives the new UHUGEINT value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The filter pushdown info handle. + * @param count Receives the number of predicates. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_uhugeint(duckdb_v2_factory_handle factory, - const duckdb_v2_uhugeint_t *in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_filter_pushdown_get_filter_count( + duckdb_v2_table_function_filter_pushdown_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a TINYINT value from an int8_t. + * Retrieves the filter predicate at the given index. * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * Fails if the index is out of bounds. The predicate is a bound expression evaluating to `BOOLEAN`; inspect it with + * `duckdb_v2_expression_get_type()` and the other `expression` functions, and resolve the column references it contains + * via `duckdb_v2_table_function_filter_pushdown_get_column_index()`. Borrowed; valid only for the duration of the + * callback. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The int8_t to wrap. - * @param out_value Receives the new TINYINT value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The filter pushdown info handle. + * @param index The index of the predicate to retrieve. + * @param filter Receives the borrowed predicate. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_tinyint(duckdb_v2_factory_handle factory, int8_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_filter_pushdown_get_filter( + duckdb_v2_table_function_filter_pushdown_info_handle info, idx_t index, duckdb_v2_expression_handle *filter, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a SMALLINT value from an int16_t. + * Accepts the filter predicate at the given index: the function will apply it itself. * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * The engine stops applying an accepted predicate, so the scan must produce only rows that satisfy it, or the query + * returns rows it should not. Predicates left unaccepted are applied by the engine as usual, so a callback that + * recognizes nothing can simply return. Fails if the index is out of bounds. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The int16_t to wrap. - * @param out_value Receives the new SMALLINT value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The filter pushdown info handle. + * @param index The index of the predicate to accept. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_smallint(duckdb_v2_factory_handle factory, int16_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_filter_pushdown_accept( + duckdb_v2_table_function_filter_pushdown_info_handle info, idx_t index, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates an INTEGER value from an int32_t. + * Returns the number of columns the predicates can refer to. * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * A column reference inside a predicate (`duckdb_v2_expression_column_ref_get_index()`) indexes the columns the query + * reads from the function, not the columns declared in bind. Valid indices for + * `duckdb_v2_table_function_filter_pushdown_get_column_index()` are `0` up to (but excluding) this count. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The int32_t to wrap. - * @param out_value Receives the new INTEGER value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The filter pushdown info handle. + * @param count Receives the number of referable columns. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_int(duckdb_v2_factory_handle factory, int32_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_filter_pushdown_get_column_count( + duckdb_v2_table_function_filter_pushdown_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a BIGINT value from an int64_t. + * Resolves a column reference found in a predicate to the declared column it refers to. * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * Takes the index a `EXPRESSION_TYPE_BOUND_COLUMN_REF` node reports and returns the index of the column among the ones + * declared with `duckdb_v2_table_function_bind_add_result_column()`, in declaration order. Fails if the index is out of + * bounds. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The int64_t to wrap. - * @param out_value Receives the new BIGINT value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The filter pushdown info handle. + * @param index The column index reported by a column reference node. + * @param column_index Receives the index of the declared column. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_bigint(duckdb_v2_factory_handle factory, int64_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_filter_pushdown_get_column_index( + duckdb_v2_table_function_filter_pushdown_info_handle info, idx_t index, idx_t *column_index, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a HUGEINT value from an int128_t. - * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The int128_t to wrap. - * @param out_value Receives the new HUGEINT value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The partitioning info handle. + * @param data Receives the user data pointer, or null if none was set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_hugeint(duckdb_v2_factory_handle factory, - const duckdb_v2_hugeint_t *in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_partitioning_get_user_data( + duckdb_v2_table_function_partitioning_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a VARCHAR value from a UTF-8 string. - * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * Retrieves the bind data set by the function's bind callback. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The UTF-8 string to wrap. - * @param in_value_length The length of `in_value` in bytes. `in_value` need not be null-terminated and may be NULL only - * when this is 0. - * @param out_value Receives the new VARCHAR value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The partitioning info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_varchar(duckdb_v2_factory_handle factory, const char *in_value, - idx_t in_value_length, duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_partitioning_get_bind_data( + duckdb_v2_table_function_partitioning_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a BLOB value from a byte string. + * Returns the number of columns the optimizer is asking about: the candidate `GROUP BY` column set. * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * Valid indices for `duckdb_v2_table_function_partitioning_get_partition_column_index()` are `0` up to (but excluding) + * this count. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The byte string to wrap. - * @param in_value_length The length of `in_value` in bytes. `in_value` need not be null-terminated and may be NULL only - * when this is 0. - * @param out_value Receives the new BLOB value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The partitioning info handle. + * @param count Receives the number of columns in the candidate set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_blob(duckdb_v2_factory_handle factory, const char *in_value, - idx_t in_value_length, duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_partitioning_get_partition_column_count( + duckdb_v2_table_function_partitioning_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a FLOAT value from a float. + * Returns which declared column the candidate `GROUP BY` column at the given index stands for. * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * The result indexes the columns declared with `duckdb_v2_table_function_bind_add_result_column()`, in declaration + * order. Fails if the index is out of bounds. * * history: * - unstable: v2.0.0 - * - * @param factory The factory to create with. - * @param in_value The float to wrap. - * @param out_value Receives the new FLOAT value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * + * @param info The partitioning info handle. + * @param index The index of the candidate column. + * @param column_index Receives the index of the declared column. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_float(duckdb_v2_factory_handle factory, float in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_partitioning_get_partition_column_index( + duckdb_v2_table_function_partitioning_info_handle info, idx_t index, idx_t *column_index, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a DOUBLE value from a double. + * Reports whether every partition the scan produces carries exactly one distinct value for the candidate `GROUP BY` + * column set. * - * The input is copied in. The returned value is caller-owned; destroy it via value_destroy. + * Only `TABLE_PARTITION_INFO_SINGLE_VALUE_PARTITIONS` unlocks the partitioned aggregate optimization; any other value + * keeps the regular hash aggregate. A callback that never calls this is treated as reporting + * `TABLE_PARTITION_INFO_NOT_PARTITIONED`. Fails with `ERROR_INPUT_INVALID` when partition_info is not one of the enum's + * declared values. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The double to wrap. - * @param out_value Receives the new DOUBLE value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The partitioning info handle. + * @param partition_info Whether, and how, the scan is partitioned by the candidate column set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_double(duckdb_v2_factory_handle factory, double in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_partitioning_set_partition_info( + duckdb_v2_table_function_partitioning_info_handle info, DUCKDB_V2_TABLE_PARTITION_INFO partition_info, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a TYPE value from a logical type. + * Returns the number of columns of the input of the function's operator (see + * `duckdb_v2_table_function_set_operator()`). * - * The logical type is borrowed and copied into the value, so the caller can destroy it independently. + * These are the vectors of the input chunks the operator's execute callback receives: the positional arguments of the + * call for `TABLE_OPERATOR_INPUT_ARGUMENTS`, or the columns of the table argument for `TABLE_OPERATOR_INPUT_TABLE`. A + * bind callback typically derives the function's result columns from them. Unlike + * `duckdb_v2_function_bind_get_arg_value()`, this also describes arguments that are not constant. 0 for a function + * without an operator. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_type The borrowed logical type to wrap. - * @param out_value Receives the new TYPE value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The bind info handle. + * @param count Receives the number of input columns. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_type(duckdb_v2_factory_handle factory, - duckdb_v2_logical_type_handle in_type, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_bind_get_input_column_count( + duckdb_v2_table_function_bind_info_handle info, idx_t *count, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a DATE value. + * Retrieves the type of the operator's input column at the given index (see + * `duckdb_v2_table_function_bind_get_input_column_count()`). * - * The payload is days since 1970-01-01, the same unit value_get_date reports. It is not range-checked here; value_cast - * is the validating path. The returned value is caller-owned; destroy it via value_destroy. + * Fails if the index is out of bounds. The returned type is owned by the caller and must be destroyed via + * `duckdb_v2_logical_type_destroy()`. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The payload to wrap. - * @param out_value Receives the new DATE value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The bind info handle. + * @param index The index of the input column. + * @param type Receives the column type. Owned by the caller; destroy via `duckdb_v2_logical_type_destroy()`. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_date(duckdb_v2_factory_handle factory, int32_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_bind_get_input_column_type( + duckdb_v2_table_function_bind_info_handle info, idx_t index, duckdb_v2_logical_type_handle *type, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a TIME value. + * Retrieves the name of the operator's input column at the given index (see + * `duckdb_v2_table_function_bind_get_input_column_count()`). * - * The payload is microseconds since midnight, the same unit value_get_time reports. It is not range-checked here; - * value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. + * For `TABLE_OPERATOR_INPUT_TABLE` this is the name of the column of the table argument. The arguments of + * `TABLE_OPERATOR_INPUT_ARGUMENTS` have no names, and yield an empty name. Fails if the index is out of bounds. The + * name is borrowed and valid only for the duration of the callback. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The payload to wrap. - * @param out_value Receives the new TIME value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The bind info handle. + * @param index The index of the input column. + * @param name Receives a borrowed pointer to the column name. Valid only for the duration of the callback. + * @param name_length Receives the length of `*name` in bytes. `*name` is not guaranteed to be null-terminated. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_time(duckdb_v2_factory_handle factory, int64_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_bind_get_input_column_name( + duckdb_v2_table_function_bind_info_handle info, idx_t index, const char **name, idx_t *name_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a TIME_NS value. - * - * The payload is nanoseconds since midnight, the same unit value_get_time_ns reports. It is not range-checked here; - * value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. + * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The payload to wrap. - * @param out_value Receives the new TIME_NS value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The stats info handle. + * @param data Receives the user data pointer, or null if none was set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_time_ns(duckdb_v2_factory_handle factory, int64_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_stats_get_user_data( + duckdb_v2_table_function_stats_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a TIME_TZ value. - * - * The payload packs the time of day and the UTC offset into one integer, in the committed layout: micros in the high 40 - * bits, a biased offset in the low 24. The same form value_get_time_tz reports. It is not range-checked here; - * value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. + * Retrieves the bind data set by the function's bind callback. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The payload to wrap. - * @param out_value Receives the new TIME_TZ value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The stats info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_time_tz(duckdb_v2_factory_handle factory, uint64_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_stats_get_bind_data( + duckdb_v2_table_function_stats_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a TIMESTAMP value. + * Returns which declared column the statistics describe. * - * The payload is microseconds since 1970-01-01, the same unit value_get_timestamp reports. It is not range-checked - * here; value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. + * The result indexes the columns declared with `duckdb_v2_table_function_bind_add_result_column()`, in declaration + * order. It is never the index of a virtual column or of a field extracted from a column; the callback is not asked + * about those. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The payload to wrap. - * @param out_value Receives the new TIMESTAMP value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The stats info handle. + * @param column_index Receives the index of the declared column. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_timestamp(duckdb_v2_factory_handle factory, int64_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_stats_get_column_index( + duckdb_v2_table_function_stats_info_handle info, idx_t *column_index, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a TIMESTAMP_SEC value. + * Retrieves the statistics of the column, for the callback to narrow. * - * The payload is seconds since 1970-01-01, the same unit value_get_timestamp_sec reports. It is not range-checked here; - * value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. + * The statistics start out unknown, with every kind of value possible, and are of the column's type as the bind + * callback declared it. The callback narrows them with `duckdb_v2_stats_set_value()`, from a STRUCT value in the shape + * `duckdb_v2_stats_get_value()` returns - e.g. `{'min': 20, 'max': 30, 'has_null': false}` for an INTEGER column, or + * the statistics of the fields of a STRUCT column under `child_stats` - and with `duckdb_v2_stats_set_can_have_null()` + * / `duckdb_v2_stats_set_can_have_valid()`. Statistics built with `duckdb_v2_stats_create()`, e.g. combined from the + * files of a scan with `duckdb_v2_stats_merge()`, are copied in with `duckdb_v2_stats_assign()`. They describe every + * value the scan produces for the column. Borrowed; valid only for the duration of the callback. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The payload to wrap. - * @param out_value Receives the new TIMESTAMP_SEC value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The stats info handle. + * @param stats Receives the borrowed, writable statistics of the column. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_timestamp_sec(duckdb_v2_factory_handle factory, int64_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_stats_get_result_stats( + duckdb_v2_table_function_stats_info_handle info, duckdb_v2_stats_handle *stats, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a TIMESTAMP_MS value. + * Registers the table function, making it available for use in SQL queries. * - * The payload is milliseconds since 1970-01-01, the same unit value_get_timestamp_ms reports. It is not range-checked - * here; value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. + * The function is registered on the connection's database, visible to every connection, in the connection's + * transaction: inside an explicit transaction, it is invisible to other connections until the transaction commits, and + * a rollback undoes it. Registration requires a name, a bind callback and either a data source or an operator (see + * `duckdb_v2_table_function_set_operator()`), and rejects a signature that declares a return type, since a table + * function declares the columns it returns from its bind callback. The table function must have been created through a + * factory of the same database. The caller still owns the handle after registration and must destroy it with + * `duckdb_v2_table_function_destroy()`, which does not affect the registered function. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The payload to wrap. - * @param out_value Receives the new TIMESTAMP_MS value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param conn The connection to register on. + * @param function The table function to register. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_timestamp_ms(duckdb_v2_factory_handle factory, int64_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_register_table_function(duckdb_v2_connection_handle conn, + duckdb_v2_table_function_handle function, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a TIMESTAMP_NS value. + * Registers the table function, making it available for use in SQL queries. * - * The payload is nanoseconds since 1970-01-01, the same unit value_get_timestamp_ns reports. It is not range-checked - * here; value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. + * The function is registered on the loading extension's database and attributed to the extension. Use this from the + * extension's load callback. Registration requires a name, a bind callback and either a data source or an operator (see + * `duckdb_v2_table_function_set_operator()`), and rejects a signature that declares a return type, since a table + * function declares the columns it returns from its bind callback. The table function must have been created through a + * factory of the same database. The caller still owns the handle after registration and must destroy it with + * `duckdb_v2_table_function_destroy()`, which does not affect the registered function. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The payload to wrap. - * @param out_value Receives the new TIMESTAMP_NS value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param extension The loading extension. + * @param function The table function to register. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_timestamp_ns(duckdb_v2_factory_handle factory, int64_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_table_function(duckdb_v2_extension_handle extension, + duckdb_v2_table_function_handle function, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a TIMESTAMP_TZ value. + * Destroys the table function, releasing its resources. * - * The payload is microseconds since 1970-01-01, in UTC, the same unit value_get_timestamp_tz reports. It is not - * range-checked here; value_cast is the validating path. The returned value is caller-owned; destroy it via - * value_destroy. + * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent + * double-destruction. Destroying the handle after registration does not affect the registered function. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The payload to wrap. - * @param out_value Receives the new TIMESTAMP_TZ value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_timestamp_tz(duckdb_v2_factory_handle factory, int64_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_destroy(duckdb_v2_table_function_handle *function); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a TIMESTAMP_TZ_NS value. + * Sets the optional "get bind info" callback of the table function. * - * The payload is nanoseconds since 1970-01-01, in UTC, the same unit value_get_timestamp_tz_ns reports. It is not - * range-checked here; value_cast is the validating path. The returned value is caller-owned; destroy it via - * value_destroy. + * The engine invokes the callback with the bind data of a bound call when it needs to know more about the call than its + * columns. E.g. a multi-file function registered with `duckdb_v2_connection_register_multi_file_function()` or + * `duckdb_v2_extension_register_multi_file_function()` asks the function it wraps for every file it binds: it maps the + * columns of the files onto the columns of its scan by the identifiers the callback reports, and exposes the options it + * reports as the metadata of the reader of the file. The callback may be invoked more than once for the same bind data, + * so it should only report what the bind already determined. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The payload to wrap. - * @param out_value Receives the new TIMESTAMP_TZ_NS value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the callback of. + * @param callback The "get bind info" callback to set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_timestamp_tz_ns(duckdb_v2_factory_handle factory, int64_t in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_get_bind_info_callback( + duckdb_v2_table_function_handle function, duckdb_v2_table_function_get_bind_info_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a INTERVAL value. - * - * The payload is the (months, days, micros) triple, the same unit value_get_interval reports. It is not range-checked - * here; value_cast is the validating path. The returned value is caller-owned; destroy it via value_destroy. + * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The payload to wrap. - * @param out_value Receives the new INTERVAL value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The get bind info handle. + * @param data Receives the user data pointer, or null if none was set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_interval(duckdb_v2_factory_handle factory, - const duckdb_v2_interval_t *in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_get_bind_info_get_user_data( + duckdb_v2_table_function_get_bind_info_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a DECIMAL value from its backing integer. - * - * The value is scaled by 10^scale, so (18500, 18, 3) is 18.500. width is the total digit count and must be at least 1; - * scale is the number of digits after the point and must not exceed width. Violating either returns - * ERROR_INPUT_INVALID, as does a value that does not fit in width digits. Widths above 38 build a wide decimal stored - * as BIGNUM, for which the 128-bit backing integer always fits; a wide decimal whose backing integer needs more than - * 128 bits is built through value_cast. - * - * The width is bounded like the width of a DECIMAL type the factory creates (see factory_create_type_from_name): by the - * max_decimal_width setting of the factory's connection, and by the default of that setting, 1000000, for an instance's - * factory. A wider width returns ERROR_INPUT_INVALID; use the factory of a connection that raised the setting. + * Retrieves the bind data the function's bind callback set for the bound call being described. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The backing integer, scaled by 10^scale. - * @param width Total digit count, at least 1 and at most the factory's maximum DECIMAL width; widths above 38 are wide - * decimals. - * @param scale Digits after the decimal point; must not exceed width. - * @param out_value Receives the new DECIMAL value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The get bind info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_decimal(duckdb_v2_factory_handle factory, - const duckdb_v2_hugeint_t *in_value, uint32_t width, - uint32_t scale, duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_get_bind_info_get_bind_data( + duckdb_v2_table_function_get_bind_info_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a UUID value from its internal 128-bit form. + * Attaches an identifier to a result column of the bound call, or to a field nested inside one. * - * The payload is the storage form a vector element holds, not the canonical byte order: the high bit is flipped so the - * integer sorts. To build one from canonical text, cast a VARCHAR with value_cast instead, which is also how a UUID - * renders back. + * A multi-file reader can then map the columns of every file onto the columns of its scan by identifier rather than by + * name - e.g. by the field ids of a file format that carries them, so that renamed columns and fields are still found. + * An identifier is an INTEGER field id or a VARCHAR name. + * + * The nested field is addressed by a path of child indexes, starting at the result column at `column_index`: a STRUCT + * field by its index, the elements of a LIST or ARRAY by `0`, the keys of a MAP by `0` and its values by `1`, and a + * UNION member by its index. An empty path addresses the result column itself. Setting an identifier again for the same + * column or field replaces it. Fails with `ERROR_INPUT_INVALID` when the column index is out of range, or the path does + * not address a nested field of the column's type. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The internal 128-bit storage form. - * @param out_value Receives the new UUID value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The get bind info handle. + * @param column_index The index of the result column, in the order the bind callback declared the columns. + * @param child_path The path of child indexes addressing the nested field, or null for the column itself. + * @param child_path_length The number of entries in the path, 0 for the column itself. + * @param identifier The identifier, an INTEGER or VARCHAR value. Borrowed and copied. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_uuid(duckdb_v2_factory_handle factory, - const duckdb_v2_hugeint_t *in_value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_get_bind_info_set_column_identifier( + duckdb_v2_table_function_get_bind_info_info_handle info, idx_t column_index, const idx_t *child_path, + idx_t child_path_length, duckdb_v2_value_handle identifier, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a BIT value from its wire bytes. + * Sets an option describing the bound call: a key-value fact about what the call reads, e.g. a property of the file it + * reads. Setting a key again replaces its value. * - * The wire form is a mandatory padding-header byte — the count of leading bits in the first data byte that are not part - * of the bit string — followed by the data bytes, so the input must be at least 1 byte. These are the same bytes - * value_get_blob reports back. + * A multi-file function registered with `duckdb_v2_connection_register_multi_file_function()` or + * `duckdb_v2_extension_register_multi_file_function()` exposes the options of the function it wraps as the metadata of + * the reader of each file, e.g. to a custom multi-file reader of another extension. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The wire bytes, a padding header byte followed by data. Must be at least 1 byte. - * @param in_value_length The length of `in_value` in bytes. `in_value` need not be null-terminated and may be NULL only - * when this is 0. - * @param out_value Receives the new BIT value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The get bind info handle. + * @param key The key of the option. Borrowed and copied. + * @param key_length The length of `key` in bytes. `key` need not be null-terminated and may be NULL only when this is + * 0. + * @param value The value of the option. Borrowed and copied. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_bit(duckdb_v2_factory_handle factory, const char *in_value, - idx_t in_value_length, duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_get_bind_info_set_option( + duckdb_v2_table_function_get_bind_info_info_handle info, const char *key, idx_t key_length, + duckdb_v2_value_handle value, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a BIGNUM value from its storage bytes. + * Sets the optional "to string" callback of the table function. * - * The bytes are opaque storage, as produced by bignum_encode from a magnitude and a sign flag; a negative is stored - * bit-inverted behind a header, so these are not the magnitude bytes. The header plus at least one magnitude byte means - * the input must exceed 3 bytes. These are the same bytes value_get_blob reports back, for bignum_decode to translate. + * The engine invokes the callback with the bind data of a bound call when it renders a query plan that scans the + * function, e.g. for `EXPLAIN`, `EXPLAIN ANALYZE` and the profiler, both for the logical and for the physical plan. The + * callback reports what the plan shows for the scan as key-value pairs with `duckdb_v2_table_function_to_string_set()`, + * e.g. the file or the remote table it reads. Without the callback the physical plan shows the name of the function + * under the key `Function`; with it, the plan shows what the callback reports instead, so a callback that wants the + * name shown reports it itself. The engine shows the projections, filters and estimated cardinality of the scan next to + * them either way. The callback may be invoked more than once for the same bind data, and is not invoked with the + * global state of a scan, so it should only report what the bind already determined. A function wrapped in a multi-file + * function is not asked: the plan describes the multi-file scan. + * + * With profiling enabled (including `EXPLAIN ANALYZE`), the engine also invokes the callback while the query executes, + * once per worker thread that scans the function. Calls can therefore run concurrently with the same bind data and user + * data, so the callback must not modify them without synchronization, and an error it reports there fails the query. + * Builds with assertions enabled also invoke it while executing queries without profiling. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param in_value The opaque storage bytes from bignum_encode. Must exceed 3 bytes. - * @param in_value_length The length of `in_value` in bytes. `in_value` need not be null-terminated and may be NULL only - * when this is 0. - * @param out_value Receives the new BIGNUM value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the callback of. + * @param callback The "to string" callback to set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_bignum(duckdb_v2_factory_handle factory, const char *in_value, - idx_t in_value_length, duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_to_string_callback( + duckdb_v2_table_function_handle function, duckdb_v2_table_function_to_string_callback_fn callback, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a LIST value from its elements. - * - * The child type is the common type of the elements, resolved by the same rule a SQL list literal follows, and every - * element is cast to it; a set with no common type surfaces the cast error. Pass child_type to name the type instead, - * which is also how an empty list is built: with child_type NULL, an empty element array has no type to resolve and - * returns ERROR_INPUT_INVALID. - * - * The elements are borrowed and copied in, and a NULL element becomes a typed NULL. The type is rebuilt from its child, - * so an alias on the outer LIST type is not preserved; value_cast is the alias-preserving path. + * Retrieves the user data set via `duckdb_v2_table_function_set_user_data()`. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param child_type Optional. The element type. Pass NULL to resolve it from the elements. - * @param children An array of child_count elements. Borrowed (copied in). Pass NULL when child_count is 0. - * @param child_count The number of elements. - * @param out_value Receives the new composite value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The to string info handle. + * @param data Receives the user data pointer, or null if none was set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_list(duckdb_v2_factory_handle factory, - duckdb_v2_logical_type_handle child_type, - const duckdb_v2_value_handle *children, idx_t child_count, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_to_string_get_user_data( + duckdb_v2_table_function_to_string_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates an ARRAY value from its elements, sized by their count. - * - * The child type is resolved exactly as for value_create_list, and child_type names it explicitly the same way. The - * minimum array size is 1, so an empty element array returns ERROR_INPUT_INVALID whether or not child_type is given. - * - * The elements are borrowed and copied in, and a NULL element becomes a typed NULL. + * Retrieves the bind data the function's bind callback set for the bound call being described. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param child_type Optional. The element type. Pass NULL to resolve it from the elements. - * @param children An array of child_count elements. Borrowed (copied in). Pass NULL when child_count is 0. - * @param child_count The number of elements. - * @param out_value Receives the new composite value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The to string info handle. + * @param data Receives the bind data pointer, or null if none was set. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_array(duckdb_v2_factory_handle factory, - duckdb_v2_logical_type_handle child_type, - const duckdb_v2_value_handle *children, idx_t child_count, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_to_string_get_bind_data( + duckdb_v2_table_function_to_string_info_handle info, void **data, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a STRUCT value from named fields, in order. - * - * Each field keeps its own child's type, so there is nothing to resolve across them; names and children are parallel - * arrays of field_count entries. An empty field list builds the empty struct, which is a real type. - * - * The names and children are borrowed and copied in, and a NULL child becomes a typed NULL. Duplicate field names are - * rejected. + * Reports a key-value pair the query plan shows for the scan, e.g. `File` and the path of the file it reads. The plan + * shows the pairs in the order they were first reported; setting a key again replaces its value in place. Fails with + * `ERROR_INPUT_INVALID` when the key is empty. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param names An array of field_count field names. Pass NULL when field_count is 0. - * @param names_lengths Byte lengths of the entries in `names`; element i is the length of `names[i]`. May be NULL only - * when `names` is NULL. - * @param children An array of field_count field values. Borrowed (copied in). Pass NULL when field_count is 0. - * @param field_count The number of fields. - * @param out_value Receives the new composite value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param info The to string info handle. + * @param key The key. Borrowed and copied. + * @param key_length The length of `key` in bytes. `key` need not be null-terminated. + * @param value The value. Borrowed and copied. May span several lines. + * @param value_length The length of `value` in bytes. `value` need not be null-terminated and may be NULL only when + * this is 0. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_struct(duckdb_v2_factory_handle factory, const char *const *names, - const idx_t *names_lengths, - const duckdb_v2_value_handle *children, idx_t field_count, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_to_string_set(duckdb_v2_table_function_to_string_info_handle info, + const char *key, idx_t key_length, + const char *value, idx_t value_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a TUPLE value from positional fields. + * Makes the table function a table in-out function, whose rows the given operator produces from an input. + * + * Instead of producing its rows from nothing by scanning a data source, the function then transforms an input into its + * rows: the operator's execute callback receives the input chunk by chunk, and writes the function's rows into its + * output chunk, which holds the columns declared by the bind callback. Where the input comes from is set by `input`, + * see `DUCKDB_V2_TABLE_OPERATOR_INPUT`. The bind callback still runs first, declares the result columns, and can + * inspect the input columns with `duckdb_v2_table_function_bind_get_input_column_count()` and its siblings; the + * operator reaches the bind data via e.g. `duckdb_v2_operator_execute_get_bind_data()`. * - * TUPLE is the unnamed struct: the same positional children as value_create_struct, under a distinct type id and with - * no names. Each field keeps its own child's type. An empty field list builds the empty tuple, which is a real type. + * The operator's configuration is copied, so the caller still owns `op` and must destroy it with + * `duckdb_v2_operator_destroy()`; it may be handed to several functions. Calling this again replaces the operator. * - * The children are borrowed and copied in, and a NULL child becomes a typed NULL. + * Registration rejects a function with an operator that also has a data source, or a callback that is part of scanning: + * init global, init local, progress, metrics, filter pushdown, partition data, partitioning and claim batch callbacks, + * projection pushdown and virtual columns. The operator itself carries the init and finalize callbacks. For + * `TABLE_OPERATOR_INPUT_TABLE`, the signature must not declare positional parameters, since the table is the only + * positional argument; registration adds it. It may declare named parameters, which are constant arguments of the call + * as usual. Such a function cannot be overloaded, and its operator cannot have a finalize callback when it is called + * with a table that is correlated with an outer query. For `TABLE_OPERATOR_INPUT_ARGUMENTS`, the operator cannot have a + * finalize callback. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param children An array of field_count field values. Borrowed (copied in). Pass NULL when field_count is 0. - * @param field_count The number of fields. - * @param out_value Receives the new composite value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the operator of. + * @param op The operator producing the function's rows. Borrowed; its configuration is copied. + * @param input Where the operator's input comes from. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_tuple(duckdb_v2_factory_handle factory, - const duckdb_v2_value_handle *children, idx_t field_count, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_table_function_set_operator(duckdb_v2_table_function_handle function, + duckdb_v2_operator_handle op, + DUCKDB_V2_TABLE_OPERATOR_INPUT input, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Creates a MAP value from parallel key and value arrays. + * Creates a new multi-file function through a factory. * - * The key and value types are the common types of the keys and of the values, resolved as for value_create_list, and - * every entry is cast to them. Pass key_type and value_type to name them instead, which is also how an empty map is - * built: with both NULL, empty key and value arrays have no types to resolve and return ERROR_INPUT_INVALID. + * The function starts out empty: give it a name with `duckdb_v2_multi_file_function_set_name()` and the single-file + * function it wraps with `duckdb_v2_multi_file_function_set_single_file_function()`, then make it available with + * `duckdb_v2_connection_register_multi_file_function()` or `duckdb_v2_extension_register_multi_file_function()`. The + * caller owns the returned handle and must destroy it with `duckdb_v2_multi_file_function_destroy()`, also after + * registration. * - * Keys and values are borrowed and copied in, and the two arrays must be the same length. Keys must be non-NULL and - * unique; both are enforced. + * The multi-file function can only be registered on the database the factory belongs to. * * history: * - unstable: v2.0.0 * - * @param factory The factory to create with. - * @param key_type Optional. The key type. Pass NULL to resolve it from the keys. - * @param value_type Optional. The value type. Pass NULL to resolve it from the values. - * @param keys An array of entry_count keys. Borrowed (copied in). Pass NULL when entry_count is 0. - * @param values An array of entry_count values, parallel to keys. Borrowed (copied in). Pass NULL when entry_count is - * 0. - * @param entry_count The number of entries. - * @param out_value Receives the new composite value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param factory The factory to create the multi-file function through. + * @param function On success, receives the newly created multi-file function. Owned by the caller. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_create_map( - duckdb_v2_factory_handle factory, duckdb_v2_logical_type_handle key_type, duckdb_v2_logical_type_handle value_type, - const duckdb_v2_value_handle *keys, const duckdb_v2_value_handle *values, idx_t entry_count, - duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_multi_file_function_create(duckdb_v2_factory_handle factory, + duckdb_v2_multi_file_function_handle *function, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the number of child values of a value. + * Sets the name of the multi-file function, as SQL will call it. * - * Per type kind: the element count for LIST and ARRAY; the field count for STRUCT and TUPLE; twice the entry count for - * MAP, whose children alternate key, value; and 2 for UNION, the tag plus the active member. Everything else reports 0, - * NULL values of any nested type included. + * The name is borrowed and copied. Calling this again replaces the previous name. A name must be set before + * registration. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out_count Receives the number of children. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the name of. + * @param name The name to set. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` need not be null-terminated and may be NULL only when this + * is 0. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_child_count(duckdb_v2_value_handle value, idx_t *out_count, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_multi_file_function_set_name(duckdb_v2_multi_file_function_handle function, + const char *name, idx_t name_length, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns one child of a composite value as an owned copy. - * - * LIST and ARRAY children are the elements. STRUCT and TUPLE children are the fields in declared order, and a STRUCT's - * field names come from its type, via logical_type_get_param. MAP children alternate key, value, symmetric with - * value_create_map. UNION children are [0] the tag, as a UTINYINT value, and [1] the active member, because a union - * value holds only that one member. - * - * Note the divergence from vector_get_child, which descends structurally and so exposes [0] = tag and [1..N] = ALL - * members. Code written to descend generically over both must account for that difference. + * Sets the name of the table function that reads a single file, which the multi-file function wraps. * - * An out-of-range index returns ERROR_INPUT_INVALID, as does any index on a non-composite or NULL value. The returned - * value is caller-owned; destroy it via value_destroy. + * The single-file function must be registered before the multi-file function is, and must take the file to read as its + * only positional parameter, of type ANY. It is bound once for every file that is read, and receives the file the way a + * multi-file function takes one: as the VARCHAR path of the file when there is nothing more to know about it, and + * otherwise as a STRUCT holding the path in its `filename` field and the options to open the file with in its other + * fields - e.g. the size of the file, as a file system reported it while globbing, or the options a caller passed along + * with the file (`read_x([{'filename': 'f.x', 'file_size': 42}])`). Opening the file with those options, set with + * `duckdb_v2_file_open_options_set_value()`, lets the file system skip work it would otherwise repeat, such as asking a + * remote store for the size of the file. A single-file function that takes a VARCHAR parameter instead is still + * accepted, and only receives the path. Every named parameter the single-file function declares is also a named + * parameter of the multi-file function, forwarded to it as given. Everything that involves several files - globbing, + * lists of files, hive partitioning, the `filename` column, `union_by_name` and the like - is provided by the + * multi-file function on top of it. The name is borrowed and copied. A single-file function must be set before + * registration. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param index The child index, in [0, child_count). - * @param out_child Receives the owned child value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the single-file function of. + * @param name The name of the registered single-file table function. Borrowed and copied. + * @param name_length The length of `name` in bytes. `name` need not be null-terminated and may be NULL only when this + * is 0. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_child(duckdb_v2_value_handle value, idx_t index, - duckdb_v2_value_handle *out_child, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR +duckdb_v2_multi_file_function_set_single_file_function(duckdb_v2_multi_file_function_handle function, const char *name, + idx_t name_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the value that a VARIANT value holds, as a value of its own type. + * Sets how the files the function reads are referred to in messages, e.g. "Avro" or "JSON". * - * A VARIANT holds a value of any other type, e.g. a TINYINT, a VARCHAR or a LIST of STRUCTs, that is only known per - * value: this reads it back, with the type that it was stored with. The value is built with the content of the variant, - * so a stored list gives a LIST with its elements, and a stored object a STRUCT with its fields. The elements of a list - * that were stored with different types, which a LIST cannot hold, stay VARIANT values: a LIST of VARIANT. Convert - * those with this function in turn. A NULL VARIANT gives a NULL value. A value that is not a VARIANT returns - * ERROR_INPUT_INVALID. The inverse is value_cast to a VARIANT type, which factory_create_type_from_text gives. The - * returned value is caller-owned; destroy it via value_destroy. + * Optional: without it, the files are referred to by the name of the multi-file function. The name is borrowed and + * copied. * * history: * - unstable: v2.0.0 * - * @param value The VARIANT value to convert. - * @param out_value Receives the owned value. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the reader type of. + * @param reader_type The reader type. Borrowed and copied. + * @param reader_type_length The length of `reader_type` in bytes. `reader_type` need not be null-terminated and may be + * NULL only when this is 0. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_variant_to_value(duckdb_v2_value_handle value, - duckdb_v2_value_handle *out_value, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR +duckdb_v2_multi_file_function_set_reader_type(duckdb_v2_multi_file_function_handle function, const char *reader_type, + idx_t reader_type_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Casts a value to a target type, using a factory. - * - * The conversion is the SQL-faithful, non-strict one, registered custom casts included, and a cast failure surfaces - * from the call. Together with a VARCHAR built through value_create_varchar, this constructs any value from text, - * extension values included; casting a member value to a union type, or a VARCHAR to an enum type, is the sanctioned - * way to build UNION and ENUM values. - * - * A connection's or callback's factory casts with that client's cast functions and settings (e.g. TimeZone). An - * instance's factory supports only the built-in casts, with default settings. + * Sets the file extension of the files the function reads, e.g. "avro". * - * The input value and target type are borrowed. The returned value is caller-owned; destroy it via value_destroy. + * Optional. With a file extension, a path that names a directory rather than a file reads the files with that extension + * inside it. Without one, the paths passed to the function must match at least one file. The extension is given without + * a leading dot, and is borrowed and copied. * * history: * - unstable: v2.0.0 * - * @param factory The factory supplying the cast functions. - * @param value The borrowed value to cast. - * @param target_type The borrowed target logical type. - * @param out_value Receives the owned cast result. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to set the file extension of. + * @param extension The file extension, without a leading dot. Borrowed and copied. + * @param extension_length The length of `extension` in bytes. `extension` need not be null-terminated and may be NULL + * only when this is 0. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_cast(duckdb_v2_factory_handle factory, duckdb_v2_value_handle value, - duckdb_v2_logical_type_handle target_type, - duckdb_v2_value_handle *out_value, duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR +duckdb_v2_multi_file_function_set_file_extension(duckdb_v2_multi_file_function_handle function, const char *extension, + idx_t extension_length, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns whether the value is NULL. + * Registers the multi-file function, making it available for use in SQL queries. + * + * The function is registered on the connection's database, visible to every connection, in the connection's + * transaction: inside an explicit transaction, it is invisible to other connections until the transaction commits, and + * a rollback undoes it. It can then be called with the path of a single file, a glob pattern, or a list of either, and + * accepts the options every multi-file function accepts (e.g. `filename`, `hive_partitioning`, `union_by_name`) next to + * the named parameters of the single-file function. Registration requires a name and a single-file function, and fails + * when no table function by that name is registered or it does not take the path of the file to read as its only + * positional parameter (see `duckdb_v2_multi_file_function_set_single_file_function()`). The multi-file function must + * have been created through a factory of the same database. The caller still owns the handle after registration and + * must destroy it with `duckdb_v2_multi_file_function_destroy()`, which does not affect the registered function. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out_is_null Receives true if the value is NULL, false otherwise. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param conn The connection to register on. + * @param function The multi-file function to register. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_is_null(duckdb_v2_value_handle value, bool *out_is_null, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_connection_register_multi_file_function( + duckdb_v2_connection_handle conn, duckdb_v2_multi_file_function_handle function, duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Returns the logical type of the value. + * Registers the multi-file function, making it available for use in SQL queries. * - * The returned logical type is caller-owned; destroy it via logical_type_destroy. + * The function is registered on the loading extension's database and attributed to the extension. Use this from the + * extension's load callback. It can then be called with the path of a single file, a glob pattern, or a list of either, + * and accepts the options every multi-file function accepts (e.g. `filename`, `hive_partitioning`, `union_by_name`) + * next to the named parameters of the single-file function. Registration requires a name and a single-file function, + * and fails when no table function by that name is registered or it does not take the path of the file to read as its + * only positional parameter (see `duckdb_v2_multi_file_function_set_single_file_function()`). The multi-file function + * must have been created through a factory of the same database. The caller still owns the handle after registration + * and must destroy it with `duckdb_v2_multi_file_function_destroy()`, which does not affect the registered function. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out_type Receives the owned logical type. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param extension The loading extension. + * @param function The multi-file function to register. + * @param err Optional. On failure, receives an opaque info handle the caller must destroy via + * `duckdb_v2_error_info_destroy()`. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_get_logical_type(duckdb_v2_value_handle value, - duckdb_v2_logical_type_handle *out_type, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_extension_register_multi_file_function( + duckdb_v2_extension_handle extension, duckdb_v2_multi_file_function_handle function, + duckdb_v2_error_info_handle *err); #endif #if DUCKDB_V2_API_ALLOW_UNSTABLE /*! - * Renders the value as a human-readable string. Diagnostic only. - * - * Writes into a caller-supplied buffer, so nothing is allocated on the caller's behalf and nothing has to be freed. - * - * Pass out_string = NULL to size the buffer without rendering into it: out_length then receives the length, and - * out_capacity is ignored. With out_string != NULL, out_capacity must be at least out_length + 1, or the call returns - * ERROR_INPUT_OBJECT_SIZE with out_length set to the required length and out_string left untouched. + * Destroys the multi-file function, releasing its resources. * - * out_length never counts the terminator, but a successful write always appends one, so the buffer is usable as a C - * string. + * Null-safe: passing a null pointer or null handle is a no-op. The handle is set to null on return to prevent + * double-destruction. Destroying the handle after registration does not affect the registered function. * * history: * - unstable: v2.0.0 * - * @param value The value to read. - * @param out_string Caller-owned buffer receiving the text plus a null terminator, or NULL to only report the required - * length in out_length. - * @param out_capacity Bytes available in out_string, terminator included. Ignored when out_string is NULL. - * @param out_length Receives the text length excluding the null terminator — written on success and on - * ERROR_INPUT_OBJECT_SIZE. - * @param err Optional. On failure, receives an opaque info handle the caller must destroy via error_info_destroy. + * @param function The function to destroy. * @return DUCKDB_V2_ERROR */ -DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_value_to_string(duckdb_v2_value_handle value, char *out_string, - idx_t out_capacity, idx_t *out_length, - duckdb_v2_error_info_handle *err); +DUCKDB_C_API DUCKDB_V2_ERROR duckdb_v2_multi_file_function_destroy(duckdb_v2_multi_file_function_handle *function); #endif -/* --- Struct definitions for value --- */ +/* --- Struct definitions for table --- */ /* ============================================================================ * MODULE: arrow diff --git a/src/duckdb/src/logging/log_manager.cpp b/src/duckdb/src/logging/log_manager.cpp index a6c0e0b86..778195ee7 100644 --- a/src/duckdb/src/logging/log_manager.cpp +++ b/src/duckdb/src/logging/log_manager.cpp @@ -1,5 +1,6 @@ #include "duckdb/logging/log_type.hpp" #include "duckdb/logging/log_manager.hpp" +#include "duckdb/common/algorithm.hpp" #include "duckdb/logging/log_sink.hpp" #include "duckdb/logging/file_system_logger.hpp" #include "duckdb/main/database.hpp" @@ -324,12 +325,24 @@ void LogManager::RegisterLogType(unique_ptr type) { auto lookup = registered_log_types.find(type->name); if (lookup != registered_log_types.end()) { - throw InvalidInputException("Registered log writer '%s' already exists", type->name); + throw InvalidInputException("Registered log type '%s' already exists", type->name); } registered_log_types[type->name] = std::move(type); } +vector LogManager::GetLogTypes() { + annotated_unique_lock lck(lock); + vector result; + for (auto &entry : registered_log_types) { + auto &type = *entry.second; + result.push_back(RegisteredLogType {type.name, type.level, type.is_structured, type.extension_name}); + } + std::sort(result.begin(), result.end(), + [](const RegisteredLogType &a, const RegisteredLogType &b) { return a.name < b.name; }); + return result; +} + void LogManager::RegisterDefaultLogTypes() { RegisterLogType(make_uniq()); RegisterLogType(make_uniq()); diff --git a/src/duckdb/src/logging/log_sink.cpp b/src/duckdb/src/logging/log_sink.cpp index b6c343baf..80000c352 100644 --- a/src/duckdb/src/logging/log_sink.cpp +++ b/src/duckdb/src/logging/log_sink.cpp @@ -400,7 +400,7 @@ void FileLogSink::SetPaths(const string &base_path) { if (StringUtil::EndsWith(base_path, ".csv")) { tables[LoggingTargetTable::ALL_LOGS].path = base_path; } else { - tables[LoggingTargetTable::LOG_ENTRIES].path = fs.JoinPath(base_path, "duckdb_log_entries.csv"); + tables[LoggingTargetTable::ALL_LOGS].path = fs.JoinPath(base_path, "duckdb_logs.csv"); } } } @@ -408,7 +408,7 @@ void FileLogSink::SetPaths(const string &base_path) { void FileLogSink::UpdateConfigInternal(DatabaseInstance &db, case_insensitive_map_t &config) { auto config_copy = config; - string new_path; + string new_path = base_path; bool normalize_contexts_new_value = normalize_contexts; bool normalize_set_explicitly = false; bool require_reinitializing_files = false; @@ -453,7 +453,8 @@ void FileLogSink::UpdateConfigInternal(DatabaseInstance &db, case_insensitive_ma FlushAllInternal(); } - require_reinitializing_files |= normalize_contexts != normalize_contexts_new_value; + const bool normalize_changed = normalize_contexts != normalize_contexts_new_value; + require_reinitializing_files |= new_path != base_path || normalize_changed; normalize_contexts = normalize_contexts_new_value; // Reset the buffers to ensure they have the correct schema @@ -466,8 +467,8 @@ void FileLogSink::UpdateConfigInternal(DatabaseInstance &db, case_insensitive_ma } } - // Apply any path change - if (new_path != base_path) { + // Apply path or normalization changes + if (new_path != base_path || normalize_changed) { base_path = new_path; SetPaths(new_path); } diff --git a/src/duckdb/src/logging/log_types.cpp b/src/duckdb/src/logging/log_types.cpp index 8cc0e0984..d74336f27 100644 --- a/src/duckdb/src/logging/log_types.cpp +++ b/src/duckdb/src/logging/log_types.cpp @@ -1,4 +1,5 @@ #include "duckdb/logging/log_type.hpp" +#include "duckdb/common/static_string_table.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/main/http/http_util.hpp" @@ -62,10 +63,10 @@ LogicalType FileSystemLogType::GetLogType() { //===--------------------------------------------------------------------===// // HTTPLogType //===--------------------------------------------------------------------===// -static const case_insensitive_set_t &HTTPRequestHeaderAllowList() { +static StaticStringSet HTTPRequestHeaderAllowList() { //! For extra info, the advise from OpenTelemetry: //! https://opentelemetry.io/docs/specs/semconv/registry/attributes/http/#http-request-header - static const case_insensitive_set_t allow_list = { + static constexpr const char *const ALLOW_LIST[] = { // HTTP semantics (https://www.rfc-editor.org/rfc/rfc9110.html). "accept", // Accepted media types and parameters. "accept-charset", // Accepted character sets. @@ -133,11 +134,11 @@ static const case_insensitive_set_t &HTTPRequestHeaderAllowList() { // AWS JSON protocol (https://smithy.io/2.0/aws/protocols/aws-json-1_1-protocol.html), e.g. AWS Glue. "x-amz-target", // Service and operation name, e.g. AWSGlue.GetTable. }; - return allow_list; + return StaticStringSet(ALLOW_LIST); } -static const case_insensitive_set_t &HTTPResponseHeaderAllowList() { - static const case_insensitive_set_t allow_list = { +static StaticStringSet HTTPResponseHeaderAllowList() { + static constexpr const char *const ALLOW_LIST[] = { // HTTP semantics (https://www.rfc-editor.org/rfc/rfc9110.html). "accept", // Accepted media types and parameters. "accept-encoding", // Accepted content codings. @@ -186,7 +187,7 @@ static const case_insensitive_set_t &HTTPResponseHeaderAllowList() { // "x-amz-server-side-encryption-customer-key-md5", // Fingerprints the customer encryption key. // "x-amz-version-id", // Identifies an object version. }; - return allow_list; + return StaticStringSet(ALLOW_LIST); } HTTPLogType::HTTPLogType() : LogType(NAME, LEVEL, GetLogType()) { @@ -216,7 +217,7 @@ LogicalType HTTPLogType::GetLogType() { return LogicalType::STRUCT(child_list); } -static Value CreateHTTPHeadersValue(const HTTPHeaders &headers, const case_insensitive_set_t &allow_list, +static Value CreateHTTPHeadersValue(const HTTPHeaders &headers, const StaticStringSet &allow_list, bool redact_http_logs) { vector keys; vector values; @@ -227,7 +228,7 @@ static Value CreateHTTPHeadersValue(const HTTPHeaders &headers, const case_insen continue; } keys.emplace_back(header.first); - const bool allow_value = !redact_http_logs || allow_list.find(header.first) != allow_list.end(); + const bool allow_value = !redact_http_logs || allow_list.ContainsCaseInsensitive(header.first); values.emplace_back(allow_value ? header.second : HTTPLogType::REDACTED_VALUE); } return Value::MAP(LogicalType::VARCHAR, LogicalType::VARCHAR, keys, values); diff --git a/src/duckdb/src/main/attached_database.cpp b/src/duckdb/src/main/attached_database.cpp index e1b18de2a..2f001322c 100644 --- a/src/duckdb/src/main/attached_database.cpp +++ b/src/duckdb/src/main/attached_database.cpp @@ -1,4 +1,5 @@ #include "duckdb/main/attached_database.hpp" +#include "duckdb/common/static_string_table.hpp" #include "duckdb/main/context.hpp" #include "duckdb/logging/log_manager.hpp" @@ -47,12 +48,15 @@ AttachOptions::AttachOptions(const DBConfigOptions &options) } //! The spellings of the access mode option, and whether `true` means read-only for each. -static const unordered_map ACCESS_MODE_OPTIONS = { - {"readonly", true}, {"read_only", true}, {"readwrite", false}, {"read_write", false}}; +static StaticStringMap AccessModeOptions() { + static constexpr StaticStringMap::Entry OPTIONS[] = { + {"readonly", true}, {"read_only", true}, {"readwrite", false}, {"read_write", false}}; + return StaticStringMap(OPTIONS); +} string AttachOptions::OptionSetting(const string &name) { auto lower = StringUtil::Lower(name); - if (ACCESS_MODE_OPTIONS.find(lower) != ACCESS_MODE_OPTIONS.end()) { + if (AccessModeOptions().Find(lower)) { return "access_mode"; } return lower; @@ -62,11 +66,11 @@ AttachOptions::AttachOptions(Context &context, const unordered_mapsecond ? AccessMode::READ_ONLY : AccessMode::READ_WRITE; + access_mode = value == *access_mode_option ? AccessMode::READ_ONLY : AccessMode::READ_WRITE; continue; } diff --git a/src/duckdb/src/main/capi/v1/arrow-c.cpp b/src/duckdb/src/main/capi/v1/arrow-c.cpp index b2d90728f..99c4d67c2 100644 --- a/src/duckdb/src/main/capi/v1/arrow-c.cpp +++ b/src/duckdb/src/main/capi/v1/arrow-c.cpp @@ -112,10 +112,10 @@ duckdb_error_data duckdb_data_chunk_to_arrow(duckdb_arrow_options arrow_options, } auto dchunk = reinterpret_cast(chunk); auto arrow_options_wrapper = reinterpret_cast(arrow_options); - auto extension_type_cast = duckdb::ArrowTypeExtensionData::GetExtensionTypes( - *arrow_options_wrapper->properties.client_context, dchunk->GetTypes()); try { + auto extension_type_cast = duckdb::ArrowTypeExtensionData::GetExtensionTypes( + *arrow_options_wrapper->properties.client_context, dchunk->GetTypes()); ArrowConverter::ToArrowArray(*dchunk, out_arrow_array, arrow_options_wrapper->properties, extension_type_cast); } catch (const duckdb::Exception &ex) { return duckdb_create_error_data(DUCKDB_ERROR_INVALID_INPUT, ex.what()); @@ -294,7 +294,11 @@ duckdb_state duckdb_prepared_arrow_schema(duckdb_prepared_statement prepared, du D_ASSERT(!result_schema->release); } - ArrowConverter::ToArrowSchema(result_schema, prepared_types, prepared_names, properties); + try { + ArrowConverter::ToArrowSchema(result_schema, prepared_types, prepared_names, properties); + } catch (...) { + return DuckDBError; + } return DuckDBSuccess; } @@ -327,11 +331,19 @@ void duckdb_result_arrow_array(duckdb_result result, duckdb_data_chunk chunk, du auto dchunk = reinterpret_cast(chunk); auto &result_data = *(reinterpret_cast(result.internal_data)); auto &client_properties = result_data.GetClientProperties(); - auto extension_type_cast = - duckdb::ArrowTypeExtensionData::GetExtensionTypes(*client_properties.client_context, result_data.GetTypes()); - - ArrowConverter::ToArrowArray(*dchunk, reinterpret_cast(*out_array), client_properties, - extension_type_cast); + auto arrow_array = reinterpret_cast(*out_array); + try { + auto extension_type_cast = duckdb::ArrowTypeExtensionData::GetExtensionTypes(*client_properties.client_context, + result_data.GetTypes()); + ArrowConverter::ToArrowArray(*dchunk, arrow_array, client_properties, extension_type_cast); + } catch (...) { + // The conversion can fail, for example on a value that has no representation in the requested Arrow format + // version. This function has no way to report an error, so the array is left released, which is how the + // Arrow C data interface marks an array that holds nothing + if (arrow_array) { + arrow_array->release = nullptr; + } + } } idx_t duckdb_arrow_row_count(duckdb_arrow result) { diff --git a/src/duckdb/src/main/capi/v1/logical_types-c.cpp b/src/duckdb/src/main/capi/v1/logical_types-c.cpp index 574ebd30c..d6c35fa5c 100644 --- a/src/duckdb/src/main/capi/v1/logical_types-c.cpp +++ b/src/duckdb/src/main/capi/v1/logical_types-c.cpp @@ -118,12 +118,7 @@ duckdb_logical_type duckdb_create_struct_type(duckdb_logical_type *member_types_ for (idx_t i = 0; i < member_count; i++) { members.emplace_back(make_pair(member_names[i], *member_types[i])); } - // an unnamed (empty member names) struct is a TUPLE - construct it as such so it is treated canonically - auto struct_type = duckdb::LogicalType::STRUCT(members); - if (duckdb::StructType::IsUnnamed(struct_type)) { - struct_type = duckdb::LogicalType::TUPLE(std::move(members)); - } - duckdb::LogicalType *mtype = new duckdb::LogicalType(std::move(struct_type)); + duckdb::LogicalType *mtype = new duckdb::LogicalType(duckdb::LogicalType::STRUCT(std::move(members))); return reinterpret_cast(mtype); } catch (...) { return nullptr; diff --git a/src/duckdb/src/main/capi/v1/scalar_function-c.cpp b/src/duckdb/src/main/capi/v1/scalar_function-c.cpp index 2325ca3ab..b5b6db13a 100644 --- a/src/duckdb/src/main/capi/v1/scalar_function-c.cpp +++ b/src/duckdb/src/main/capi/v1/scalar_function-c.cpp @@ -2,6 +2,7 @@ #include "duckdb/main/capi/capi_function_signature.hpp" #include "duckdb/common/type_visitor.hpp" #include "duckdb/common/types.hpp" +#include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/function/function.hpp" #include "duckdb/function/scalar_function.hpp" #include "duckdb/main/capi/capi_internal.hpp" @@ -215,6 +216,7 @@ void CAPIScalarFunction(DataChunk &input, ExpressionState &state, Vector &result if (!function_info.success) { throw InvalidInputException(function_info.error); } + FlatVector::DropAllValidMasks(result); } } // namespace diff --git a/src/duckdb/src/main/capi/v1/table_function-c.cpp b/src/duckdb/src/main/capi/v1/table_function-c.cpp index 92598e08a..7df74902a 100644 --- a/src/duckdb/src/main/capi/v1/table_function-c.cpp +++ b/src/duckdb/src/main/capi/v1/table_function-c.cpp @@ -2,6 +2,7 @@ #include "duckdb/main/capi/capi_function_signature.hpp" #include "duckdb/common/type_visitor.hpp" #include "duckdb/common/types.hpp" +#include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/function/table_function.hpp" #include "duckdb/main/capi/capi_internal.hpp" #include "duckdb/main/capi/capi_internal_table.hpp" @@ -171,6 +172,9 @@ void CTableFunction(ClientContext &context, TableFunctionInput &data_p, DataChun if (!function_info.success) { throw InvalidInputException(function_info.error); } + for (auto &column : output.data) { + FlatVector::DropAllValidMasks(column); + } } } // namespace diff --git a/src/duckdb/src/main/capi/v2/capi_v2_crypto.cpp b/src/duckdb/src/main/capi/v2/capi_v2_crypto.cpp index e1f6c01f2..7108ac69e 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_crypto.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_crypto.cpp @@ -2,6 +2,7 @@ #include "duckdb/common/encryption_state.hpp" #include "duckdb/common/mutex.hpp" +#include "duckdb/common/no_destructor.hpp" #include "duckdb/main/config.hpp" namespace duckdb::capiv2 { @@ -208,8 +209,8 @@ class CV2CryptoProvider { if (!callbacks.random) { throw InvalidInputException("The random callback must be set for the crypto provider."); } - static mutex registration_lock; - lock_guard guard(registration_lock); + static NoDestructor registration_lock; + lock_guard guard(*registration_lock); auto &config = DBConfig::GetConfig(target); if (config.encryption_util) { throw InvalidInputException("A crypto provider is already registered on this database."); diff --git a/src/duckdb/src/main/capi/v2/capi_v2_data_source.cpp b/src/duckdb/src/main/capi/v2/capi_v2_data_source.cpp index 5e3e4947c..3d34a163e 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_data_source.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_data_source.cpp @@ -3,6 +3,7 @@ #include "duckdb/common/multi_file/multi_file_data.hpp" #include "duckdb/common/multi_file/multi_file_reader.hpp" #include "duckdb/common/multi_file/table_function_multi_file.hpp" +#include "duckdb/common/vector/flat_vector.hpp" #include "duckdb/execution/expression_executor.hpp" #include "duckdb/execution/partition_info.hpp" #include "duckdb/function/partition_stats.hpp" @@ -804,6 +805,9 @@ static auto CV2TableExecBatchOnce(ClientContext &context, TableFunctionInput &in return; } output.SetChildCardinality(row_count); + for (auto &column : output.data) { + FlatVector::DropAllValidMasks(column); + } } static auto CV2DataSourceProgress(ClientContext &context, const FunctionData *bind_data, diff --git a/src/duckdb/src/main/capi/v2/capi_v2_func.cpp b/src/duckdb/src/main/capi/v2/capi_v2_func.cpp index d21e156ce..11471b92f 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_func.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_func.cpp @@ -1,9 +1,10 @@ #include "duckdb/main/capi_v2/capi_v2_function_internal.hpp" +#include "duckdb/common/no_destructor.hpp" namespace duckdb::capiv2 { const Identifier &CV2FunctionBindInfo::GetArgName(idx_t index) const { - static const Identifier variadic_name; + static const NoDestructor variadic_name; const auto positional_count = function.GetPositionalArgumentCount(); if (index >= positional_count) { return function.GetNamedArguments()[index - positional_count]; @@ -11,7 +12,7 @@ const Identifier &CV2FunctionBindInfo::GetArgName(idx_t index) const { if (index < signature.GetPositionalParameterCount()) { return signature.GetParameter(index).GetName(); } - return variadic_name; + return *variadic_name; } optional_idx CV2FunctionBindInfo::FindArg(const Identifier &name) const { diff --git a/src/duckdb/src/main/capi/v2/capi_v2_func_cast.cpp b/src/duckdb/src/main/capi/v2/capi_v2_func_cast.cpp index 60dc596a4..e5e389d02 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_func_cast.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_func_cast.cpp @@ -1,99 +1,319 @@ #include "duckdb/main/capi_v2/capi_v2_internal.hpp" +#include "duckdb/main/capi_v2/capi_v2_function_internal.hpp" #include "duckdb/common/operator/cast_operators.hpp" +#include "duckdb/common/types/bignum.hpp" +#include "duckdb/common/types/bit.hpp" +#include "duckdb/common/types/geometry.hpp" +#include "duckdb/common/vector/flat_vector.hpp" +#include "duckdb/common/vector/string_vector.hpp" +#include "duckdb/common/vector/array_vector.hpp" +#include "duckdb/common/vector/struct_vector.hpp" #include "duckdb/function/cast/cast_function_set.hpp" +#include "duckdb/function/function_binder.hpp" +#include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/expression/bound_reference_expression.hpp" namespace duckdb::capiv2 { +//! A cast is a pair of scalar functions of one parameter. These are the calls of them that a bound cast executes. class CV2CastBoundData final : public BoundCastData { public: - CV2CastBoundData(duckdb_v2_cast_function_exec_callback_fn exec_cb, shared_ptr user_data) - : exec_cb(exec_cb), user_data(std::move(user_data)) { + CV2CastBoundData(DatabaseInstance &db, shared_ptr call, + shared_ptr try_call) + : db(db), call(std::move(call)), try_call(std::move(try_call)) { } auto Copy() const -> unique_ptr override { - return make_uniq(exec_cb, user_data); + return make_uniq(db, call, try_call); } public: - duckdb_v2_cast_function_exec_callback_fn exec_cb; - shared_ptr user_data; + //! The database the cast was bound in, which provides the services of a cast that runs without a client context + DatabaseInstance &db; + shared_ptr call; + shared_ptr try_call; }; -// CastParameters carries no context, so the only place to pick one up is the local state init, which does receive -// one. The state exists purely to forward it to the exec callback. -class CV2CastLocalState final : public FunctionLocalState { +//! The per-cast info the engine hands to the bind function +class CV2CastBindFunctionInfo final : public BindCastInfo { public: - unique_ptr context; + CV2CastBindFunctionInfo(ScalarFunction function, ScalarFunction try_function) + : function(std::move(function)), try_function(std::move(try_function)) { + } + + ScalarFunction function; + ScalarFunction try_function; }; -class CV2CastExecInfo { +//! The init state of the two functions, made the first time the cast runs each of them +class CV2CastLocalState final : public FunctionLocalState { public: - void *in_user_data = nullptr; + explicit CV2CastLocalState(optional_ptr context) : context(context) { + } - Vector *input = nullptr; - Vector *output = nullptr; - idx_t count = 0; - DUCKDB_V2_CAST_MODE mode = DUCKDB_V2_CAST_MODE_NORMAL; + //! The client context the cast runs in - an index maintains its keys without one + optional_ptr context; + unique_ptr state; + unique_ptr try_state; + bool state_initialized = false; + bool try_state_initialized = false; }; -static auto Convert(duckdb_v2_cast_function_exec_info_handle info) -> CV2CastExecInfo * { - return reinterpret_cast(info); -} -static auto Convert(CV2CastExecInfo *info) -> duckdb_v2_cast_function_exec_info_handle { - return reinterpret_cast(info); +static auto InitCallState(const BoundFunctionExpression &call, optional_ptr context) + -> unique_ptr { + return CV2ScalarInitState(call.Function(), call.BindInfo().get(), context); } static auto CV2CastInitLocalState(CastLocalStateParameters ¶meters) -> unique_ptr { - auto state = make_uniq(); + return make_uniq(parameters.context); +} - if (!parameters.context) { - throw InvalidInputException("Cannot initialize local state for extension cast function without a context"); +//! Sets `count` rows of a flat string vector to one value stored in it +static void FillString(Vector &vector, idx_t count, string_t stored) { + auto data = FlatVector::GetDataMutable(vector); + for (idx_t row = 0; row < count; row++) { + data[row] = stored; } +} + +static void FillString(Vector &vector, idx_t count, const string &value) { + FillString(vector, count, StringVector::AddStringOrBlob(vector, value.data(), value.size())); +} + +//! Sets `count` rows of a vector to NULL, including the children of a nested type +static void SetAllNull(Vector &vector, idx_t count) { + for (idx_t row = 0; row < count; row++) { + FlatVector::SetNull(vector, row, true); + } +} - state->context = make_uniq(*parameters.context); - return std::move(state); +//! Sets `count` rows of a new vector to the zero value of its type, recursively: zero, an empty string or list, the +//! first member of an ENUM or UNION, an empty point, a VARIANT holding 0. A type without a listed zero value, such as +//! a wide DECIMAL, GEOGRAPHY or an ENUM without members, gets NULL rows. The context holds the services of the client +//! the cast runs for, or those of the database when there is none. +static void ZeroInitialize(Context &context, Vector &vector, idx_t count) { + const auto &type = vector.GetType(); + switch (type.id()) { + case LogicalTypeId::BOOLEAN: + case LogicalTypeId::TINYINT: + case LogicalTypeId::SMALLINT: + case LogicalTypeId::INTEGER: + case LogicalTypeId::BIGINT: + case LogicalTypeId::HUGEINT: + case LogicalTypeId::UTINYINT: + case LogicalTypeId::USMALLINT: + case LogicalTypeId::UINTEGER: + case LogicalTypeId::UBIGINT: + case LogicalTypeId::UHUGEINT: + case LogicalTypeId::FLOAT: + case LogicalTypeId::DOUBLE: + case LogicalTypeId::DATE: + case LogicalTypeId::TIME: + case LogicalTypeId::TIME_NS: + case LogicalTypeId::TIME_TZ: + case LogicalTypeId::TIMESTAMP_SEC: + case LogicalTypeId::TIMESTAMP_MS: + case LogicalTypeId::TIMESTAMP: + case LogicalTypeId::TIMESTAMP_NS: + case LogicalTypeId::TIMESTAMP_TZ: + case LogicalTypeId::TIMESTAMP_TZ_NS: + case LogicalTypeId::INTERVAL: + case LogicalTypeId::UUID: + case LogicalTypeId::VARCHAR: + case LogicalTypeId::BLOB: + // zero bytes are zero, or an empty string + memset(FlatVector::GetDataMutable(vector), 0, count * GetTypeIdSize(type.InternalType())); + return; + case LogicalTypeId::DECIMAL: + switch (type.InternalType()) { + case PhysicalType::INT16: + case PhysicalType::INT32: + case PhysicalType::INT64: + case PhysicalType::INT128: + memset(FlatVector::GetDataMutable(vector), 0, count * GetTypeIdSize(type.InternalType())); + return; + default: + break; + } + break; + case LogicalTypeId::ENUM: + if (EnumType::GetSize(type) > 0) { + memset(FlatVector::GetDataMutable(vector), 0, count * GetTypeIdSize(type.InternalType())); + return; + } + break; + case LogicalTypeId::BIT: + FillString(vector, count, Bit::ToBit(string_t("0"))); + return; + case LogicalTypeId::BIGNUM: + FillString(vector, count, Bignum::InitializeBignumZero()); + return; + case LogicalTypeId::GEOMETRY: { + string_t empty_point; + Geometry::FromString(string_t("POINT EMPTY"), empty_point, vector, true); + FillString(vector, count, empty_point); + return; + } + case LogicalTypeId::VARIANT: { + // the engine's own conversion of a zero INTEGER, which writes every child of the variant + Vector zero(LogicalType::INTEGER, count); + memset(FlatVector::GetDataMutable(zero), 0, count * sizeof(int32_t)); + auto get_input = GetCastFunctionInput(context); + BindCastInput bind_input(CastFunctionSet::Get(context), nullptr, get_input); + auto cast = DefaultCasts::GetDefaultCastFunction(bind_input, LogicalType::INTEGER, type); + unique_ptr cast_state; + if (cast.HasInitLocalState()) { + CastLocalStateParameters state_parameters(context.TryGetClientContext(), cast.GetCastData()); + cast_state = cast.InitLocalState(state_parameters); + } + CastParameters cast_parameters(cast.GetCastData(), false, nullptr, cast_state.get()); + cast.Cast(zero, vector, count, cast_parameters); + vector.Flatten(); + return; + } + case LogicalTypeId::STRUCT: + for (auto &child : StructVector::GetEntries(vector)) { + ZeroInitialize(context, child, count); + } + return; + case LogicalTypeId::UNION: { + // the tag selects the first member, which holds its zero value; the other members are NULL, with their children + auto &entries = StructVector::GetEntries(vector); + for (idx_t member = 0; member < entries.size(); member++) { + if (member == 0) { + memset(FlatVector::GetDataMutable(entries[member]), 0, count * sizeof(union_tag_t)); + } else if (member == 1) { + ZeroInitialize(context, entries[member], count); + } else { + SetAllNull(entries[member], count); + } + } + return; + } + case LogicalTypeId::ARRAY: + ZeroInitialize(context, ArrayVector::GetChildMutable(vector), count * ArrayType::GetSize(type)); + return; + case LogicalTypeId::LIST: + case LogicalTypeId::MAP: + memset(FlatVector::GetDataMutable(vector), 0, count * sizeof(list_entry_t)); + return; + default: + break; + } + // no zero value is known to be valid for the type + SetAllNull(vector, count); } static auto CV2CastExec(Vector &input, Vector &output, idx_t count, CastParameters ¶meters) -> bool { + if (count == 0) { + return true; + } const auto &bound_data = parameters.cast_data->Cast(); // A try cast is exactly the case where the engine handed us a slot to write a message into instead of aborting. const auto is_try_cast = parameters.error_message != nullptr; + const auto &call = is_try_cast ? *bound_data.try_call : *bound_data.call; + if (!call.Function().HasExtraFunctionInfo()) { + throw InternalException("A cast can only execute the extension scalar function it was registered with"); + } - CV2CastExecInfo args = {}; - args.in_user_data = bound_data.user_data ? bound_data.user_data->GetData() : nullptr; - args.input = &input; - args.output = &output; - args.count = count; - args.mode = is_try_cast ? DUCKDB_V2_CAST_MODE_TRY : DUCKDB_V2_CAST_MODE_NORMAL; + if (!parameters.local_state) { + throw InvalidInputException("Cannot run an extension cast function without its local state"); + } + auto &local_state = parameters.local_state->Cast(); + // not set when the cast runs without a client context: the callbacks of the function then get no context either + auto context = local_state.context; + // a cast only runs the init callback of the function it executes + auto &initialized = is_try_cast ? local_state.try_state_initialized : local_state.state_initialized; + auto &state_slot = is_try_cast ? local_state.try_state : local_state.state; + if (!initialized) { + state_slot = InitCallState(call, context); + initialized = true; + } + optional_ptr state = state_slot.get(); - optional_ptr context = nullptr; - if (parameters.local_state) { - context = parameters.local_state->Cast().context.get(); + if (is_try_cast) { + // a try function can report an error before writing every row: the rows it does not write hold zero values + Vector result(output.GetType(), count); + ZeroInitialize(Context::GetOrDatabase(context, bound_data.db), result, count); + output.Reference(result); } + DataChunk chunk; + chunk.InitializeEmpty(vector {input.GetType()}); + chunk.data[0].Reference(input); + chunk.SetCardinalityUnsafe(count); CV2ErrorInfo err = {}; - auto err_ptr = Convert(&err); - bound_data.exec_cb(Convert(&args), Convert(context.get()), &err_ptr); - + CV2ScalarInvoke(call.Function(), call.BindInfo().get(), state, context, chunk, output, err); if (!err.HasError()) { return true; } - if (is_try_cast) { - // The engine discards the message and keeps whatever the callback left in the output vector. - HandleCastError::AssignError(err.message, parameters); - return false; + if (!is_try_cast) { + err.ThrowAsException(); + } + // The engine discards the message and keeps the rows the function wrote; the others hold zero values. + HandleCastError::AssignError(err.message, parameters); + return false; +} + +static auto BindCall(BindCastInput &input, const ScalarFunction &function, const LogicalType &source, + const LogicalType &target) -> shared_ptr { + vector> children; + children.push_back(make_uniq(source, 0)); + + if (!input.context) { + throw InvalidInputException("Cannot bind extension cast function %s without a context", function.GetName()); + } + auto call = FunctionBinder(*input.context).BindScalarFunction(function, std::move(children)); + // the cast executes the function it was registered with, so a bind callback cannot replace the call + if (call->GetExpressionClass() != ExpressionClass::BOUND_FUNCTION || + call->Cast().Function().GetFunctionInfo() != function.GetFunctionInfo()) { + throw BinderException("Cast function %s cannot replace its call", function.GetName()); + } + if (call->GetReturnType() != target) { + throw InvalidInputException("Cast function %s returns %s, not the %s it casts to", function.GetName(), + call->GetReturnType().ToString(), target.ToString()); + } + return shared_ptr(unique_ptr_cast(std::move(call))); +} + +//! The least stable of two stabilities +static auto LeastStable(FunctionStability a, FunctionStability b) -> FunctionStability { + if (a == FunctionStability::VOLATILE || b == FunctionStability::VOLATILE) { + return FunctionStability::VOLATILE; } - err.ThrowAsException(); + if (a == FunctionStability::CONSISTENT_WITHIN_QUERY || b == FunctionStability::CONSISTENT_WITHIN_QUERY) { + return FunctionStability::CONSISTENT_WITHIN_QUERY; + } + return FunctionStability::CONSISTENT; +} + +static auto CV2CastBind(BindCastInput &input, const LogicalType &source, const LogicalType &target) -> BoundCastInfo { + D_ASSERT(input.info); + const auto &info = input.info->Cast(); + + auto call = BindCall(input, info.function, source, target); + auto try_call = BindCall(input, info.try_function, source, target); + auto stability = LeastStable(call->Function().GetStability(), try_call->Function().GetStability()); + + // binding the calls requires a client context, so there is one here + auto &db = DatabaseInstance::GetDatabase(*input.context); + BoundCastInfo cast_info(CV2CastExec, make_uniq(db, std::move(call), std::move(try_call)), + CV2CastInitLocalState); + cast_info.SetStability(stability); + // the callbacks of the functions can report an error for any types + cast_info.SetFallible(); + return cast_info; } +//! A cast function being built: the types it converts between and the scalar functions that execute it class CV2CastFunction { public: explicit CV2CastFunction(DatabaseInstance &db) : db(db) { } - //! Validates the configuration and builds the cast to register on `target`. - BoundCastInfo Build(DatabaseInstance &target) { + //! Validates the configuration and builds the info the cast is registered with + unique_ptr Build(DatabaseInstance &target) const { CheckRegistrationTarget(db, target, "cast function"); if (!source_type.IsComplete()) { throw InvalidInputException("Source type must be set to a fully defined concrete type"); @@ -101,12 +321,19 @@ class CV2CastFunction { if (!target_type.IsComplete()) { throw InvalidInputException("Target type must be set to a fully defined concrete type"); } - if (!exec_cb) { - throw InvalidInputException("Exec callback must be set for the function."); + if (!function || !try_function) { + throw InvalidInputException("The scalar functions of CAST and TRY_CAST must be set for the function."); } - - BoundCastInfo cast_info(CV2CastExec, make_uniq(exec_cb, user_data), CV2CastInitLocalState); - return cast_info; + for (auto &entry : {function.get(), try_function.get()}) { + auto &signature = entry->GetSignature(); + if (signature.GetParameter(0).GetType() != source_type || signature.GetReturnType() != target_type) { + throw InvalidInputException("The scalar function %s of a cast must convert %s to %s, not %s to %s", + entry->GetName(), source_type.ToString(), target_type.ToString(), + signature.GetParameter(0).GetType().ToString(), + signature.GetReturnType().ToString()); + } + } + return make_uniq(*function, *try_function); } public: @@ -115,8 +342,8 @@ class CV2CastFunction { LogicalType source_type; LogicalType target_type; int64_t implicit_cast_cost = -1; - duckdb_v2_cast_function_exec_callback_fn exec_cb = nullptr; - shared_ptr user_data = nullptr; + unique_ptr function; + unique_ptr try_function; }; static auto Convert(duckdb_v2_cast_function_handle func) -> CV2CastFunction * { @@ -174,58 +401,27 @@ DUCKDB_V2_ERROR duckdb_v2_cast_function_set_implicit_cast_cost(duckdb_v2_cast_fu return WithErrorHandler(err, [&]() { Convert(function)->implicit_cast_cost = cost; }); } -DUCKDB_V2_ERROR duckdb_v2_cast_function_set_user_data(duckdb_v2_cast_function_handle function, - duckdb_v2_opaque *user_data, duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_cast_function_set_function(duckdb_v2_cast_function_handle function, + duckdb_v2_scalar_function_handle scalar_function, + duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(function); - DUCKDB_CHECK_ARG(user_data); + DUCKDB_CHECK_ARG(scalar_function); return WithErrorHandler(err, [&]() { - Convert(function)->user_data = - duckdb::make_shared_ptr(user_data->ptr, user_data->destroy, user_data->equals); + auto &self = *Convert(function); + self.function = duckdb::make_uniq(BuildScalarFunctionForCast(scalar_function, self.db)); }); } -DUCKDB_V2_ERROR duckdb_v2_cast_function_set_exec_callback(duckdb_v2_cast_function_handle function, - duckdb_v2_cast_function_exec_callback_fn callback, - duckdb_v2_error_info_handle *err) { +DUCKDB_V2_ERROR duckdb_v2_cast_function_set_try_function(duckdb_v2_cast_function_handle function, + duckdb_v2_scalar_function_handle scalar_function, + duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(function); - return WithErrorHandler(err, [&]() { Convert(function)->exec_cb = callback; }); -} - -DUCKDB_V2_ERROR duckdb_v2_cast_function_exec_get_user_data(duckdb_v2_cast_function_exec_info_handle info, void **data, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(data); - return WithErrorHandler(err, [&]() { *data = Convert(info)->in_user_data; }); -} - -DUCKDB_V2_ERROR duckdb_v2_cast_function_exec_get_row_count(duckdb_v2_cast_function_exec_info_handle info, idx_t *count, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(count); - return WithErrorHandler(err, [&]() { *count = Convert(info)->count; }); -} - -DUCKDB_V2_ERROR duckdb_v2_cast_function_exec_get_input(duckdb_v2_cast_function_exec_info_handle info, - duckdb_v2_vector_handle *vector, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(vector); - return WithErrorHandler(err, [&]() { *vector = Convert(Convert(info)->input); }); -} - -DUCKDB_V2_ERROR duckdb_v2_cast_function_exec_get_output(duckdb_v2_cast_function_exec_info_handle info, - duckdb_v2_vector_handle *vector, - duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(vector); - return WithErrorHandler(err, [&]() { *vector = Convert(Convert(info)->output); }); -} - -DUCKDB_V2_ERROR duckdb_v2_cast_function_exec_get_mode(duckdb_v2_cast_function_exec_info_handle info, - DUCKDB_V2_CAST_MODE *mode, duckdb_v2_error_info_handle *err) { - DUCKDB_CHECK_ARG(info); - DUCKDB_CHECK_ARG(mode); - return WithErrorHandler(err, [&]() { *mode = Convert(info)->mode; }); + DUCKDB_CHECK_ARG(scalar_function); + return WithErrorHandler(err, [&]() { + auto &self = *Convert(function); + self.try_function = + duckdb::make_uniq(BuildScalarFunctionForCast(scalar_function, self.db)); + }); } DUCKDB_V2_ERROR duckdb_v2_connection_register_cast_function(duckdb_v2_connection_handle conn, @@ -236,9 +432,9 @@ DUCKDB_V2_ERROR duckdb_v2_connection_register_cast_function(duckdb_v2_connection return WithErrorHandler(err, [&]() { auto &self = *Convert(function); auto &db = *Convert(conn)->context->db; - auto cast_info = self.Build(db); - duckdb::DBConfig::GetConfig(db).GetCastFunctions().RegisterCastFunction( - self.source_type, self.target_type, std::move(cast_info), self.implicit_cast_cost); + duckdb::shared_ptr info = self.Build(db); + auto &casts = duckdb::DBConfig::GetConfig(db).GetCastFunctions(); + casts.RegisterCastFunction(self.source_type, self.target_type, CV2CastBind, info, self.implicit_cast_cost); }); } @@ -250,8 +446,8 @@ DUCKDB_V2_ERROR duckdb_v2_extension_register_cast_function(duckdb_v2_extension_h return WithErrorHandler(err, [&]() { auto &self = *Convert(function); auto &loader = GetExtensionLoader(extension); - auto cast_info = self.Build(loader.GetDatabaseInstance()); - loader.RegisterCastFunction(self.source_type, self.target_type, std::move(cast_info), self.implicit_cast_cost); + duckdb::shared_ptr info = self.Build(loader.GetDatabaseInstance()); + loader.RegisterCastFunction(self.source_type, self.target_type, CV2CastBind, info, self.implicit_cast_cost); }); } diff --git a/src/duckdb/src/main/capi/v2/capi_v2_func_copy.cpp b/src/duckdb/src/main/capi/v2/capi_v2_func_copy.cpp index b478b16b0..574b9b8d7 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_func_copy.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_func_copy.cpp @@ -484,8 +484,8 @@ static auto CV2CopyToGetWrittenStatistics(ClientContext &context, const Function //---------------------------------------------------------------------------------------------------------------------- // COPY TO sink interface //---------------------------------------------------------------------------------------------------------------------- -// COPY TO itself drives the function through its batch interface. These hooks serve callers that write a file through -// the copy function directly, sinking chunks into it one at a time - every chunk is written as a batch of its own. +// A COPY TO that keeps the insertion order drives the function through its batch interface. Otherwise, and for callers +// that write a file through the copy function directly, chunks are sunk one at a time, each written as its own batch. static auto CV2CopyToInitLocal(ExecutionContext &context, const FunctionData &bind_data) -> unique_ptr { @@ -505,6 +505,18 @@ static auto CV2CopyToSink(ExecutionContext &context, const FunctionData &bind_da CV2CopyToFlushBatch(context.client, bind_data, gstate, *prepared); } +// Batches are prepared by any thread: in order when the insertion order is kept, as they come otherwise +static auto CV2CopyToExecutionMode(bool preserve_insertion_order, bool supports_batch_index) + -> CopyFunctionExecutionMode { + if (!preserve_insertion_order) { + return CopyFunctionExecutionMode::PARALLEL_COPY_TO_FILE; + } + if (supports_batch_index) { + return CopyFunctionExecutionMode::BATCH_COPY_TO_FILE; + } + return CopyFunctionExecutionMode::REGULAR_COPY_TO_FILE; +} + static auto CV2CopyToCombine(ExecutionContext &context, const FunctionData &bind_data, GlobalFunctionData &gstate, LocalFunctionData &lstate) -> void { } @@ -617,6 +629,7 @@ class CV2CopyFunction { function.copy_to_initialize_local = CV2CopyToInitLocal; function.copy_to_sink = CV2CopyToSink; function.copy_to_combine = CV2CopyToCombine; + function.execution_mode = CV2CopyToExecutionMode; if (function_info->to_batch_size_cb) { function.desired_batch_size = CV2CopyToBatchSize; } @@ -693,11 +706,7 @@ static auto GetOptionValue(INFO &args, idx_t index, const char *function) -> duc if (values.size() == 1) { return Convert(new Value(values[0])); } - child_list_t elements; - for (auto &value : values) { - elements.emplace_back(string(), value); - } - return Convert(new Value(Value::STRUCT(std::move(elements)))); + return Convert(new Value(Value::TUPLE(values))); } } // namespace duckdb::capiv2 diff --git a/src/duckdb/src/main/capi/v2/capi_v2_func_scalar.cpp b/src/duckdb/src/main/capi/v2/capi_v2_func_scalar.cpp index e6079fec3..3ca8afdc9 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_func_scalar.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_func_scalar.cpp @@ -1,7 +1,12 @@ #include "duckdb/main/capi_v2/capi_v2_internal.hpp" #include "duckdb/main/capi_v2/capi_v2_function_internal.hpp" #include "duckdb/catalog/catalog.hpp" +#include "duckdb/catalog/catalog_entry/scalar_function_catalog_entry.hpp" +#include "duckdb/common/limits.hpp" +#include "duckdb/common/vector/flat_vector.hpp" +#include "duckdb/function/function_binder.hpp" #include "duckdb/parser/parsed_data/create_scalar_function_info.hpp" +#include "duckdb/planner/binder.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" namespace duckdb::capiv2 { @@ -23,11 +28,51 @@ class CV2FunctionData final : public FunctionData { } }; +//! The bind data of a call replaced by another call: the bound replacement, which bind_expression emits instead +class CV2ReplacementData final : public FunctionData { +public: + explicit CV2ReplacementData(unique_ptr expression_p) : expression(std::move(expression_p)) { + } + + unique_ptr expression; + + auto Copy() const -> unique_ptr override { + return make_uniq(expression->Copy()); + } + + auto Equals(const FunctionData &other) const -> bool override { + return expression->Equals(*other.Cast().expression); + } +}; + class CV2FunctionLocalState final : public FunctionLocalState { public: CV2UserData handle; }; +//! How deep replacement calls may nest, so that a function replacing its call with itself fails to bind +static constexpr idx_t MAX_REPLACEMENT_DEPTH = 32; +//! The replacement calls being bound on this thread +static thread_local idx_t replacement_depth = 0; + +class CV2ReplacementDepthGuard { +public: + CV2ReplacementDepthGuard() { + if (replacement_depth >= MAX_REPLACEMENT_DEPTH) { + throw BinderException( + "Scalar function replacements nest more than %llu calls deep: a function replaces its " + "call with itself, directly or through other functions", + MAX_REPLACEMENT_DEPTH); + } + replacement_depth++; + } + ~CV2ReplacementDepthGuard() { + replacement_depth--; + } + CV2ReplacementDepthGuard(const CV2ReplacementDepthGuard &) = delete; + CV2ReplacementDepthGuard &operator=(const CV2ReplacementDepthGuard &) = delete; +}; + static constexpr const char *SCALAR_BIND_DATA_ERROR = "Scalar functions set the bind data through duckdb_v2_scalar_function_bind_set_bind_data"; @@ -54,8 +99,20 @@ class CV2ResolveTypesBindInfo final : public CV2FunctionBindInfo { class CV2BindInfo { public: + explicit CV2BindInfo(idx_t arg_count) : arg_count(arg_count) { + } + + //! The number of arguments of the call + idx_t arg_count; //! The bind data the callback set, or nullptr shared_ptr out_bind_data; + //! The stability the callback set for this call, if any + optional stability; + //! The monotonicity the callback set for this call, per argument + vector> monotonicity; + //! The function the callback replaced the call with, if any + optional replacement_name; + vector replacement_args; }; static auto Convert(duckdb_v2_scalar_function_bind_info_handle info) -> CV2BindInfo * { @@ -144,6 +201,8 @@ class CV2ScalarFunctionInfo : public ScalarFunctionInfo { duckdb_v2_scalar_function_exec_callback_fn exec_cb = nullptr; duckdb_v2_scalar_function_stats_callback_fn stats_cb = nullptr; shared_ptr user_data = nullptr; + //! The schema the function is registered in, where a replacement call is looked up + Identifier schema = Identifier::DefaultSchema(); }; static auto CV2ScalarResolveTypes(ResolveScalarFunctionTypesInput &input) -> void { @@ -163,13 +222,94 @@ static auto CV2ScalarResolveTypes(ResolveScalarFunctionTypesInput &input) -> voi } } +//! Emits the bound replacement of a replaced call +static auto CV2ScalarEmitReplacement(FunctionBindExpressionInput &input) -> unique_ptr { + return input.bind_data->Cast().expression->Copy(); +} + +//! How much a stability restricts reuse of the result: VOLATILE restricts most +static auto StabilityRank(FunctionStability stability) -> idx_t { + switch (stability) { + case FunctionStability::CONSISTENT: + return 0; + case FunctionStability::CONSISTENT_WITHIN_QUERY: + return 1; + case FunctionStability::VOLATILE: + return 2; + default: + throw InternalException("Unknown function stability"); + } +} + +//! Makes bind_expression emit the bound replacement in place of the call being bound +static auto CV2ScalarUseReplacement(BindScalarFunctionInput &input, unique_ptr expression, + const optional &bind_stability) -> unique_ptr { + // the call is as stable as the expression it is replaced with, which binding it already accounted for + auto stability = FunctionStability::CONSISTENT; + if (expression->IsVolatile()) { + stability = FunctionStability::VOLATILE; + } else if (expression->RequiresRebind()) { + stability = FunctionStability::CONSISTENT_WITHIN_QUERY; + } + // unless the bind callback set a stricter one for the call, e.g. because it picked the replacement from state + // outside the query - the stability the function was registered with does not count + if (bind_stability && StabilityRank(*bind_stability) > StabilityRank(stability)) { + stability = *bind_stability; + // the emitted replacement carries the declaration, as folding and index validation read it from there + if (expression->GetExpressionClass() == ExpressionClass::BOUND_FUNCTION) { + expression->Cast().FunctionMutable().SetStability(stability); + } else if (stability == FunctionStability::VOLATILE) { + throw BinderException("A scalar function call declared volatile at bind time cannot be replaced with an " + "expression that is not a function call"); + } + } + // a choice that depends on state outside the query is made again for every execution + if (bind_stability && *bind_stability != FunctionStability::CONSISTENT && input.HasBinder()) { + input.GetBinder().SetAlwaysRequireRebind(); + } + input.GetBoundFunction().SetStability(stability); + input.GetBoundFunction().SetBindExpressionCallback(CV2ScalarEmitReplacement); + return make_uniq(std::move(expression)); +} + +//! The binder of the query the call is bound in, if any: a replacement that depends on the query rebinds it +static auto QueryBinder(BindScalarFunctionInput &input) -> optional_ptr { + return input.HasBinder() ? &input.GetBinder() : nullptr; +} + +//! Binds the replacement call, which bind_expression then emits in place of the call being bound +static auto CV2ScalarReplaceCall(BindScalarFunctionInput &input, const Identifier &schema, const string &name, + const vector &arg_indices, const optional &bind_stability) + -> unique_ptr { + auto &context = input.GetClientContext(); + auto &arguments = input.GetArguments(); + vector> children; + for (auto index : arg_indices) { + if (index >= arguments.size()) { + throw InvalidInputException("Argument index %llu of the replacement call is out of range", index); + } + children.push_back(arguments[index]->Copy()); + } + CV2ReplacementDepthGuard depth_guard; + auto &catalog = Catalog::GetSystemCatalog(context); + QualifiedName qualified_name(catalog.GetName(), schema, Identifier(name)); + auto &entry = catalog.GetEntry(context, qualified_name); + auto binder = input.NestedFunctionBinder(); + ErrorData error; + auto expression = binder.BindScalarFunction(entry, std::move(children), error, false, QueryBinder(input)); + if (!expression) { + error.Throw(); + } + return CV2ScalarUseReplacement(input, std::move(expression), bind_stability); +} + static auto CV2ScalarBind(BindScalarFunctionInput &input) -> unique_ptr { const auto &info = input.GetBoundFunction().GetExtraFunctionInfo().Cast(); auto &bound_function = input.GetBoundFunction(); CV2ExpressionBindInfo bind_info(bound_function, info.user_data ? info.user_data->GetData() : nullptr, input); bind_info.bind_data_error = SCALAR_BIND_DATA_ERROR; - CV2BindInfo result_info; + CV2BindInfo result_info(input.GetArguments().size()); CV2ErrorInfo err = {}; auto err_ptr = Convert(&err); @@ -187,23 +327,50 @@ static auto CV2ScalarBind(BindScalarFunctionInput &input) -> unique_ptr bind_data) -> unique_ptr { - const auto &info = expr.Function().GetExtraFunctionInfo().Cast(); +static auto CV2BindDataPointer(optional_ptr bind_data) -> void * { + if (!bind_data) { + return nullptr; + } + auto &handle = bind_data->Cast().handle; + return handle ? handle->GetData() : nullptr; +} - auto user_bind_data = bind_data ? bind_data->Cast().handle : nullptr; +unique_ptr CV2ScalarInitState(const BoundScalarFunction &function, + optional_ptr bind_data, + optional_ptr context) { + const auto &info = function.GetExtraFunctionInfo().Cast(); + if (!info.init_cb) { + return nullptr; + } CV2InitInfo args = {}; args.in_user_data = info.user_data ? info.user_data->GetData() : nullptr; - args.in_bind_data = user_bind_data ? user_bind_data->GetData() : nullptr; + args.in_bind_data = CV2BindDataPointer(bind_data); CV2ErrorInfo err = {}; auto err_ptr = Convert(&err); - CV2CallbackContext callback_context(state.GetClientContext()); - info.init_cb(Convert(&args), Convert(&callback_context), &err_ptr); + // an index maintains its keys without a client context + optional callback_context; + if (context) { + callback_context.emplace(*context); + } + info.init_cb(Convert(&args), callback_context ? Convert(&*callback_context) : nullptr, &err_ptr); unique_ptr result = nullptr; if (args.out_init_data.ptr) { @@ -213,45 +380,51 @@ static auto CV2ScalarInit(ExpressionState &state, const BoundFunctionExpression } // Throw after setting the state, so that it is destroyed even if we error. - if (err.HasError()) { err.ThrowAsException(); } - return result; } -static auto CV2ScalarExec(DataChunk &input, ExpressionState &state, Vector &result) -> void { - auto &expr = state.expr.Cast(); - const auto &info = expr.Function().GetExtraFunctionInfo().Cast(); +void CV2ScalarInvoke(const BoundScalarFunction &function, optional_ptr bind_data, + optional_ptr local_state, optional_ptr context, + DataChunk &input, Vector &result, CV2ErrorInfo &err) { + const auto &info = function.GetExtraFunctionInfo().Cast(); CV2ExecInfo args; args.in_user_data = info.user_data ? info.user_data->GetData() : nullptr; + args.in_bind_data = CV2BindDataPointer(bind_data); + if (local_state) { + args.in_init_data = local_state->Cast().handle.GetData(); + } args.input = &input; - args.function = &expr.Function(); + args.function = &function; args.result = &result; - // Setup bind data (if provided) - if (auto bind_ptr = expr.BindInfo().get()) { - const auto &bind_data = bind_ptr->Cast(); - args.in_bind_data = bind_data.handle ? bind_data.handle->GetData() : nullptr; + auto err_ptr = Convert(&err); + // an index maintains its keys without a client context + optional callback_context; + if (context) { + callback_context.emplace(*context); } + info.exec_cb(Convert(&args), callback_context ? Convert(&*callback_context) : nullptr, &err_ptr); +} - // Setup local state (if provided) - if (auto state_ptr = ExecuteFunctionState::GetFunctionState(state)) { - const auto &state_data = state_ptr->Cast(); - args.in_init_data = state_data.handle.GetData(); - } +static auto CV2ScalarInit(ExpressionState &state, const BoundFunctionExpression &expr, + optional_ptr bind_data) -> unique_ptr { + return CV2ScalarInitState(expr.Function(), bind_data, + state.HasClientContext() ? &state.GetClientContext() : nullptr); +} +static auto CV2ScalarExec(DataChunk &input, ExpressionState &state, Vector &result) -> void { + auto &expr = state.expr.Cast(); CV2ErrorInfo err = {}; - auto err_ptr = Convert(&err); - - CV2CallbackContext callback_context(state.GetClientContext()); - info.exec_cb(Convert(&args), Convert(&callback_context), &err_ptr); - + CV2ScalarInvoke(expr.Function(), expr.BindInfo().get(), ExecuteFunctionState::GetFunctionState(state), + state.HasClientContext() ? &state.GetClientContext() : nullptr, input, result, err); if (err.HasError()) { err.ThrowAsException(); } + FlatVector::DropAllValidMasks(result); } static auto CV2ScalarStats(ClientContext &context, FunctionStatisticsInput &input) -> unique_ptr { @@ -290,8 +463,42 @@ class CV2ScalarFunction { properties.SetFallible(); } - //! Validates the configuration and builds the scalar function to register on `target`. + //! Validates the configuration and builds the scalar function to register on `target`. The function takes over + //! the callbacks and user data. ScalarFunction Build(DatabaseInstance &target) { + Validate(target); + return Assemble(std::move(info)); + } + + //! Builds the function a cast is registered from: one concrete parameter, converting to the concrete return type. + //! The handle keeps its configuration: the function gets a copy, sharing the user data. + ScalarFunction BuildForCast(DatabaseInstance &target) { + ValidateForCast(target); + return Assemble(info); + } + + //! Throws unless the function can be registered as a cast on `target` + void ValidateForCast(DatabaseInstance &target) { + if (signature.GetParameterCount() != 1 || signature.IsVariadic() || + !signature.GetParameter(0).AcceptsPosition()) { + throw InvalidInputException("A cast function must take exactly one standard parameter: the value to cast."); + } + if (!signature.GetParameter(0).GetType().IsComplete()) { + throw InvalidInputException("The parameter of a cast function must be a fully defined concrete type"); + } + if (info.resolve_types_cb) { + throw InvalidInputException("A cast function cannot have a resolve types callback: its types are fixed."); + } + // a cast converts its input as it is: there is no call whose arguments a collation could be pushed into + if (properties.GetCollationHandling() != FunctionCollationHandling::PROPAGATE_COLLATIONS) { + throw InvalidInputException("A cast function cannot declare a collation handling other than the default."); + } + Validate(target); + } + +private: + //! Throws unless the configuration can be registered on `target` + void Validate(DatabaseInstance &target) { CheckRegistrationTarget(db, target, "scalar function"); if (name.empty()) { throw InvalidInputException("Function name cannot be empty."); @@ -319,24 +526,37 @@ class CV2ScalarFunction { } signature.Verify(); + if (!signature.IsVariadic() && arg_properties.size() > signature.GetParameterCount()) { + throw InvalidInputException("Argument monotonicity was set for argument %llu, but the function has %llu " + "parameters", + arg_properties.size() - 1, signature.GetParameterCount()); + } + } + //! The scalar function made of the validated configuration and `function_info` + ScalarFunction Assemble(CV2ScalarFunctionInfo function_info) { + const auto &return_type = signature.GetReturnType(); ScalarFunction function(name, {}, return_type, CV2ScalarExec); function.SetProperties(properties); function.GetSignature() = signature; + if (!arg_properties.empty()) { + function.SetArgProperties(arg_properties); + } - if (info.resolve_types_cb) { + if (function_info.resolve_types_cb) { function.SetResolveTypesCallback(CV2ScalarResolveTypes); } - if (info.bind_cb) { + if (function_info.bind_cb) { function.SetBindCallback(CV2ScalarBind); } - if (info.init_cb) { + if (function_info.init_cb) { function.SetInitStateCallback(CV2ScalarInit); } - if (info.stats_cb) { + if (function_info.stats_cb) { function.SetStatisticsCallback(CV2ScalarStats); } - function.SetExtraFunctionInfo(std::move(info)); + function_info.schema = schema; + function.SetExtraFunctionInfo(std::move(function_info)); return function; } @@ -351,8 +571,28 @@ class CV2ScalarFunction { //! The schema of the system catalog the function is registered in Identifier schema = Identifier::DefaultSchema(); FunctionProperties properties; + vector arg_properties; }; +static auto ConvertMonotonicity(DUCKDB_V2_FUNCTION_MONOTONICITY monotonicity) -> Monotonicity { + switch (monotonicity) { + case DUCKDB_V2_FUNCTION_MONOTONICITY_UNKNOWN: + return Monotonicity::UNKNOWN; + case DUCKDB_V2_FUNCTION_MONOTONICITY_CONSTANT: + return Monotonicity::CONSTANT; + case DUCKDB_V2_FUNCTION_MONOTONICITY_NON_DECREASING: + return Monotonicity::NON_DECREASING; + case DUCKDB_V2_FUNCTION_MONOTONICITY_STRICTLY_INCREASING: + return Monotonicity::STRICTLY_INCREASING; + case DUCKDB_V2_FUNCTION_MONOTONICITY_NON_INCREASING: + return Monotonicity::NON_INCREASING; + case DUCKDB_V2_FUNCTION_MONOTONICITY_STRICTLY_DECREASING: + return Monotonicity::STRICTLY_DECREASING; + default: + throw InvalidInputException("Unknown function monotonicity %d", static_cast(monotonicity)); + } +} + static auto Convert(duckdb_v2_scalar_function_handle func) -> CV2ScalarFunction * { return reinterpret_cast(func); } @@ -360,6 +600,10 @@ static auto Convert(CV2ScalarFunction *func) -> duckdb_v2_scalar_function_handle return reinterpret_cast(func); } +ScalarFunction BuildScalarFunctionForCast(duckdb_v2_scalar_function_handle function, DatabaseInstance &target) { + return Convert(function)->BuildForCast(target); +} + } // namespace duckdb::capiv2 //---------------------------------------------------------------------------------------------------------------------- @@ -516,6 +760,75 @@ DUCKDB_V2_ERROR duckdb_v2_scalar_function_bind_set_bind_data(duckdb_v2_scalar_fu }); } +DUCKDB_V2_ERROR duckdb_v2_scalar_function_set_argument_monotonicity(duckdb_v2_scalar_function_handle function, + idx_t index, + DUCKDB_V2_FUNCTION_MONOTONICITY monotonicity, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(function); + return WithErrorHandler(err, [&]() { + if (index == duckdb::NumericLimits::Maximum()) { + throw duckdb::InvalidInputException("Argument index %llu of the monotonicity is out of range", index); + } + auto value = ConvertMonotonicity(monotonicity); + auto &props = Convert(function)->arg_properties; + if (props.size() <= index) { + props.resize(index + 1); + } + props[index].monotonicity = value; + }); +} + +DUCKDB_V2_ERROR duckdb_v2_scalar_function_bind_set_property(duckdb_v2_scalar_function_bind_info_handle info, + DUCKDB_V2_FUNCTION_PROPERTY_KEY key, + DUCKDB_V2_FUNCTION_PROPERTY_VALUE value, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + return WithErrorHandler(err, [&]() { + if (key != DUCKDB_V2_FUNCTION_PROPERTY_STABILITY) { + throw duckdb::InvalidInputException("Only the stability of a scalar function call can be set at bind time"); + } + duckdb::FunctionProperties props; + SetScalarFunctionProperty(props, key, value); + Convert(info)->stability = props.GetStability(); + }); +} + +DUCKDB_V2_ERROR +duckdb_v2_scalar_function_bind_set_argument_monotonicity(duckdb_v2_scalar_function_bind_info_handle info, idx_t index, + DUCKDB_V2_FUNCTION_MONOTONICITY monotonicity, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + return WithErrorHandler(err, [&]() { + auto &bind_info = *Convert(info); + if (index >= bind_info.arg_count) { + throw duckdb::InvalidInputException("Argument index %llu of the monotonicity is out of range for a call " + "with %llu arguments", + index, bind_info.arg_count); + } + bind_info.monotonicity.emplace_back(index, ConvertMonotonicity(monotonicity)); + }); +} + +DUCKDB_V2_ERROR duckdb_v2_scalar_function_bind_replace_call(duckdb_v2_scalar_function_bind_info_handle info, + const char *name, idx_t name_length, + const idx_t *arg_indices, idx_t arg_count, + duckdb_v2_error_info_handle *err) { + DUCKDB_CHECK_ARG(info); + DUCKDB_CHECK_STR_ARG(name, name_length); + if (arg_count > 0) { + DUCKDB_CHECK_ARG(arg_indices); + } + return WithErrorHandler(err, [&]() { + auto function_name = ConvertIdentifierName(name, name_length); + if (function_name.empty()) { + throw duckdb::InvalidInputException("The name of the replacement function cannot be empty"); + } + auto &bind_info = *Convert(info); + bind_info.replacement_name = duckdb::string(function_name); + bind_info.replacement_args.assign(arg_indices, arg_indices + arg_count); + }); +} + DUCKDB_V2_ERROR duckdb_v2_scalar_function_init_get_user_data(duckdb_v2_scalar_function_init_info_handle info, void **data, duckdb_v2_error_info_handle *err) { DUCKDB_CHECK_ARG(info); diff --git a/src/duckdb/src/main/capi/v2/capi_v2_func_table.cpp b/src/duckdb/src/main/capi/v2/capi_v2_func_table.cpp index 37a163df3..962ee2fbb 100644 --- a/src/duckdb/src/main/capi/v2/capi_v2_func_table.cpp +++ b/src/duckdb/src/main/capi/v2/capi_v2_func_table.cpp @@ -35,6 +35,8 @@ class CV2TableFunctionData final : public CV2DataSourceBindData { //! For a function with an operator: whether the operator receives its input from a child of the plan, rather than //! once from the constant arguments of the call bool streaming_input = false; + //! Whether the filter pushdown callback accepted filters, which then live only in the bind data + bool accepted_filters = false; auto Copy() const -> unique_ptr override { auto copy = make_uniq(); @@ -45,8 +47,13 @@ class CV2TableFunctionData final : public CV2DataSourceBindData { copy->cardinality_set = cardinality_set; copy->column_names = column_names; copy->streaming_input = streaming_input; + copy->accepted_filters = accepted_filters; return std::move(copy); } + //! A function of the C API is bound from its call only, unless its scan took over filters of the plan + auto IsIdentifiedByCall() const -> bool override { + return !accepted_filters; + } }; class CV2TableBindInfo { @@ -601,6 +608,9 @@ static auto CV2TableFilterPushdown(ClientContext &context, LogicalGet &get, remaining.push_back(std::move(filters[i])); } } + if (remaining.size() < filters.size()) { + get.bind_data.write().Cast().accepted_filters = true; + } filters = std::move(remaining); } diff --git a/src/duckdb/src/main/client_context.cpp b/src/duckdb/src/main/client_context.cpp index 442c383a7..94d455ce6 100644 --- a/src/duckdb/src/main/client_context.cpp +++ b/src/duckdb/src/main/client_context.cpp @@ -1219,9 +1219,10 @@ void ClientContext::DisableProfiling() { void ClientContext::RegisterFunction(CreateFunctionInfo &info) { RunFunctionInTransaction([&]() { + // look the function up where it is created: in the system catalog, under its whole schema path + auto schema_path = info.GetQualifiedName().SchemaPath(); auto existing_function = Catalog::GetEntry( - *this, - QualifiedName(Identifier::InvalidCatalog(), info.GetQualifiedName().Schema(), info.GetFunctionName()), + *this, QualifiedName::FromCatalogSchema(Identifier::SystemCatalog(), schema_path, info.GetFunctionName()), OnEntryNotFound::RETURN_NULL); if (existing_function) { auto &new_info = info.Cast(); diff --git a/src/duckdb/src/main/client_verify.cpp b/src/duckdb/src/main/client_verify.cpp index b458dad39..034434b09 100644 --- a/src/duckdb/src/main/client_verify.cpp +++ b/src/duckdb/src/main/client_verify.cpp @@ -9,6 +9,9 @@ #include "duckdb/parser/statement/insert_statement.hpp" #include "duckdb/parser/statement/update_statement.hpp" #include "duckdb/parser/statement/transaction_statement.hpp" +#include "duckdb/parser/query_node/delete_query_node.hpp" +#include "duckdb/parser/query_node/insert_query_node.hpp" +#include "duckdb/parser/query_node/merge_query_node.hpp" #include "duckdb/parser/query_node/update_query_node.hpp" #include "duckdb/common/serializer/binary_deserializer.hpp" #include "duckdb/common/serializer/binary_serializer.hpp" @@ -19,7 +22,9 @@ #include "duckdb/parser/expression/subquery_expression.hpp" #include "duckdb/parser/parsed_expression_iterator.hpp" #include "duckdb/parser/statement/execute_statement.hpp" +#include "duckdb/parser/statement/merge_into_statement.hpp" #include "duckdb/parser/statement/prepare_statement.hpp" +#include "duckdb/parser/statement/select_statement.hpp" namespace duckdb { @@ -98,6 +103,38 @@ static void ReplaceStatement(unique_ptr &statement, unique_ptr node; + switch (statement.type) { + case StatementType::SELECT_STATEMENT: + node = statement.Cast().node.get(); + break; + case StatementType::INSERT_STATEMENT: + node = statement.Cast().node.get(); + break; + case StatementType::DELETE_STATEMENT: + node = statement.Cast().node.get(); + break; + case StatementType::UPDATE_STATEMENT: + node = statement.Cast().node.get(); + break; + case StatementType::MERGE_INTO_STATEMENT: + node = statement.Cast().node.get(); + break; + default: + return false; + } + if (!node) { + return false; + } + bool scans_column_data = false; + ParsedExpressionIterator::EnumerateQueryNodeChildren( + *node, [](unique_ptr &) {}, + [&](TableRef &ref) { scans_column_data |= ref.type == TableReferenceType::COLUMN_DATA; }); + return scans_column_data; +} + void ClientContext::StatementVerification(ClientContextLock &lock, unique_ptr &statement, QueryParameters query_parameters, bool allow_nested_statements) { auto verification = Settings::Get(*this); @@ -108,6 +145,9 @@ void ClientContext::StatementVerification(ClientContextLock &lock, unique_ptrCopy()); } else if (verification == DebugStatementVerification::REPARSE_STATEMENT) { + if (ScansColumnData(*statement)) { + return; + } // ToString() writes identifiers as they were folded when the statement was first parsed, so folding // them a second time would corrupt any identifier that was quoted in the original statement Parser parser(*this, IdentifierCaseMode::PRESERVE_CASE); diff --git a/src/duckdb/src/main/config.cpp b/src/duckdb/src/main/config.cpp index 4d6d5897a..1e695ec21 100644 --- a/src/duckdb/src/main/config.cpp +++ b/src/duckdb/src/main/config.cpp @@ -216,6 +216,7 @@ static const ConfigurationOption internal_options[] = { DUCKDB_SETTING(IeeeFloatingPointOpsSetting), DUCKDB_SETTING(IgnoreUnknownCrsSetting), DUCKDB_SETTING(ImmediateTransactionModeSetting), + DUCKDB_SETTING_CALLBACK(ImplicitLateralSubqueriesSetting), DUCKDB_SETTING(IndexScanMaxCountSetting), DUCKDB_SETTING_CALLBACK(IndexScanPercentageSetting), DUCKDB_SETTING_CALLBACK(InitialColumnSegmentSizeSetting), diff --git a/src/duckdb/src/main/database.cpp b/src/duckdb/src/main/database.cpp index 70cd6730e..5ce82d27b 100644 --- a/src/duckdb/src/main/database.cpp +++ b/src/duckdb/src/main/database.cpp @@ -610,6 +610,7 @@ void DatabaseInstance::Configure(DBConfig &new_config, const char *database_path Settings::Get(config), DBConfig::ParseMemoryLimitOrMaximum(Settings::Get(config))); } + config.block_allocator->SetBufferPool(config.buffer_pool); config.db_cache_entry = std::move(new_config.db_cache_entry); config.path_manager = std::move(new_config.path_manager); } diff --git a/src/duckdb/src/main/extension/extension_loader.cpp b/src/duckdb/src/main/extension/extension_loader.cpp index 94595965d..d060234d2 100644 --- a/src/duckdb/src/main/extension/extension_loader.cpp +++ b/src/duckdb/src/main/extension/extension_loader.cpp @@ -17,6 +17,9 @@ #include "duckdb/main/client_data.hpp" #include "duckdb/main/config.hpp" #include "duckdb/main/secret/secret_manager.hpp" +#include "duckdb/execution/index/index_type_set.hpp" +#include "duckdb/logging/log_manager.hpp" +#include "duckdb/logging/log_type.hpp" #include "duckdb/main/database.hpp" #include "duckdb/main/profiler/metrics_manager.hpp" @@ -364,6 +367,17 @@ void ExtensionLoader::RegisterSecretType(SecretType secret_type) { config.secret_manager->RegisterSecretType(secret_type); } +void ExtensionLoader::RegisterLogType(unique_ptr type) { + type->extension_name = GetRegisteredExtensionName().GetIdentifierName(); + db.GetLogManager().RegisterLogType(std::move(type)); +} + +void ExtensionLoader::RegisterIndexType(const IndexType &index_type) { + auto attributed = index_type; + attributed.registered_by = GetRegisteredExtensionName().GetIdentifierName(); + DBConfig::GetConfig(db).GetIndexTypes().RegisterIndexType(attributed); +} + void ExtensionLoader::RegisterCastFunction(const LogicalType &source, const LogicalType &target, bind_cast_function_t bind_function, int64_t implicit_cast_cost) { auto &config = DBConfig::GetConfig(db); @@ -371,6 +385,14 @@ void ExtensionLoader::RegisterCastFunction(const LogicalType &source, const Logi casts.RegisterCastFunction(source, target, bind_function, implicit_cast_cost); } +void ExtensionLoader::RegisterCastFunction(const LogicalType &source, const LogicalType &target, + bind_cast_function_t bind_function, shared_ptr bind_info, + int64_t implicit_cast_cost) { + auto &config = DBConfig::GetConfig(db); + config.GetCastFunctions().RegisterCastFunction(source, target, bind_function, std::move(bind_info), + implicit_cast_cost); +} + void ExtensionLoader::RegisterCastFunction(const LogicalType &source, const LogicalType &target, BoundCastInfo function, int64_t implicit_cast_cost) { auto &config = DBConfig::GetConfig(db); diff --git a/src/duckdb/src/main/extension/linked_extension_registry.cpp b/src/duckdb/src/main/extension/linked_extension_registry.cpp index 1f769e5c3..913160170 100644 --- a/src/duckdb/src/main/extension/linked_extension_registry.cpp +++ b/src/duckdb/src/main/extension/linked_extension_registry.cpp @@ -1,4 +1,5 @@ #include "duckdb/main/extension/linked_extension_registry.hpp" +#include "duckdb/common/no_destructor.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/string_util.hpp" @@ -28,8 +29,8 @@ struct RegistryState { // function-local so that registrations during static initialization always find it constructed RegistryState &GetRegistryState() { - static RegistryState state; - return state; + static NoDestructor state; + return *state; } void SetDescriptorError(duckdb_extension_descriptor *descriptor, const char *message) { diff --git a/src/duckdb/src/main/http/http_client_httplib.cpp b/src/duckdb/src/main/http/http_client_httplib.cpp index fe70bfb7f..be02a93cd 100644 --- a/src/duckdb/src/main/http/http_client_httplib.cpp +++ b/src/duckdb/src/main/http/http_client_httplib.cpp @@ -1,9 +1,13 @@ #include "duckdb/main/http/http_util.hpp" +#include "duckdb/common/no_destructor.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/main/database.hpp" #include "duckdb_static_extension.h" +// vendored code with statics we do not control +DUCKDB_ALLOW_STATIC_LIFETIME_BEGIN #include "httplib.hpp" +DUCKDB_ALLOW_STATIC_LIFETIME_END #if defined(DUCKDB_DISABLE_BUILTIN_HTTPLIB) || defined(DISABLE_DUCKDB_REMOTE_INSTALL) || \ defined(DUCKDB_DISABLE_EXTENSION_LOAD) diff --git a/src/duckdb/src/main/http/http_retry_budget.cpp b/src/duckdb/src/main/http/http_retry_budget.cpp index 07e44926a..2d5787361 100644 --- a/src/duckdb/src/main/http/http_retry_budget.cpp +++ b/src/duckdb/src/main/http/http_retry_budget.cpp @@ -1,4 +1,5 @@ #include "duckdb/main/http/http_retry_budget.hpp" +#include "duckdb/common/no_destructor.hpp" #include "duckdb/common/limits.hpp" #include "duckdb/common/operator/cast_operators.hpp" @@ -224,14 +225,14 @@ uint64_t HTTPRetryBudget::BackoffMs(uint64_t retry_wait_ms, float retry_backoff, static const StrpTimeFormat &RetryAfterDateFormat() { // RFC 7231 IMF-fixdate, e.g. "Sun, 06 Nov 1994 08:49:37 GMT". - static const StrpTimeFormat format = []() { + static const NoDestructor format([]() { StrpTimeFormat result; auto error = StrTimeFormat::ParseFormatSpecifier("%a, %d %b %Y %H:%M:%S GMT", result); D_ASSERT(error.empty()); (void)error; return result; - }(); - return format; + }()); + return *format; } bool HTTPRetryBudget::TryParseRetryAfterMs(const string &retry_after, uint64_t &delay_ms) { diff --git a/src/duckdb/src/main/result_format.cpp b/src/duckdb/src/main/result_format.cpp index 7b056287a..32d0edacc 100644 --- a/src/duckdb/src/main/result_format.cpp +++ b/src/duckdb/src/main/result_format.cpp @@ -1,4 +1,5 @@ #include "duckdb/main/result_format.hpp" +#include "duckdb/common/no_destructor.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/main/buffered_data/buffered_data.hpp" @@ -31,13 +32,15 @@ ChunkFormat::ChunkFormat(QueryResultMemoryType memory_type_p) : memory_type(memo } const shared_ptr &ChunkFormat::InMemory() { - static const shared_ptr format = make_shared_ptr(QueryResultMemoryType::IN_MEMORY); - return format; + static const NoDestructor> format( + make_shared_ptr(QueryResultMemoryType::IN_MEMORY)); + return *format; } const shared_ptr &ChunkFormat::BufferManaged() { - static const shared_ptr format = make_shared_ptr(QueryResultMemoryType::BUFFER_MANAGED); - return format; + static const NoDestructor> format( + make_shared_ptr(QueryResultMemoryType::BUFFER_MANAGED)); + return *format; } QueryResultMemoryType ChunkFormat::MemoryType() const { diff --git a/src/duckdb/src/main/settings/autogenerated_settings.cpp b/src/duckdb/src/main/settings/autogenerated_settings.cpp index 2f1f06608..65747c57c 100644 --- a/src/duckdb/src/main/settings/autogenerated_settings.cpp +++ b/src/duckdb/src/main/settings/autogenerated_settings.cpp @@ -204,6 +204,16 @@ void FsyncModeSetting::OnSet(SettingCallbackInfo &info, Value ¶meter) { EnumUtil::FromString(StringValue::Get(parameter)); } +//===----------------------------------------------------------------------===// +// Implicit Lateral Subqueries +//===----------------------------------------------------------------------===// +void ImplicitLateralSubqueriesSetting::OnSet(SettingCallbackInfo &info, Value ¶meter) { + if (parameter.IsNull()) { + throw InvalidInputException("implicit_lateral_subqueries setting cannot be NULL"); + } + EnumUtil::FromString(StringValue::Get(parameter)); +} + //===----------------------------------------------------------------------===// // Lambda Syntax //===----------------------------------------------------------------------===// diff --git a/src/duckdb/src/main/settings/custom_settings.cpp b/src/duckdb/src/main/settings/custom_settings.cpp index a6b65ce37..fb66c6f99 100644 --- a/src/duckdb/src/main/settings/custom_settings.cpp +++ b/src/duckdb/src/main/settings/custom_settings.cpp @@ -217,8 +217,7 @@ void AllowPersistentSecretsSetting::SetGlobal(DatabaseInstance *db, DBConfig &co if (input.IsNull()) { throw InvalidInputException("%s setting cannot be NULL", AllowPersistentSecretsSetting::Name); } - auto value = input.DefaultCastAs(LogicalType::BOOLEAN); - config.secret_manager->SetEnablePersistentSecrets(value.GetValue()); + config.secret_manager->SetEnablePersistentSecrets(input.GetValue()); } void AllowPersistentSecretsSetting::ResetGlobal(DatabaseInstance *db, DBConfig &config) { diff --git a/src/duckdb/src/main/user_settings.cpp b/src/duckdb/src/main/user_settings.cpp index 45f7beb08..d0a3fa335 100644 --- a/src/duckdb/src/main/user_settings.cpp +++ b/src/duckdb/src/main/user_settings.cpp @@ -1,4 +1,5 @@ #include "duckdb/main/user_settings.hpp" +#include "duckdb/common/no_destructor.hpp" #include "duckdb/main/settings.hpp" #include "duckdb/common/type_visitor.hpp" #include "duckdb/common/types/string.hpp" @@ -270,8 +271,10 @@ static CachedGlobalSettings &GetThreadSettingsCache() { if (worker_settings_cache) { return *worker_settings_cache; } - // the first use on a thread registers the destructor, which allocates + // the first use on a thread registers the destructor, which allocates and releases the cache at thread exit + DUCKDB_ALLOW_STATIC_LIFETIME_BEGIN thread_local CachedGlobalSettings current_cache; + DUCKDB_ALLOW_STATIC_LIFETIME_END return current_cache; #endif } diff --git a/src/duckdb/src/optimizer/aggregate_filter_extractor.cpp b/src/duckdb/src/optimizer/aggregate_filter_extractor.cpp new file mode 100644 index 000000000..ef71d2ce6 --- /dev/null +++ b/src/duckdb/src/optimizer/aggregate_filter_extractor.cpp @@ -0,0 +1,127 @@ +#include "duckdb/optimizer/aggregate_filter_extractor.hpp" + +#include "duckdb/optimizer/filter_combiner.hpp" +#include "duckdb/optimizer/optimizer.hpp" +#include "duckdb/optimizer/removed_subtree_effects.hpp" +#include "duckdb/parser/expression_map.hpp" +#include "duckdb/planner/expression/bound_aggregate_expression.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression/bound_conjunction_expression.hpp" +#include "duckdb/planner/expression/bound_reference_expression.hpp" +#include "duckdb/planner/expression/expression_barrier.hpp" +#include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/planner/filter/expression_filter.hpp" +#include "duckdb/planner/filter/table_filter_functions.hpp" +#include "duckdb/planner/operator/logical_aggregate.hpp" +#include "duckdb/planner/operator/logical_filter.hpp" + +namespace duckdb { + +static unique_ptr CreateInputFilter(unique_ptr predicate) { + optional_ptr column; + bool single_column = true; + ExpressionIterator::VisitExpression(*predicate, [&](const BoundColumnRefExpression &ref) { + if (!column) { + column = ref; + } else if (column->Binding() != ref.Binding() || column->Depth() != ref.Depth()) { + single_column = false; + } + }); + if (!single_column) { + return nullptr; + } + if (!column || predicate->GetExpressionType() != ExpressionType::CONJUNCTION_OR) { + return predicate; + } + // Redundant disjunctions can prune row groups without adding per-row evaluation. + auto input = column->Copy(); + BoundReferenceExpression placeholder(input->GetReturnType(), 0ULL); + ExpressionFilter::ReplaceExpressionRecursive(predicate, placeholder, ExpressionType::BOUND_COLUMN_REF); + ExpressionFilter filter(CreateOptionalFilterExpression(std::move(predicate), input->GetReturnType())); + return filter.ToExpression(*input); +} + +AggregateFilterExtractor::AggregateFilterExtractor(Optimizer &optimizer, LogicalAggregate &aggr) + : optimizer(optimizer), aggr(aggr) { + if (optimizer.OptimizerDisabled(OptimizerType::FILTER_PUSHDOWN) || !aggr.groups.empty() || + aggr.grouping_sets.size() > 1) { + can_filter_input = false; + } +} + +unique_ptr AggregateFilterExtractor::Extract(const vector &aggregate_indices) { + if ((can_filter_input.has_value() && !can_filter_input.value()) || aggregate_indices.empty()) { + return nullptr; + } + expression_set_t seen; + vector> predicates; + for (auto aggregate_idx : aggregate_indices) { + auto &aggregate = aggr.expressions[aggregate_idx]->Cast(); + auto &filter = aggregate.GetFilter(); + if (!filter || aggregate.IsVolatile() || ExpressionBarrier::Contains(*filter) || + !FilterCombiner::CanMatchExpression(*filter)) { + return nullptr; + } + bool can_throw = false; + ExpressionIterator::EnumerateChildren(aggregate, + [&](const Expression &child) { can_throw |= child.CanThrow(); }); + if (can_throw) { + return nullptr; + } + if (seen.insert(*filter).second) { + predicates.push_back(filter->Copy()); + } + } + const bool shared_filter = predicates.size() == 1; + LogicalFilter rewritten; + rewritten.expressions.push_back( + BoundConjunctionExpression::Create(ExpressionType::CONJUNCTION_OR, std::move(predicates))); + if (!optimizer.OptimizerDisabled(OptimizerType::EXPRESSION_REWRITER)) { + optimizer.rewriter.VisitOperator(rewritten); + } + if (!shared_filter) { + vector> input_filters; + for (auto &predicate : rewritten.expressions) { + auto input_filter = CreateInputFilter(std::move(predicate)); + if (input_filter) { + input_filters.push_back(std::move(input_filter)); + } + } + rewritten.expressions = std::move(input_filters); + } + if (rewritten.expressions.empty()) { + return nullptr; + } + if (!can_filter_input.has_value()) { + RemovedSubtreeEffects effects(*aggr.children[0]); + can_filter_input = !effects.HasEffect(*aggr.children[0]); + } + if (!can_filter_input.value()) { + return nullptr; + } + if (shared_filter) { + for (auto aggregate_idx : aggregate_indices) { + aggr.expressions[aggregate_idx]->Cast().GetFilterMutable().reset(); + } + } + return BoundConjunctionExpression::Create(ExpressionType::CONJUNCTION_AND, std::move(rewritten.expressions)); +} + +unique_ptr AggregateFilterExtractor::GuardDeferredFilter(const LogicalAggregate &aggr, + const BoundAggregateExpression &source, + unique_ptr filter) { + if (!filter || !aggr.groups.empty()) { + return filter; + } + bool needs_barrier = source.GetFilter() && ExpressionBarrier::Contains(*source.GetFilter()); + if (!needs_barrier) { + ExpressionIterator::EnumerateChildren(source, + [&](const Expression &child) { needs_barrier |= child.CanThrow(); }); + } + if (!needs_barrier) { + return filter; + } + return ExpressionBarrier::Wrap(std::move(filter)); +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/aggregate_rewrite.cpp b/src/duckdb/src/optimizer/aggregate_rewrite.cpp index 862ba08ce..e41d5f54e 100644 --- a/src/duckdb/src/optimizer/aggregate_rewrite.cpp +++ b/src/duckdb/src/optimizer/aggregate_rewrite.cpp @@ -3,6 +3,7 @@ #include "duckdb/function/aggregate/distributive_functions.hpp" #include "duckdb/function/function_binder.hpp" #include "duckdb/function/builtin_function_lookup.hpp" +#include "duckdb/optimizer/aggregate_filter_extractor.hpp" #include "duckdb/optimizer/optimizer.hpp" #include "duckdb/planner/binder.hpp" #include "duckdb/planner/expression/bound_aggregate_expression.hpp" @@ -170,6 +171,7 @@ unique_ptr FrequencyAggregateRewrite::Create(AggregateRewr filter = std::move(not_null); } } + filter = AggregateFilterExtractor::GuardDeferredFilter(op, input.aggregate, std::move(filter)); unique_ptr order_key; if (order_column.IsValid()) { diff --git a/src/duckdb/src/optimizer/column_binding_replacer.cpp b/src/duckdb/src/optimizer/column_binding_replacer.cpp index 630a71a54..366e3a2af 100644 --- a/src/duckdb/src/optimizer/column_binding_replacer.cpp +++ b/src/duckdb/src/optimizer/column_binding_replacer.cpp @@ -4,6 +4,7 @@ #include "duckdb/planner/expression/bound_subquery_expression.hpp" #include "duckdb/planner/operator/logical_cte.hpp" #include "duckdb/planner/operator/logical_dependent_join.hpp" +#include "duckdb/planner/operator/logical_filter.hpp" #include "duckdb/planner/operator/logical_secure_view.hpp" #include "duckdb/planner/column_binding_map.hpp" @@ -19,20 +20,46 @@ ReplacementBinding::ReplacementBinding(ColumnBinding old_binding, ColumnBinding ReplacementBinding BindingReplacementGraph::ResolveReplacement(ColumnBinding binding) const { ReplacementBinding result(binding, binding); + auto last_type_binding = binding; idx_t traversed_edges = 0; - while (auto replacement = Find(result.new_binding)) { + while (auto replacement = FindCached(result.new_binding)) { if (++traversed_edges > replacement_bindings.size()) { throw InternalException("Cyclic column binding replacements"); } result.new_binding = replacement->new_binding; if (replacement->replace_type) { + last_type_binding = replacement->old_binding; result.replace_type = true; result.new_type = replacement->new_type; } } + auto replace_type = result.replace_type; + while (auto replacement = FindCached(binding)) { + auto next = replacement->new_binding; + replacement->new_binding = result.new_binding; + replacement->replace_type = replace_type; + replacement->new_type = replace_type ? result.new_type : LogicalType(); + if (binding == last_type_binding) { + replace_type = false; + } + binding = next; + } return result; } +optional_ptr BindingReplacementGraph::FindCached(ColumnBinding binding) const { + auto entry = binding_slots.find(binding); + if (entry == binding_slots.end()) { + return nullptr; + } + auto &cached = cached_replacements[entry->second]; + if (cached.type_version != type_version) { + cached.replacement = replacement_bindings[entry->second]; + cached.type_version = type_version; + } + return cached.replacement; +} + optional_ptr BindingReplacementGraph::Find(ColumnBinding old_binding) const { auto entry = binding_slots.find(old_binding); if (entry == binding_slots.end()) { @@ -67,6 +94,7 @@ bool BindingReplacementGraph::TryAdd(const ReplacementBinding &replacement) { if (!existing.replace_type && replacement.replace_type) { existing.replace_type = true; existing.new_type = replacement.new_type; + type_version++; } return true; } @@ -76,6 +104,7 @@ bool BindingReplacementGraph::TryAdd(const ReplacementBinding &replacement) { } else { replacement_bindings.emplace_back(replacement.old_binding, replacement.new_binding); } + cached_replacements.emplace_back(replacement_bindings.back(), type_version); return true; } @@ -232,6 +261,10 @@ void ColumnBindingReplacer::VisitOperatorBindings(LogicalOperator &op) { VisitOperatorExpressions(op); } +void ColumnBindingReplacer::VisitExpression(unique_ptr *expression) { + VisitExpressionIteratively(expression); +} + unique_ptr ColumnBindingReplacer::VisitReplace(BoundColumnRefExpression &expr, unique_ptr *expr_ptr) { if (replacement_graph) { @@ -346,6 +379,67 @@ void ColumnBindingRewrite::ApplyToOperatorBindings(LogicalOperator &op, const Bi replacer.VisitOperatorBindings(op); } +void ColumnBindingRewrite::ReplaceOutputBindings(unique_ptr &op, + const vector &old_bindings, + BindingReplacementGraph &replacements) { + auto new_bindings = op->GetColumnBindings(); + if (old_bindings.size() != new_bindings.size()) { + throw InternalException("Binding replacement must preserve output arity"); + } + column_binding_map_t first_occurrence; + vector selection; + bool needs_selection = false; + for (idx_t index = 0; index < old_bindings.size(); index++) { + auto entry = first_occurrence.emplace(old_bindings[index], ProjectionIndex(index)); + selection.push_back(entry.first->second); + if (entry.second) { + replacements.Add(old_bindings[index], new_bindings[index]); + } else { + needs_selection |= new_bindings[index] != new_bindings[entry.first->second]; + } + } + if (needs_selection) { + auto filter = make_uniq(); + filter->projection_map = std::move(selection); + filter->children.push_back(std::move(op)); + filter->ResolveOperatorTypesFromChildren(); + op = std::move(filter); + } +} + +void LayoutPreservingRewriter::RewritePlan(unique_ptr &op) { + struct Frame { + explicit Frame(unique_ptr &op_p) : op(op_p) { + } + + reference> op; + idx_t child_index = 0; + }; + if (!EnterOperator(*op)) { + return; + } + vector pending; + BindingReplacementGraph replacements; + pending.emplace_back(op); + while (!pending.empty()) { + auto &frame = pending.back(); + auto ¤t = frame.op.get(); + if (frame.child_index < current->children.size()) { + auto child_index = frame.child_index++; + EnterChild(*current, child_index); + auto &child = current->children[child_index]; + if (EnterOperator(*child)) { + pending.emplace_back(child); + } + continue; + } + ColumnBindingRewrite::ApplyToOperatorBindings(*current, replacements); + current->ResolveOperatorTypesFromChildren(); + RewriteOperator(current, replacements); + pending.pop_back(); + } +} + static bool TryResolveToOutput(ColumnBinding binding, const column_binding_set_t &new_bindings, const BindingReplacementGraph &replacements, ReplacementBinding &result) { result = ReplacementBinding(binding, binding); diff --git a/src/duckdb/src/optimizer/column_origin.cpp b/src/duckdb/src/optimizer/column_origin.cpp index 5f1d67854..56066d260 100644 --- a/src/duckdb/src/optimizer/column_origin.cpp +++ b/src/duckdb/src/optimizer/column_origin.cpp @@ -35,7 +35,8 @@ optional_idx ColumnOriginHelper::GetInvertibleReferenceIndex(const Expression &e return result; } auto &cast = expression.Cast(); - if (!BoundCastExpression::CastIsInvertible(BoundCastExpression::SourceType(cast), + if (BoundCastExpression::IsTryCast(cast) || cast.CanThrow() || + !BoundCastExpression::CastIsInvertible(BoundCastExpression::SourceType(cast), BoundCastExpression::TargetType(cast))) { return optional_idx(); } diff --git a/src/duckdb/src/optimizer/common_subplan_optimizer.cpp b/src/duckdb/src/optimizer/common_subplan_optimizer.cpp index a6c699d15..fce47a630 100644 --- a/src/duckdb/src/optimizer/common_subplan_optimizer.cpp +++ b/src/duckdb/src/optimizer/common_subplan_optimizer.cpp @@ -384,39 +384,18 @@ class PlanSignatureTableIndexMap { auto entry = restore_original_table_filter_index.emplace(canonical_index, filter_index); return entry.second || entry.first->second == filter_index; }; - for (auto &entry : get.table_filters) { - if (!register_filter_index(entry.GetIndex())) { - restore_original_table_filter_index.clear(); - return false; - } - } - for (const auto &filter : get.table_filters.GetMultiColumnFilters()) { - const auto &expression_filter = - ExpressionFilter::GetExpressionFilter(*filter, "CommonSubplanOptimizer::ConvertTableIndex"); - for (const auto &column_index : expression_filter.column_indexes) { - if (!register_filter_index(column_index)) { - restore_original_table_filter_index.clear(); - return false; - } - } + bool valid_filter_indexes = true; + get.table_filters.VisitColumns([&](ProjectionIndex column) { + valid_filter_indexes = valid_filter_indexes && register_filter_index(column); + }); + if (!valid_filter_indexes) { + restore_original_table_filter_index.clear(); + return false; } if (!restore_original_table_filter_index.empty()) { - TableFilterSet remapped_filters; - for (auto &entry : get.table_filters) { - const auto canonical_index = - ProjectionIndex(column_ids[entry.GetIndex().GetIndex()].GetPrimaryIndex()); - remapped_filters.PushFilter(canonical_index, entry.TakeFilter()); - } - for (const auto &filter : get.table_filters.GetMultiColumnFilters()) { - auto remapped_filter = - ExpressionFilter::GetExpressionFilter(*filter, "CommonSubplanOptimizer::ConvertTableIndex") - .Copy(); - for (auto &column_index : remapped_filter->column_indexes) { - column_index = ProjectionIndex(column_ids[column_index.GetIndex()].GetPrimaryIndex()); - } - remapped_filters.PushMultiColumnFilter(std::move(remapped_filter)); - } - get.table_filters = std::move(remapped_filters); + get.table_filters.RemapColumns([&](ProjectionIndex column) { + return ProjectionIndex(column_ids[column.GetIndex()].GetPrimaryIndex()); + }); } // Store mapping for base tables @@ -441,21 +420,8 @@ class PlanSignatureTableIndexMap { D_ASSERT(get.projection_ids.empty()); get.projection_ids = std::move(projection_ids); if (!restore_original_table_filter_index.empty()) { - TableFilterSet remapped_filters; - for (auto &entry : get.table_filters) { - remapped_filters.PushFilter(restore_original_table_filter_index.at(entry.GetIndex()), - entry.TakeFilter()); - } - for (const auto &filter : get.table_filters.GetMultiColumnFilters()) { - auto remapped_filter = - ExpressionFilter::GetExpressionFilter(*filter, "CommonSubplanOptimizer::ConvertTableIndex") - .Copy(); - for (auto &column_index : remapped_filter->column_indexes) { - column_index = restore_original_table_filter_index.at(column_index); - } - remapped_filters.PushMultiColumnFilter(std::move(remapped_filter)); - } - get.table_filters = std::move(remapped_filters); + get.table_filters.RemapColumns( + [&](ProjectionIndex column) { return restore_original_table_filter_index.at(column); }); } break; } @@ -697,7 +663,8 @@ class PlanSignature { if (ClassifyLogicalOperatorRepeatability(get) != LogicalOperatorRepeatability::REPEATABLE) { return false; } - if (get.bind_data && !get.function.HasSerializationCallbacks() && get.parameters.empty()) { + if (get.bind_data && !get.bind_data->IsIdentifiedByCall() && !get.function.HasSerializationCallbacks() && + get.parameters.empty()) { // Without serialization callbacks, the serialized form carries only the call parameters // (see LogicalGet::Serialize). A scan without positional parameters - e.g., one created through // an attached catalog - keeps its identity solely in the bind data, and its options do not diff --git a/src/duckdb/src/optimizer/constant_propagation.cpp b/src/duckdb/src/optimizer/constant_propagation.cpp new file mode 100644 index 000000000..cedfc5d54 --- /dev/null +++ b/src/duckdb/src/optimizer/constant_propagation.cpp @@ -0,0 +1,166 @@ +#include "duckdb/optimizer/constant_propagation.hpp" + +#include "duckdb/optimizer/rule/constant_folding.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression/bound_constant_expression.hpp" +#include "duckdb/planner/expression/expression_barrier.hpp" +#include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/planner/logical_operator_visitor.hpp" +#include "duckdb/planner/operator/logical_expression_get.hpp" +#include "duckdb/planner/operator/logical_join.hpp" +#include "duckdb/planner/operator/logical_projection.hpp" + +namespace duckdb { + +ConstantPropagation::ConstantPropagation(ClientContext &context) : context(context) { +} + +bool ConstantPropagation::RewriteExpression(unique_ptr &expr, const ConstantMap &constants) { + if (expr->GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { + auto &colref = expr->Cast(); + auto entry = constants.find(colref.Binding()); + if (colref.Depth() != 0 || entry == constants.end()) { + return false; + } + auto replacement = make_uniq(entry->second); + replacement->SetAlias(expr->GetAlias()); + expr = std::move(replacement); + return true; + } + bool changed = false; + ExpressionIterator::EnumerateChildren( + *expr, [&](unique_ptr &child) { changed |= RewriteExpression(child, constants); }); + if (changed && !ExpressionBarrier::Contains(*expr)) { + auto replacement = ConstantFoldingRule::TryFold(context, *expr); + if (replacement) { + replacement->SetAlias(expr->GetAlias()); + expr = std::move(replacement); + } + } + return changed; +} + +static bool CanPropagateConstants(const LogicalOperator &op) { + switch (op.type) { + case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: + case LogicalOperatorType::LOGICAL_ANY_JOIN: + // Null extension and the cardinality checks of other join types need their own proofs. + return op.Cast().join_type == JoinType::INNER; + case LogicalOperatorType::LOGICAL_PROJECTION: + case LogicalOperatorType::LOGICAL_EXPRESSION_GET: + case LogicalOperatorType::LOGICAL_FILTER: + case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: + case LogicalOperatorType::LOGICAL_ORDER_BY: + case LogicalOperatorType::LOGICAL_TOP_N: + case LogicalOperatorType::LOGICAL_LIMIT: + case LogicalOperatorType::LOGICAL_DISTINCT: + return true; + default: + return false; + } +} + +void ConstantPropagation::RewriteExpressions(LogicalOperator &op, const ConstantMap &constants) { + if (constants.empty()) { + return; + } + // LIMIT validates its dynamic values at execution; rebinding a constant can change those errors. + if (op.type == LogicalOperatorType::LOGICAL_LIMIT) { + return; + } + + const bool preserve_effects = op.type == LogicalOperatorType::LOGICAL_FILTER || + op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN || + op.type == LogicalOperatorType::LOGICAL_ANY_JOIN; + if (preserve_effects) { + vector> rewritten_expressions; + bool has_effects = false; + LogicalOperatorVisitor::EnumerateExpressions(op, [&](unique_ptr *expr) { + auto rewritten = (*expr)->Copy(); + RewriteExpression(rewritten, constants); + has_effects |= ExpressionBarrier::Required(*rewritten); + rewritten_expressions.push_back(std::move(rewritten)); + }); + // Keep bindings and predicate order if any expression still has an observable effect. + if (!has_effects) { + idx_t expression_index = 0; + LogicalOperatorVisitor::EnumerateExpressions(op, [&](unique_ptr *expr) { + *expr = std::move(rewritten_expressions[expression_index++]); + }); + } + return; + } + LogicalOperatorVisitor::EnumerateExpressions(op, [&](unique_ptr *expr) { + if ((*expr)->CanThrow()) { + auto rewritten = (*expr)->Copy(); + RewriteExpression(rewritten, constants); + // Retain the original bindings unless folding removes the possible error. + if (!rewritten->CanThrow()) { + *expr = std::move(rewritten); + } + return; + } + RewriteExpression(*expr, constants); + }); +} + +ConstantPropagation::ConstantMap +ConstantPropagation::ExtractConstants(TableIndex table_index, const vector> &expressions) { + ConstantMap result; + for (idx_t i = 0; i < expressions.size(); i++) { + auto &expr = *expressions[i]; + if (expr.GetExpressionClass() == ExpressionClass::BOUND_CONSTANT) { + result.emplace(ColumnBinding(table_index, ProjectionIndex(i)), + expr.Cast().GetValue()); + } + } + return result; +} + +ConstantPropagation::ConstantMap ConstantPropagation::GetOutputConstants(LogicalOperator &op, + const ConstantMap &constants) { + switch (op.type) { + case LogicalOperatorType::LOGICAL_PROJECTION: { + auto &projection = op.Cast(); + return ExtractConstants(projection.table_index, projection.expressions); + } + case LogicalOperatorType::LOGICAL_EXPRESSION_GET: { + auto &get = op.Cast(); + if (get.expressions.size() != 1) { + return {}; + } + return ExtractConstants(get.table_index, get.expressions[0]); + } + default: + break; + } + + ConstantMap result; + for (auto &binding : op.GetColumnBindings()) { + auto entry = constants.find(binding); + if (entry != constants.end()) { + result.emplace(binding, entry->second); + } + } + return result; +} + +ConstantPropagation::ConstantMap ConstantPropagation::Propagate(LogicalOperator &op) { + ConstantMap constants; + for (auto &child : op.children) { + auto child_constants = Propagate(*child); + constants.insert(child_constants.begin(), child_constants.end()); + } + if (!CanPropagateConstants(op)) { + return {}; + } + + RewriteExpressions(op, constants); + return GetOutputConstants(op, constants); +} + +void ConstantPropagation::Optimize(LogicalOperator &op) { + Propagate(op); +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/cte_filter_helpers.cpp b/src/duckdb/src/optimizer/cte_filter_helpers.cpp new file mode 100644 index 000000000..71b5db93d --- /dev/null +++ b/src/duckdb/src/optimizer/cte_filter_helpers.cpp @@ -0,0 +1,70 @@ +#include "duckdb/optimizer/cte_filter_helpers.hpp" + +#include "duckdb/planner/operator/logical_cteref.hpp" +#include "duckdb/planner/operator/logical_filter.hpp" +#include "duckdb/planner/operator/logical_materialized_cte.hpp" + +namespace duckdb { + +CTEFilterInfo::Consumer::Consumer(LogicalCTERef &ref, optional_ptr parent) : ref(ref) { + if (parent && parent->type == LogicalOperatorType::LOGICAL_FILTER) { + filter = parent->Cast(); + } +} + +CTEFilterInfo::CTEFilterInfo(LogicalMaterializedCTE &cte) : cte(cte) { +} + +bool CTEFilterInfo::ContainsRecursiveCTE(const LogicalOperator &op) { + if (op.type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) { + return true; + } + for (auto &child : op.children) { + if (ContainsRecursiveCTE(*child)) { + return true; + } + } + return false; +} + +void CTEFilterInfo::Collect(LogicalOperator &op, optional_ptr parent, + unordered_map> &ctes) { + if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { + auto &cte = op.Cast(); + auto inserted = ctes.emplace(cte.table_index, make_uniq(cte)); + D_ASSERT(inserted.second); + } else if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { + auto &ref = op.Cast(); + auto entry = ctes.find(ref.cte_index); + if (entry != ctes.end()) { + entry->second->consumers.emplace_back(ref, parent); + } + } + for (auto &child : op.children) { + Collect(*child, op, ctes); + } +} + +unordered_map> CTEFilterInfo::Collect(LogicalOperator &root) { + unordered_map> result; + Collect(root, nullptr, result); + return result; +} + +bool CTEFilterInfo::ValidateProducerBindings() { + auto &producer = *cte.children[0]; + consumer_indexes.clear(); + producer_bindings = producer.GetColumnBindings(); + if (producer_bindings.size() != producer.types.size()) { + return false; + } + for (idx_t i = 0; i < consumers.size(); i++) { + auto &ref = consumers[i].ref; + if (ref.chunk_types != producer.types || !consumer_indexes.emplace(ref.table_index, i).second) { + return false; + } + } + return true; +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/cte_filter_pusher.cpp b/src/duckdb/src/optimizer/cte_filter_pusher.cpp deleted file mode 100644 index 8c446ee36..000000000 --- a/src/duckdb/src/optimizer/cte_filter_pusher.cpp +++ /dev/null @@ -1,185 +0,0 @@ -#include "duckdb/optimizer/cte_filter_pusher.hpp" -#include "duckdb/optimizer/cte_join_filter_pusher.hpp" - -#include "duckdb/optimizer/column_binding_replacer.hpp" -#include "duckdb/optimizer/filter_pushdown.hpp" -#include "duckdb/optimizer/optimizer.hpp" -#include "duckdb/planner/expression/bound_conjunction_expression.hpp" -#include "duckdb/planner/expression/expression_barrier.hpp" -#include "duckdb/planner/operator/logical_cteref.hpp" -#include "duckdb/planner/operator/logical_filter.hpp" -#include "duckdb/planner/operator/logical_materialized_cte.hpp" - -namespace duckdb { - -CTEFilterPusher::MaterializedCTEInfo::MaterializedCTEInfo(LogicalOperator &materialized_cte_p) - : materialized_cte(materialized_cte_p), all_cte_refs_are_filtered(true), - has_filter_dependency(materialized_cte_p.Cast().filter_dependency != nullptr) { -} - -CTEFilterPusher::CTEFilterPusher(Optimizer &optimizer_p) : optimizer(optimizer_p) { -} - -unique_ptr CTEFilterPusher::Optimize(unique_ptr op) { - FindCandidates(*op); - // A join that keeps only the matching rows of a CTE reference filters that reference like a consumer filter. - GenerateSemiJoinFilters(*op); - if (cte_info_map.empty()) { - return op; - } - auto ctes = std::move(cte_info_map); - - // Iterate once over all materialized CTEs - for (auto it = ctes.rbegin(); it != ctes.rend(); it++) { - if (it->second->filters.empty() || - (!it->second->all_cte_refs_are_filtered && !it->second->has_filter_dependency)) { - continue; - } - - // The cte_info_map must be reconstructed each time. - // Changes to the plan otherwise break the non-unique_ptr references. - cte_info_map = InsertionOrderPreservingMap>(); - FindCandidates(*op); - - auto &info = *cte_info_map[it->first]; - if (CanPushFilter(info)) { - PushFilterIntoCTE(info); - } - } - CTEJoinFilterPusher join_pusher(optimizer); - join_pusher.Optimize(*op); - return op; -} - -void CTEFilterPusher::ClearDependencies(LogicalOperator &op) { - if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { - op.Cast().filter_dependency.reset(); - } - for (auto &child : op.children) { - ClearDependencies(*child); - } -} - -bool CTEFilterPusher::CanPushFilter(const MaterializedCTEInfo &info) { - if (info.all_cte_refs_are_filtered) { - return true; - } - if (info.filters.size() != 1 || !HasValidDependency(info)) { - return false; - } - auto &cte = info.materialized_cte.Cast(); - D_ASSERT(info.filters[0].get().children[0]->type == LogicalOperatorType::LOGICAL_CTE_REF); - auto &filtered_ref = info.filters[0].get().children[0]->Cast(); - return filtered_ref.table_index == cte.filter_dependency->row_scan; -} - -bool CTEFilterPusher::HasValidDependency(const MaterializedCTEInfo &info) { - auto &cte = info.materialized_cte.Cast(); - return cte.filter_dependency && cte.filter_dependency->MatchesConsumers(info.references); -} - -void CTEFilterPusher::FindCandidates(LogicalOperator &op) { - if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { - // We encountered a new CTE, add it to the map - auto key = to_string(op.Cast().table_index.index); - auto value = make_uniq(op); - - cte_info_map.insert(key, std::move(value)); - } else if (op.type == LogicalOperatorType::LOGICAL_FILTER && - op.children[0]->type == LogicalOperatorType::LOGICAL_CTE_REF) { - // We encountered a filtered CTE ref, update the according CTE info - auto &cte_ref = op.children[0]->Cast(); - auto it = cte_info_map.find(to_string(cte_ref.cte_index.index)); - if (it != cte_info_map.end()) { - it->second->filters.push_back(op); - it->second->references.push_back(cte_ref); - } - return; - } else if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { - // We encountered a CTE ref without a filter on top, so we can't do the optimization - auto &cte_ref = op.Cast(); - auto it = cte_info_map.find(to_string(cte_ref.cte_index.index)); - if (it != cte_info_map.end()) { - it->second->all_cte_refs_are_filtered = false; - it->second->references.push_back(cte_ref); - } - return; - } - for (auto &child : op.children) { - FindCandidates(*child); - } -} - -void CTEFilterPusher::PushFilterIntoCTE(MaterializedCTEInfo &info) { - D_ASSERT(info.materialized_cte.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE); - if (info.filters.empty()) { - return; - } - - // Create an OR expression with all the filters on all references of the CTE - unique_ptr outer_expr; - for (auto &filter : info.filters) { - D_ASSERT(filter.get().type == LogicalOperatorType::LOGICAL_FILTER); - - auto old_bindings = filter.get().children[0]->GetColumnBindings(); - auto new_bindings = info.materialized_cte.children[0]->GetColumnBindings(); - D_ASSERT(old_bindings.size() == new_bindings.size()); - - ColumnBindingReplacer replacer; - replacer.replacement_bindings.reserve(old_bindings.size()); - for (idx_t i = 0; i < old_bindings.size(); i++) { - replacer.replacement_bindings.emplace_back(old_bindings[i], new_bindings[i]); - } - - bool all_conjuncts_repeatable = true; - for (auto &expr : filter.get().expressions) { - all_conjuncts_repeatable &= !expr->IsVolatile() && !ExpressionBarrier::Contains(*expr); - } - - // We copy the filters and replace the CTE reference bindings with the bindings in the CTE definition - unique_ptr inner_expr; - for (auto &filter_expr : filter.get().expressions) { - // Dropping a conjunct must not expose errors it previously short-circuited. - if (filter_expr->IsVolatile() || ExpressionBarrier::Contains(*filter_expr) || - (!all_conjuncts_repeatable && filter_expr->CanThrow())) { - continue; - } - auto filter_expr_copy = filter_expr->Copy(); - replacer.VisitExpression(&filter_expr_copy); - if (inner_expr) { - inner_expr = make_uniq(ExpressionType::CONJUNCTION_AND, - std::move(inner_expr), std::move(filter_expr_copy)); - } else { - inner_expr = std::move(filter_expr_copy); - } - } - - // An unrestricted consumer makes the disjunction true. - if (!inner_expr) { - return; - } - - if (outer_expr) { - outer_expr = make_uniq(ExpressionType::CONJUNCTION_OR, std::move(outer_expr), - std::move(inner_expr)); - } else { - outer_expr = std::move(inner_expr); - } - } - - // Add the filter on top of the CTE definition and split the predicates - auto new_cte = make_uniq_base(std::move(outer_expr)); - LogicalFilter::SplitPredicates(new_cte->Cast().expressions); - - // Rewrite the operator expressions before adding the child op (children should be rewritten already) - optimizer.rewriter.VisitOperator(*new_cte); - new_cte->children.push_back(std::move(info.materialized_cte.children[0])); - - // Push down the filter - FilterPushdown pushdown(optimizer, FilterPushdown::ProjectionMode::PRESERVE_COMPUTED_EXPRESSIONS); - new_cte = pushdown.Rewrite(std::move(new_cte)); - - info.materialized_cte.children[0] = std::move(new_cte); -} - -} // namespace duckdb diff --git a/src/duckdb/src/optimizer/cte_join_filter_collector.cpp b/src/duckdb/src/optimizer/cte_join_filter_collector.cpp index 819241377..b950ca924 100644 --- a/src/duckdb/src/optimizer/cte_join_filter_collector.cpp +++ b/src/duckdb/src/optimizer/cte_join_filter_collector.cpp @@ -1,5 +1,7 @@ #include "duckdb/optimizer/cte_join_filter_collector.hpp" #include "duckdb/common/numeric_utils.hpp" +#include "duckdb/common/reference_map.hpp" +#include "duckdb/common/types/hash.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" #include "duckdb/planner/expression/expression_barrier.hpp" @@ -10,17 +12,19 @@ #include "duckdb/planner/operator/logical_cteref.hpp" #include "duckdb/planner/operator/logical_get.hpp" #include "duckdb/planner/operator/logical_projection.hpp" +#include "duckdb/planner/operator/logical_set_operation.hpp" namespace duckdb { CTEJoinFilterCollector::CTEJoinFilterCollector(const unordered_map &targets) - : join_targets(targets) { + : join_targets(targets), filter_index(0, FilterIdentity {join_filters}, FilterIdentity {join_filters}) { } vector CTEJoinFilterCollector::Collect(LogicalOperator &op, const unordered_map &targets) { CTEJoinFilterCollector collector(targets); collector.VisitOperator(op); + collector.filter_index.clear(); return std::move(collector.join_filters); } @@ -56,6 +60,36 @@ CTEJoinFilterKey CTEJoinFilterKey::Copy() const { return CTEJoinFilterKey {expression->Copy(), column}; } +hash_t CTEJoinFilterKey::Hash() const { + return CombineHash(duckdb::Hash(column), duckdb::Hash(expression->Hash())); +} + +bool CTEJoinFilterKey::operator==(const CTEJoinFilterKey &other) const { + return column == other.column && expression->Equals(*other.expression); +} + +hash_t CTEJoinFilter::Hash() const { + auto source_hash = source_parent ? CombineHash(ReferenceHashFunction()(*source_parent), + duckdb::Hash(source_child)) + : duckdb::Hash(source); + auto result = CombineHash(duckdb::Hash(source_hash), duckdb::Hash(target)); + result = CombineHash(duckdb::Hash(result), duckdb::Hash(target_scan)); + D_ASSERT(source_keys.size() == comparisons.size() && target_keys.size() == comparisons.size()); + for (idx_t i = 0; i < comparisons.size(); i++) { + result = CombineHash(duckdb::Hash(result), duckdb::Hash(comparisons[i])); + result = CombineHash(duckdb::Hash(result), source_keys[i].Hash()); + result = CombineHash(duckdb::Hash(result), target_keys[i].Hash()); + } + return result; +} + +bool CTEJoinFilter::operator==(const CTEJoinFilter &other) const { + return (source_parent ? other.source_parent == source_parent && other.source_child == source_child + : !other.source_parent && other.source == source) && + target == other.target && target_scan == other.target_scan && comparisons == other.comparisons && + source_keys == other.source_keys && target_keys == other.target_keys; +} + unique_ptr CTEJoinFilterKey::BindExpression(const LogicalType &type, ColumnBinding binding) const { auto result = expression->Copy(); ReplaceCTEJoinKeyColumnRef(result, make_uniq(type, binding)); @@ -83,7 +117,33 @@ static bool MapCTEJoinKey(CTEJoinFilterCollector::CTEJoinKey &key, const Express return true; } +static bool ContainsCTEJoinKeys(TableIndex table_index, idx_t column_count, + const vector &keys) { + for (auto &key : keys) { + if (key.binding.table_index != table_index || key.binding.column_index >= ProjectionIndex(column_count)) { + return false; + } + } + return true; +} + static bool ContainsCTEJoinKeys(LogicalOperator &op, const vector &keys) { + switch (op.type) { + case LogicalOperatorType::LOGICAL_CTE_REF: { + auto &ref = op.Cast(); + return ContainsCTEJoinKeys(ref.table_index, ref.chunk_types.size(), keys); + } + case LogicalOperatorType::LOGICAL_PROJECTION: { + auto &projection = op.Cast(); + return ContainsCTEJoinKeys(projection.table_index, projection.expressions.size(), keys); + } + case LogicalOperatorType::LOGICAL_UNION: { + auto &setop = op.Cast(); + return ContainsCTEJoinKeys(setop.table_index, setop.column_count, keys); + } + default: + break; + } auto bindings = op.GetColumnBindings(); for (auto &key : keys) { if (std::find(bindings.begin(), bindings.end(), key.binding) == bindings.end()) { @@ -199,15 +259,34 @@ static bool CanCopyCTEJoinSource(LogicalOperator &op) { return true; } -void CTEJoinFilterCollector::VisitOperator(LogicalOperator &op) { +bool CTEJoinFilterCollector::IsTarget(const LogicalCTERef &ref) const { + auto target = join_targets.find(ref.cte_index); + return !ref.is_recurring && target != join_targets.end() && target->second == ref.table_index; +} + +bool CTEJoinFilterCollector::VisitOperator(LogicalOperator &op) { + if (op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + D_ASSERT(op.children.size() == 2); + auto &join = op.Cast(); + auto left_has_target = VisitOperator(*op.children[0]); + auto right_has_target = VisitOperator(*op.children[1]); + if ((left_has_target || right_has_target) && join.join_type == JoinType::INNER && CanPassCTEJoinFilter(op)) { + CollectJoinFilters(join, left_has_target, right_has_target); + } + return left_has_target || right_has_target; + } + bool has_target = false; for (auto &child : op.children) { - VisitOperator(*child); + has_target |= VisitOperator(*child); } - if (op.type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN || - op.Cast().join_type != JoinType::INNER || !CanPassCTEJoinFilter(op)) { - return; + if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { + return IsTarget(op.Cast()); } - auto &join = op.Cast(); + return has_target; +} + +void CTEJoinFilterCollector::CollectJoinFilters(LogicalComparisonJoin &join, bool left_has_target, + bool right_has_target) { vector left_keys, right_keys; vector comparisons; for (auto &condition : join.conditions) { @@ -227,20 +306,23 @@ void CTEJoinFilterCollector::VisitOperator(LogicalOperator &op) { return; } for (idx_t side = 0; side < 2; side++) { + if (!(side == 0 ? right_has_target : left_has_target)) { + continue; + } auto source_keys = CopyCTEJoinKeys(side == 0 ? left_keys : right_keys); - auto source_ref = FindCTEJoinSource(*op.children[side], source_keys); + auto source_ref = FindCTEJoinSource(*join.children[side], source_keys); if (source_ref) { CTEJoinSource source {source_ref.get(), nullptr, 0}; - PushFilter(*op.children[1 - side], source, source_keys, CopyCTEJoinKeys(side == 0 ? right_keys : left_keys), - comparisons); + PushFilter(*join.children[1 - side], source, source_keys, + CopyCTEJoinKeys(side == 0 ? right_keys : left_keys), comparisons); continue; } - if (!CanCopyCTEJoinSource(*op.children[side])) { + if (!CanCopyCTEJoinSource(*join.children[side])) { continue; } // Rebind the keys to output positions of the copyable subtree source_keys = CopyCTEJoinKeys(side == 0 ? left_keys : right_keys); - auto child_bindings = op.children[side]->GetColumnBindings(); + auto child_bindings = join.children[side]->GetColumnBindings(); bool found_keys = true; for (auto &key : source_keys) { auto entry = std::find(child_bindings.begin(), child_bindings.end(), key.binding); @@ -254,8 +336,8 @@ void CTEJoinFilterCollector::VisitOperator(LogicalOperator &op) { if (!found_keys) { continue; } - CTEJoinSource source {nullptr, &op, side}; - PushFilter(*op.children[1 - side], source, source_keys, CopyCTEJoinKeys(side == 0 ? right_keys : left_keys), + CTEJoinSource source {nullptr, &join, side}; + PushFilter(*join.children[1 - side], source, source_keys, CopyCTEJoinKeys(side == 0 ? right_keys : left_keys), comparisons); } } @@ -268,7 +350,7 @@ void CTEJoinFilterCollector::PushFilter(LogicalOperator &op, const CTEJoinSource } switch (op.type) { case LogicalOperatorType::LOGICAL_CTE_REF: - AddFilter(source, op.Cast(), source_keys, target_keys, comparisons); + AddFilter(source, op.Cast(), source_keys, std::move(target_keys), comparisons); return; case LogicalOperatorType::LOGICAL_MATERIALIZED_CTE: PushFilter(*op.children[1], source, source_keys, std::move(target_keys), comparisons); @@ -287,16 +369,18 @@ void CTEJoinFilterCollector::PushFilter(LogicalOperator &op, const CTEJoinSource } break; case LogicalOperatorType::LOGICAL_UNION: { - auto bindings = op.GetColumnBindings(); - for (auto &child : op.children) { - auto child_bindings = child->GetColumnBindings(); - auto child_keys = CopyCTEJoinKeys(target_keys); + auto push_child = [&](LogicalOperator &child, vector child_keys) { + auto child_bindings = child.GetColumnBindings(); for (auto &key : child_keys) { - auto position = - NumericCast(std::find(bindings.begin(), bindings.end(), key.binding) - bindings.begin()); - key.binding = child_bindings[position]; + key.binding = child_bindings[key.binding.column_index]; } - PushFilter(*child, source, source_keys, std::move(child_keys), comparisons); + PushFilter(child, source, source_keys, std::move(child_keys), comparisons); + }; + for (idx_t child_idx = 0; child_idx + 1 < op.children.size(); child_idx++) { + push_child(*op.children[child_idx], CopyCTEJoinKeys(target_keys)); + } + if (!op.children.empty()) { + push_child(*op.children.back(), std::move(target_keys)); } return; } @@ -306,11 +390,13 @@ void CTEJoinFilterCollector::PushFilter(LogicalOperator &op, const CTEJoinSource join.join_type != JoinType::ANTI && join.join_type != JoinType::MARK) { return; } - if (ContainsCTEJoinKeys(*op.children[0], target_keys)) { + auto push_left = ContainsCTEJoinKeys(*op.children[0], target_keys); + auto push_right = join.join_type == JoinType::INNER && ContainsCTEJoinKeys(*op.children[1], target_keys); + if (push_left && push_right) { PushFilter(*op.children[0], source, source_keys, CopyCTEJoinKeys(target_keys), comparisons); - } - if (join.join_type == JoinType::INNER && ContainsCTEJoinKeys(*op.children[1], target_keys)) { PushFilter(*op.children[1], source, source_keys, std::move(target_keys), comparisons); + } else if (push_left || push_right) { + PushFilter(*op.children[push_right ? 1 : 0], source, source_keys, std::move(target_keys), comparisons); } return; } @@ -321,12 +407,11 @@ void CTEJoinFilterCollector::PushFilter(LogicalOperator &op, const CTEJoinSource } void CTEJoinFilterCollector::AddFilter(const CTEJoinSource &source, const LogicalCTERef &target, - const vector &source_keys, const vector &target_keys, + const vector &source_keys, vector target_keys, const vector &comparisons) { D_ASSERT(!comparisons.empty() && source_keys.size() == comparisons.size() && target_keys.size() == comparisons.size()); - auto target_entry = join_targets.find(target.cte_index); - if (target.is_recurring || target_entry == join_targets.end() || target_entry->second != target.table_index) { + if (!IsTarget(target)) { return; } CTEJoinFilter filter; @@ -347,29 +432,13 @@ void CTEJoinFilterCollector::AddFilter(const CTEJoinSource &source, const Logica D_ASSERT(target_keys[i].binding.table_index == target.table_index); filter.source_keys.push_back( CTEJoinFilterKey {source_keys[i].expression->Copy(), ProjectionIndex(source_keys[i].binding.column_index)}); - filter.target_keys.push_back( - CTEJoinFilterKey {target_keys[i].expression->Copy(), ProjectionIndex(target_keys[i].binding.column_index)}); - } - auto keys_match = [](const vector &left, const vector &right) { - for (idx_t i = 0; i < left.size(); i++) { - if (left[i].column != right[i].column || !left[i].expression->Equals(*right[i].expression)) { - return false; - } - } - return true; - }; - for (auto &existing : join_filters) { - if ((filter.source_parent - ? existing.source_parent == filter.source_parent && existing.source_child == filter.source_child - : !existing.source_parent && existing.source == filter.source) && - existing.target == filter.target && existing.target_scan == filter.target_scan && - existing.comparisons == filter.comparisons && existing.source_keys.size() == filter.source_keys.size() && - keys_match(existing.source_keys, filter.source_keys) && - keys_match(existing.target_keys, filter.target_keys)) { - return; - } + filter.target_keys.push_back(CTEJoinFilterKey {std::move(target_keys[i].expression), + ProjectionIndex(target_keys[i].binding.column_index)}); } join_filters.push_back(std::move(filter)); + if (!filter_index.insert(join_filters.size() - 1).second) { + join_filters.pop_back(); + } } } // namespace duckdb diff --git a/src/duckdb/src/optimizer/cte_join_filter_pusher.cpp b/src/duckdb/src/optimizer/cte_join_filter_pusher.cpp index b8e3218c6..368c74df1 100644 --- a/src/duckdb/src/optimizer/cte_join_filter_pusher.cpp +++ b/src/duckdb/src/optimizer/cte_join_filter_pusher.cpp @@ -43,18 +43,18 @@ bool CTEJoinFilterPusher::HasValidDependency(const MaterializedCTEInfo &info) { void CTEJoinFilterPusher::FindCandidates(LogicalOperator &op) { if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { auto &cte = op.Cast(); - auto info = make_uniq(op); - info->ancestors = available_ctes; - cte_info_map.insert(to_string(cte.table_index.index), std::move(info)); + auto info = make_uniq(op, cte_info_map.size()); + auto &cte_info = *info; + cte_info_map.insert(cte.table_index, std::move(info)); FindCandidates(*op.children[0]); - available_ctes.push_back(cte.table_index); + cte_info.consumer_begin = cte_info_map.size(); FindCandidates(*op.children[1]); - available_ctes.pop_back(); + cte_info.consumer_end = cte_info_map.size(); return; } if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { auto &ref = op.Cast(); - auto entry = cte_info_map.find(to_string(ref.cte_index.index)); + auto entry = cte_info_map.find(ref.cte_index); if (entry != cte_info_map.end()) { entry->second->references.push_back(ref); } @@ -89,25 +89,27 @@ void CTEJoinFilterPusher::Optimize(LogicalOperator &op) { return; } - cte_info_map.clear(); - FindCandidates(op); + unordered_map>> filters_by_target; + for (auto &filter : join_filters) { + filters_by_target[filter.target].push_back(filter); + } vector targets; for (auto &entry : cte_info_map) { - targets.push_back(entry.second->materialized_cte.Cast().table_index); + auto target = entry.second->materialized_cte.Cast().table_index; + if (filters_by_target.count(target)) { + targets.push_back(target); + } } unordered_map restricted_stats; for (auto target : targets) { - // Producer rewrites invalidate operator references and cached statistics. - cte_info_map.clear(); - FindCandidates(op); - auto target_entry = cte_info_map.find(to_string(target.index)); + auto target_entry = cte_info_map.find(target); if (target_entry == cte_info_map.end() || !HasValidDependency(*target_entry->second)) { continue; } auto &info = *target_entry->second; auto &cte = info.materialized_cte.Cast(); RelationStatsExtractor extractor(optimizer.context, [&](TableIndex index) -> optional_ptr { - auto entry = cte_info_map.find(to_string(index.index)); + auto entry = cte_info_map.find(index); return entry == cte_info_map.end() ? nullptr : entry->second->materialized_cte.children[0].get(); }); auto target_stats = extractor.Extract(*cte.children[0]); @@ -117,8 +119,9 @@ void CTEJoinFilterPusher::Optimize(LogicalOperator &op) { optional_ptr best; CardinalityValue best_fraction(1); CardinalityValue best_source_count(0); - for (auto &filter : join_filters) { - if (filter.target != target || filter.target_scan != cte.filter_dependency->row_scan) { + for (auto &filter_ref : filters_by_target.at(target)) { + auto &filter = filter_ref.get(); + if (filter.target_scan != cte.filter_dependency->row_scan) { continue; } optional_ptr source_stats; @@ -130,11 +133,8 @@ void CTEJoinFilterPusher::Optimize(LogicalOperator &op) { } source_stats = extractor.Extract(source); } else { - if (std::find(info.ancestors.begin(), info.ancestors.end(), filter.source) == info.ancestors.end()) { - continue; - } - auto source_entry = cte_info_map.find(to_string(filter.source.index)); - if (source_entry == cte_info_map.end()) { + auto source_entry = cte_info_map.find(filter.source); + if (source_entry == cte_info_map.end() || !source_entry->second->IsVisibleTo(info)) { continue; } auto &source_cte = source_entry->second->materialized_cte; @@ -188,7 +188,7 @@ void CTEJoinFilterPusher::Optimize(LogicalOperator &op) { continue; } } else { - auto &source_cte = cte_info_map[to_string(best->source.index)]->materialized_cte; + auto &source_cte = cte_info_map[best->source]->materialized_cte; source_cte.children[0]->ResolveOperatorTypes(); auto &cte_types = source_cte.children[0]->types; vector names; @@ -220,6 +220,10 @@ void CTEJoinFilterPusher::Optimize(LogicalOperator &op) { restricted_stats.emplace(target, std::move(stats)); join->children.push_back(std::move(cte.children[0])); join->children.push_back(std::move(source_plan)); + // SEMI insertion preserves the CTE definitions; only its new reader changes the inventory. + if (!best->source_parent) { + cte_info_map[best->source]->references.push_back(join->children[1]->Cast()); + } cte.children[0] = std::move(join); } return; diff --git a/src/duckdb/src/optimizer/cte_runtime_filter_pushdown.cpp b/src/duckdb/src/optimizer/cte_runtime_filter_pushdown.cpp index 76278675a..618787f62 100644 --- a/src/duckdb/src/optimizer/cte_runtime_filter_pushdown.cpp +++ b/src/duckdb/src/optimizer/cte_runtime_filter_pushdown.cpp @@ -1,5 +1,7 @@ #include "duckdb/optimizer/join_filter_pushdown_optimizer.hpp" +#include "duckdb/optimizer/cte_filter_helpers.hpp" +#include "duckdb/common/unordered_set.hpp" #include "duckdb/execution/operator/join/physical_comparison_join.hpp" #include "duckdb/planner/operator/logical_comparison_join.hpp" #include "duckdb/planner/operator/logical_cteref.hpp" @@ -8,82 +10,88 @@ namespace duckdb { -static bool ContainsRecursiveCTE(const LogicalOperator &op) { - if (op.type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) { - return true; - } - for (auto &child : op.children) { - if (ContainsRecursiveCTE(*child)) { - return true; - } - } - return false; -} - void JoinFilterPushdownOptimizer::Optimize(LogicalOperator &op) { - if (!ContainsRecursiveCTE(op)) { - CollectCTEFilters(op); + // A DML CTE can invalidate the scan statistics before the scan runs. + use_scan_statistics = !op.CTEContainsDML(); + if (!CTEFilterInfo::ContainsRecursiveCTE(op)) { + GenerateCTEFilters(op); } VisitOperator(op); } -void JoinFilterPushdownOptimizer::CollectCTEFilters(LogicalOperator &op) { - if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { - CollectCTEFilters(*op.children[1]); - GenerateCTEFilters(op.Cast()); - CollectCTEFilters(*op.children[0]); - return; - } - for (auto &child : op.children) { - CollectCTEFilters(*child); - } -} +//! This phase only registers runtime filters; operator structure and consumer identities stay fixed. +class JoinFilterPushdownOptimizer::CTEFilterCollector { + struct Contribution { + LogicalComparisonJoin &join; + idx_t consumer_idx; + JoinFilterPushdownColumn column; + }; -static void CollectCTEConsumers(LogicalOperator &op, TableIndex cte_index, vector> &references, - vector> &joins) { - if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { - auto &ref = op.Cast(); - if (ref.cte_index == cte_index) { - references.push_back(ref); + struct Producer { + explicit Producer(unique_ptr info_p) : info(std::move(info_p)) { } - } else if (op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { - joins.push_back(op.Cast()); + + unique_ptr info; + reference_map_t>> contributions; + }; + +public: + explicit CTEFilterCollector(JoinFilterPushdownOptimizer &pushdown) : pushdown(pushdown) { } - for (auto &child : op.children) { - CollectCTEConsumers(*child, cte_index, references, joins); + + void Generate(LogicalOperator &op) { + auto ctes = CTEFilterInfo::Collect(op); + bool has_shared_cte = false; + for (auto &entry : ctes) { + has_shared_cte |= entry.second->consumers.size() >= 2; + } + if (!has_shared_cte) { + return; + } + op.ResolveOperatorTypes(); + for (auto &entry : ctes) { + auto &info = *entry.second; + bool eligible = info.consumers.size() >= 2; + for (auto &consumer : info.consumers) { + eligible &= !consumer.ref.is_recurring && consumer.ref.correlated_columns == 0; + } + if (eligible && info.ValidateProducerBindings()) { + producers.emplace(entry.first, make_uniq(std::move(entry.second))); + } + } + if (!producers.empty()) { + CollectJoins(op); + Finalize(op); + } } -} -struct CTEFilterContribution { - LogicalComparisonJoin &join; - idx_t consumer_idx; - JoinFilterPushdownColumn column; -}; +private: + JoinFilterPushdownOptimizer &pushdown; + unordered_map> producers; + unordered_set active_consumers; -void JoinFilterPushdownOptimizer::GenerateCTEFilters(LogicalMaterializedCTE &cte) { - vector> references; - vector> joins; - CollectCTEConsumers(*cte.children[1], cte.table_index, references, joins); - if (references.size() < 2 || joins.empty()) { - return; - } - cte.children[0]->ResolveOperatorTypes(); - auto bindings = cte.children[0]->GetColumnBindings(); - unordered_map consumer_indexes; - for (auto &ref : references) { - auto &consumer = ref.get(); - if (consumer.is_recurring || consumer.correlated_columns != 0 || - consumer.chunk_types != cte.children[0]->types || - !consumer_indexes.emplace(consumer.table_index, consumer_indexes.size()).second) { + void CollectJoins(LogicalOperator &op) { + if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { + auto &cte = op.Cast(); + CollectJoins(*cte.children[0]); + if (producers.count(cte.table_index)) { + active_consumers.insert(cte.table_index); + } + CollectJoins(*cte.children[1]); + active_consumers.erase(cte.table_index); return; } + if (!active_consumers.empty() && op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + CollectJoin(op.Cast()); + } + for (auto &child : op.children) { + CollectJoins(*child); + } } - reference_map_t>> contributions; - for (auto &join_ref : joins) { - auto &join = join_ref.get(); + void CollectJoin(LogicalComparisonJoin &join) { if (!CanGenerateJoinFilters(join)) { - continue; + return; } PhysicalComparisonJoin::ReorderConditions(join.conditions); vector columns; @@ -97,52 +105,90 @@ void JoinFilterPushdownOptimizer::GenerateCTEFilters(LogicalMaterializedCTE &cte column.join_filter_idx = i; columns.push_back(std::move(column)); } + if (columns.empty()) { + return; + } reference_map_t> targets; GetCTEFilterTargets(*join.children[0], columns, targets); for (auto &target : targets) { auto &ref = target.first.get(); - auto consumer = consumer_indexes.find(ref.table_index); - if (ref.cte_index != cte.table_index || consumer == consumer_indexes.end()) { + auto entry = producers.find(ref.cte_index); + // The contributing join must lie inside this CTE's consumer subtree. + if (entry == producers.end() || !active_consumers.count(ref.cte_index)) { continue; } - for (auto &column : target.second) { - column.probe_column_index = bindings.at(column.probe_column_index.column_index.GetIndex()); - vector producer_columns; - producer_columns.push_back(std::move(column)); - vector scans; - GetPushdownFilterTargets(*cte.children[0], producer_columns, scans); - for (auto &scan : scans) { - for (auto &scan_column : scan.columns) { - auto index = scan_column.probe_column_index.column_index; - contributions[scan.get][index].push_back({join, consumer->second, std::move(scan_column)}); - } - } + auto &producer = *entry->second; + auto consumer = producer.info->consumer_indexes.find(ref.table_index); + if (consumer != producer.info->consumer_indexes.end()) { + CollectTargets(join, producer, consumer->second, target.second); } } } - for (auto &scan : contributions) { - auto &get = scan.first.get(); - for (auto &entry : scan.second) { - vector covered(references.size(), false); - for (auto &contribution : entry.second) { - covered[contribution.consumer_idx] = true; - } - if (std::find(covered.begin(), covered.end(), false) != covered.end()) { - continue; + + void CollectTargets(LogicalComparisonJoin &join, Producer &producer, idx_t consumer_idx, + vector &columns) { + for (auto &column : columns) { + column.probe_column_index = + producer.info->producer_bindings.at(column.probe_column_index.column_index.GetIndex()); + vector producer_columns; + producer_columns.push_back(std::move(column)); + vector scans; + GetPushdownFilterTargets(*producer.info->cte.children[0], producer_columns, scans); + for (auto &scan : scans) { + for (auto &scan_column : scan.columns) { + auto index = scan_column.probe_column_index.column_index; + producer.contributions[scan.get][index].push_back({join, consumer_idx, std::move(scan_column)}); + } } - if (!get.dynamic_filters) { - get.dynamic_filters = make_shared_ptr(); + } + } + + void Finalize(LogicalOperator &op) { + if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { + auto &cte = op.Cast(); + Finalize(*cte.children[1]); + auto entry = producers.find(cte.table_index); + if (entry != producers.end()) { + FinalizeProducer(*entry->second); } - auto alternatives = get.dynamic_filters->AddDisjunction(entry.first, references.size()); - for (auto &contribution : entry.second) { - JoinFilterPushdownFilter filter; - filter.dynamic_filters = alternatives[contribution.consumer_idx]; - filter.columns.push_back(std::move(contribution.column)); - filter.estimated_scan_cardinality = get.has_estimated_cardinality ? get.estimated_cardinality : 0; - cte_filters[contribution.join].push_back(std::move(filter)); + Finalize(*cte.children[0]); + return; + } + for (auto &child : op.children) { + Finalize(*child); + } + } + + void FinalizeProducer(Producer &producer) { + for (auto &scan : producer.contributions) { + auto &get = scan.first.get(); + for (auto &entry : scan.second) { + vector covered(producer.info->consumers.size(), false); + for (auto &contribution : entry.second) { + covered[contribution.consumer_idx] = true; + } + if (std::find(covered.begin(), covered.end(), false) != covered.end()) { + continue; + } + if (!get.dynamic_filters) { + get.dynamic_filters = make_shared_ptr(); + } + auto alternatives = get.dynamic_filters->AddDisjunction(entry.first, producer.info->consumers.size()); + for (auto &contribution : entry.second) { + JoinFilterPushdownFilter filter; + filter.dynamic_filters = alternatives[contribution.consumer_idx]; + filter.columns.push_back(std::move(contribution.column)); + filter.estimated_scan_cardinality = get.has_estimated_cardinality ? get.estimated_cardinality : 0; + pushdown.cte_filters[contribution.join].push_back(std::move(filter)); + } } } } +}; + +void JoinFilterPushdownOptimizer::GenerateCTEFilters(LogicalOperator &op) { + CTEFilterCollector collector(*this); + collector.Generate(op); } } // namespace duckdb diff --git a/src/duckdb/src/optimizer/cte_semi_join_filter_transfer.cpp b/src/duckdb/src/optimizer/cte_semi_join_filter_transfer.cpp deleted file mode 100644 index 277aad053..000000000 --- a/src/duckdb/src/optimizer/cte_semi_join_filter_transfer.cpp +++ /dev/null @@ -1,333 +0,0 @@ -#include "duckdb/optimizer/cte_filter_pusher.hpp" - -#include "duckdb/optimizer/filter_combiner.hpp" -#include "duckdb/planner/expression/bound_columnref_expression.hpp" -#include "duckdb/planner/expression/bound_conjunction_expression.hpp" -#include "duckdb/planner/expression_iterator.hpp" -#include "duckdb/planner/filter/expression_filter.hpp" -#include "duckdb/planner/operator/logical_aggregate.hpp" -#include "duckdb/planner/operator/logical_comparison_join.hpp" -#include "duckdb/planner/operator/logical_cteref.hpp" -#include "duckdb/planner/operator/logical_filter.hpp" -#include "duckdb/planner/operator/logical_get.hpp" -#include "duckdb/planner/operator/logical_projection.hpp" - -namespace duckdb { - -//! The search follows one column, but the equalities of an INNER join fork it: the bound keeps it linear -static constexpr idx_t MAX_SEARCH_STEPS = 256; - -static optional_ptr PlainColumn(const Expression &expr) { - if (expr.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { - return nullptr; - } - auto &column_ref = expr.Cast(); - if (column_ref.Depth() != 0) { - return nullptr; - } - return &column_ref; -} - -static bool IsEquality(const JoinCondition &condition) { - return condition.IsComparison() && (condition.GetComparisonType() == ExpressionType::COMPARE_EQUAL || - condition.GetComparisonType() == ExpressionType::COMPARE_NOT_DISTINCT_FROM); -} - -static bool HasBinding(LogicalOperator &op, const ColumnBinding &binding) { - for (auto &op_binding : op.GetColumnBindings()) { - if (op_binding == binding) { - return true; - } - } - return false; -} - -//! Adds the conjuncts of the filter that compare `column` with constants and cannot throw -static void AddColumnFilters(const Expression &filter, const BoundColumnRefExpression &column, - vector> &result) { - if (filter.GetExpressionType() == ExpressionType::CONJUNCTION_AND) { - for (auto &child : filter.Cast().GetChildren()) { - AddColumnFilters(*child, column, result); - } - return; - } - auto compared = FilterCombiner::GetComparedExpression(filter); - if (compared && compared->Equals(column) && !filter.CanThrow()) { - result.push_back(filter.Copy()); - } -} - -//! Adds the filters that compare `column`, a column of `op`, with constants and that every row of `op` passes -static void GuaranteedColumnFilters(LogicalOperator &op, const BoundColumnRefExpression &column, idx_t &steps, - vector> &result) { - if (++steps > MAX_SEARCH_STEPS) { - return; - } - // the filters on a column of the child that is passed on as `column` - auto follow = [&](LogicalOperator &child, const BoundColumnRefExpression &source) { - if (source.Binding() == column.Binding()) { - GuaranteedColumnFilters(child, column, steps, result); - return; - } - if (source.GetReturnType() != column.GetReturnType()) { - return; - } - vector> source_filters; - GuaranteedColumnFilters(child, source, steps, source_filters); - for (auto &filter : source_filters) { - result.push_back(ExpressionIterator::ReplaceExpression(*filter, source, column)); - } - }; - auto &binding = column.Binding(); - switch (op.type) { - case LogicalOperatorType::LOGICAL_FILTER: - for (auto &expr : op.expressions) { - AddColumnFilters(*expr, column, result); - } - follow(*op.children[0], column); - break; - case LogicalOperatorType::LOGICAL_PROJECTION: { - auto &projection = op.Cast(); - if (binding.table_index != projection.table_index || binding.column_index.GetIndex() >= op.expressions.size()) { - break; - } - auto source = PlainColumn(*op.expressions[binding.column_index.GetIndex()]); - if (source) { - follow(*op.children[0], *source); - } - break; - } - case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { - // grouping sets add NULL groups that the filters below do not describe - auto &aggregate = op.Cast(); - if (binding.table_index != aggregate.group_index || aggregate.grouping_sets.size() > 1 || - binding.column_index.GetIndex() >= aggregate.groups.size()) { - break; - } - auto source = PlainColumn(*aggregate.groups[binding.column_index.GetIndex()]); - if (source) { - follow(*op.children[0], *source); - } - break; - } - case LogicalOperatorType::LOGICAL_GET: { - auto &get = op.Cast(); - if (binding.table_index != get.table_index || !op.children.empty()) { - break; - } - auto filter = get.table_filters.TryGetFilterByColumnIndex(binding.column_index); - // an optional filter is a hint the scan may ignore - if (!filter || ExpressionFilter::IsOptionalFilter(*filter)) { - break; - } - AddColumnFilters(*filter->ToExpression(column), column, result); - break; - } - case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: { - auto &join = op.Cast(); - if (op.children.size() != 2) { - break; - } - optional_idx side; - for (idx_t child_idx = 0; child_idx < 2; child_idx++) { - if (HasBinding(*op.children[child_idx], binding)) { - side = child_idx; - break; - } - } - if (!side.IsValid()) { - break; - } - // the side that an outer join extends with NULLs has rows its filters do not describe - const auto side_idx = side.GetIndex(); - bool preserved; - switch (join.join_type) { - case JoinType::INNER: - preserved = true; - break; - case JoinType::LEFT: - case JoinType::SEMI: - case JoinType::ANTI: - case JoinType::MARK: - preserved = side_idx == 0; - break; - case JoinType::RIGHT: - preserved = side_idx == 1; - break; - default: - preserved = false; - break; - } - if (!preserved) { - break; - } - follow(*op.children[side_idx], column); - if (join.join_type != JoinType::INNER) { - break; - } - // the rows of an INNER join also pass what the filters on the other side imply through its equalities - auto &other_child = *op.children[1 - side_idx]; - vector> other_filters; - for (auto &condition : join.conditions) { - if (!IsEquality(condition)) { - continue; - } - auto own = PlainColumn(side_idx == 0 ? condition.GetLHS() : condition.GetRHS()); - auto other = PlainColumn(side_idx == 0 ? condition.GetRHS() : condition.GetLHS()); - if (own && other && own->Binding() == binding && HasBinding(other_child, other->Binding())) { - GuaranteedColumnFilters(other_child, *other, steps, other_filters); - } - } - vector> filters; - for (auto &filter : other_filters) { - filters.push_back(*filter); - } - FilterCombiner::GenerateJoinFilters(join.conditions, filters, side_idx == 0 ? JoinSide::LEFT : JoinSide::RIGHT, - [&](unique_ptr filter) { - // an equality of the other column with another column of this side - AddColumnFilters(*filter, column, result); - }); - break; - } - case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: - for (auto &child : op.children) { - if (HasBinding(*child, binding)) { - follow(*child, column); - break; - } - } - break; - case LogicalOperatorType::LOGICAL_ORDER_BY: - case LogicalOperatorType::LOGICAL_LIMIT: - case LogicalOperatorType::LOGICAL_TOP_N: - case LogicalOperatorType::LOGICAL_DISTINCT: - case LogicalOperatorType::LOGICAL_WINDOW: - // rows are removed, reordered or kept, the columns of the child pass through under their own bindings - if (op.children.size() == 1 && HasBinding(*op.children[0], binding)) { - follow(*op.children[0], column); - } - break; - default: - // set operations and CTE references end the search - break; - } -} - -//! The join that keeps only the left rows with a match: a SEMI join, or a MARK join below a filter on its bare mark -static optional_ptr FilteringJoin(LogicalOperator &op) { - if (op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { - auto &join = op.Cast(); - return join.join_type == JoinType::SEMI && op.children.size() == 2 ? &join : nullptr; - } - if (op.type != LogicalOperatorType::LOGICAL_FILTER || - op.children[0]->type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { - return nullptr; - } - auto &join = op.children[0]->Cast(); - if (join.join_type != JoinType::MARK || join.children.size() != 2) { - return nullptr; - } - for (auto &expr : op.expressions) { - auto column_ref = PlainColumn(*expr); - if (column_ref && column_ref->Binding().table_index == join.mark_index) { - return &join; - } - } - return nullptr; -} - -void CTEFilterPusher::GenerateSemiJoinFilters(LogicalOperator &op) { - if (cte_info_map.empty()) { - return; - } - // children first, so that a nested join has filtered its left side before the join above searches that side - for (auto &child : op.children) { - GenerateSemiJoinFilters(*child); - } - auto join = FilteringJoin(op); - if (!join) { - return; - } - // the left side is a reference of a materialized CTE whose other references are all filtered - optional_ptr ref_op = join->children[0].get(); - optional_ptr ref_filter; - if (ref_op->type == LogicalOperatorType::LOGICAL_FILTER && !ref_op->Cast().HasProjectionMap()) { - ref_filter = ref_op; - ref_op = ref_op->children[0].get(); - } - if (ref_op->type != LogicalOperatorType::LOGICAL_CTE_REF) { - return; - } - auto &cte_ref = ref_op->Cast(); - auto entry = cte_info_map.find(to_string(cte_ref.cte_index.index)); - if (entry == cte_info_map.end() || cte_ref.is_recurring || cte_ref.correlated_columns != 0) { - return; - } - auto &info = *entry->second; - if (info.references.size() != info.filters.size() + (ref_filter ? 0 : 1)) { - return; - } - - // the filters on the join keys that every right row passes - vector> right_filters; - for (auto &condition : join->conditions) { - if (!IsEquality(condition)) { - continue; - } - auto right_key = PlainColumn(condition.GetRHS()); - if (right_key && HasBinding(*join->children[1], right_key->Binding())) { - idx_t steps = 0; - GuaranteedColumnFilters(*join->children[1], *right_key, steps, right_filters); - } - } - if (right_filters.empty()) { - return; - } - - // a left row with a match passes what they imply for the left side - vector> filters; - for (auto &filter : right_filters) { - filters.push_back(*filter); - } - vector> left_filters; - FilterCombiner::GenerateJoinFilters(join->conditions, filters, JoinSide::LEFT, - [&](unique_ptr left_filter) { - bool exists = false; - if (ref_filter) { - for (auto &existing : ref_filter->expressions) { - exists = exists || existing->Equals(*left_filter); - } - } - for (auto &existing : left_filters) { - exists = exists || existing->Equals(*left_filter); - } - if (!exists) { - left_filters.push_back(std::move(left_filter)); - } - }); - if (left_filters.empty()) { - return; - } - if (ref_filter) { - for (auto &left_filter : left_filters) { - ref_filter->expressions.push_back(std::move(left_filter)); - } - return; - } - // The CTE is restricted by the disjunction of the filters of its references, which this filter usually repeats in - // part. As one flat conjunction it is a branch that the expression rewriter reduces: (A AND B AND C) OR A is A. - auto filter = make_uniq(); - if (left_filters.size() == 1) { - filter->expressions = std::move(left_filters); - } else { - auto conjunction = make_uniq(ExpressionType::CONJUNCTION_AND); - conjunction->GetChildrenMutable() = std::move(left_filters); - filter->expressions.push_back(std::move(conjunction)); - } - filter->children.push_back(std::move(join->children[0])); - info.filters.push_back(*filter); - info.all_cte_refs_are_filtered = true; - join->children[0] = std::move(filter); -} - -} // namespace duckdb diff --git a/src/duckdb/src/optimizer/distinctness.cpp b/src/duckdb/src/optimizer/distinctness.cpp index c58e32a3a..6107b540e 100644 --- a/src/duckdb/src/optimizer/distinctness.cpp +++ b/src/duckdb/src/optimizer/distinctness.cpp @@ -2,6 +2,8 @@ #include "duckdb/catalog/catalog_entry/table_catalog_entry.hpp" #include "duckdb/function/cast/cast_function_set.hpp" +#include "duckdb/planner/operator/logical_cteref.hpp" +#include "duckdb/planner/operator/logical_materialized_cte.hpp" #include "duckdb/parser/constraints/not_null_constraint.hpp" #include "duckdb/parser/constraints/unique_constraint.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" @@ -60,34 +62,62 @@ bool Distinctness::IsDistinctOn(LogicalOperator &op, const vector(); - column_binding_set_t child_keys; - for (auto expr_idx : ProjectionIndex::GetIndexes(projection.expressions.size())) { - if (!keys.count(ColumnBinding(projection.table_index, expr_idx))) { +bool Distinctness::IsDistinctOnProjectedKeys(LogicalOperator &op, column_binding_set_t keys) { + optional_ptr current = op; + reference_set_t visited_ctes; + while (!keys.empty()) { + if (IsDistinctOn(*current, keys)) { + return true; + } + if (ForwardsChildUniqueSets(current->type, propagation)) { + current = *current->children[0]; continue; } - auto binding = GetInjectiveColumnBinding(*projection.expressions[expr_idx], context); - if (binding) { - child_keys.insert(*binding); + column_binding_set_t child_keys; + if (current->type == LogicalOperatorType::LOGICAL_PROJECTION) { + auto &projection = current->Cast(); + for (auto expr_idx : ProjectionIndex::GetIndexes(projection.expressions.size())) { + if (!keys.count(ColumnBinding(projection.table_index, expr_idx))) { + continue; + } + auto binding = GetInjectiveColumnBinding(*projection.expressions[expr_idx], context); + if (binding) { + child_keys.insert(*binding); + } + } + current = *projection.children[0]; + } else if (current->type == LogicalOperatorType::LOGICAL_CTE_REF) { + auto &ref = current->Cast(); + if (!cte_scope || ref.is_recurring || !visited_ctes.insert(*current).second) { + return false; + } + auto definition = cte_scope->Find(ref.cte_index); + if (!definition) { + return false; + } + auto bindings = definition->GetColumnBindings(); + if (bindings.size() != ref.chunk_types.size()) { + return false; + } + for (auto &key : keys) { + if (key.table_index == ref.table_index && key.column_index.GetIndex() < bindings.size()) { + child_keys.insert(bindings[key.column_index.GetIndex()]); + } + } + current = definition; + } else { + return false; } + keys = std::move(child_keys); } - return IsDistinctOnProjectedKeys(*projection.children[0], child_keys); + return false; +} + +void Distinctness::Invalidate(LogicalOperator &op) { + unique_sets.erase(op); } bool Distinctness::IsDistinctOn(LogicalOperator &op, const column_binding_set_t &keys) { @@ -178,8 +208,10 @@ const vector &Distinctness::GetUniqueSets(LogicalOperator if (entry != unique_sets.end()) { return entry->second; } - // every operator is computed once: its children are looked up in the cache - return unique_sets.emplace(op, ComputeUniqueSets(op)).first->second; + // An unfinished entry also makes cyclic CTE lookups conservatively return no proof. + auto &result = unique_sets.emplace(op, vector()).first->second; + result = ComputeUniqueSets(op); + return result; } vector Distinctness::ComputeScanUniqueSets(LogicalGet &get) { @@ -277,12 +309,18 @@ vector Distinctness::ComputeProjectionUniqueSets(LogicalPr forwarded.emplace(*binding, ColumnBinding(projection.table_index, expr_idx)); } } - for (auto &child_set : child_sets) { + return RemapUniqueSets(child_sets, forwarded); +} + +vector Distinctness::RemapUniqueSets(const vector &sets, + const column_binding_map_t &bindings) { + vector result; + for (auto &child_set : sets) { column_binding_set_t key; bool complete = true; for (auto &binding : child_set) { - auto entry = forwarded.find(binding); - if (entry == forwarded.end()) { + auto entry = bindings.find(binding); + if (entry == bindings.end()) { complete = false; break; } @@ -295,6 +333,29 @@ vector Distinctness::ComputeProjectionUniqueSets(LogicalPr return result; } +vector Distinctness::ComputeCTEUniqueSets(LogicalCTERef &cte_ref) { + if (!cte_scope || cte_ref.is_recurring) { + return {}; + } + auto definition = cte_scope->Find(cte_ref.cte_index); + if (!definition) { + return {}; + } + auto &sets = GetUniqueSets(*definition); + if (sets.empty()) { + return {}; + } + auto bindings = definition->GetColumnBindings(); + if (bindings.size() != cte_ref.chunk_types.size()) { + return {}; + } + column_binding_map_t forwarded; + for (idx_t i = 0; i < bindings.size(); i++) { + forwarded.emplace(bindings[i], ColumnBinding(cte_ref.table_index, ProjectionIndex(i))); + } + return RemapUniqueSets(sets, forwarded); +} + vector Distinctness::ComputeUniqueSets(LogicalOperator &op) { if (ForwardsChildUniqueSets(op.type, propagation)) { return GetUniqueSets(*op.children[0]); @@ -306,6 +367,8 @@ vector Distinctness::ComputeUniqueSets(LogicalOperator &op return ComputeAggregateUniqueSets(op.Cast()); case LogicalOperatorType::LOGICAL_PROJECTION: return ComputeProjectionUniqueSets(op.Cast()); + case LogicalOperatorType::LOGICAL_CTE_REF: + return ComputeCTEUniqueSets(op.Cast()); case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: if (propagation != DistinctnessPropagation::UNARY_OPERATORS_AND_JOINS) { break; @@ -316,6 +379,15 @@ vector Distinctness::ComputeUniqueSets(LogicalOperator &op break; } // the output of a materialized CTE is the output of the query that reads it (the second child) + if (cte_scope) { + auto &cte = op.Cast(); + auto outer = cte_scope; + CTEDefinitionScope local(*outer, cte.table_index, *cte.children[0]); + cte_scope = local; + auto result = GetUniqueSets(*cte.children[1]); + cte_scope = outer; + return result; + } return GetUniqueSets(*op.children[1]); default: break; diff --git a/src/duckdb/src/optimizer/duplicate_eliminated_domain/aggregate_domain.cpp b/src/duckdb/src/optimizer/duplicate_eliminated_domain/aggregate_domain.cpp new file mode 100644 index 000000000..2af831640 --- /dev/null +++ b/src/duckdb/src/optimizer/duplicate_eliminated_domain/aggregate_domain.cpp @@ -0,0 +1,530 @@ +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_aggregate.hpp" +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_expression.hpp" +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_restriction.hpp" +#include "duckdb/optimizer/duplicate_eliminated_domain_optimizer.hpp" + +#include "duckdb/optimizer/aggregate_rewrite_helper.hpp" +#include "duckdb/optimizer/optimizer.hpp" +#include "duckdb/parser/expression_map.hpp" +#include "duckdb/planner/binder.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/planner/logical_operator_deep_copy.hpp" +#include "duckdb/planner/operator/logical_cteref.hpp" +#include "duckdb/planner/operator/logical_dummy_scan.hpp" +#include "duckdb/planner/operator/logical_expression_get.hpp" +#include "duckdb/planner/operator/logical_materialized_cte.hpp" + +namespace duckdb { + +bool DomainAggregate::HasSimpleGrouping(const LogicalAggregate &aggregate) { + return !aggregate.groups.empty() && aggregate.grouping_functions.empty() && + (aggregate.grouping_sets.empty() || + (aggregate.grouping_sets.size() == 1 && aggregate.grouping_sets[0].size() == aggregate.groups.size())); +} + +unique_ptr DomainAggregate::GroupKey(const LogicalAggregate &domain) { + return make_uniq(domain.groups[0]->GetReturnType(), + ColumnBinding(domain.group_index, ProjectionIndex(0))); +} + +static void ResolveDomainTypes(LogicalOperator &op) { + vector> pending {op}; + for (idx_t index = 0; index < pending.size(); index++) { + for (auto &child : pending[index].get().children) { + pending.push_back(*child); + } + } + for (auto entry = pending.rbegin(); entry != pending.rend(); ++entry) { + entry->get().ResolveOperatorTypesFromChildren(); + } +} + +//! One full grouping set preserves the directly referenced key and its comparison semantics. +static optional_idx GroupKeyIndex(LogicalAggregate &aggregate, idx_t key, const LogicalType &type, + const DomainAnalysis &analysis) { + if (!DomainAggregate::HasSimpleGrouping(aggregate) || key >= aggregate.groups.size() || + !aggregate.groups[key]->GetReturnType().EqualsIncludingCollation(type)) { + return {}; + } + return analysis.ReferenceIndex(*aggregate.groups[key], *aggregate.children[0]); +} + +//! Trace output positions to the complete grouping key. +optional DomainAggregate::Match(LogicalOperator &op, vector keys, + const DomainAnalysis &analysis) { + auto candidate = analysis.Get(op).aggregate; + if (!candidate || candidate->preserve_input_order || candidate->groups.size() != keys.size() || + !DomainAggregate::HasSimpleGrouping(*candidate) || !analysis.Get(*candidate).repeatable) { + return {}; + } + auto &bindings = analysis.Bindings(op); + vector matched(keys.size(), false); + for (auto &key : keys) { + if (key >= bindings.size()) { + return {}; + } + auto origin = analysis.ResolveBinding(bindings[key]); + key = origin.column_index.GetIndex(); + if (origin.table_index != candidate->group_index || key >= keys.size() || matched[key] || + !analysis.ReferenceIndex(*candidate->groups[key], *candidate->children[0]).IsValid()) { + return {}; + } + matched[key] = true; + } + for (auto &expression : candidate->expressions) { + bool supported = true; + ExpressionIterator::EnumerateChildren( + *expression, [&](const Expression &child) { supported &= DomainExpression::IsWorkReference(child); }); + if (!supported) { + return {}; + } + } + return AggregateKeyMatch {*candidate, std::move(keys)}; +} + +static bool AppendFixedKey(vector>> &rows, const Expression &expression, + const LogicalType &type) { + if ((expression.GetExpressionClass() != ExpressionClass::BOUND_CONSTANT && + expression.GetExpressionClass() != ExpressionClass::BOUND_PARAMETER) || + !expression.GetReturnType().EqualsIncludingCollation(type)) { + return false; + } + vector> row; + row.push_back(expression.Copy()); + rows.push_back(std::move(row)); + return true; +} + +//! Copy keys already represented by expressions, leaving columnar inputs on the runtime path. +//! The caller's payload and its evaluation remain in place. +static bool CopyFixedKeys(LogicalOperator &op, idx_t key, const LogicalType &type, + vector>> &rows, const DomainAnalysis &analysis) { + optional_ptr current = op; + while (true) { + switch (current->type) { + case LogicalOperatorType::LOGICAL_PROJECTION: { + auto &expression = *current->expressions[key]; + auto index = analysis.ReferenceIndex(expression, *current->children[0]); + if (!index.IsValid()) { + auto count = analysis.Get(*current->children[0]).fixed_rows; + return count.IsValid() && (count.GetIndex() == 0 || AppendFixedKey(rows, expression, type)); + } + key = index.GetIndex(); + break; + } + case LogicalOperatorType::LOGICAL_FILTER: { + auto index = analysis.BindingIndex(*current->children[0], analysis.Bindings(*current)[key]); + if (!index.IsValid()) { + return false; + } + key = index.GetIndex(); + break; + } + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { + auto index = GroupKeyIndex(current->Cast(), key, type, analysis); + if (!index.IsValid()) { + return false; + } + key = index.GetIndex(); + break; + } + case LogicalOperatorType::LOGICAL_EXPRESSION_GET: + if (!analysis.Get(*current).fixed_rows.IsValid()) { + return false; + } + for (auto &row : current->Cast().expressions) { + if (!AppendFixedKey(rows, *row[key], type)) { + return false; + } + } + return true; + case LogicalOperatorType::LOGICAL_EMPTY_RESULT: + return true; + default: + return false; + } + current = *current->children[0]; + } +} + +//! The old restriction must be proven to contain every demanded key. +static bool CopyExactFixedKeys(LogicalOperator &op, idx_t key, const LogicalType &type, + vector>> &rows, const DomainAnalysis &analysis) { + optional_ptr current = op; + while (true) { + optional_idx index; + switch (current->type) { + case LogicalOperatorType::LOGICAL_PROJECTION: { + auto &expression = *current->expressions[key]; + index = analysis.ReferenceIndex(expression, *current->children[0], type); + if (!index.IsValid()) { + return current->children[0]->type == LogicalOperatorType::LOGICAL_DUMMY_SCAN && + AppendFixedKey(rows, expression, type); + } + break; + } + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: + index = GroupKeyIndex(current->Cast(), key, type, analysis); + break; + case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: + case LogicalOperatorType::LOGICAL_ANY_JOIN: { + if (current->Cast().join_type != JoinType::LEFT) { + return false; + } + index = analysis.BindingIndex(*current->children[0], analysis.Bindings(*current)[key]); + break; + } + case LogicalOperatorType::LOGICAL_EXPRESSION_GET: + case LogicalOperatorType::LOGICAL_EMPTY_RESULT: + return CopyFixedKeys(*current, key, type, rows, analysis); + default: + return false; + } + if (!index.IsValid()) { + return false; + } + key = index.GetIndex(); + current = *current->children[0]; + } +} + +static unique_ptr CreateKeyDomain(Optimizer &optimizer, unique_ptr input, + unique_ptr key) { + auto domain = make_uniq(optimizer.binder.GenerateTableIndex(), + optimizer.binder.GenerateTableIndex(), vector>()); + domain->groups.push_back(std::move(key)); + domain->grouping_sets.push_back({ProjectionIndex(0)}); + domain->children.push_back(std::move(input)); + ResolveDomainTypes(*domain); + return domain; +} + +enum class DomainProducerKind { FIXED_KEYS, SOURCE_REFERENCE, MATERIALIZED_DEMAND, SCAN_COPY }; + +//! Owns a candidate's new nodes; rejected candidates discard their transient facts. +struct DomainProducer { +public: + DomainProducer(DomainAnalysis &analysis_p, DomainProducerKind kind_p, unique_ptr plan_p) + : analysis(analysis_p), kind(kind_p), plan(std::move(plan_p)) { + D_ASSERT(kind != DomainProducerKind::SCAN_COPY && plan); + } + DomainProducer(DomainAnalysis &analysis_p, DomainScanSource scan_p, DomainChoice choice_p) + : analysis(analysis_p), kind(DomainProducerKind::SCAN_COPY), scan(scan_p), choice(choice_p) { + D_ASSERT(scan.input && choice.restriction != RestrictionAction::INSERT); + } + ~DomainProducer() { + if (plan) { + analysis.RemoveSubtree(*plan); + } + } + +public: + //! A reference or fixed-key plan is ready to install. A scan is copied only if replacement wins. + DomainAnalysis &analysis; + DomainProducerKind kind; + unique_ptr plan; + DomainScanSource scan; + DomainChoice choice; +}; + +static bool FixedRestrictionContainsDemand(const DomainRestriction &existing, LogicalAggregate &domain, + const DomainAnalysis &analysis) { + auto restriction = existing.GetJoin(); + if (!restriction || analysis.Get(*restriction->children[1]).shared_source) { + return false; + } + auto &condition = existing.GetCondition(0); + auto key = analysis.ReferenceIndex(condition.GetRHS(), *restriction->children[1]).GetIndex(); + vector>> original_rows; + if (!CopyExactFixedKeys(*restriction->children[1], key, condition.GetRHS().GetReturnType(), original_rows, + analysis)) { + return false; + } + expression_set_t original_keys; + for (auto &row : original_rows) { + original_keys.insert(*row[0]); + } + for (auto &row : domain.children[0]->Cast().expressions) { + if (!original_keys.count(*row[0])) { + return false; + } + } + return true; +} + +static optional EstimateDomainProducer(LogicalAggregate &domain, const RelationStats &source, + DomainAnalysis &analysis) { + auto rebound = RelationStatisticsHelper::RebindOutputStats(source, *domain.children[0]); + if (!rebound) { + return {}; + } + auto &extractor = analysis.Statistics(); + auto result = RelationStatisticsHelper::ExtractAggregationStats(domain, *rebound, extractor); + // Keep shared producer facts, but discard facts keyed by the temporary proposal. + extractor.Invalidate(*domain.children[0]); + return result; +} + +//! Prices exact key domains against the same aggregate and its existing restriction. +struct AggregateDomainConsumer { +public: + AggregateDomainConsumer(DomainAnalysis &analysis_p, LogicalAggregate &aggregate_p, ExpressionType comparison_p, + JoinType join_type_p) + : analysis(analysis_p), aggregate(aggregate_p), existing(analysis, aggregate, comparison_p), + comparison(comparison_p), join_type(join_type_p) { + } + +public: + DomainChoice ChooseExact(LogicalAggregate &domain, const RelationStats &keys, bool contains_demand, + double input_rows, double reader_work) const { + DomainCostModel costs(analysis, aggregate, input_rows, reader_work); + DomainChoice best; + if (contains_demand) { + best = costs.ChooseRestriction(existing, domain, keys, DomainKeyContainment::EXACT); + // Replacement applies these keys without retaining the redundant restriction. + if (best.restriction == RestrictionAction::REPLACE && + existing.GetCondition(0).GetComparisonType() == comparison) { + return best; + } + } + LogicalComparisonJoin restriction(JoinType::SEMI); + restriction.conditions.emplace_back(aggregate.groups[0]->Copy(), DomainAggregate::GroupKey(domain), comparison); + auto choice = best; + choice.Consider(costs.ChooseInsertion(restriction, keys)); + if (choice.restriction == RestrictionAction::INSERT && + (join_type == JoinType::SINGLE || !analysis.HasRuntimeFilterTargets(aggregate))) { + return choice; + } + return best; + } + + void Apply(Optimizer &optimizer, DomainProducer &producer); + +public: + //! Matched aggregate input and its consumer's key comparison. + DomainAnalysis &analysis; + LogicalAggregate &aggregate; + DomainRestriction existing; + ExpressionType comparison; + JoinType join_type; +}; + +void AggregateDomainConsumer::Apply(Optimizer &optimizer, DomainProducer &producer) { + switch (producer.choice.restriction) { + case RestrictionAction::REMOVE: + existing.Remove(); + return; + case RestrictionAction::REPLACE: + if (producer.kind == DomainProducerKind::SCAN_COPY) { + auto parameters = optimizer.binder.GetParameters(); + LogicalOperatorDeepCopy copier(optimizer.binder, parameters ? parameters->GetParametersPtr() : nullptr); + auto scan = copier.DeepCopy(*producer.scan.input); + auto key = make_uniq(aggregate.groups[0]->GetReturnType(), + scan->GetColumnBindings()[producer.scan.key]); + producer.plan = CreateKeyDomain(optimizer, std::move(scan), std::move(key)); + } + existing.Replace(producer.plan); + return; + case RestrictionAction::INSERT: { + auto restriction = make_uniq(JoinType::SEMI); + restriction->conditions.emplace_back(aggregate.groups[0]->Copy(), DomainAggregate::GroupKey(*producer.plan), + comparison); + restriction->children.push_back(std::move(aggregate.children[0])); + restriction->children.push_back(std::move(producer.plan)); + restriction->ResolveOperatorTypesFromChildren(); + aggregate.children[0] = std::move(restriction); + return; + } + default: + throw InternalException("Cannot apply an unchanged aggregate domain"); + } +} + +struct RuntimeDomainSource { +public: + //! Existing CTE definition or a demand input that can be materialized for a second reader. + LogicalOperator &input; + optional_ptr owner; + idx_t key; +}; + +static optional FindRuntimeDomainSource(LogicalOperator &demand, idx_t demand_index, + const DomainAnalysis &analysis) { + auto &input = analysis.Get(demand); + auto key = analysis.KeySource(demand, demand_index); + if (key && input.HasAllSourceRows()) { + auto owner = analysis.FindMaterializedOwner(input.row_source->cte_index); + // Statistics can make the original reader filterable after this pass. + if (!owner || !analysis.Get(*input.row_source).can_change_readers) { + return {}; + } + return RuntimeDomainSource {*owner->children[0], owner, key->column_index.GetIndex()}; + } + if (!input.can_change_readers) { + return {}; + } + return RuntimeDomainSource {demand, nullptr, demand_index}; +} + +static unique_ptr CreateReferenceDomain(Optimizer &optimizer, TableIndex owner, + const vector &types, idx_t key_index, + const string &name) { + auto reference = make_uniq(optimizer.binder.GenerateTableIndex(), owner, types, + AggregateRewriteHelper::GenerateColumnNames(name, types.size())); + auto key = make_uniq(types[key_index], + ColumnBinding(reference->table_index, ProjectionIndex(key_index))); + return CreateKeyDomain(optimizer, std::move(reference), std::move(key)); +} + +static unique_ptr ChooseScanProducer(Optimizer &optimizer, AggregateDomainConsumer &consumer, + const RuntimeDomainSource &source) { + auto scan = consumer.analysis.FindScanSource(*source.owner, source.key); + if (!scan.input) { + return nullptr; + } + // Price the scan with its own output statistics, without copying it or refining against another CTE. + auto estimate = CreateReferenceDomain(optimizer, optimizer.binder.GenerateTableIndex(), (*scan.input)->types, + scan.key, "scan_domain"); + auto keys = EstimateDomainProducer(*estimate, *consumer.analysis.Stats(**scan.input), consumer.analysis); + if (!keys) { + return nullptr; + } + DomainCostModel costs(consumer.analysis, consumer.aggregate, scan.rows, scan.scan_rows); + auto choice = costs.ChooseRestriction(consumer.existing, *estimate, *keys, DomainKeyContainment::SUPERSET); + if (choice.IsKeep()) { + return nullptr; + } + return make_uniq(consumer.analysis, scan, choice); +} + +static unique_ptr ChooseRuntimeProducer(Optimizer &optimizer, AggregateDomainConsumer &consumer, + const RuntimeDomainSource &source, + const RelationStats &source_stats, bool contains_demand) { + unique_ptr best; + if (source.owner && contains_demand) { + best = ChooseScanProducer(optimizer, consumer, source); + } + auto owner = source.owner ? source.owner->table_index : optimizer.binder.GenerateTableIndex(); + auto kind = source.owner ? DomainProducerKind::SOURCE_REFERENCE : DomainProducerKind::MATERIALIZED_DEMAND; + auto domain = CreateReferenceDomain(optimizer, owner, source.input.types, source.key, "domain"); + auto keys = EstimateDomainProducer(*domain, source_stats, consumer.analysis); + if (keys) { + auto rows = source_stats.cardinality.GetDouble(); + auto reader_work = (source.owner ? 1 : 3) * rows * static_cast(source.input.types.size()); + auto choice = consumer.ChooseExact(*domain, *keys, contains_demand, rows, reader_work); + if (!choice.IsKeep() && (!best || choice.savings > best->choice.savings)) { + best = make_uniq(consumer.analysis, kind, std::move(domain)); + best->choice = choice; + } + } + return best; +} + +static BindingReplacementGraph MaterializeRuntimeDomain(Optimizer &optimizer, const DomainAnalysis &analysis, + unique_ptr &op, idx_t demand_side, + const LogicalCTERef &domain) { + BindingReplacementGraph replacements; + auto definition = std::move(op->children[demand_side]); + auto &reference = op->children[demand_side]; + reference = make_uniq(optimizer.binder.GenerateTableIndex(), domain.cte_index, domain.chunk_types, + domain.bound_columns); + reference->ResolveOperatorTypesFromChildren(); + ColumnBindingRewrite::ReplaceOutputBindings(reference, analysis.Bindings(*definition), replacements); + ColumnBindingRewrite::ApplyToOperatorBindings(*op, replacements); + op = + make_uniq("domain_source", domain.cte_index, domain.chunk_types.size(), + std::move(definition), std::move(op), CTEMaterialize::CTE_MATERIALIZE_ALWAYS); + op->ResolveOperatorTypesFromChildren(); + return replacements; +} + +bool DuplicateEliminatedDomainOptimizer::TryOptimizeRuntimeDomain(unique_ptr &op, + LogicalAggregate &aggregate, idx_t aggregate_side, + idx_t demand_index, ExpressionType comparison, + BindingReplacementGraph &replacements) { + auto &join = op->Cast(); + auto &demand = *join.children[1 - aggregate_side]; + if (!analysis.Get(demand).visible_references || !analysis.Get(aggregate).visible_references) { + return false; + } + auto source = FindRuntimeDomainSource(demand, demand_index, analysis); + if (!source) { + return false; + } + auto stats = analysis.Stats(source->input); + if (!stats) { + return false; + } + AggregateDomainConsumer consumer(analysis, aggregate, comparison, join.join_type); + auto contains_demand = consumer.existing.ContainsDemand(demand, {demand_index}); + auto producer = ChooseRuntimeProducer(optimizer, consumer, *source, *stats, contains_demand); + if (!producer) { + return false; + } + optional_ptr new_reader; + if (producer->kind == DomainProducerKind::MATERIALIZED_DEMAND && + producer->choice.restriction != RestrictionAction::REMOVE) { + new_reader = producer->plan->children[0]->Cast(); + } + consumer.Apply(optimizer, *producer); + if (new_reader) { + replacements.Merge(MaterializeRuntimeDomain(optimizer, analysis, op, 1 - aggregate_side, *new_reader)); + } + return true; +} + +bool DuplicateEliminatedDomainOptimizer::TryOptimizeDomain(unique_ptr &op, idx_t aggregate_side, + idx_t condition_index, + BindingReplacementGraph &replacements) { + auto &join = op->Cast(); + auto &condition = join.conditions[condition_index]; + auto &aggregate_key = aggregate_side == 0 ? condition.GetLHS() : condition.GetRHS(); + auto &demand_key = aggregate_side == 0 ? condition.GetRHS() : condition.GetLHS(); + auto aggregate_index = analysis.ReferenceIndex(aggregate_key, *join.children[aggregate_side]); + auto demand_index = analysis.ReferenceIndex(demand_key, *join.children[1 - aggregate_side]); + if (!aggregate_index.IsValid() || !demand_index.IsValid() || + !aggregate_key.GetReturnType().EqualsIncludingCollation(demand_key.GetReturnType())) { + return false; + } + auto match = DomainAggregate::Match(*join.children[aggregate_side], {aggregate_index.GetIndex()}, analysis); + if (!match) { + return false; + } + auto &aggregate = match->aggregate.get(); + vector>> rows; + if (!CopyFixedKeys(*join.children[1 - aggregate_side], demand_index.GetIndex(), demand_key.GetReturnType(), rows, + analysis)) { + auto changed = TryOptimizeRuntimeDomain(op, aggregate, aggregate_side, demand_index.GetIndex(), + condition.GetComparisonType(), replacements); + if (changed) { + analysis.InvalidateProjectionPath(*join.children[aggregate_side], aggregate); + } + return changed; + } + auto key_index = optimizer.binder.GenerateTableIndex(); + auto fixed = + make_uniq(key_index, vector {demand_key.GetReturnType()}, std::move(rows)); + fixed->children.push_back(make_uniq(optimizer.binder.GenerateTableIndex())); + auto key_expression = + make_uniq(demand_key.GetReturnType(), ColumnBinding(key_index, ProjectionIndex(0))); + DomainProducer producer(analysis, DomainProducerKind::FIXED_KEYS, + CreateKeyDomain(optimizer, std::move(fixed), std::move(key_expression))); + analysis.Refresh(*producer.plan); + auto stats = analysis.Stats(*producer.plan); + if (!stats) { + return false; + } + auto row_count = producer.plan->children[0]->Cast().expressions.size(); + AggregateDomainConsumer consumer(analysis, aggregate, condition.GetComparisonType(), join.join_type); + auto contains_demand = FixedRestrictionContainsDemand(consumer.existing, *producer.plan, analysis); + producer.choice = consumer.ChooseExact(*producer.plan, *stats, contains_demand, static_cast(row_count), 0); + if (producer.choice.IsKeep()) { + return false; + } + consumer.Apply(optimizer, producer); + analysis.InvalidateProjectionPath(*join.children[aggregate_side], aggregate); + return true; +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_analysis.cpp b/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_analysis.cpp new file mode 100644 index 000000000..91a684b3c --- /dev/null +++ b/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_analysis.cpp @@ -0,0 +1,869 @@ +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_analysis.hpp" +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_aggregate.hpp" +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_expression.hpp" +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_cost_model.hpp" + +#include "duckdb/common/reference_map.hpp" +#include "duckdb/function/cast/cast_function_set.hpp" +#include "duckdb/optimizer/expression_heuristics.hpp" +#include "duckdb/optimizer/join_filter_pushdown_optimizer.hpp" +#include "duckdb/optimizer/optimizer.hpp" +#include "duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp" +#include "duckdb/planner/expression/bound_cast_expression.hpp" +#include "duckdb/planner/expression/bound_aggregate_expression.hpp" +#include "duckdb/storage/statistics/node_statistics.hpp" +#include "duckdb/storage/statistics/numeric_stats.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression/bound_comparison_expression.hpp" +#include "duckdb/planner/expression/bound_operator_expression.hpp" +#include "duckdb/planner/expression/expression_barrier.hpp" +#include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/planner/filter/expression_filter.hpp" +#include "duckdb/planner/logical_operator_repeatability.hpp" +#include "duckdb/planner/operator/logical_aggregate.hpp" +#include "duckdb/planner/operator/logical_comparison_join.hpp" +#include "duckdb/planner/operator/logical_cteref.hpp" +#include "duckdb/planner/operator/logical_filter.hpp" +#include "duckdb/planner/operator/logical_get.hpp" +#include "duckdb/planner/operator/logical_materialized_cte.hpp" +#include "duckdb/planner/operator/logical_projection.hpp" +#include "duckdb/planner/operator/logical_recursive_cte.hpp" +#include "duckdb/planner/operator/logical_order.hpp" + +#include + +#include "duckdb/planner/operator/logical_column_data_get.hpp" +#include "duckdb/planner/operator/logical_expression_get.hpp" +#include "duckdb/common/types/column/column_data_collection.hpp" +#include "duckdb/catalog/catalog_entry/duck_table_entry.hpp" +#include "duckdb/storage/data_table.hpp" +#include "duckdb/storage/table/table_index_list.hpp" + +namespace duckdb { + +DomainAnalysis::DomainAnalysis(ClientContext &context_p) + : context(context_p), distinctness(DistinctnessPropagation::UNARY_OPERATORS, context_p), + statistics( + context_p, [this](LogicalOperator &op) { return Stats(op); }, + [this](TableIndex index) -> optional_ptr { + auto owner = FindOwner(index); + return owner && owner->type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE ? owner->children[0].get() + : nullptr; + }, + distinctness) { +} + +DomainAnalysis::~DomainAnalysis() = default; + +void DomainAnalysis::Initialize(LogicalOperator &root) { + vector> pending {root}; + while (!pending.empty()) { + auto &op = pending.back().get(); + pending.pop_back(); + if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { + registered_references.insert(op); + reference_counts[op.Cast().cte_index]++; + } + for (auto &child : op.children) { + pending.push_back(*child); + } + } +} + +bool DomainAnalysis::RegisterOwner(LogicalCTE &cte) { + auto entry = source_order.emplace(cte.table_index, source_order.size() + 1); + if (entry.second && cte.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { + PublishKeys(cte.Cast()); + } + return owners.emplace(cte.table_index, cte).second; +} + +idx_t DomainAnalysis::ReferenceCount(TableIndex index) const { + auto entry = reference_counts.find(index); + return entry == reference_counts.end() ? 0 : entry->second; +} + +bool DomainAnalysis::ReadsEarlierSources(LogicalOperator &op, TableIndex source) const { + auto entry = source_order.find(source); + return entry != source_order.end() && Get(op).latest_source < entry->second; +} + +void DomainAnalysis::EnterChild(LogicalOperator &op, idx_t child_index) { + if (child_index == 1 && (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE || + op.type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE)) { + auto &cte = op.Cast(); + RegisterOwner(cte); + } +} + +DomainScanSource DomainAnalysis::FindScanSource(const LogicalMaterializedCTE &owner, idx_t key) { + auto entry = scan_sources.find(owner.table_index); + if (entry == scan_sources.end()) { + entry = scan_sources + .emplace(owner.table_index, make_uniq(context, *this, owner.children[0])) + .first; + } + return entry->second->Find(key); +} + +void DomainAnalysis::CaptureColumns(LogicalOperator &op, DomainInput &result) { + vector bindings; + switch (op.type) { + case LogicalOperatorType::LOGICAL_PROJECTION: { + auto table = op.Cast().table_index; + for (idx_t index = 0; index < op.expressions.size(); index++) { + auto column = DomainExpression::DirectColumn(*op.expressions[index]); + if (column && ReferenceIndex(*column, *op.children[0], column->GetReturnType()).IsValid()) { + origins.insert_or_assign(ColumnBinding(table, ProjectionIndex(index)), + ResolveBinding(column->Binding())); + } + } + bindings = op.GetColumnBindings(); + break; + } + case LogicalOperatorType::LOGICAL_FILTER: { + auto &child = inputs.at(*op.children[0]); + if (!child.layout) { + return; + } + auto &map = op.Cast().projection_map; + if (map.empty()) { + result.layout = child.layout; + return; + } + bindings = child.layout->ProjectBindings(map); + break; + } + case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: + case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: { + auto &left = inputs.at(*op.children[0]); + auto &right = inputs.at(*op.children[1]); + if (!left.layout || !right.layout) { + return; + } + if (op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + bindings = + op.Cast().GetColumnBindings(left.layout->bindings, right.layout->bindings); + } else { + bindings = left.layout->bindings; + bindings.insert(bindings.end(), right.layout->bindings.begin(), right.layout->bindings.end()); + } + break; + } + case LogicalOperatorType::LOGICAL_MATERIALIZED_CTE: + result.layout = inputs.at(*op.children[1]).layout; + return; + case LogicalOperatorType::LOGICAL_ORDER_BY: { + auto &child = inputs.at(*op.children[0]); + if (!child.layout) { + return; + } + bindings = child.layout->ProjectBindings(op.Cast().projection_map); + break; + } + case LogicalOperatorType::LOGICAL_LIMIT: + case LogicalOperatorType::LOGICAL_TOP_N: + case LogicalOperatorType::LOGICAL_SAMPLE: + result.layout = inputs.at(*op.children[0]).layout; + return; + case LogicalOperatorType::LOGICAL_CTE_REF: + case LogicalOperatorType::LOGICAL_GET: + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: + case LogicalOperatorType::LOGICAL_UNION: + case LogicalOperatorType::LOGICAL_INTERSECT: + case LogicalOperatorType::LOGICAL_EXCEPT: + case LogicalOperatorType::LOGICAL_RECURSIVE_CTE: + case LogicalOperatorType::LOGICAL_EXPRESSION_GET: + case LogicalOperatorType::LOGICAL_CHUNK_GET: + case LogicalOperatorType::LOGICAL_DUMMY_SCAN: + case LogicalOperatorType::LOGICAL_EMPTY_RESULT: + bindings = op.GetColumnBindings(); + break; + default: + return; + } + result.layout = make_shared_ptr(std::move(bindings), "domain input", + ColumnBindingLayout::DuplicatePosition::FIRST); +} + +void DomainAnalysis::SummarizeSafety(LogicalOperator &op, DomainInput &result) { + result.safe = !op.HasLocalSideEffects(); + result.can_change_readers = result.safe; + result.repeatable = ClassifyLogicalOperatorLocalRepeatability(op) == LogicalOperatorRepeatability::REPEATABLE; + switch (op.type) { + case LogicalOperatorType::LOGICAL_GET: + case LogicalOperatorType::LOGICAL_PROJECTION: + case LogicalOperatorType::LOGICAL_FILTER: + case LogicalOperatorType::LOGICAL_CTE_REF: + case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: + case LogicalOperatorType::LOGICAL_DUMMY_SCAN: + case LogicalOperatorType::LOGICAL_EMPTY_RESULT: + break; + case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: + result.safe &= op.Cast().join_type != JoinType::SINGLE; + break; + default: + result.safe = false; + break; + } + LogicalOperatorVisitor::EnumerateExpressions(op, [&](const unique_ptr *expression) { + auto safe = DomainExpression::IsSafe(**expression); + result.safe &= safe; + result.can_change_readers &= safe; + }); + if (op.type == LogicalOperatorType::LOGICAL_GET) { + auto &get = op.Cast(); + // Scan predicates are not included in EnumerateExpressions. + result.safe &= get.GetTable() && get.children.empty(); + for (auto &entry : get.table_filters) { + auto &expression = *ExpressionFilter::GetExpressionFilter(entry.Filter(), "DomainAnalysis").expr; + auto safe = DomainExpression::IsSafe(expression); + result.can_change_readers &= safe; + result.safe &= safe; + } + } + for (auto &child : op.children) { + auto &child_input = inputs.at(*child); + result.safe &= child_input.safe; + result.repeatable &= child_input.repeatable; + result.can_change_readers &= child_input.can_change_readers; + } + result.can_change_readers &= result.repeatable; + if (op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + result.can_change_readers &= op.Cast().join_type != JoinType::SINGLE; + } +} + +void DomainAnalysis::SummarizeSources(LogicalOperator &op, DomainInput &result) { + for (auto &child : op.children) { + auto &input = Get(*child); + result.visible_references &= input.visible_references; + result.shared_source |= input.shared_source; + result.latest_source = MaxValue(result.latest_source, input.latest_source); + result.indexed_scan_work += input.indexed_scan_work; + result.reference_count += input.reference_count; + if (input.single_reference) { + result.single_reference = input.single_reference; + } + } + if (result.reference_count != 1) { + result.single_reference = nullptr; + } +} + +void DomainAnalysis::SummarizeReference(LogicalCTERef &ref, DomainInput &result) { + result.row_source = ref; + result.single_reference = ref; + result.reference_count = 1; + if (registered_references.insert(ref).second) { + reference_counts[ref.cte_index]++; + } + auto order = source_order.find(ref.cte_index); + result.latest_source = order == source_order.end() ? NumericLimits::Maximum() : order->second; + result.shared_source = true; + result.visible_references = !ref.is_recurring && !ref.correlated_columns && FindMaterializedOwner(ref.cte_index); + result.source_rows = DomainSourceRows::DIRECT; + auto owner = owners.find(ref.cte_index); + if (owner != owners.end()) { + auto &cte = owner->second.get(); + if (cte.type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) { + result.latest_source = NumericLimits::Maximum(); + } + auto &definition = inputs.at(*cte.children[0]); + result.repeatable = definition.repeatable; + result.safe &= definition.safe; + result.can_change_readers &= definition.can_change_readers && result.visible_references; + if (cte.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { + if (definition.domain) { + result.domain.emplace(definition.domain->aggregate, DomainProduction::SHARED); + } + if (definition.layout && definition.layout->bindings.size() == ref.chunk_types.size()) { + for (idx_t index = 0; index < ref.chunk_types.size(); index++) { + auto binding = ColumnBinding(ref.table_index, ProjectionIndex(index)); + auto source = definition.layout->bindings[index]; + if (result.domain) { + origins.insert_or_assign(binding, ResolveBinding(source)); + } + } + } else { + result.domain.reset(); + } + } + } else { + result.safe = false; + result.can_change_readers = false; + } +} + +void DomainAnalysis::SummarizeDomain(LogicalAggregate &aggregate, DomainInput &result) { + auto &child = inputs.at(*aggregate.children[0]); + if (!DomainAggregate::HasSimpleGrouping(aggregate)) { + return; + } + result.row_source = child.row_source; + result.source_rows = child.HasAllSourceRows() ? DomainSourceRows::COMPLETE : DomainSourceRows::FILTERED; + if (!child.row_source || !child.IsDirectSource() || !aggregate.expressions.empty()) { + return; + } + for (auto &group : aggregate.groups) { + auto column = DomainExpression::DirectColumn(*group); + if (!column || ResolveBinding(column->Binding()).table_index != child.row_source->table_index) { + return; + } + } + result.domain.emplace(aggregate, DomainProduction::INLINE); +} + +void DomainAnalysis::SummarizePassthrough(LogicalOperator &op, DomainInput &result) { + auto &child = inputs.at(*op.children[0]); + result.row_source = child.row_source; + result.source_rows = + op.type == LogicalOperatorType::LOGICAL_FILTER ? DomainSourceRows::FILTERED : child.source_rows; + if (op.type != LogicalOperatorType::LOGICAL_PROJECTION) { + return; + } + result.domain = child.domain; + for (auto &expression : op.expressions) { + if (!DomainExpression::DirectColumn(*expression)) { + result.domain.reset(); + if (result.IsDirectSource() && expression->GetExpressionClass() != ExpressionClass::BOUND_CONSTANT) { + result.source_rows = DomainSourceRows::COMPLETE; + } + } + } +} + +static bool DomainScanHasIndex(LogicalGet &get) { + auto table = get.GetTable(); + if (!table || !table->IsDuckTable()) { + return false; + } + auto &storage = table->Cast().GetStorage(); + for (auto &index : storage.GetDataTableInfo()->GetIndexes().GetStorageInfo()) { + // Compound index scans are not supported. + if (index.column_set.size() == 1) { + return true; + } + } + return false; +} + +void DomainAnalysis::Summarize(LogicalOperator &op) { + DomainInput result; + SummarizeSafety(op, result); + SummarizeSources(op, result); + if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { + SummarizeReference(op.Cast(), result); + } else if (op.type == LogicalOperatorType::LOGICAL_PROJECTION || op.type == LogicalOperatorType::LOGICAL_FILTER) { + SummarizePassthrough(op, result); + } else if (op.type == LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { + SummarizeDomain(op.Cast(), result); + } + CaptureColumns(op, result); + CaptureKeys(op, result); + distinctness.GetUniqueSets(op); + auto stats = EstimateStats(op, result); + if (stats) { + result.maximum_rows = stats->max_cardinality; + result.stats = make_shared_ptr(std::move(*stats)); + if (op.type == LogicalOperatorType::LOGICAL_GET && DomainScanHasIndex(op.Cast())) { + result.indexed_scan_work += result.stats->cardinality.GetDouble(); + } + if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { + result.key_production_work = + result.stats->cardinality.GetDouble() * static_cast(result.stats->columns.size()); + } else if (op.type == LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { + auto &child = inputs.at(*op.children[0]); + if (child.stats) { + result.key_production_work = + DomainCostModel::EstimateDomainProductionWork(child.stats->cardinality.GetDouble(), + result.stats->cardinality.GetDouble()) + + child.key_production_work; + } + } + } + if (op.type == LogicalOperatorType::LOGICAL_PROJECTION) { + result.key_production_work = inputs.at(*op.children[0]).key_production_work; + } + SummarizeStructure(op, result); + CaptureBounds(op, result); + inputs.insert_or_assign(op, std::move(result)); +} + +optional_ptr DomainAnalysis::Stats(const LogicalOperator &op) const { + auto entry = inputs.find(op); + return entry == inputs.end() ? nullptr : entry->second.stats.get(); +} + +RelationStatsExtractor &DomainAnalysis::Statistics() { + return statistics; +} + +optional DomainAnalysis::EstimateStats(LogicalOperator &op, DomainInput &input_layout) { + static constexpr idx_t MAX_ESTIMATION_NODES = 64; + for (auto &child : op.children) { + input_layout.estimation_nodes = + MinValue(MAX_ESTIMATION_NODES + 1, input_layout.estimation_nodes + Get(*child).estimation_nodes); + } + input_layout.join_region = op.type == LogicalOperatorType::LOGICAL_CROSS_PRODUCT || + (op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN && + (op.Cast().join_type == JoinType::INNER || + op.Cast().join_type == JoinType::LEFT)) || + (op.type == LogicalOperatorType::LOGICAL_FILTER && Get(*op.children[0]).join_region); + if (!input_layout.layout) { + return {}; + } + if (input_layout.join_region) { + // Do not substitute generic join estimates when a region exceeds the work budget. + if (input_layout.estimation_nodes > MAX_ESTIMATION_NODES) { + return {}; + } + auto stats = statistics.ExtractJoinStats(op); + if (stats) { + return stats; + } + // Retain operator-specific estimates for boundaries the join model cannot represent. + } + if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { + auto &reference = op.Cast(); + auto owner = FindOwner(reference.cte_index); + if (!owner || reference.is_recurring || reference.correlated_columns) { + return {}; + } + auto input = Stats(*owner->children[0]); + if (!input) { + return {}; + } + if (owner->type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) { + auto frontier = RelationStatisticsHelper::RecursiveReferenceStats(*input, input->cardinality); + return RelationStatisticsHelper::RebindOutputStats(frontier, op); + } + return RelationStatisticsHelper::RebindOutputStats(*input, op); + } + if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { + auto input = Stats(*op.children[1]); + return input ? RelationStatisticsHelper::ProjectOutputStats(*input, input_layout.layout->bindings) + : optional(); + } + if (op.type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) { + return {}; + } + vector> children; + for (auto &child : op.children) { + auto stats = Stats(*child); + if (!stats) { + return {}; + } + children.push_back(*stats); + } + if (op.type == LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { + return RelationStatisticsHelper::ExtractAggregationStats(op.Cast(), children[0], statistics); + } + return RelationStatisticsHelper::ExtractOperatorStats(op, context, children, input_layout.layout->bindings); +} + +void DomainAnalysis::EnterOperator(LogicalOperator &op) { + if (op.type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) { + recursive_depth++; + } +} + +void DomainAnalysis::LeaveOperator(LogicalOperator &op) { + if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE || + op.type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) { + owners.erase(op.Cast().table_index); + scan_sources.erase(op.Cast().table_index); + } + if (op.type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) { + D_ASSERT(recursive_depth > 0); + recursive_depth--; + } +} + +bool DomainAnalysis::InRecursiveScope() const { + return recursive_depth != 0; +} + +optional_ptr DomainAnalysis::FindOwner(TableIndex index) const { + auto entry = owners.find(index); + return entry == owners.end() ? nullptr : optional_ptr(entry->second.get()); +} + +optional_ptr DomainAnalysis::FindMaterializedOwner(TableIndex index) const { + auto owner = FindOwner(index); + return owner && owner->type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE + ? &owner->Cast() + : nullptr; +} + +const DomainInput &DomainAnalysis::Get(const LogicalOperator &op) const { + return inputs.at(op); +} + +ColumnBinding DomainAnalysis::ResolveBinding(ColumnBinding binding) const { + auto entry = origins.find(binding); + return entry == origins.end() ? binding : entry->second; +} + +void DomainAnalysis::CaptureKeys(LogicalOperator &op, const DomainInput &input) { + if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { + if (!input.visible_references) { + return; + } + auto &ref = op.Cast(); + for (idx_t index = 0; index < ref.chunk_types.size(); index++) { + lineage.SetSource(ColumnBinding(ref.table_index, ProjectionIndex(index)), + ColumnBinding(ref.cte_index, ProjectionIndex(index))); + } + return; + } + if (!input.row_source || !input.layout || !Get(*input.row_source).visible_references) { + return; + } + if (op.type != LogicalOperatorType::LOGICAL_PROJECTION && + op.type != LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { + return; + } + auto &expressions = + op.type == LogicalOperatorType::LOGICAL_PROJECTION ? op.expressions : op.Cast().groups; + for (idx_t index = 0; index < expressions.size(); index++) { + auto child_key = ReferenceIndex(*expressions[index], *op.children[0], op.types[index]); + if (!child_key.IsValid()) { + continue; + } + auto source = KeySource(*op.children[0], child_key.GetIndex()); + if (source) { + lineage.SetSource(input.layout->bindings[index], *source); + } + } +} + +optional DomainAnalysis::KeySource(LogicalOperator &op, idx_t key) const { + auto &input = Get(op); + if (!input.row_source || key >= Bindings(op).size()) { + return {}; + } + auto source = lineage.Source(Bindings(op)[key]); + return source && source->table_index == input.row_source->cte_index ? source : optional(); +} + +void DomainAnalysis::PublishKeys(LogicalMaterializedCTE &cte) { + auto &definition = *cte.children[0]; + auto &input = Get(definition); + vector> sources; + for (idx_t index = 0; index < definition.types.size(); index++) { + sources.push_back(KeySource(definition, index)); + } + lineage.Publish(cte.table_index, + input.row_source ? optional(input.row_source->cte_index) : optional(), + !input.HasAllSourceRows(), sources); +} + +bool DomainAnalysis::ContainsKeys(LogicalOperator &original, const vector &original_keys, + LogicalOperator &demand, const vector &demand_keys) const { + auto &input = Get(original); + if (!input.row_source || !input.HasAllSourceRows() || original_keys.empty() || + original_keys.size() != demand_keys.size()) { + return false; + } + vector originals, demands; + for (idx_t index = 0; index < original_keys.size(); index++) { + auto original_key = KeySource(original, original_keys[index]); + auto demand_key = KeySource(demand, demand_keys[index]); + if (!original_key || !demand_key || + !original.types[original_keys[index]].EqualsIncludingCollation(demand.types[demand_keys[index]])) { + return false; + } + originals.push_back(*original_key); + demands.push_back(*demand_key); + } + return lineage.Contains(input.row_source->cte_index, originals, demands); +} + +const vector &DomainAnalysis::Bindings(LogicalOperator &op) const { + auto &input = Get(op); + return input.layout ? input.layout->bindings : empty_bindings; +} + +optional_idx DomainAnalysis::BindingIndex(LogicalOperator &op, ColumnBinding binding) const { + auto &input = Get(op); + if (!input.layout) { + return {}; + } + auto entry = input.layout->positions.find(binding); + return entry == input.layout->positions.end() ? optional_idx() : optional_idx(entry->second); +} + +bool DomainAnalysis::IsDistinctOn(LogicalOperator &op, const column_binding_set_t &keys) { + return distinctness.IsDistinctOn(op, keys); +} + +optional_idx DomainAnalysis::ReferenceIndex(const Expression &expression, LogicalOperator &op) const { + auto column = DomainExpression::DirectColumn(expression); + return column ? BindingIndex(op, column->Binding()) : optional_idx(); +} + +optional_idx DomainAnalysis::ReferenceIndex(const Expression &expression, LogicalOperator &op, + const LogicalType &type) const { + auto index = ReferenceIndex(expression, op); + return index.IsValid() && expression.GetReturnType().EqualsIncludingCollation(type) && + op.types[index.GetIndex()].EqualsIncludingCollation(type) + ? index + : optional_idx(); +} + +bool DomainAnalysis::HasRuntimeFilterTargets(LogicalAggregate &aggregate) { + if (!filter_targets) { + filter_targets = make_uniq(); + } + return filter_targets->HasTargets(aggregate); +} + +void DomainAnalysis::Invalidate(LogicalOperator &op) { + auto entry = inputs.find(op); + if (entry != inputs.end() && entry->second.layout && + (op.type == LogicalOperatorType::LOGICAL_PROJECTION || op.type == LogicalOperatorType::LOGICAL_CTE_REF || + op.type == LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY)) { + for (auto &binding : entry->second.layout->bindings) { + origins.erase(binding); + lineage.RemoveSource(binding); + value_bounds.erase(binding); + } + } + inputs.erase(op); + statistics.Invalidate(op); + if (filter_targets) { + filter_targets->Invalidate(op); + } +} + +void DomainAnalysis::Refresh(LogicalOperator &op) { + struct Frame { + explicit Frame(LogicalOperator &op_p) : op(op_p) { + } + reference op; + idx_t child = 0; + bool owns_scope = false; + }; + vector stack; + stack.emplace_back(op); + while (!stack.empty()) { + auto &frame = stack.back(); + auto &node = frame.op.get(); + if (inputs.find(node) != inputs.end()) { + stack.pop_back(); + continue; + } + if (frame.child < node.children.size()) { + if (frame.child == 1 && node.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { + auto &cte = node.Cast(); + frame.owns_scope = RegisterOwner(cte); + } + stack.emplace_back(*node.children[frame.child++]); + continue; + } + Summarize(node); + if (frame.owns_scope) { + owners.erase(node.Cast().table_index); + } + stack.pop_back(); + } +} + +void DomainAnalysis::InvalidateProjectionPath(LogicalOperator &root, LogicalOperator &target) { + optional_ptr current = root; + while (current.get() != &target) { + D_ASSERT(current->type == LogicalOperatorType::LOGICAL_PROJECTION); + Invalidate(*current); + current = *current->children[0]; + } + Invalidate(target); +} + +void DomainAnalysis::RemoveSubtree(LogicalOperator &op) { + vector> pending {op}; + while (!pending.empty()) { + auto &node = pending.back().get(); + pending.pop_back(); + if (registered_references.erase(node)) { + auto &count = reference_counts.at(node.Cast().cte_index); + D_ASSERT(count > 0); + count--; + } + Invalidate(node); + for (auto &child : node.children) { + if (!child) { + continue; + } + pending.push_back(*child); + } + } +} + +unique_ptr DomainAnalysis::ExpressionBounds(const Expression &expression) const { + auto column = DomainExpression::DirectColumn(expression); + if (column) { + auto entry = value_bounds.find(column->Binding()); + if (entry != value_bounds.end()) { + return entry->second->Copy().ToUnique(); + } + } + auto &type = expression.GetReturnType(); + if (type.id() != LogicalTypeId::DECIMAL || BaseStatistics::GetStatsType(type) != StatisticsType::NUMERIC_STATS) { + return nullptr; + } + auto stats = NumericStats::CreateUnknown(type).ToUnique(); + NumericStats::SetMin(*stats, Value::MinimumValue(type)); + NumericStats::SetMax(*stats, Value::MaximumValue(type)); + return stats; +} + +void DomainAnalysis::CaptureBounds(LogicalOperator &op, DomainInput &result) { + if (!result.layout) { + return; + } + auto remember = [&](ColumnBinding binding, unique_ptr bounds) { + if (bounds) { + value_bounds.insert_or_assign(binding, std::move(bounds)); + } + }; + if (op.type == LogicalOperatorType::LOGICAL_PROJECTION) { + for (idx_t index = 0; index < op.expressions.size(); index++) { + remember(result.layout->bindings[index], ExpressionBounds(*op.expressions[index])); + } + } else if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { + auto &ref = op.Cast(); + auto owner = FindMaterializedOwner(ref.cte_index); + if (!owner || ref.correlated_columns || ref.is_recurring) { + return; + } + auto &bindings = Bindings(*owner->children[0]); + if (bindings.size() != result.layout->bindings.size()) { + return; + } + for (idx_t index = 0; index < bindings.size(); index++) { + auto entry = value_bounds.find(bindings[index]); + if (entry != value_bounds.end()) { + remember(result.layout->bindings[index], entry->second->Copy().ToUnique()); + } + } + } else if (op.type == LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { + auto &aggregate = op.Cast(); + if (aggregate.grouping_sets.size() > 1 || !aggregate.grouping_functions.empty()) { + return; + } + for (idx_t index = 0; index < aggregate.groups.size(); index++) { + remember(ColumnBinding(aggregate.group_index, ProjectionIndex(index)), + ExpressionBounds(*aggregate.groups[index])); + } + result.aggregate_can_expand = true; + for (idx_t index = 0; index < aggregate.expressions.size(); index++) { + auto copy = aggregate.expressions[index]->Copy(); + unique_ptr bounds; + auto maximum = Get(*op.children[0]).maximum_rows; + if (copy->GetExpressionClass() == ExpressionClass::BOUND_AGGREGATE && maximum.IsValid()) { + auto &bound = copy->Cast(); + if (bound.Function().HasStatisticsCallback()) { + vector children; + for (auto &child : bound.GetChildren()) { + auto stats = ExpressionBounds(*child); + children.push_back(stats ? stats->Copy() + : BaseStatistics::CreateUnknown(child->GetReturnType())); + } + NodeStatistics rows(maximum.GetIndex(), maximum.GetIndex()); + AggregateStatisticsInput statistics(bound.BindInfoMutable(), children, &rows); + bounds = bound.Function().GetCallbacks().GetStatisticsCallback()(context, bound, statistics); + } + } + result.aggregate_can_expand &= !copy->CanThrow(); + if (!copy->CanThrow()) { + remember(ColumnBinding(aggregate.aggregate_index, ProjectionIndex(index)), std::move(bounds)); + } + } + } +} + +void DomainAnalysis::SummarizeStructure(LogicalOperator &op, DomainInput &result) { + switch (op.type) { + case LogicalOperatorType::LOGICAL_DUMMY_SCAN: + result.fixed_rows = 1; + break; + case LogicalOperatorType::LOGICAL_EMPTY_RESULT: + result.fixed_rows = 0; + break; + case LogicalOperatorType::LOGICAL_CHUNK_GET: { + auto &get = op.Cast(); + if (get.collection.get_owned_unique()) { + result.fixed_rows = get.collection->Count(); + } + break; + } + case LogicalOperatorType::LOGICAL_EXPRESSION_GET: + if (op.children.size() == 1 && op.children[0]->type == LogicalOperatorType::LOGICAL_DUMMY_SCAN) { + result.fixed_rows = op.Cast().expressions.size(); + } + break; + case LogicalOperatorType::LOGICAL_GET: + if (op.children.empty() && op.Cast().GetTable()) { + result.closed_scan = op.Cast(); + } + break; + case LogicalOperatorType::LOGICAL_PROJECTION: + case LogicalOperatorType::LOGICAL_FILTER: { + auto &child = inputs.at(*op.children[0]); + result.fixed_rows = child.fixed_rows; + result.maximum_rows = child.maximum_rows; + result.closed_scan = child.closed_scan; + if (op.type == LogicalOperatorType::LOGICAL_PROJECTION) { + bool safe_projection = true; + for (auto &expression : op.expressions) { + safe_projection &= !expression->CanThrow() && !expression->IsVolatile(); + } + if (safe_projection) { + result.aggregate = child.aggregate; + } + } + break; + } + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { + auto &aggregate = op.Cast(); + result.aggregate = aggregate; + if (aggregate.groups.empty() && aggregate.grouping_sets.size() <= 1) { + result.maximum_rows = 1; + } else if (!aggregate.groups.empty() && aggregate.grouping_functions.empty() && + (aggregate.grouping_sets.empty() || + (aggregate.grouping_sets.size() == 1 && + aggregate.grouping_sets[0].size() == aggregate.groups.size()))) { + result.maximum_rows = inputs.at(*op.children[0]).maximum_rows; + } + if (aggregate.grouping_sets.size() == 1 && !aggregate.grouping_sets[0].empty()) { + result.fixed_rows = inputs.at(*op.children[0]).fixed_rows; + } + break; + } + case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: + case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: { + auto &left = inputs.at(*op.children[0]); + auto &right = inputs.at(*op.children[1]); + auto type = op.type == LogicalOperatorType::LOGICAL_CROSS_PRODUCT ? JoinType::INNER + : op.Cast().join_type; + if (type == JoinType::SEMI || type == JoinType::ANTI) { + result.maximum_rows = left.maximum_rows; + } else if (type == JoinType::INNER) { + result.maximum_rows = + RelationStatisticsHelper::MultiplyCardinalityBounds(left.maximum_rows, right.maximum_rows); + } + break; + } + case LogicalOperatorType::LOGICAL_MATERIALIZED_CTE: + result.shared_source = true; + break; + default: + break; + } + if (!result.maximum_rows.IsValid()) { + result.maximum_rows = result.fixed_rows; + } +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_cost_model.cpp b/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_cost_model.cpp new file mode 100644 index 000000000..6ce900a34 --- /dev/null +++ b/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_cost_model.cpp @@ -0,0 +1,312 @@ +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_cost_model.hpp" +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_aggregate.hpp" +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_analysis.hpp" +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_restriction.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" + +#include +#include + +namespace duckdb { + +double DomainCostModel::EstimateDomainProductionWork(double key_rows, double distinct_key_rows) { + return DOMAIN_INPUT_WORK * key_rows + distinct_key_rows + DOMAIN_STARTUP_WORK; +} + +DomainCostModel::DomainCostModel(DomainAnalysis &analysis_p, LogicalAggregate &aggregate_p, double key_input_rows_p, + double source_read_write_work_p) + : analysis(analysis_p), extractor(analysis_p.Statistics()), aggregate(aggregate_p), + key_input_rows(key_input_rows_p), source_read_write_work(source_read_write_work_p) { +} + +double DomainCostModel::ExistenceBaseWork(JoinType type, const RelationStats &base, const RelationStats &domain, + const vector> &keys, double filter_work, + double indexed_scan_work) { + const auto base_rows = base.cardinality.GetDouble(); + const auto filter_cost = base_rows * EstimateRecoveryRowWork(filter_work, 0); + if (type == JoinType::MARK) { + return base_rows + filter_cost; + } + CardinalityValue fraction(1); + for (auto &key : keys) { + auto &probe = domain.columns[key.first]; + auto &build = base.columns[key.second]; + if (probe.total_domain.IsObserved() && build.total_domain.CanEstimateCoverage() && + !build.total_domain.distinct_count.IsZero()) { + fraction = MinValue(fraction, probe.current_domain.distinct_count / build.total_domain.distinct_count); + } + } + // Both alternatives process the base. Charge separately for losing a selective access path. + // Unknown membership supplies no scan discount; an index can still avoid the whole input. + return MaxValue(indexed_scan_work, base_rows * (1.0 - fraction.GetDouble())) + filter_cost; +} + +DomainChoice DomainCostModel::ChooseExistence(const RelationStats &outer, const RelationStats &domain, + double expression_work, double added_base_work, double released_work) { + const auto domain_rows = EstimateRecoveryDomainRows(domain); + const auto expanded_rows = MaxValue(0.0, outer.cardinality.GetDouble() - domain_rows); + const auto added = added_base_work + expanded_rows * EstimateRecoveryRowWork(expression_work, 0); + const auto saved = domain_rows + released_work; + if (!IsCheaper(added, saved)) { + return {}; + } + return {RestrictionAction::REMOVE, RecoveryAction::REMOVE, saved - added}; +} + +double DomainCostModel::EstimateReleasedWork(const DomainAnalysis &analysis, ReleasedDomainWork released) { + // Discount producer work relative to the hash-row work removed from the consumer. + auto production_work = released.production ? analysis.Get(*released.production).key_production_work : 0; + double source_values = 0; + if (released.source) { + auto stats = analysis.Stats(*released.source); + if (stats) { + source_values = stats->cardinality.GetDouble() * static_cast(stats->columns.size()); + } + } + return RELEASED_WORK_SCALE * (production_work + source_values); +} + +void DomainCostModel::SetReleasedWork(const ReleasedDomainWork &released) { + released_work = EstimateReleasedWork(analysis, released); +} + +bool DomainCostModel::IsCheaper(double candidate, double original) { + auto tolerance = COST_TOLERANCE * std::numeric_limits::epsilon() * MaxValue(original, candidate); + return std::isfinite(original) && std::isfinite(candidate) && original - candidate > tolerance; +} + +double DomainCostModel::EstimateAggregateWork(double input_rows, double group_count) const { + auto aggregate_work_per_row = static_cast(aggregate.expressions.size()) + 1; + return aggregate_work_per_row * input_rows + (aggregate_work_per_row + 1) * group_count; +} + +double DomainCostModel::EstimateSemiJoinWork(double input_rows, double output_rows, double key_rows) { + return key_rows + input_rows + output_rows; +} + +double DomainCostModel::EstimateRecoveryDomainRows(const RelationStats &domain) { + CardinalityValue distinct_count(0); + for (auto &column : domain.columns) { + // Key independence and range-based estimates can hide repeated tuples. + if (column.total_domain.IsObserved()) { + distinct_count = MaxValue(distinct_count, column.current_domain.distinct_count); + } + } + return MinValue(distinct_count, domain.cardinality).GetDouble(); +} + +double DomainCostModel::EstimateRecoveryRowWork(double expression_work, idx_t single_row_joins) { + // Scalar-expression scores and conditionless row processing are cheaper than hash-table row work. + return expression_work / EXPRESSION_WORK_PER_HASH_ROW + + static_cast(single_row_joins) * SINGLE_ROW_JOIN_WORK; +} + +double DomainCostModel::RecoverySavings(double outer_rows, const RelationStats &domain, double expression_work, + idx_t single_row_joins, double released_work) { + auto domain_rows = EstimateRecoveryDomainRows(domain); + auto saved_work = EstimateSemiJoinWork(domain_rows, domain_rows, domain_rows) + released_work; + auto added_work = + MaxValue(0.0, outer_rows - domain_rows) * EstimateRecoveryRowWork(expression_work, single_row_joins); + return std::isfinite(saved_work) && std::isfinite(added_work) ? saved_work - added_work + : -std::numeric_limits::infinity(); +} + +double DomainCostModel::EstimateAggregateWork(const RelationStats &input, + const vector &group_bindings) const { + vector domains; + RelationColumnStatsLookup columns(input); + for (auto &binding : group_bindings) { + auto column = columns.Find(binding); + if (!column) { + return std::numeric_limits::quiet_NaN(); + } + domains.push_back(column->current_domain); + } + auto group_count = RelationStatisticsHelper::EstimateDistinctCardinality(domains, input.cardinality); + return EstimateAggregateWork(input.cardinality.GetDouble(), group_count.GetDouble()); +} + +static optional EstimateRestrictionStats(LogicalComparisonJoin &restriction, const RelationStats &input, + const RelationStats &keys) { + auto estimate = RelationStatisticsHelper::EstimateSemiAntiJoinCardinality(restriction, input, keys); + if (!estimate.used_domain_evidence) { + return {}; + } + auto restricted = input; + RelationStatisticsHelper::ApplySemiAntiJoinStats(restriction, input, keys, restricted); + return restricted; +} + +optional DomainCostModel::EstimateRestriction(const DomainRestriction &existing, + const RelationStats &input, + const RelationStats &keys) { + auto &restriction = *existing.GetJoin(); + if (aggregate.groups.size() == 1) { + auto restricted = EstimateRestrictionStats(restriction, input, keys); + if (!restricted) { + return {}; + } + auto binding = existing.GetCondition(0).GetLHS().Cast().Binding(); + auto column = restricted->GetColumnStats(binding); + if (!column) { + return {}; + } + auto groups = + RelationStatisticsHelper::EstimateDistinctCardinality({column->current_domain}, restricted->cardinality); + return TupleDomainRestrictionEstimate {restricted->cardinality.GetDouble(), groups.GetDouble()}; + } + return RelationStatisticsHelper::EstimateTupleDomainRestriction(restriction, input, keys, extractor); +} + +DomainChoice DomainCostModel::ChooseInsertion(LogicalComparisonJoin &restriction, const RelationStats &keys) { + auto input = extractor.Extract(*aggregate.children[0]); + auto groups = extractor.Extract(aggregate); + if (!input || !groups) { + return {}; + } + auto restricted = EstimateRestrictionStats(restriction, *input, keys); + if (!restricted) { + return {}; + } + auto column = restricted->GetColumnStats(aggregate.groups[0]->Cast().Binding()); + if (!column) { + return {}; + } + // The inserted SEMI is the new aggregate input; old input-shape refinements no longer apply. + auto group_count = + RelationStatisticsHelper::EstimateDistinctCardinality({column->current_domain}, restricted->cardinality); + auto input_rows = input->cardinality.GetDouble(); + auto restricted_rows = restricted->cardinality.GetDouble(); + auto original_groups = groups->cardinality.GetDouble(); + auto restricted_groups = group_count.GetDouble(); + auto distinct_key_rows = keys.cardinality.GetDouble(); + // Cancel unchanged input/caller work and the consumer's identical output. + auto canonical = EstimateAggregateWork(input_rows, original_groups); + auto candidate = EstimateAggregateWork(restricted_rows, restricted_groups) + + EstimateSemiJoinWork(input_rows, restricted_rows, distinct_key_rows) + + EstimateDomainProductionWork(key_input_rows, distinct_key_rows) + source_read_write_work; + return IsCheaper(candidate, canonical) + ? DomainChoice {RestrictionAction::INSERT, RecoveryAction::KEEP, canonical - candidate} + : DomainChoice(); +} + +struct DomainCostModel::RestrictionCost { +public: + explicit RestrictionCost(const RelationStats &input_p) : input(input_p) { + } + +public: + //! Existing restriction estimates and aggregate key correspondence. + reference input; + optional restricted; + vector group_bindings; + + //! Baseline work against which all alternatives are compared. + double input_rows = 0; + double key_rows = 0; + double producer_work = 0; + double original_work = 0; + + //! Best alternative retains its work directly, avoiding cancellation through savings. + double best_work = 0; +}; + +optional DomainCostModel::CostRestriction(const DomainRestriction &existing) { + auto &restriction = *existing.GetJoin(); + auto input = extractor.Extract(*restriction.children[0]); + auto keys = extractor.Extract(*restriction.children[1]); + if (!input || !keys) { + return {}; + } + RestrictionCost cost(*input); + cost.restricted = EstimateRestriction(existing, *input, *keys); + cost.input_rows = input->cardinality.GetDouble(); + cost.key_rows = keys->cardinality.GetDouble(); + cost.producer_work = analysis.Get(*restriction.children[1]).key_production_work; + for (idx_t key = 0; key < aggregate.groups.size(); key++) { + cost.group_bindings.push_back(existing.GetCondition(key).GetLHS().Cast().Binding()); + } + cost.original_work = cost.restricted + ? EstimateAggregateWork(cost.restricted->rows, cost.restricted->groups) + + EstimateSemiJoinWork(cost.input_rows, cost.restricted->rows, cost.key_rows) + + cost.producer_work + released_work + : std::numeric_limits::quiet_NaN(); + cost.best_work = cost.original_work; + return cost; +} + +void DomainCostModel::ConsiderRestrictionWork(RestrictionCost &cost, double work, RestrictionAction action, + DomainChoice &choice) { + if (IsCheaper(work, cost.best_work)) { + choice = {action, RecoveryAction::KEEP, cost.original_work - work}; + cost.best_work = work; + } +} + +DomainChoice DomainCostModel::ChooseReplacement(const DomainRestriction &existing, RestrictionCost &cost, + LogicalAggregate &domain, const RelationStats &keys, + DomainKeyContainment containment) { + D_ASSERT(aggregate.groups.size() == 1); + auto &condition = existing.GetCondition(0); + LogicalComparisonJoin replacement(JoinType::SEMI); + replacement.conditions.emplace_back(condition.GetLHS().Copy(), DomainAggregate::GroupKey(domain), + condition.GetComparisonType()); + auto restricted = EstimateRestrictionStats(replacement, cost.input, keys); + auto key_rows = keys.cardinality.GetDouble(); + auto producer_work = EstimateDomainProductionWork(key_input_rows, key_rows) + source_read_write_work; + auto key_work = key_rows + producer_work; + if (!cost.restricted) { + // Containment can price key production without making a selectivity assumption. + auto old_work = cost.key_rows + cost.producer_work; + return containment == DomainKeyContainment::EXACT && IsCheaper(key_work, old_work) + ? DomainChoice {RestrictionAction::REPLACE, RecoveryAction::KEEP, old_work - key_work} + : DomainChoice(); + } + DomainChoice choice; + if (restricted) { + ConsiderRestrictionWork( + cost, + EstimateAggregateWork(*restricted, cost.group_bindings) + + EstimateSemiJoinWork(cost.input_rows, restricted->cardinality.GetDouble(), key_rows) + producer_work, + RestrictionAction::REPLACE, choice); + } else if (containment == DomainKeyContainment::EXACT) { + ConsiderRestrictionWork(cost, cost.original_work - cost.key_rows - cost.producer_work + key_work, + RestrictionAction::REPLACE, choice); + } + return choice; +} + +void DomainCostModel::ConsiderRemoval(const DomainRestriction &existing, RestrictionCost &cost, DomainChoice &choice) { + if (cost.restricted && existing.CanRemove()) { + // Charge NULL filters without taking credit for rows they remove. + ConsiderRestrictionWork(cost, + EstimateAggregateWork(cost.input, cost.group_bindings) + + static_cast(existing.NullFilterCount()) * cost.input_rows, + RestrictionAction::REMOVE, choice); + } +} + +DomainChoice DomainCostModel::ChooseRestriction(const DomainRestriction &existing) { + auto cost = CostRestriction(existing); + DomainChoice choice; + if (cost) { + ConsiderRemoval(existing, *cost, choice); + } + return choice; +} + +DomainChoice DomainCostModel::ChooseRestriction(const DomainRestriction &existing, LogicalAggregate &domain, + const RelationStats &keys, DomainKeyContainment containment) { + if (containment == DomainKeyContainment::SUPERSET && !existing.CanRemove()) { + return {}; + } + auto cost = CostRestriction(existing); + if (!cost) { + return {}; + } + auto choice = ChooseReplacement(existing, *cost, domain, keys, containment); + ConsiderRemoval(existing, *cost, choice); + return choice; +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_expression.cpp b/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_expression.cpp new file mode 100644 index 000000000..e8a08951b --- /dev/null +++ b/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_expression.cpp @@ -0,0 +1,60 @@ +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_expression.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/expression/expression_barrier.hpp" +#include "duckdb/planner/expression_iterator.hpp" + +namespace duckdb { + +optional_ptr DomainExpression::DirectColumn(const Expression &expression) { + if (expression.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { + return nullptr; + } + auto &column = expression.Cast(); + return column.Depth() == 0 ? &column : nullptr; +} + +bool DomainExpression::IsSafe(const Expression &expression, DomainExpressionScope scope) { + if (expression.CanThrow() || expression.IsVolatile() || ExpressionBarrier::Contains(expression)) { + return false; + } + vector> pending {expression}; + while (!pending.empty()) { + auto ¤t = pending.back().get(); + pending.pop_back(); + if (scope == DomainExpressionScope::NAMED_COLUMNS_ONLY && + (current.GetExpressionClass() == ExpressionClass::BOUND_REF || + current.GetExpressionClass() == ExpressionClass::BOUND_SUBQUERY || + (current.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF && + current.Cast().Depth() != 0))) { + return false; + } + if (current.GetExpressionClass() == ExpressionClass::BOUND_LAMBDA || + current.GetExpressionClass() == ExpressionClass::BOUND_LAMBDA_REF) { + // Lambda bodies have a separate binding scope and are not enumerated here. + return false; + } + if (current.GetExpressionClass() == ExpressionClass::BOUND_FUNCTION) { + auto &function = current.Cast().Function(); + if (function.RequiresOrderedExecution() || function.HasBindLambdaCallback()) { + return false; + } + } + ExpressionIterator::EnumerateChildren(current, [&](const Expression &child) { pending.push_back(child); }); + } + return true; +} + +bool DomainExpression::IsWorkReference(const Expression &expression) { + switch (expression.GetExpressionClass()) { + case ExpressionClass::BOUND_COLUMN_REF: + return expression.Cast().Depth() == 0; + case ExpressionClass::BOUND_CONSTANT: + case ExpressionClass::BOUND_PARAMETER: + return true; + default: + return false; + } +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_key_lineage.cpp b/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_key_lineage.cpp new file mode 100644 index 000000000..560b374a5 --- /dev/null +++ b/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_key_lineage.cpp @@ -0,0 +1,129 @@ +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_key_lineage.hpp" + +namespace duckdb { + +void DomainKeyLineage::SetSource(ColumnBinding binding, ColumnBinding source) { + key_sources.insert_or_assign(binding, source); +} + +optional DomainKeyLineage::Source(ColumnBinding binding) const { + auto entry = key_sources.find(binding); + return entry == key_sources.end() ? optional() : optional(entry->second); +} + +void DomainKeyLineage::RemoveSource(ColumnBinding binding) { + key_sources.erase(binding); +} + +void DomainKeyLineage::Publish(TableIndex producer, optional parent_id, bool filtered, + const vector> &sources) { + ProducerLineage lineage; + if (parent_id) { + auto parent = producer_lineage.find(*parent_id); + if (parent != producer_lineage.end()) { + lineage.depth = parent->second.depth + 1; + lineage.unfiltered_depth = filtered ? lineage.depth : parent->second.unfiltered_depth; + } + } + producer_lineage.emplace(producer, lineage); + for (idx_t index = 0; index < sources.size(); index++) { + KeyLineage key(ColumnBinding(producer, ProjectionIndex(index)), lineage.depth); + auto &source = sources[index]; + auto parent = source ? producer_keys.find(*source) : producer_keys.end(); + if (parent != producer_keys.end() && key_lineage[parent->second].depth + 1 == lineage.depth) { + key.ancestors.push_back(parent->second); + for (idx_t level = 0; level < key.ancestors.size(); level++) { + auto &ancestor = key_lineage[key.ancestors[level]]; + if (level >= ancestor.ancestors.size()) { + break; + } + key.ancestors.push_back(ancestor.ancestors[level]); + } + } + producer_keys.emplace(key.binding, key_lineage.size()); + key_lineage.push_back(std::move(key)); + } +} + +optional_idx DomainKeyLineage::LiftKey(idx_t key, idx_t depth) const { + D_ASSERT(depth <= key_lineage[key].depth); + auto distance = key_lineage[key].depth - depth; + for (idx_t level = 0; distance; level++, distance >>= 1) { + if (!(distance & 1)) { + continue; + } + if (level >= key_lineage[key].ancestors.size()) { + return {}; + } + key = key_lineage[key].ancestors[level]; + } + return key; +} + +optional_idx DomainKeyLineage::CommonKey(idx_t left, idx_t right) const { + auto depth = MinValue(key_lineage[left].depth, key_lineage[right].depth); + auto l = LiftKey(left, depth); + auto r = LiftKey(right, depth); + if (!l.IsValid() || !r.IsValid()) { + return {}; + } + left = l.GetIndex(); + right = r.GetIndex(); + if (left == right) { + return left; + } + auto levels = MinValue(key_lineage[left].ancestors.size(), key_lineage[right].ancestors.size()); + for (idx_t level = levels; level-- > 0;) { + auto &left_ancestors = key_lineage[left].ancestors; + auto &right_ancestors = key_lineage[right].ancestors; + if (level < left_ancestors.size() && level < right_ancestors.size() && + left_ancestors[level] != right_ancestors[level]) { + left = left_ancestors[level]; + right = right_ancestors[level]; + } + } + auto &left_ancestors = key_lineage[left].ancestors; + auto &right_ancestors = key_lineage[right].ancestors; + if (left_ancestors.empty() || right_ancestors.empty() || left_ancestors[0] != right_ancestors[0]) { + return {}; + } + return left_ancestors[0]; +} + +bool DomainKeyLineage::Contains(TableIndex producer_id, const vector &originals, + const vector &demands) const { + D_ASSERT(!originals.empty() && originals.size() == demands.size()); + auto producer = producer_lineage.find(producer_id); + if (producer == producer_lineage.end()) { + return false; + } + vector> keys; + auto depth = producer->second.depth; + for (idx_t index = 0; index < originals.size(); index++) { + auto left = producer_keys.find(originals[index]); + auto right = producer_keys.find(demands[index]); + if (left == producer_keys.end() || right == producer_keys.end()) { + return false; + } + auto common = CommonKey(left->second, right->second); + if (!common.IsValid()) { + return false; + } + depth = MinValue(depth, key_lineage[common.GetIndex()].depth); + keys.emplace_back(left->second, right->second); + } + if (depth < producer->second.unfiltered_depth) { + return false; + } + // All columns must agree at one producer to preserve tuple correlation. + for (auto &key : keys) { + auto left = LiftKey(key.first, depth); + auto right = LiftKey(key.second, depth); + if (!left.IsValid() || !right.IsValid() || left.GetIndex() != right.GetIndex()) { + return false; + } + } + return true; +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_optimizer.cpp b/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_optimizer.cpp new file mode 100644 index 000000000..1ebd57358 --- /dev/null +++ b/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_optimizer.cpp @@ -0,0 +1,153 @@ +#include "duckdb/optimizer/duplicate_eliminated_domain_optimizer.hpp" +#include "duckdb/optimizer/optimizer.hpp" +#include "duckdb/planner/expression/bound_aggregate_expression.hpp" +#include "duckdb/planner/expression/bound_window_expression.hpp" +#include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/planner/operator/logical_aggregate.hpp" +#include "duckdb/planner/operator/logical_comparison_join.hpp" + +namespace duckdb { + +DuplicateEliminatedDomainOptimizer::DuplicateEliminatedDomainOptimizer(Optimizer &optimizer_p) + : optimizer(optimizer_p), analysis(optimizer_p.context) { +} + +static bool IsDomainConsumer(const LogicalOperator &op) { + if (op.type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + return false; + } + switch (op.Cast().join_type) { + case JoinType::INNER: + case JoinType::LEFT: + case JoinType::SINGLE: + case JoinType::MARK: + case JoinType::SEMI: + case JoinType::ANTI: + return true; + default: + return false; + } +} + +static bool CanOptimizeDomains(const LogicalOperator &op) { + struct WorkItem { + public: + //! A grouped input or CTE reader below a consumer can supply a domain. + reference op; + bool under_consumer; + }; + vector pending {{op, false}}; + vector> expressions; + bool has_groups = false; + bool has_grouped_input = false; + bool has_shared_input = false; + while (!pending.empty()) { + auto item = pending.back(); + pending.pop_back(); + auto ¤t = item.op.get(); + if (current.type == LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY && + !current.Cast().groups.empty()) { + has_groups = true; + has_grouped_input |= item.under_consumer; + } + has_shared_input |= item.under_consumer && current.type == LogicalOperatorType::LOGICAL_CTE_REF; + LogicalOperatorVisitor::EnumerateExpressions( + current, [&](const unique_ptr *expression) { expressions.push_back(**expression); }); + while (!expressions.empty()) { + auto &expression = expressions.back().get(); + expressions.pop_back(); + optional_ptr function; + if (expression.GetExpressionClass() == ExpressionClass::BOUND_AGGREGATE) { + function = expression.Cast().Function(); + } else if (expression.GetExpressionClass() == ExpressionClass::BOUND_WINDOW) { + function = expression.Cast().AggregateFunction().get(); + } + if (function && function->GetName() == "bitstring_agg" && function->HasStatisticsCallback()) { + return false; + } + ExpressionIterator::EnumerateChildren(expression, + [&](const Expression &child) { expressions.push_back(child); }); + } + auto under_consumer = item.under_consumer || IsDomainConsumer(current); + for (auto child = current.children.rbegin(); child != current.children.rend(); ++child) { + pending.push_back({**child, under_consumer}); + } + } + return has_grouped_input || (has_groups && has_shared_input); +} + +void DuplicateEliminatedDomainOptimizer::Optimize(unique_ptr &op) { + // Implicit bitstring bounds depend on statistics, including those propagated through CTE references. + if (CanOptimizeDomains(*op)) { + analysis.Initialize(*op); + RewritePlan(op); + } +} + +bool DuplicateEliminatedDomainOptimizer::EnterOperator(LogicalOperator &op) { + analysis.EnterOperator(op); + return true; +} + +void DuplicateEliminatedDomainOptimizer::EnterChild(LogicalOperator &op, idx_t child_index) { + analysis.EnterChild(op, child_index); +} + +bool DuplicateEliminatedDomainOptimizer::OptimizeConsumer(unique_ptr &op, + BindingReplacementGraph &replacements) { + if (op->type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + return false; + } + auto &join = op->Cast(); + switch (join.join_type) { + case JoinType::MARK: + case JoinType::SEMI: + case JoinType::ANTI: + return TryOptimizeExistence(op); + case JoinType::INNER: + case JoinType::LEFT: + case JoinType::SINGLE: + break; + default: + return false; + } + if (analysis.InRecursiveScope()) { + return false; + } + if (TryPullUpOuterDomainJoin(op, replacements)) { + return true; + } + bool safe_conditions = true; + LogicalOperatorVisitor::EnumerateExpressions(join, [&](const unique_ptr *expression) { + safe_conditions &= !(*expression)->CanThrow() && !(*expression)->IsVolatile(); + }); + if (!safe_conditions || !join.expressions.empty() || !join.duplicate_eliminated_columns.empty()) { + return false; + } + for (idx_t index = 0; index < join.conditions.size(); index++) { + auto &condition = join.conditions[index]; + if (!condition.IsComparison() || (condition.GetComparisonType() != ExpressionType::COMPARE_EQUAL && + condition.GetComparisonType() != ExpressionType::COMPARE_NOT_DISTINCT_FROM)) { + continue; + } + if ((join.join_type == JoinType::INNER && TryOptimizeDomain(op, 0, index, replacements)) || + TryOptimizeDomain(op, 1, index, replacements)) { + return true; + } + } + return false; +} + +void DuplicateEliminatedDomainOptimizer::RewriteOperator(unique_ptr &op, + BindingReplacementGraph &replacements) { + analysis.Refresh(*op); + // Consumer rewrites preserve this node, possibly below a new parent. + auto &original = *op; + if (OptimizeConsumer(op, replacements)) { + analysis.Invalidate(original); + analysis.Refresh(*op); + } + analysis.LeaveOperator(original); +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_recovery.cpp b/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_recovery.cpp new file mode 100644 index 000000000..1d1413ac7 --- /dev/null +++ b/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_recovery.cpp @@ -0,0 +1,558 @@ +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_recovery.hpp" + +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_aggregate.hpp" +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_expression.hpp" +#include "duckdb/optimizer/duplicate_eliminated_domain_optimizer.hpp" +#include "duckdb/optimizer/expression_heuristics.hpp" +#include "duckdb/optimizer/optimizer.hpp" +#include "duckdb/planner/binder.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression/bound_comparison_expression.hpp" +#include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/planner/operator/logical_cteref.hpp" +#include "duckdb/planner/operator/logical_materialized_cte.hpp" + +namespace duckdb { + +DomainRecovery::DomainRecovery(DomainAnalysis &analysis_p, LogicalComparisonJoin &outer_p, + LogicalComparisonJoin &domain_join_p, vector> chain_p) + : analysis(analysis_p), outer(outer_p), domain_join(domain_join_p), chain(std::move(chain_p)) { +} + +static bool IsSingleRow(LogicalOperator &op) { + reference current = op; + while (current.get().type == LogicalOperatorType::LOGICAL_PROJECTION) { + current = *current.get().children[0]; + } + if (current.get().type != LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { + return false; + } + auto &aggregate = current.get().Cast(); + return aggregate.groups.empty() && aggregate.grouping_sets.size() <= 1; +} + +static bool PreservesDomainLayout(LogicalOperator &input, const vector &map, + const DomainAnalysis &analysis) { + if (map.empty()) { + return true; + } + if (map.size() != input.types.size()) { + return false; + } + auto &bindings = analysis.Bindings(input); + for (idx_t index = 0; index < bindings.size(); index++) { + if (bindings[map[index]] != bindings[index]) { + return false; + } + } + return true; +} + +//! Follow operators that compute exactly one row per row of the domain LEFT join. +static optional_ptr MatchRecoveryChain(LogicalComparisonJoin &outer, + vector> &chain, + const DomainAnalysis &analysis) { + if ((outer.join_type != JoinType::SINGLE && outer.join_type != JoinType::LEFT && + outer.join_type != JoinType::INNER) || + !outer.expressions.empty() || !outer.duplicate_eliminated_columns.empty() || outer.filter_pushdown || + outer.children[1]->type != LogicalOperatorType::LOGICAL_PROJECTION || + !PreservesDomainLayout(*outer.children[0], outer.left_projection_map, analysis)) { + return nullptr; + } + optional_ptr node = *outer.children[1]; + while (true) { + if (node->type == LogicalOperatorType::LOGICAL_PROJECTION) { + for (auto &expression : node->expressions) { + if (!DomainExpression::IsSafe(*expression, DomainExpressionScope::NAMED_COLUMNS_ONLY)) { + return nullptr; + } + } + } else if (node->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + auto &join = node->Cast(); + if (join.join_type != JoinType::LEFT || !join.expressions.empty() || + !join.duplicate_eliminated_columns.empty() || join.filter_pushdown || + !PreservesDomainLayout(*join.children[0], join.left_projection_map, analysis) || + !PreservesDomainLayout(*join.children[1], join.right_projection_map, analysis)) { + return nullptr; + } + if (!join.conditions.empty()) { + return join; + } + if (!IsSingleRow(*join.children[1])) { + return nullptr; + } + } else { + return nullptr; + } + chain.push_back(*node); + node = *node->children[0]; + } +} + +static optional_ptr ForwardedColumn(LogicalOperator &projection, ColumnBinding binding, + const DomainAnalysis &analysis) { + auto index = analysis.BindingIndex(projection, binding); + return index.IsValid() ? DomainExpression::DirectColumn(*projection.expressions[index.GetIndex()]) : nullptr; +} + +//! All RHS join keys must pass directly through projections and filters to a full grouping set. +static bool MatchesGroupedRHS(LogicalOperator &rhs, vector keys, DomainAnalysis &analysis) { + optional_ptr node = rhs; + while (node->type == LogicalOperatorType::LOGICAL_FILTER || node->type == LogicalOperatorType::LOGICAL_PROJECTION) { + if (node->type == LogicalOperatorType::LOGICAL_PROJECTION) { + for (auto &key : keys) { + auto column = ForwardedColumn(*node, key, analysis); + if (!column) { + return false; + } + key = column->Binding(); + } + } + node = *node->children[0]; + } + if (node->type != LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { + return false; + } + auto &aggregate = node->Cast(); + if (aggregate.groups.empty()) { + return aggregate.grouping_functions.empty() && + (aggregate.grouping_sets.empty() || + (aggregate.grouping_sets.size() == 1 && aggregate.grouping_sets[0].empty())); + } + return DomainAggregate::HasSimpleGrouping(aggregate) && + analysis.IsDistinctOn(aggregate, {keys.begin(), keys.end()}); +} + +//! Identify the CTE column forwarded by an unfiltered reader of the source. +static optional TraceSourceColumn(LogicalOperator &op, ColumnBinding binding, + const DomainAnalysis &analysis) { + auto &input = analysis.Get(op); + auto reader = input.row_source; + auto origin = analysis.ResolveBinding(binding); + if (!input.HasAllSourceRows() || !reader || reader->is_recurring || reader->correlated_columns || + origin.table_index != reader->table_index) { + return {}; + } + return ColumnBinding(reader->cte_index, origin.column_index); +} + +//! Every domain output compares one distinct group of the same materialized CTE, exactly once. +static optional> MatchDomainKeys(LogicalComparisonJoin &join, idx_t key_count, + DomainAnalysis &analysis) { + auto &domain = *join.children[0]; + auto &input = analysis.Get(domain); + auto &bindings = analysis.Bindings(domain); + if (key_count == 0 || bindings.size() != key_count || join.conditions.size() != key_count || + !input.HasAllSourceRows() || !input.domain) { + return {}; + } + auto &distinct = input.domain->aggregate.get(); + if (distinct.groups.size() != key_count) { + return {}; + } + vector sources(key_count), rhs_keys; + vector matched(key_count, false); + for (auto &condition : join.conditions) { + if (!condition.IsComparison() || (condition.GetComparisonType() != ExpressionType::COMPARE_EQUAL && + condition.GetComparisonType() != ExpressionType::COMPARE_NOT_DISTINCT_FROM)) { + return {}; + } + auto rhs = DomainExpression::DirectColumn(condition.GetRHS()); + auto index = analysis.ReferenceIndex(condition.GetLHS(), domain); + if (!index.IsValid() || !rhs) { + return {}; + } + auto group = analysis.ResolveBinding(bindings[index.GetIndex()]); + if (group.table_index != distinct.group_index || group.column_index.GetIndex() >= key_count || + matched[group.column_index.GetIndex()]) { + return {}; + } + matched[group.column_index.GetIndex()] = true; + auto column = DomainExpression::DirectColumn(*distinct.groups[group.column_index]); + auto origin = column ? TraceSourceColumn(*distinct.children[0], column->Binding(), analysis) : nullopt; + if (!origin) { + return {}; + } + sources[index.GetIndex()] = *origin; + rhs_keys.push_back(rhs->Binding()); + } + if (!MatchesGroupedRHS(*join.children[1], std::move(rhs_keys), analysis)) { + return {}; + } + return sources; +} + +struct RecoveryOuterKey { +public: + //! Trace the RHS binding down to the domain while retaining the corresponding outer column. + ColumnBinding binding; + ColumnBinding source; + idx_t demand_index; + bool sensitive; +}; + +struct ProjectionKeyUses { +public: + explicit ProjectionKeyUses(LogicalOperator &projection) { + vector> pending; + for (auto &expression : projection.expressions) { + pending.push_back(*expression); + } + while (!pending.empty()) { + auto &child = pending.back().get(); + pending.pop_back(); + switch (child.GetExpressionClass()) { + case ExpressionClass::BOUND_COLUMN_REF: { + auto &column = child.Cast(); + opaque |= column.Depth() != 0; + observations[column.Binding()]++; + break; + } + case ExpressionClass::BOUND_LAMBDA: + case ExpressionClass::BOUND_LAMBDA_REF: + case ExpressionClass::BOUND_SUBQUERY: + case ExpressionClass::BOUND_REF: + opaque = true; + break; + default: + break; + } + ExpressionIterator::EnumerateChildren(child, + [&](const Expression &expression) { pending.push_back(expression); }); + } + } + +public: + //! A sensitive key can only occur in its own direct passthrough expression. + column_binding_map_t observations; + bool opaque = false; +}; + +static bool TraceProjectedKeys(const vector> &chain, vector &keys, + const DomainAnalysis &analysis) { + const auto has_sensitive = + std::any_of(keys.begin(), keys.end(), [](const RecoveryOuterKey &key) { return key.sensitive; }); + for (auto &entry : chain) { + auto &node = entry.get(); + if (node.type != LogicalOperatorType::LOGICAL_PROJECTION) { + continue; + } + optional uses; + if (has_sensitive) { + uses.emplace(node); + if (uses->opaque) { + return false; + } + } + for (auto &key : keys) { + auto column = ForwardedColumn(node, key.binding, analysis); + if (!column || (key.sensitive && (!uses || uses->observations.at(column->Binding()) != 1))) { + return false; + } + key.binding = column->Binding(); + } + } + return true; +} + +bool DomainRecovery::MatchOuterKeys(const vector &source_keys) { + auto &demand = *outer.children[0]; + vector keys; + for (auto &condition : outer.conditions) { + if (!condition.IsComparison() || condition.GetComparisonType() != ExpressionType::COMPARE_NOT_DISTINCT_FROM) { + return false; + } + auto index = analysis.ReferenceIndex(condition.GetLHS(), demand); + auto rhs = DomainExpression::DirectColumn(condition.GetRHS()); + if (!index.IsValid() || !rhs) { + return false; + } + auto origin = TraceSourceColumn(demand, analysis.Bindings(demand)[index.GetIndex()], analysis); + auto &type = condition.GetLHS().GetReturnType(); + auto sensitive = !BoundComparisonExpression::EqualityPreservesValueRepresentation(type); + if (!origin || (sensitive && (!type.IsFloating() || analysis.BindingIndex(outer, rhs->Binding()).IsValid()))) { + return false; + } + keys.push_back({rhs->Binding(), *origin, index.GetIndex(), sensitive}); + } + if (!TraceProjectedKeys(chain, keys, analysis)) { + return false; + } + vector matched(keys.size(), false); + demand_indices.resize(keys.size()); + for (auto &key : keys) { + auto index = analysis.BindingIndex(*domain_join.children[0], key.binding); + if (!index.IsValid() || matched[index.GetIndex()] || key.source != source_keys[index.GetIndex()]) { + return false; + } + matched[index.GetIndex()] = true; + demand_indices[index.GetIndex()] = key.demand_index; + } + return true; +} + +void DomainRecovery::MatchAggregateRestriction() { + auto &input = *domain_join.children[1]; + vector aggregate_keys; + for (auto &condition : domain_join.conditions) { + auto index = analysis.ReferenceIndex(condition.GetRHS(), input); + if (!index.IsValid()) { + return; + } + aggregate_keys.push_back(index.GetIndex()); + } + auto match = DomainAggregate::Match(input, std::move(aggregate_keys), analysis); + if (!match) { + return; + } + vector demand_keys(demand_indices.size()); + vector comparisons(demand_indices.size()); + for (idx_t index = 0; index < domain_join.conditions.size(); index++) { + auto group = match->group_indices[index]; + auto &condition = domain_join.conditions[index]; + auto domain_key = analysis.ReferenceIndex(condition.GetLHS(), *domain_join.children[0]); + demand_keys[group] = demand_indices[domain_key.GetIndex()]; + comparisons[group] = condition.GetComparisonType(); + } + DomainRestriction candidate(analysis, match->aggregate, comparisons); + auto join = candidate.GetJoin(); + if (join && analysis.ReadsEarlierSources(*join->children[0], source) && + candidate.ContainsDemand(*outer.children[0], demand_keys)) { + restriction.emplace(AggregateRestriction {match->aggregate, std::move(candidate)}); + } +} + +optional DomainRecovery::Match(DomainAnalysis &analysis, LogicalComparisonJoin &outer) { + vector> chain; + auto domain_join = MatchRecoveryChain(outer, chain, analysis); + if (!domain_join) { + return {}; + } + auto sources = MatchDomainKeys(*domain_join, outer.conditions.size(), analysis); + if (!sources) { + return {}; + } + DomainRecovery result(analysis, outer, *domain_join, std::move(chain)); + result.source = sources->front().table_index; + if (!result.MatchOuterKeys(*sources)) { + return {}; + } + result.MatchAggregateRestriction(); + return result; +} + +//! Only a single direct reader is needed by the matched domain shapes. +static idx_t CountDomainReference(LogicalOperator &op, TableIndex source, const DomainAnalysis &analysis) { + auto reference = analysis.Get(op).single_reference; + return reference && reference->cte_index == source ? 1 : 0; +} + +//! Credit an inline domain, or a shared producer whose last readers disappear with the rewrite. +static ReleasedDomainWork FindReleasedDomainWork(LogicalOperator &demand, LogicalOperator &domain, + optional_ptr restriction_keys, TableIndex source, + const DomainAnalysis &analysis) { + ReleasedDomainWork released; + reference production = domain; + while (production.get().type == LogicalOperatorType::LOGICAL_PROJECTION) { + production = *production.get().children[0]; + } + auto released_source_references = + CountDomainReference(domain, source, analysis) + + (restriction_keys ? CountDomainReference(*restriction_keys, source, analysis) : 0); + bool production_stops = true; + if (production.get().type == LogicalOperatorType::LOGICAL_CTE_REF) { + auto index = production.get().Cast().cte_index; + auto owner = analysis.FindMaterializedOwner(index); + production_stops = owner && index != source && + analysis.ReferenceCount(index) == + CountDomainReference(domain, index, analysis) + + (restriction_keys ? CountDomainReference(*restriction_keys, index, analysis) : 0); + if (production_stops) { + production = *owner->children[0]; + released_source_references += CountDomainReference(production, source, analysis); + } + } + if (production_stops) { + released.production = production.get(); + } + auto owner = analysis.FindMaterializedOwner(source); + if (owner && owner->materialize != CTEMaterialize::CTE_MATERIALIZE_ALWAYS && + CountDomainReference(demand, source, analysis) == 1 && + analysis.ReferenceCount(source) == 1 + released_source_references) { + released.source = *owner->children[0]; + } + return released; +} + +optional DomainRecovery::RecoverySavings(const ReleasedDomainWork &released) const { + double expression_work = 0; + idx_t single_row_joins = 0; + for (auto &entry : chain) { + auto &node = entry.get(); + if (node.type == LogicalOperatorType::LOGICAL_PROJECTION) { + for (auto &expression : node.expressions) { + if (!DomainExpression::IsWorkReference(*expression)) { + expression_work += static_cast(ExpressionHeuristics::Cost(*expression)); + } + } + } else { + single_row_joins++; + } + } + if (expression_work == 0 && single_row_joins == 0) { + return 0.0; + } + auto outer_stats = analysis.Stats(*outer.children[0]); + auto domain_stats = analysis.Stats(*domain_join.children[0]); + if (!outer_stats || !domain_stats) { + return {}; + } + return DomainCostModel::RecoverySavings(outer_stats->cardinality.GetDouble(), *domain_stats, expression_work, + single_row_joins, + DomainCostModel::EstimateReleasedWork(analysis, released)); +} + +DomainChoice DomainRecovery::Choose() const { + auto &demand = *outer.children[0]; + auto &domain = *domain_join.children[0]; + auto collapse_released = FindReleasedDomainWork(demand, domain, nullptr, source, analysis); + auto recovery_savings = RecoverySavings(collapse_released); + DomainChoice choice; + if (recovery_savings) { + choice.Consider({RestrictionAction::KEEP, RecoveryAction::REMOVE, *recovery_savings}); + } + if (!restriction) { + return choice; + } + auto &existing = restriction->input; + DomainCostModel costs(analysis, restriction->aggregate); + choice.Consider(costs.ChooseRestriction(existing)); + if (recovery_savings) { + auto released = FindReleasedDomainWork(demand, domain, *existing.GetJoin()->children[1], source, analysis); + // Credit only the work released in addition to collapsing recovery alone. + if (collapse_released.production) { + released.production = nullptr; + } + if (collapse_released.source) { + released.source = nullptr; + } + costs.SetReleasedWork(released); + auto combined = costs.ChooseRestriction(existing); + if (combined.restriction == RestrictionAction::REMOVE) { + combined.recovery = RecoveryAction::REMOVE; + combined.savings += *recovery_savings; + choice.Consider(combined); + } + } + return choice; +} + +unique_ptr DomainRecovery::SpliceJoin(unique_ptr &op, + const BindingReplacementGraph &keys) { + auto top = std::move(outer.children[1]); + auto &slot = chain.back().get().children[0]; + D_ASSERT(slot.get() == &domain_join); + outer.left_projection_map.clear(); + outer.right_projection_map.clear(); + outer.children[1] = std::move(domain_join.children[1]); + analysis.RemoveSubtree(domain_join); + outer.conditions = std::move(domain_join.conditions); + ColumnBindingRewrite::ApplyToOperatorBindings(outer, keys); + outer.join_type = JoinType::LEFT; + outer.ResolveOperatorTypesFromChildren(); + slot = std::move(op); + return top; +} + +void DomainRecovery::PassOuterColumns(vector bindings, const BindingReplacementGraph &keys) { + auto &types = outer.children[0]->types; + for (auto entry = chain.rbegin(); entry != chain.rend(); ++entry) { + auto &node = entry->get(); + analysis.Invalidate(node); + if (node.type == LogicalOperatorType::LOGICAL_PROJECTION) { + ColumnBindingRewrite::ApplyToOperatorBindings(node, keys); + auto index = node.Cast().table_index; + for (idx_t column = 0; column < bindings.size(); column++) { + auto passed = ColumnBinding::PushExpression( + node.expressions, make_uniq(types[column], bindings[column])); + bindings[column] = ColumnBinding(index, passed); + } + } else { + auto &join = node.Cast(); + join.left_projection_map.clear(); + join.right_projection_map.clear(); + } + node.ResolveOperatorTypesFromChildren(); + } +} + +//! The lifted projection emits its original RHS columns followed by the appended outer columns. +static unique_ptr RestoreRecoveryLayout(Optimizer &optimizer, unique_ptr top, + idx_t rhs_count, const vector &rhs_map) { + auto table = top->Cast().table_index; + vector> expressions; + auto append = [&](ProjectionIndex index) { + expressions.push_back(make_uniq(top->types[index], ColumnBinding(table, index))); + }; + for (idx_t column = rhs_count; column < top->types.size(); column++) { + append(ProjectionIndex(column)); + } + if (rhs_map.empty()) { + for (auto index : ProjectionIndex::GetIndexes(rhs_count)) { + append(index); + } + } else { + for (auto index : rhs_map) { + append(index); + } + } + auto projection = make_uniq(optimizer.binder.GenerateTableIndex(), std::move(expressions)); + projection->children.push_back(std::move(top)); + projection->ResolveOperatorTypesFromChildren(); + return std::move(projection); +} + +void DomainRecovery::Apply(Optimizer &optimizer, unique_ptr &op, const DomainChoice &choice, + BindingReplacementGraph &replacements) { + D_ASSERT(choice.restriction == RestrictionAction::KEEP || choice.restriction == RestrictionAction::REMOVE); + if (restriction && choice.restriction == RestrictionAction::REMOVE) { + analysis.InvalidateProjectionPath(*domain_join.children[1], restriction->aggregate); + restriction->input.Remove(); + } + if (choice.recovery == RecoveryAction::KEEP) { + analysis.Invalidate(domain_join); + for (auto &node : chain) { + analysis.Invalidate(node.get()); + } + return; + } + auto old_bindings = analysis.Bindings(outer); + auto outer_bindings = analysis.Bindings(*outer.children[0]); + auto &domain_bindings = analysis.Bindings(*domain_join.children[0]); + BindingReplacementGraph keys; + for (idx_t index = 0; index < demand_indices.size(); index++) { + keys.Add(domain_bindings[index], outer_bindings[demand_indices[index]]); + } + auto rhs_map = std::move(outer.right_projection_map); + auto rhs_count = chain.front().get().expressions.size(); + auto top = SpliceJoin(op, keys); + PassOuterColumns(std::move(outer_bindings), keys); + op = RestoreRecoveryLayout(optimizer, std::move(top), rhs_count, rhs_map); + ColumnBindingRewrite::ReplaceOutputBindings(op, old_bindings, replacements); +} + +bool DuplicateEliminatedDomainOptimizer::TryPullUpOuterDomainJoin(unique_ptr &op, + BindingReplacementGraph &replacements) { + auto recovery = DomainRecovery::Match(analysis, op->Cast()); + if (!recovery) { + return false; + } + auto choice = recovery->Choose(); + if (choice.IsKeep()) { + return false; + } + recovery->Apply(optimizer, op, choice, replacements); + return true; +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_restriction.cpp b/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_restriction.cpp new file mode 100644 index 000000000..2e09545db --- /dev/null +++ b/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_restriction.cpp @@ -0,0 +1,155 @@ +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_restriction.hpp" +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_aggregate.hpp" +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_expression.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression/bound_operator_expression.hpp" +#include "duckdb/planner/operator/logical_filter.hpp" +#include "duckdb/parser/expression_map.hpp" + +namespace duckdb { + +DomainRestriction::DomainRestriction(DomainAnalysis &scopes, LogicalAggregate &aggregate_p, + ExpressionType consumer_comparison_p) + : DomainRestriction(scopes, aggregate_p, vector {consumer_comparison_p}) { +} + +DomainRestriction::DomainRestriction(DomainAnalysis &scopes, LogicalAggregate &aggregate_p, + const vector &comparisons) + : aggregate(aggregate_p), analysis(scopes), consumer_comparisons(comparisons) { + vector> keys; + for (auto &group : aggregate.groups) { + keys.push_back(*group); + } + D_ASSERT(keys.size() == comparisons.size()); + join = Find(*aggregate.children[0], keys); +} + +optional_ptr DomainRestriction::Find(LogicalOperator &input, + const vector> &keys) { + auto projected = keys; + optional_ptr current = input; + while (current->type == LogicalOperatorType::LOGICAL_PROJECTION) { + for (auto &key : projected) { + auto index = analysis.ReferenceIndex(key, *current); + if (!index.IsValid()) { + return nullptr; + } + key = *current->expressions[index.GetIndex()]; + } + projections.push_back(current->Cast()); + current = *current->children[0]; + } + if (current->type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + return nullptr; + } + auto &join = current->Cast(); + if (join.join_type != JoinType::SEMI || join.conditions.size() != projected.size() || !join.expressions.empty() || + !join.duplicate_eliminated_columns.empty() || join.filter_pushdown) { + return nullptr; + } + expression_map_t matched; + for (idx_t index = 0; index < join.conditions.size(); index++) { + auto &condition = join.conditions[index]; + if (!condition.IsComparison() || + (condition.GetComparisonType() != ExpressionType::COMPARE_EQUAL && + condition.GetComparisonType() != ExpressionType::COMPARE_NOT_DISTINCT_FROM) || + !analysis.ReferenceIndex(condition.GetLHS(), *join.children[0]).IsValid() || + !analysis.ReferenceIndex(condition.GetRHS(), *join.children[1]).IsValid() || + !matched.emplace(condition.GetLHS(), index).second) { + return nullptr; + } + } + for (auto &key : projected) { + auto entry = matched.find(key.get()); + if (entry == matched.end()) { + return nullptr; + } + conditions.push_back(entry->second); + matched.erase(entry); + } + return join; +} + +bool DomainRestriction::HasSimpleProjections() const { + for (auto &projection : projections) { + for (auto &expression : projection.get().expressions) { + if (!DomainExpression::IsWorkReference(*expression)) { + return false; + } + } + } + return true; +} + +bool DomainRestriction::CanRemove() const { + if (!HasSimpleProjections()) { + return false; + } + for (idx_t key = 0; key < conditions.size(); key++) { + if (FiltersNullKey(key) && GetCondition(key).GetLHS().GetReturnType().id() == LogicalTypeId::UNION) { + // An active NULL member fails equality but passes IS NOT NULL on the union. + return false; + } + } + return analysis.Get(aggregate).aggregate_can_expand; +} + +bool DomainRestriction::ContainsDemand(LogicalOperator &demand, const vector &demand_indices) const { + if (!join || !HasSimpleProjections()) { + return false; + } + if (!analysis.Get(*join->children[1]).can_change_readers) { + return false; + } + vector keys; + for (idx_t key = 0; key < demand_indices.size(); key++) { + auto &condition = GetCondition(key); + keys.push_back(analysis.ReferenceIndex(condition.GetRHS(), *join->children[1]).GetIndex()); + } + return analysis.ContainsKeys(*join->children[1], keys, demand, demand_indices); +} + +void DomainRestriction::Replace(unique_ptr &domain) { + D_ASSERT(conditions.size() == 1 && domain); + auto &restriction = *join; + restriction.conditions[0].RightReference() = DomainAggregate::GroupKey(*domain); + analysis.RemoveSubtree(*restriction.children[1]); + analysis.Invalidate(restriction); + for (auto &projection : projections) { + analysis.Invalidate(projection.get()); + } + analysis.Invalidate(aggregate); + restriction.children[1] = std::move(domain); +} + +void DomainRestriction::Remove() { + auto &restriction = *join; + auto &slot = projections.empty() ? aggregate.children[0] : projections.back().get().children[0]; + D_ASSERT(slot.get() == &restriction); + auto input = std::move(restriction.children[0]); + analysis.RemoveSubtree(restriction); + for (auto &projection : projections) { + analysis.Invalidate(projection.get()); + } + analysis.Invalidate(aggregate); + auto filter = make_uniq(); + for (idx_t key = 0; key < conditions.size(); key++) { + if (FiltersNullKey(key)) { + filter->expressions.push_back(make_uniq( + ExpressionType::OPERATOR_IS_NOT_NULL, LogicalType::BOOLEAN, GetCondition(key).GetLHS().Copy())); + } + } + filter->projection_map = std::move(restriction.left_projection_map); + if (!filter->expressions.empty() || !filter->projection_map.empty()) { + if (filter->expressions.empty() && input->has_estimated_cardinality) { + filter->SetEstimatedCardinality(input->estimated_cardinality); + } + filter->children.push_back(std::move(input)); + filter->ResolveOperatorTypesFromChildren(); + input = std::move(filter); + } + slot = std::move(input); + join = nullptr; +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_scan_source.cpp b/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_scan_source.cpp new file mode 100644 index 000000000..64a92376d --- /dev/null +++ b/src/duckdb/src/optimizer/duplicate_eliminated_domain/domain_scan_source.cpp @@ -0,0 +1,144 @@ +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_scan_source.hpp" +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_analysis.hpp" +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_expression.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/operator/logical_comparison_join.hpp" +#include "duckdb/planner/operator/logical_get.hpp" + +namespace duckdb { + +DomainScanSourceFinder::DomainScanSourceFinder(ClientContext &context_p, const DomainAnalysis &analysis_p, + const unique_ptr &definition_p) + : context(context_p), analysis(analysis_p), definition(definition_p) { +} + +const DomainScanSourceFinder::JoinSources &DomainScanSourceFinder::GetJoinSources(LogicalComparisonJoin &join) { + auto entry = join_sources.find(join); + if (entry != join_sources.end()) { + return entry->second; + } + JoinSources sources; + for (auto &condition : join.conditions) { + if (!condition.IsComparison() || condition.GetComparisonType() != ExpressionType::COMPARE_EQUAL) { + continue; + } + for (idx_t side = 0; side < 2; side++) { + auto &other = side == 0 ? condition.GetRHS() : condition.GetLHS(); + auto &candidate = side == 0 ? condition.GetLHS() : condition.GetRHS(); + auto column = DomainExpression::DirectColumn(other); + auto index = analysis.ReferenceIndex(candidate, *join.children[side], other.GetReturnType()); + if (column && index.IsValid()) { + auto &direction = side == 0 ? sources.left : sources.right; + direction.emplace(column->Binding(), EqualitySource {index.GetIndex(), other.GetReturnType()}); + } + } + } + return join_sources.emplace(join, std::move(sources)).first->second; +} + +vector DomainScanSourceFinder::GetChildren(const InputKey &input) { + vector children; + auto ¤t = input.input.get(); + auto key = input.key; + if (key >= analysis.Bindings(*current).size() || analysis.Get(*current).closed_scan) { + return children; + } + auto &type = current->types[key]; + BoundColumnRefExpression reference(type, analysis.Bindings(*current)[key]); + if (current->type == LogicalOperatorType::LOGICAL_PROJECTION || + current->type == LogicalOperatorType::LOGICAL_FILTER) { + auto &expression = + current->type == LogicalOperatorType::LOGICAL_PROJECTION ? *current->expressions[key] : reference; + auto index = analysis.ReferenceIndex(expression, *current->children[0], type); + if (index.IsValid()) { + children.emplace_back(current->children[0], index.GetIndex()); + } + return children; + } + if (current->type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + return children; + } + auto &join = current->Cast(); + if (join.join_type != JoinType::INNER || !join.duplicate_eliminated_columns.empty()) { + return children; + } + for (idx_t side = 0; side < 2; side++) { + auto index = analysis.ReferenceIndex(reference, *join.children[side]); + if (!index.IsValid()) { + auto &sources = GetJoinSources(join); + auto &direction = side == 0 ? sources.left : sources.right; + auto source = direction.find(reference.Binding()); + if (source != direction.end() && source->second.type.EqualsIncludingCollation(type)) { + index = source->second.key; + } + } + if (index.IsValid()) { + children.emplace_back(join.children[side], index.GetIndex()); + } + } + return children; +} + +DomainScanSource DomainScanSourceFinder::GetCandidate(const InputKey &input) { + auto ¤t = input.input.get(); + auto &facts = analysis.Get(*current); + if (input.key >= analysis.Bindings(*current).size() || !facts.closed_scan || !facts.safe || !facts.repeatable) { + return {}; + } + auto stats = analysis.Stats(*current); + if (!stats) { + return {}; + } + auto scan = facts.closed_scan; + auto entry = scan_rows.find(*scan); + if (entry == scan_rows.end()) { + entry = scan_rows.emplace(*facts.closed_scan, scan->EstimateSourceCardinality(context)).first; + } + return {current, input.key, stats->cardinality.GetDouble(), entry->second}; +} + +DomainScanSource DomainScanSourceFinder::Find(idx_t key) { + struct Frame { + public: + Frame(InputKey input_p, vector children_p, DomainScanSource candidate_p) + : input(input_p), children(std::move(children_p)), candidate(candidate_p) { + } + + public: + //! Pending child results are combined in the original left-to-right order. + InputKey input; + vector children; + DomainScanSource candidate; + idx_t child = 0; + }; + vector stack; + auto push = [&](const InputKey &input) { + stack.emplace_back(input, GetChildren(input), GetCandidate(input)); + }; + if (!results[*definition].count(key)) { + push(InputKey(definition, key)); + } + while (!stack.empty()) { + auto &frame = stack.back(); + if (frame.child == frame.children.size()) { + results[*frame.input.input.get()].emplace(frame.input.key, frame.candidate); + stack.pop_back(); + continue; + } + auto child = frame.children[frame.child]; + auto &cached = results[*child.input.get()]; + auto entry = cached.find(child.key); + if (entry == cached.end()) { + push(child); + continue; + } + auto &candidate = entry->second; + if (candidate.input && (!frame.candidate.input || candidate.rows < frame.candidate.rows)) { + frame.candidate = candidate; + } + frame.child++; + } + return results.at(*definition).at(key); +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/duplicate_eliminated_domain/existence_domain.cpp b/src/duckdb/src/optimizer/duplicate_eliminated_domain/existence_domain.cpp new file mode 100644 index 000000000..351d1c785 --- /dev/null +++ b/src/duckdb/src/optimizer/duplicate_eliminated_domain/existence_domain.cpp @@ -0,0 +1,391 @@ +#include "duckdb/optimizer/duplicate_eliminated_domain_optimizer.hpp" + +#include "duckdb/function/cast/cast_function_set.hpp" +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_cost_model.hpp" +#include "duckdb/optimizer/duplicate_eliminated_domain/domain_expression.hpp" +#include "duckdb/optimizer/expression_heuristics.hpp" +#include "duckdb/planner/expression/bound_cast_expression.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression/bound_comparison_expression.hpp" +#include "duckdb/planner/expression/bound_operator_expression.hpp" +#include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/planner/operator/logical_aggregate.hpp" +#include "duckdb/planner/operator/logical_comparison_join.hpp" +#include "duckdb/planner/operator/logical_cte.hpp" +#include "duckdb/planner/operator/logical_cteref.hpp" +#include "duckdb/planner/operator/logical_filter.hpp" +#include "duckdb/planner/operator/logical_projection.hpp" + +namespace duckdb { + +struct ExistenceMatch { +public: + void AddCondition(JoinCondition condition, idx_t domain_index, idx_t base_index) { + expression_work += static_cast(ExpressionHeuristics::Cost(condition.GetLHS())); + key_columns.emplace_back(domain_index, base_index); + conditions.push_back(std::move(condition)); + } + + double FilterWork() const { + double work = 0; + for (auto &filter : filters) { + work += static_cast(ExpressionHeuristics::Cost(*filter)); + } + return work; + } + +public: + //! The restriction, its duplicate-eliminated domain, and the consuming join. + optional_ptr restriction; + optional_ptr domain; + idx_t base_side = 0; + JoinType recovery = JoinType::INVALID; + + //! Predicates above the restriction and bindings connecting them to the probe. + vector> predicates; + BindingReplacementGraph aliases; + BindingReplacementGraph probe_keys; + + //! Conditions on the probe and filters retained on the base input. + vector conditions; + vector> filters; + + //! Matched domain/base positions and the expression work used in costing. + vector> key_columns; + double expression_work = 0; +}; + +//! Matches and rewrites one consumer of a duplicate-eliminated existence domain. +class ExistenceDomainUse { +public: + explicit ExistenceDomainUse(DomainAnalysis &analysis_p) : analysis(analysis_p) { + } + +public: + bool Apply(unique_ptr &op); + +private: + bool MatchRecovery(LogicalComparisonJoin &join, ExistenceMatch &match); + bool MatchRestriction(LogicalOperator &input, ExistenceMatch &match); + bool TransferPredicates(ExistenceMatch &match); + optional_ptr FindProbeKey(const Expression &expression, + const ExistenceMatch &match) const; + bool TransferKeyCondition(const Expression &predicate, const ColumnBindingLayout &base_layout, + const ColumnBindingLayout &domain_layout, ExistenceMatch &match); + DomainChoice Choose(LogicalComparisonJoin &join, const ExistenceMatch &match); + +private: + //! Published facts shared with the other domain consumers in this plan. + DomainAnalysis &analysis; +}; + +bool ExistenceDomainUse::MatchRestriction(LogicalOperator &input, ExistenceMatch &match) { + optional_ptr current = input; + while (current->type == LogicalOperatorType::LOGICAL_PROJECTION || + current->type == LogicalOperatorType::LOGICAL_FILTER) { + if (current->HasProjectionMap()) { + return false; + } + if (current->type == LogicalOperatorType::LOGICAL_PROJECTION) { + auto table = current->Cast().table_index; + for (idx_t index = 0; index < current->expressions.size(); index++) { + auto &expression = *current->expressions[index]; + auto column = DomainExpression::DirectColumn(expression); + if (column) { + match.aliases.Add(ColumnBinding(table, ProjectionIndex(index)), column->Binding()); + } else if (expression.GetExpressionClass() != ExpressionClass::BOUND_CONSTANT) { + return false; + } + } + } else { + for (auto &expression : current->expressions) { + match.predicates.push_back(*expression); + } + } + current = *current->children[0]; + } + if (current->children.size() != 2 || current->HasProjectionMap()) { + return false; + } + if (current->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + auto &join = current->Cast(); + if (join.join_type != JoinType::INNER || !join.expressions.empty() || join.filter_pushdown || + !join.duplicate_eliminated_columns.empty() || join.HasArbitraryConditions()) { + return false; + } + } else if (current->type != LogicalOperatorType::LOGICAL_CROSS_PRODUCT) { + return false; + } + auto &left = analysis.Get(*current->children[0]); + auto &right = analysis.Get(*current->children[1]); + if (left.domain) { + if (right.domain) { + return false; + } + match.base_side = 1; + match.domain = left.domain->aggregate.get(); + } else if (right.domain) { + match.base_side = 0; + match.domain = right.domain->aggregate.get(); + } else { + return false; + } + match.restriction = current; + auto &base = analysis.Get(*current->children[match.base_side]); + return base.safe && base.repeatable; +} + +bool ExistenceDomainUse::MatchRecovery(LogicalComparisonJoin &join, ExistenceMatch &match) { + if ((join.join_type != JoinType::MARK && join.join_type != JoinType::SEMI && join.join_type != JoinType::ANTI) || + !join.expressions.empty() || !join.duplicate_eliminated_columns.empty() || !join.right_projection_map.empty() || + join.filter_pushdown || !MatchRestriction(*join.children[1], match)) { + return false; + } + match.recovery = join.join_type; + if (!join.mark_types.empty() && join.mark_types.size() != join.conditions.size()) { + return false; + } + auto &outer = analysis.Get(*join.children[0]); + auto &domain_input = analysis.Get(*match.domain->children[0]); + if (!outer.row_source || outer.row_source->cte_index != domain_input.row_source->cte_index || + join.conditions.size() != match.domain->groups.size()) { + return false; + } + auto owner = analysis.FindOwner(outer.row_source->cte_index); + if (!owner || + (owner->type != LogicalOperatorType::LOGICAL_MATERIALIZED_CTE && + owner->type != LogicalOperatorType::LOGICAL_RECURSIVE_CTE) || + outer.row_source->correlated_columns || outer.row_source->is_recurring || + domain_input.row_source->correlated_columns || domain_input.row_source->is_recurring) { + return false; + } + vector seen(match.domain->groups.size(), false); + for (auto &condition : join.conditions) { + if (!condition.IsComparison() || condition.GetComparisonType() != ExpressionType::COMPARE_NOT_DISTINCT_FROM) { + return false; + } + auto left = DomainExpression::DirectColumn(condition.GetLHS()); + auto right = DomainExpression::DirectColumn(condition.GetRHS()); + if (!left || !right || !left->GetReturnType().EqualsIncludingCollation(right->GetReturnType())) { + return false; + } + auto key = analysis.ResolveBinding(match.aliases.Resolve(right->Binding())); + if (key.table_index != match.domain->group_index || key.column_index.GetIndex() >= seen.size()) { + return false; + } + auto index = key.column_index.GetIndex(); + auto &group = *match.domain->groups[index]; + auto source = analysis.ResolveBinding(DomainExpression::DirectColumn(group)->Binding()); + auto demand = analysis.ResolveBinding(left->Binding()); + if (seen[index] || source.table_index != domain_input.row_source->table_index || + demand.table_index != outer.row_source->table_index || source.column_index != demand.column_index || + !group.GetReturnType().EqualsIncludingCollation(left->GetReturnType())) { + return false; + } + seen[index] = true; + match.probe_keys.Add(key, left->Binding()); + } + return true; +} + +static unique_ptr CopyProbeKey(const Expression &expression, ExpressionType comparison) { + if (DomainExpression::DirectColumn(expression)) { + return expression.Copy(); + } + if (!BoundCastExpression::IsCast(expression)) { + return nullptr; + } + auto &cast = expression.Cast(); + if (!BoundCastExpression::HasValidBindData(cast) || + !DomainExpression::DirectColumn(BoundCastExpression::Child(cast))) { + return nullptr; + } + auto source_type = BoundCastExpression::SourceType(cast); + if (!BoundComparisonExpression::EqualityPreservesValueRepresentation(source_type) && + !(source_type.IsFloating() && cast.GetReturnType().IsIntegral())) { + return nullptr; + } + if (DomainExpression::IsSafe(cast) && !source_type.IsFloating()) { + return cast.Copy(); + } + if (!source_type.IsFloating() || !cast.GetReturnType().IsIntegral()) { + return nullptr; + } + auto &bound = BoundCastExpression::GetBoundCast(cast); + CastFunctionSet defaults; + auto input = GetCastFunctionInput::Default(); + auto expected = defaults.GetCastFunction(BoundCastExpression::SourceType(cast), cast.GetReturnType(), input); + if (bound.GetCastData() || bound.HasInitLocalState() || !bound.Equals(expected) || cast.IsVolatile()) { + return nullptr; + } + if (DomainExpression::IsSafe(cast)) { + return cast.Copy(); + } + if (comparison != ExpressionType::COMPARE_EQUAL) { + return nullptr; + } + return BoundCastExpression::Create(BoundCastExpression::Child(cast).Copy(), cast.GetReturnType(), bound.Copy(), + true); +} + +static vector> CollectRestrictionPredicates(const ExistenceMatch &match) { + vector> predicates; + for (auto &expression : match.predicates) { + predicates.push_back(expression.get().Copy()); + } + auto &restriction = *match.restriction; + if (restriction.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + for (auto &condition : restriction.Cast().conditions) { + predicates.push_back(BoundComparisonExpression::Create( + condition.GetComparisonType(), condition.GetLHS().Copy(), condition.GetRHS().Copy())); + } + } + return predicates; +} + +static bool UsesOnlyBaseColumns(const Expression &predicate, const ColumnBindingLayout &base_layout) { + bool base_only = true; + ExpressionIterator::VisitExpression(predicate, [&](const auto &column) { + base_only &= column.Depth() == 0 && base_layout.positions.count(column.Binding()); + }); + return base_only; +} + +optional_ptr ExistenceDomainUse::FindProbeKey(const Expression &expression, + const ExistenceMatch &match) const { + auto &key = BoundCastExpression::IsCast(expression) + ? BoundCastExpression::Child(expression.Cast()) + : expression; + auto column = DomainExpression::DirectColumn(key); + return column ? match.probe_keys.Find(analysis.ResolveBinding(column->Binding())) : nullptr; +} + +static bool PreserveMarkNulls(JoinCondition &condition, ExistenceMatch &match) { + if (condition.GetComparisonType() == ExpressionType::COMPARE_NOT_DISTINCT_FROM) { + return true; + } + auto &base = condition.GetRHS(); + if (base.GetReturnType().id() == LogicalTypeId::UNION) { + return false; + } + // Ordinary equality discarded NULL base keys before the original null-safe MARK join. + match.filters.push_back( + make_uniq(ExpressionType::OPERATOR_IS_NOT_NULL, LogicalType::BOOLEAN, base.Copy())); + condition.SetComparisonType(ExpressionType::COMPARE_NOT_DISTINCT_FROM); + return true; +} + +bool ExistenceDomainUse::TransferKeyCondition(const Expression &predicate, const ColumnBindingLayout &base_layout, + const ColumnBindingLayout &domain_layout, ExistenceMatch &match) { + auto type = predicate.GetExpressionType(); + if (!BoundComparisonExpression::IsComparison(predicate) || + (type != ExpressionType::COMPARE_EQUAL && type != ExpressionType::COMPARE_NOT_DISTINCT_FROM)) { + return false; + } + auto &comparison = predicate.Cast(); + auto &left = BoundComparisonExpression::Left(comparison); + auto &right = BoundComparisonExpression::Right(comparison); + auto left_key = FindProbeKey(left, match); + auto right_key = FindProbeKey(right, match); + if (bool(left_key) == bool(right_key)) { + return false; + } + auto base_column = DomainExpression::DirectColumn(left_key ? right : left); + if (!base_column) { + return false; + } + auto domain_binding = (left_key ? left_key : right_key)->old_binding; + auto domain_index = domain_layout.positions.find(domain_binding); + auto base_index = base_layout.positions.find(base_column->Binding()); + if (domain_index == domain_layout.positions.end() || base_index == base_layout.positions.end()) { + return false; + } + auto key = CopyProbeKey(left_key ? left : right, type); + if (!key) { + return false; + } + // The transferred key is a single column, optionally wrapped in the validated cast. + auto &column = BoundCastExpression::IsCast(*key) + ? BoundCastExpression::ChildMutable(key->Cast()) + : key; + column = column->Cast().WithBinding(match.probe_keys.Resolve(domain_binding)); + JoinCondition condition(std::move(key), base_column->Copy(), type); + if (match.recovery == JoinType::MARK && !PreserveMarkNulls(condition, match)) { + return false; + } + match.AddCondition(std::move(condition), domain_index->second, base_index->second); + return true; +} + +bool ExistenceDomainUse::TransferPredicates(ExistenceMatch &match) { + auto &base = analysis.Get(*match.restriction->children[match.base_side]); + auto &domain = analysis.Get(*match.domain); + if (!base.layout || !domain.layout) { + return false; + } + ColumnBindingReplacer chain_replacer(match.aliases); + auto predicates = CollectRestrictionPredicates(match); + for (auto &predicate : predicates) { + chain_replacer.VisitExpression(&predicate); + if (UsesOnlyBaseColumns(*predicate, *base.layout)) { + if (!DomainExpression::IsSafe(*predicate, DomainExpressionScope::NAMED_COLUMNS_ONLY)) { + return false; + } + match.filters.push_back(std::move(predicate)); + } else if (!TransferKeyCondition(*predicate, *base.layout, *domain.layout, match)) { + return false; + } + } + return !match.conditions.empty(); +} + +DomainChoice ExistenceDomainUse::Choose(LogicalComparisonJoin &join, const ExistenceMatch &match) { + auto outer = analysis.Stats(*join.children[0]); + auto domain = analysis.Stats(*match.domain); + auto base = analysis.Stats(*match.restriction->children[match.base_side]); + if (!outer || !domain || !base) { + return {}; + } + auto &input = analysis.Get(*match.restriction->children[1 - match.base_side]); + ReleasedDomainWork released; + if (input.IsInlineDomain()) { + released.production = match.domain.get_mutable(); + } + auto base_work = DomainCostModel::ExistenceBaseWork( + join.join_type, *base, *domain, match.key_columns, match.FilterWork(), + analysis.Get(*match.restriction->children[match.base_side]).indexed_scan_work); + return DomainCostModel::ChooseExistence(*outer, *domain, match.expression_work, base_work, + DomainCostModel::EstimateReleasedWork(analysis, released)); +} + +bool ExistenceDomainUse::Apply(unique_ptr &op) { + if (op->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { + auto &join = op->Cast(); + ExistenceMatch match; + if (MatchRecovery(join, match) && TransferPredicates(match) && !Choose(join, match).IsKeep()) { + auto base = std::move(match.restriction->children[match.base_side]); + analysis.RemoveSubtree(*join.children[1]); + if (!match.filters.empty()) { + auto filter = make_uniq(); + filter->expressions = std::move(match.filters); + filter->children.push_back(std::move(base)); + filter->ResolveOperatorTypesFromChildren(); + analysis.Summarize(*filter); + base = std::move(filter); + } + join.children[1] = std::move(base); + join.conditions = std::move(match.conditions); + join.mark_types.clear(); + join.ResolveOperatorTypesFromChildren(); + return true; + } + } + return false; +} + +bool DuplicateEliminatedDomainOptimizer::TryOptimizeExistence(unique_ptr &op) { + ExistenceDomainUse use(analysis); + return use.Apply(op); +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/duplicate_eliminated_domain_optimizer.cpp b/src/duckdb/src/optimizer/duplicate_eliminated_domain_optimizer.cpp deleted file mode 100644 index 0fac6b12b..000000000 --- a/src/duckdb/src/optimizer/duplicate_eliminated_domain_optimizer.cpp +++ /dev/null @@ -1,2086 +0,0 @@ -#include "duckdb/optimizer/duplicate_eliminated_domain_optimizer.hpp" - -#include "duckdb/common/operator/multiply.hpp" -#include "duckdb/storage/statistics/node_statistics.hpp" -#include "duckdb/storage/statistics/numeric_stats.hpp" -#include "duckdb/optimizer/aggregate_rewrite_helper.hpp" -#include "duckdb/optimizer/expression_heuristics.hpp" -#include "duckdb/optimizer/join_filter_pushdown_optimizer.hpp" -#include "duckdb/optimizer/optimizer.hpp" -#include "duckdb/optimizer/relation_statistics/relation_statistics_extractor.hpp" -#include "duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp" -#include "duckdb/planner/binder.hpp" -#include "duckdb/planner/expression/bound_aggregate_expression.hpp" -#include "duckdb/planner/expression/bound_columnref_expression.hpp" -#include "duckdb/planner/expression/bound_comparison_expression.hpp" -#include "duckdb/planner/expression/bound_operator_expression.hpp" -#include "duckdb/planner/expression/bound_window_expression.hpp" -#include "duckdb/planner/expression_iterator.hpp" -#include "duckdb/planner/logical_operator_deep_copy.hpp" -#include "duckdb/planner/filter/expression_filter.hpp" -#include "duckdb/planner/logical_operator_repeatability.hpp" -#include "duckdb/planner/operator/logical_aggregate.hpp" -#include "duckdb/planner/operator/logical_column_data_get.hpp" -#include "duckdb/planner/operator/logical_comparison_join.hpp" -#include "duckdb/planner/operator/logical_cteref.hpp" -#include "duckdb/planner/operator/logical_dummy_scan.hpp" -#include "duckdb/planner/operator/logical_expression_get.hpp" -#include "duckdb/planner/operator/logical_filter.hpp" -#include "duckdb/planner/operator/logical_get.hpp" -#include "duckdb/planner/operator/logical_materialized_cte.hpp" -#include "duckdb/planner/operator/logical_projection.hpp" -#include "duckdb/parser/expression_map.hpp" - -#include -#include - -namespace duckdb { - -DuplicateEliminatedDomainOptimizer::DuplicateEliminatedDomainOptimizer(Optimizer &optimizer_p) - : optimizer(optimizer_p) { -} - -static bool HasImplicitBitstringAggregate(const LogicalOperator &op) { - bool found = false; - LogicalOperatorVisitor::EnumerateExpressions(op, [&](const unique_ptr *expression) { - ExpressionIterator::VisitExpression(**expression, [&](const auto &aggregate) { - found |= aggregate.Function().GetName() == "bitstring_agg" && aggregate.Function().HasStatisticsCallback(); - }); - ExpressionIterator::VisitExpression(**expression, [&](const auto &window) { - auto &function = window.AggregateFunction(); - found |= function && function->GetName() == "bitstring_agg" && function->HasStatisticsCallback(); - }); - }); - if (found) { - return true; - } - for (auto &child : op.children) { - if (HasImplicitBitstringAggregate(*child)) { - return true; - } - } - return false; -} - -void DuplicateEliminatedDomainOptimizer::Optimize(unique_ptr &op) { - // Implicit bitstring bounds depend on statistics, including those propagated through CTE references. - if (!HasImplicitBitstringAggregate(*op)) { - VisitOperator(op); - op->ResolveOperatorTypes(); - } -} - -static bool IsWorkReference(const Expression &expression) { - switch (expression.GetExpressionClass()) { - case ExpressionClass::BOUND_COLUMN_REF: - return expression.Cast().Depth() == 0; - case ExpressionClass::BOUND_CONSTANT: - case ExpressionClass::BOUND_PARAMETER: - return true; - default: - return false; - } -} - -static optional_idx ReferenceIndex(const Expression &expression, LogicalOperator &input) { - if (expression.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF || - expression.Cast().Depth() != 0) { - return {}; - } - return AggregateRewriteHelper::GetDirectReferenceIndex(expression, input); -} - -static optional_idx ReferenceIndex(const Expression &expression, LogicalOperator &input, const LogicalType &type) { - if (!expression.GetReturnType().EqualsIncludingCollation(type)) { - return {}; - } - return ReferenceIndex(expression, input); -} - -static bool HasSimpleGrouping(const LogicalAggregate &aggregate) { - return !aggregate.groups.empty() && aggregate.grouping_functions.empty() && - (aggregate.grouping_sets.empty() || - (aggregate.grouping_sets.size() == 1 && aggregate.grouping_sets[0].size() == aggregate.groups.size())); -} - -//! One full grouping set preserves the directly referenced key and its comparison semantics. -static optional_idx GroupKeyIndex(LogicalAggregate &aggregate, idx_t key) { - if (!HasSimpleGrouping(aggregate) || key >= aggregate.groups.size()) { - return {}; - } - return ReferenceIndex(*aggregate.groups[key], *aggregate.children[0]); -} - -static optional_idx GroupKeyIndex(LogicalAggregate &aggregate, idx_t key, const LogicalType &type) { - auto index = GroupKeyIndex(aggregate, key); - if (!index.IsValid() || !aggregate.groups[key]->GetReturnType().EqualsIncludingCollation(type)) { - return {}; - } - return index; -} - -struct AggregateKeyMatch { - reference aggregate; - vector group_indices; -}; - -//! Trace output positions to the complete grouping key. -static optional FindAggregate(LogicalOperator &op, vector keys) { - if (op.type == LogicalOperatorType::LOGICAL_PROJECTION) { - for (auto &expression : op.expressions) { - if (expression->CanThrow() || expression->IsVolatile()) { - return {}; - } - } - for (auto &key : keys) { - if (key >= op.expressions.size()) { - return {}; - } - auto index = ReferenceIndex(*op.expressions[key], *op.children[0]); - if (!index.IsValid()) { - return {}; - } - key = index.GetIndex(); - } - return FindAggregate(*op.children[0], std::move(keys)); - } - if (op.type != LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { - return {}; - } - auto &aggregate = op.Cast(); - if (aggregate.preserve_input_order || aggregate.groups.size() != keys.size() || !HasSimpleGrouping(aggregate)) { - return {}; - } - vector matched(keys.size(), false); - for (auto key : keys) { - if (key >= keys.size() || matched[key] || - !ReferenceIndex(*aggregate.groups[key], *aggregate.children[0]).IsValid()) { - return {}; - } - matched[key] = true; - } - for (auto &expression : aggregate.expressions) { - bool supported = true; - ExpressionIterator::EnumerateChildren(*expression, - [&](const Expression &child) { supported &= IsWorkReference(child); }); - if (!supported) { - return {}; - } - } - if (!LogicalSubtreeIsRepeatable(aggregate)) { - return {}; - } - return AggregateKeyMatch {aggregate, std::move(keys)}; -} - -static optional_ptr FindAggregate(LogicalOperator &op, idx_t key) { - auto match = FindAggregate(op, vector {key}); - return match ? &match->aggregate.get() : nullptr; -} - -//! An upper bound from the actual closed input, not a cardinality estimate. -static optional_idx FixedRowCount(LogicalOperator &op) { - switch (op.type) { - case LogicalOperatorType::LOGICAL_DUMMY_SCAN: - return 1; - case LogicalOperatorType::LOGICAL_EMPTY_RESULT: - return 0; - case LogicalOperatorType::LOGICAL_CHUNK_GET: { - auto &get = op.Cast(); - return get.collection ? optional_idx(get.collection->Count()) : optional_idx(); - } - case LogicalOperatorType::LOGICAL_EXPRESSION_GET: - if (op.children.size() == 1 && op.children[0]->type == LogicalOperatorType::LOGICAL_DUMMY_SCAN) { - return op.Cast().expressions.size(); - } - return {}; - case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { - auto &aggregate = op.Cast(); - // Empty grouping sets can produce a row from empty input. - if (aggregate.grouping_sets.size() != 1 || aggregate.grouping_sets[0].empty()) { - return {}; - } - return FixedRowCount(*op.children[0]); - } - case LogicalOperatorType::LOGICAL_PROJECTION: - case LogicalOperatorType::LOGICAL_FILTER: - return FixedRowCount(*op.children[0]); - default: - return {}; - } -} - -static bool AppendFixedKey(vector>> &rows, const Expression &expression, - const LogicalType &type) { - if ((expression.GetExpressionClass() != ExpressionClass::BOUND_CONSTANT && - expression.GetExpressionClass() != ExpressionClass::BOUND_PARAMETER) || - !expression.GetReturnType().EqualsIncludingCollation(type)) { - return false; - } - vector> row; - row.push_back(expression.Copy()); - rows.push_back(std::move(row)); - return true; -} - -//! Copy keys already represented by expressions, leaving columnar inputs on the runtime path. -//! The caller's payload and its evaluation remain in place. -static bool CopyFixedKeys(LogicalOperator &op, idx_t key, const LogicalType &type, - vector>> &rows) { - switch (op.type) { - case LogicalOperatorType::LOGICAL_PROJECTION: { - auto &expression = *op.expressions[key]; - auto index = ReferenceIndex(expression, *op.children[0]); - if (index.IsValid()) { - return CopyFixedKeys(*op.children[0], index.GetIndex(), type, rows); - } - auto count = FixedRowCount(*op.children[0]); - return count.IsValid() && (count.GetIndex() == 0 || AppendFixedKey(rows, expression, type)); - } - case LogicalOperatorType::LOGICAL_FILTER: { - auto binding = op.GetColumnBindings()[key]; - BoundColumnRefExpression reference(type, binding); - auto index = ReferenceIndex(reference, *op.children[0]); - return index.IsValid() && CopyFixedKeys(*op.children[0], index.GetIndex(), type, rows); - } - case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { - auto index = GroupKeyIndex(op.Cast(), key, type); - return index.IsValid() && CopyFixedKeys(*op.children[0], index.GetIndex(), type, rows); - } - case LogicalOperatorType::LOGICAL_EXPRESSION_GET: { - if (!FixedRowCount(op).IsValid()) { - return false; - } - for (auto &row : op.Cast().expressions) { - if (!AppendFixedKey(rows, *row[key], type)) { - return false; - } - } - return true; - } - case LogicalOperatorType::LOGICAL_EMPTY_RESULT: - return true; - default: - return false; - } -} - -//! The old restriction must be proven to contain every demanded key. -static bool CopyExactFixedKeys(LogicalOperator &op, idx_t key, const LogicalType &type, - vector>> &rows) { - switch (op.type) { - case LogicalOperatorType::LOGICAL_PROJECTION: { - auto &expression = *op.expressions[key]; - auto index = ReferenceIndex(expression, *op.children[0], type); - if (index.IsValid()) { - return CopyExactFixedKeys(*op.children[0], index.GetIndex(), type, rows); - } - return op.children[0]->type == LogicalOperatorType::LOGICAL_DUMMY_SCAN && - AppendFixedKey(rows, expression, type); - } - case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { - auto index = GroupKeyIndex(op.Cast(), key, type); - return index.IsValid() && CopyExactFixedKeys(*op.children[0], index.GetIndex(), type, rows); - } - case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: - case LogicalOperatorType::LOGICAL_ANY_JOIN: { - auto &join = op.Cast(); - if (join.join_type != JoinType::LEFT) { - return false; - } - BoundColumnRefExpression reference(type, op.GetColumnBindings()[key]); - auto index = ReferenceIndex(reference, *op.children[0]); - return index.IsValid() && CopyExactFixedKeys(*op.children[0], index.GetIndex(), type, rows); - } - case LogicalOperatorType::LOGICAL_EXPRESSION_GET: - case LogicalOperatorType::LOGICAL_EMPTY_RESULT: - return CopyFixedKeys(op, key, type, rows); - default: - return false; - } -} - -enum class RestrictionAction { KEEP, REPLACE, REMOVE }; - -//! The chosen action and the work saved if the restriction is removed. -struct RestrictionDecision { - RestrictionAction action = RestrictionAction::KEEP; - double removal_savings = 0; -}; - -static unique_ptr CreateKeyDomain(Optimizer &optimizer, unique_ptr input, - unique_ptr key) { - auto domain = make_uniq(optimizer.binder.GenerateTableIndex(), - optimizer.binder.GenerateTableIndex(), vector>()); - domain->groups.push_back(std::move(key)); - domain->grouping_sets.push_back({ProjectionIndex(0)}); - domain->children.push_back(std::move(input)); - return domain; -} - -static unique_ptr DomainKey(const LogicalAggregate &domain) { - return make_uniq(domain.groups[0]->GetReturnType(), - ColumnBinding(domain.group_index, ProjectionIndex(0))); -} - -static optional_ptr -FindVisibleOwner(TableIndex index, const vector> &cte_scopes) { - for (auto &owner : cte_scopes) { - if (owner.get().table_index == index) { - return owner.get(); - } - } - return nullptr; -} - -//! Guaranteed bounds valid before and after expanding a domain; callbacks only modify expression copies. -class DomainAggregateBounds { -public: - DomainAggregateBounds(ClientContext &context_p, const vector> &scopes_p) - : context(context_p), scopes(scopes_p) { - } - - bool CanEvaluate(LogicalAggregate &aggregate) const { - for (auto &expression : aggregate.expressions) { - if (!expression->CanThrow()) { - continue; - } - if (expression->GetExpressionClass() != ExpressionClass::BOUND_AGGREGATE) { - return false; - } - auto copy = expression->Copy(); - column_binding_set_t visited; - AggregateStats(copy->Cast(), *aggregate.children[0], visited); - if (copy->CanThrow()) { - return false; - } - } - return true; - } - -private: - optional_idx MaxRows(LogicalOperator &input, unordered_set &visited) const { - switch (input.type) { - case LogicalOperatorType::LOGICAL_GET: { - auto &get = input.Cast(); - if (!get.children.empty() || !get.function.cardinality || !get.bind_data) { - return {}; - } - auto stats = get.function.cardinality(context, get.bind_data.get()); - return stats && stats->has_max_cardinality ? optional_idx(stats->max_cardinality) : optional_idx(); - } - case LogicalOperatorType::LOGICAL_PROJECTION: - case LogicalOperatorType::LOGICAL_FILTER: - return MaxRows(*input.children[0], visited); - case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { - auto &aggregate = input.Cast(); - if (aggregate.groups.empty() && aggregate.grouping_sets.size() <= 1) { - return 1; - } - return HasSimpleGrouping(aggregate) ? MaxRows(*input.children[0], visited) : optional_idx(); - } - case LogicalOperatorType::LOGICAL_CTE_REF: { - auto &reference = input.Cast(); - auto owner = FindVisibleOwner(reference.cte_index, scopes); - // Reject repeated definitions as well as cycles: a CTE DAG can otherwise require exponential work. - if (!owner || reference.correlated_columns || reference.is_recurring || - !visited.insert(reference.cte_index).second) { - return {}; - } - return MaxRows(*owner->children[0], visited); - } - case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: - case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: { - if (input.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { - auto &join = input.Cast(); - if (join.join_type == JoinType::SEMI || join.join_type == JoinType::ANTI) { - return MaxRows(*input.children[0], visited); - } - if (join.join_type != JoinType::INNER) { - return {}; - } - } - auto left = MaxRows(*input.children[0], visited); - auto right = MaxRows(*input.children[1], visited); - idx_t product; - return left.IsValid() && right.IsValid() && - TryMultiplyOperator::Operation(left.GetIndex(), right.GetIndex(), product) - ? optional_idx(product) - : optional_idx(); - } - default: - return FixedRowCount(input); - } - } - - unique_ptr AggregateStats(BoundAggregateExpression ©, LogicalOperator &input, - column_binding_set_t &visited) const { - if (!copy.Function().HasStatisticsCallback()) { - return nullptr; - } - unordered_set row_visits; - auto maximum = MaxRows(input, row_visits); - if (!maximum.IsValid()) { - return nullptr; - } - vector children; - for (auto &child : copy.GetChildren()) { - auto stats = ExpressionStats(*child, input, visited); - children.push_back(stats ? stats->Copy() : BaseStatistics::CreateUnknown(child->GetReturnType())); - } - NodeStatistics rows(maximum.GetIndex(), maximum.GetIndex()); - AggregateStatisticsInput statistics(copy.BindInfoMutable(), children, &rows); - return copy.Function().GetCallbacks().GetStatisticsCallback()(context, copy, statistics); - } - - unique_ptr ExpressionStats(const Expression &expression, LogicalOperator &input, - column_binding_set_t &visited) const { - if (expression.GetExpressionClass() == ExpressionClass::BOUND_AGGREGATE) { - auto copy = expression.Copy(); - auto stats = AggregateStats(copy->Cast(), input, visited); - return copy->CanThrow() ? nullptr : std::move(stats); - } - auto index = ReferenceIndex(expression, input); - if (index.IsValid()) { - switch (input.type) { - case LogicalOperatorType::LOGICAL_PROJECTION: { - auto &projected = *input.expressions[index.GetIndex()]; - if (!expression.GetReturnType().EqualsIncludingCollation(projected.GetReturnType())) { - return nullptr; - } - return ExpressionStats(projected, *input.children[0], visited); - } - case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { - auto &aggregate = input.Cast(); - if (HasSimpleGrouping(aggregate)) { - auto binding = expression.Cast().Binding(); - auto &source = aggregate.GetExpression(binding); - if (!expression.GetReturnType().EqualsIncludingCollation(source.GetReturnType())) { - return nullptr; - } - return ExpressionStats(source, *input.children[0], visited); - } - break; - } - case LogicalOperatorType::LOGICAL_CTE_REF: { - auto &reference = input.Cast(); - auto owner = FindVisibleOwner(reference.cte_index, scopes); - if (!owner || reference.is_recurring || reference.correlated_columns || - !visited.emplace(reference.cte_index, ProjectionIndex(index.GetIndex())).second) { - break; - } - auto bindings = owner->children[0]->GetColumnBindings(); - if (index.GetIndex() >= bindings.size() || index.GetIndex() >= reference.chunk_types.size() || - !expression.GetReturnType().EqualsIncludingCollation(reference.chunk_types[index.GetIndex()])) { - break; - } - BoundColumnRefExpression source(expression.GetReturnType(), bindings[index.GetIndex()]); - return ExpressionStats(source, *owner->children[0], visited); - } - case LogicalOperatorType::LOGICAL_FILTER: - case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: - case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: - for (auto &child : input.children) { - if (ReferenceIndex(expression, *child).IsValid()) { - return ExpressionStats(expression, *child, visited); - } - } - break; - default: - break; - } - } - // Declared DECIMAL endpoints remain valid without evaluating predicates or propagating statistics. - auto &type = expression.GetReturnType(); - if (type.id() != LogicalTypeId::DECIMAL) { - return nullptr; - } - auto stats = NumericStats::CreateUnknown(type).ToUnique(); - NumericStats::SetMin(*stats, Value::MinimumValue(type)); - NumericStats::SetMax(*stats, Value::MaximumValue(type)); - return stats; - } - -private: - ClientContext &context; - const vector> &scopes; -}; - -//! A matched input restriction and the projections between it and its aggregate. -//! Borrows the plan for one decision. Apply may destroy the matched join. -class DomainRestriction { -public: - DomainRestriction(ClientContext &context, const vector> &scopes, - LogicalAggregate &aggregate_p, ExpressionType consumer_comparison_p) - : DomainRestriction(context, scopes, aggregate_p, vector {consumer_comparison_p}) { - } - - DomainRestriction(ClientContext &context, const vector> &scopes, - LogicalAggregate &aggregate_p, const vector &comparisons) - : aggregate(aggregate_p), consumer_comparisons(comparisons), bounds(context, scopes) { - vector> keys; - for (auto &group : aggregate.groups) { - keys.push_back(*group); - } - D_ASSERT(keys.size() == comparisons.size()); - join = Find(*aggregate.children[0], keys); - } - -public: - optional_ptr GetJoin() const { - return join; - } - - bool HasSimpleProjections() const; - bool CanRemove() const; - const JoinCondition &GetCondition(idx_t key) const { - return join->conditions[conditions[key]]; - } - bool FiltersNullKey(idx_t key) const { - return GetCondition(key).GetComparisonType() == ExpressionType::COMPARE_EQUAL && - consumer_comparisons[key] == ExpressionType::COMPARE_NOT_DISTINCT_FROM; - } - idx_t NullFilterCount() const { - idx_t count = 0; - for (idx_t key = 0; key < conditions.size(); key++) { - count += FiltersNullKey(key); - } - return count; - } - void Apply(unique_ptr &domain, RestrictionAction action); - void Remove(); - -private: - optional_ptr Find(LogicalOperator &input, const vector> &keys); - -private: - LogicalAggregate &aggregate; - vector consumer_comparisons; - vector conditions; - DomainAggregateBounds bounds; - optional_ptr join; - vector> projections; -}; - -optional_ptr DomainRestriction::Find(LogicalOperator &input, - const vector> &keys) { - if (input.type == LogicalOperatorType::LOGICAL_PROJECTION) { - vector> projected; - for (auto &key : keys) { - auto index = ReferenceIndex(key, input); - if (!index.IsValid()) { - return nullptr; - } - projected.push_back(*input.expressions[index.GetIndex()]); - } - projections.push_back(input.Cast()); - return Find(*input.children[0], projected); - } - if (input.type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { - return nullptr; - } - auto &join = input.Cast(); - if (join.join_type != JoinType::SEMI || join.conditions.size() != keys.size() || !join.expressions.empty() || - !join.duplicate_eliminated_columns.empty() || join.filter_pushdown) { - return nullptr; - } - vector matched(keys.size(), false); - for (auto &key : keys) { - optional_idx found; - for (idx_t index = 0; index < join.conditions.size(); index++) { - auto &condition = join.conditions[index]; - if (matched[index] || !condition.IsComparison() || - (condition.GetComparisonType() != ExpressionType::COMPARE_EQUAL && - condition.GetComparisonType() != ExpressionType::COMPARE_NOT_DISTINCT_FROM) || - !key.get().Equals(condition.GetLHS()) || !ReferenceIndex(key, *join.children[0]).IsValid() || - !ReferenceIndex(condition.GetRHS(), *join.children[1]).IsValid()) { - continue; - } - found = index; - break; - } - if (!found.IsValid()) { - return nullptr; - } - matched[found.GetIndex()] = true; - conditions.push_back(found.GetIndex()); - } - return join; -} - -bool DomainRestriction::HasSimpleProjections() const { - for (auto &projection : projections) { - for (auto &expression : projection.get().expressions) { - if (!IsWorkReference(*expression)) { - return false; - } - } - } - return true; -} - -bool DomainRestriction::CanRemove() const { - if (!HasSimpleProjections()) { - return false; - } - return bounds.CanEvaluate(aggregate); -} - -void DomainRestriction::Apply(unique_ptr &domain, RestrictionAction action) { - auto &restriction = *join; - auto &condition = restriction.conditions[0]; - if (action == RestrictionAction::REPLACE) { - D_ASSERT(conditions.size() == 1 && domain); - condition.RightReference() = DomainKey(*domain); - restriction.children[1] = std::move(domain); - } else { - D_ASSERT(action == RestrictionAction::REMOVE); - Remove(); - } -} - -void DomainRestriction::Remove() { - auto &restriction = *join; - auto &slot = projections.empty() ? aggregate.children[0] : projections.back().get().children[0]; - D_ASSERT(slot.get() == &restriction); - auto input = std::move(restriction.children[0]); - auto filter = make_uniq(); - for (idx_t key = 0; key < conditions.size(); key++) { - if (FiltersNullKey(key)) { - filter->expressions.push_back(make_uniq( - ExpressionType::OPERATOR_IS_NOT_NULL, LogicalType::BOOLEAN, GetCondition(key).GetLHS().Copy())); - } - } - if (!filter->expressions.empty()) { - filter->children.push_back(std::move(input)); - input = std::move(filter); - } - slot = LogicalJoin::PromoteJoinSide(std::move(input), std::move(restriction.left_projection_map)); - join = nullptr; -} - -static double EstimateFixedDomainWork(double key_rows, double distinct_key_rows) { - return 2 * key_rows + distinct_key_rows + 3; -} - -static double EstimateKeyProductionWork(RelationStatsExtractor &extractor, LogicalOperator &input) { - if (input.type == LogicalOperatorType::LOGICAL_PROJECTION) { - return EstimateKeyProductionWork(extractor, *input.children[0]); - } - auto rows = extractor.Extract(input); - if (!rows) { - return 0; - } - if (input.type == LogicalOperatorType::LOGICAL_CTE_REF) { - // This reader disappears; its shared definition may still be used elsewhere. - return rows->cardinality.GetDouble() * static_cast(input.GetColumnBindings().size()); - } - if (input.type == LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { - auto child_rows = extractor.Extract(*input.children[0]); - if (child_rows) { - return EstimateFixedDomainWork(child_rows->cardinality.GetDouble(), rows->cardinality.GetDouble()) + - EstimateKeyProductionWork(extractor, *input.children[0]); - } - } - return 0; -} - -struct ReleasedDomainWork { - optional_ptr production; - optional_ptr source; -}; - -//! Compare alternatives using the same statistics source and domain-production costs. -//! Statistics are extracted for each decision, never retained across a plan rewrite. -class DomainCostModel { -public: - DomainCostModel(RelationStatsExtractor &extractor_p, LogicalAggregate &aggregate_p) - : extractor(extractor_p), aggregate(aggregate_p) { - } - - DomainCostModel(RelationStatsExtractor &extractor_p, LogicalAggregate &aggregate_p, double key_input_rows_p, - double source_read_write_work_p) - : extractor(extractor_p), aggregate(aggregate_p), key_input_rows(key_input_rows_p), - source_read_write_work(source_read_write_work_p) { - } - -public: - bool IsProfitable(LogicalComparisonJoin &restriction, LogicalOperator &domain); - //! Keeping and safe removal are always considered; a supplied domain also permits scalar replacement. - RestrictionDecision ChooseRestrictionAction(const DomainRestriction &existing, - optional_ptr domain, bool keys_may_expand = false); - //! Price only producers that the caller has proven will stop. - static double EstimateReleasedWork(RelationStatsExtractor &extractor, ReleasedDomainWork released); - void SetReleasedWork(const ReleasedDomainWork &released); - static bool IsRecoveryProfitable(double outer_rows, const RelationStats &domain, double expression_work, - idx_t single_row_joins, double released_work, double restriction_savings); - -private: - static bool IsCheaper(double candidate, double original); - static double EstimateSemiJoinWork(double input_rows, double output_rows, double key_rows); - static double EstimateRecoveryDomainRows(const RelationStats &domain); - static double EstimateRecoveryRowWork(double expression_work, idx_t single_row_joins); - double EstimateAggregateWork(double input_rows, double group_count) const; - double EstimateAggregateWork(const RelationStats &input, const vector &group_bindings) const; - optional EstimateRestriction(const DomainRestriction &existing, - const RelationStats &input, const RelationStats &keys); - -private: - RelationStatsExtractor &extractor; - LogicalAggregate &aggregate; - double key_input_rows = 0; - double source_read_write_work = 0; - double released_work = 0; -}; - -double DomainCostModel::EstimateReleasedWork(RelationStatsExtractor &extractor, ReleasedDomainWork released) { - // The unit of this model is one row through a hash table. Producing the key domain and materializing its source - // are counted per value by the formulas, but measured they cost about one such unit per source row each (0.25 to - // 0.46 of the formula for sources of 3 columns and 1 column), so the released work is scaled down. - static constexpr double RELEASED_WORK_SCALE = 0.3; - auto production_work = released.production ? EstimateKeyProductionWork(extractor, *released.production) : 0; - double source_values = 0; - if (released.source) { - auto stats = extractor.Extract(*released.source); - if (stats) { - source_values = - stats->cardinality.GetDouble() * static_cast(released.source->GetColumnBindings().size()); - } - } - return RELEASED_WORK_SCALE * (production_work + source_values); -} - -void DomainCostModel::SetReleasedWork(const ReleasedDomainWork &released) { - released_work = EstimateReleasedWork(extractor, released); -} - -bool DomainCostModel::IsCheaper(double candidate, double original) { - auto tolerance = 32 * std::numeric_limits::epsilon() * MaxValue(original, candidate); - return std::isfinite(original) && std::isfinite(candidate) && original - candidate > tolerance; -} - -double DomainCostModel::EstimateAggregateWork(double input_rows, double group_count) const { - auto aggregate_work_per_row = static_cast(aggregate.expressions.size()) + 1; - return aggregate_work_per_row * input_rows + (aggregate_work_per_row + 1) * group_count; -} - -double DomainCostModel::EstimateSemiJoinWork(double input_rows, double output_rows, double key_rows) { - return key_rows + input_rows + output_rows; -} - -double DomainCostModel::EstimateRecoveryDomainRows(const RelationStats &domain) { - CardinalityValue distinct_count(1); - for (auto &column : domain.columns) { - // Key independence and range-based estimates can hide repeated tuples. - if (column.total_domain.IsObserved()) { - distinct_count = MaxValue(distinct_count, column.current_domain.distinct_count); - } - } - return MinValue(distinct_count, domain.cardinality).GetDouble(); -} - -double DomainCostModel::EstimateRecoveryRowWork(double expression_work, idx_t single_row_joins) { - // Scalar-expression scores and conditionless row processing are cheaper than hash-table row work. - static constexpr double EXPRESSION_WORK_PER_HASH_ROW = 64; - static constexpr double SINGLE_ROW_JOIN_WORK = 0.3; - return expression_work / EXPRESSION_WORK_PER_HASH_ROW + - static_cast(single_row_joins) * SINGLE_ROW_JOIN_WORK; -} - -bool DomainCostModel::IsRecoveryProfitable(double outer_rows, const RelationStats &domain, double expression_work, - idx_t single_row_joins, double released_work, double restriction_savings) { - auto domain_rows = EstimateRecoveryDomainRows(domain); - if (outer_rows <= domain_rows) { - return true; - } - // Cancelling unchanged joins leaves one domain-sized build, probe and output. - auto saved_work = EstimateSemiJoinWork(domain_rows, domain_rows, domain_rows) + released_work + restriction_savings; - auto added_work = (outer_rows - domain_rows) * EstimateRecoveryRowWork(expression_work, single_row_joins); - return std::isfinite(saved_work) && std::isfinite(added_work) && added_work <= saved_work; -} - -double DomainCostModel::EstimateAggregateWork(const RelationStats &input, - const vector &group_bindings) const { - vector domains; - for (auto &binding : group_bindings) { - auto column = input.GetColumnStats(binding); - if (!column) { - return std::numeric_limits::quiet_NaN(); - } - domains.push_back(column->current_domain); - } - auto group_count = RelationStatisticsHelper::EstimateDistinctCardinality(domains, input.cardinality); - return EstimateAggregateWork(input.cardinality.GetDouble(), group_count.GetDouble()); -} - -static optional EstimateRestrictionStats(LogicalComparisonJoin &restriction, const RelationStats &input, - const RelationStats &keys) { - auto estimate = RelationStatisticsHelper::EstimateSemiAntiJoinCardinality(restriction, input, keys); - if (!estimate.used_domain_evidence) { - return {}; - } - auto restricted = input; - RelationStatisticsHelper::ApplySemiAntiJoinStats(restriction, input, keys, restricted); - return restricted; -} - -optional DomainCostModel::EstimateRestriction(const DomainRestriction &existing, - const RelationStats &input, - const RelationStats &keys) { - auto &restriction = *existing.GetJoin(); - if (aggregate.groups.size() == 1) { - auto restricted = EstimateRestrictionStats(restriction, input, keys); - if (!restricted) { - return {}; - } - auto binding = existing.GetCondition(0).GetLHS().Cast().Binding(); - auto column = restricted->GetColumnStats(binding); - if (!column) { - return {}; - } - auto groups = - RelationStatisticsHelper::EstimateDistinctCardinality({column->current_domain}, restricted->cardinality); - return TupleDomainRestrictionEstimate {restricted->cardinality.GetDouble(), groups.GetDouble()}; - } - return RelationStatisticsHelper::EstimateTupleDomainRestriction(restriction, input, keys, extractor); -} - -bool DomainCostModel::IsProfitable(LogicalComparisonJoin &restriction, LogicalOperator &domain) { - auto input = extractor.Extract(*aggregate.children[0]); - auto groups = extractor.Extract(aggregate); - auto keys = extractor.Extract(domain); - if (!input || !groups || !keys) { - return false; - } - auto restricted = EstimateRestrictionStats(restriction, *input, *keys); - if (!restricted) { - return false; - } - auto column = restricted->GetColumnStats(aggregate.groups[0]->Cast().Binding()); - if (!column) { - return false; - } - // The inserted SEMI is the new aggregate input; old input-shape refinements no longer apply. - auto group_count = - RelationStatisticsHelper::EstimateDistinctCardinality({column->current_domain}, restricted->cardinality); - auto input_rows = input->cardinality.GetDouble(); - auto restricted_rows = restricted->cardinality.GetDouble(); - auto original_groups = groups->cardinality.GetDouble(); - auto restricted_groups = group_count.GetDouble(); - auto distinct_key_rows = keys->cardinality.GetDouble(); - // Cancel unchanged input/caller work and the consumer's identical output. - auto canonical = EstimateAggregateWork(input_rows, original_groups); - auto candidate = EstimateAggregateWork(restricted_rows, restricted_groups) + - EstimateSemiJoinWork(input_rows, restricted_rows, distinct_key_rows) + - EstimateFixedDomainWork(key_input_rows, distinct_key_rows) + source_read_write_work; - return IsCheaper(candidate, canonical); -} - -RestrictionDecision DomainCostModel::ChooseRestrictionAction(const DomainRestriction &existing, - optional_ptr domain, - bool keys_may_expand) { - if (keys_may_expand && !existing.CanRemove()) { - return {}; - } - auto &restriction = *existing.GetJoin(); - auto input = extractor.Extract(*restriction.children[0]); - auto old_keys = extractor.Extract(*restriction.children[1]); - if (!input || !old_keys) { - return {}; - } - auto old_input = EstimateRestriction(existing, *input, *old_keys); - auto old_key_rows = old_keys->cardinality.GetDouble(); - auto old_producer_work = EstimateKeyProductionWork(extractor, *restriction.children[1]); - vector group_bindings; - for (idx_t key = 0; key < aggregate.groups.size(); key++) { - group_bindings.push_back(existing.GetCondition(key).GetLHS().Cast().Binding()); - } - auto input_rows = input->cardinality.GetDouble(); - auto best_work = old_input ? EstimateAggregateWork(old_input->rows, old_input->groups) + - EstimateSemiJoinWork(input_rows, old_input->rows, old_key_rows) + - old_producer_work + released_work - : std::numeric_limits::quiet_NaN(); - auto original_work = best_work; - auto action = RestrictionAction::KEEP; - auto consider = [&](double work, RestrictionAction alternative) { - if (IsCheaper(work, best_work)) { - best_work = work; - action = alternative; - } - }; - if (domain) { - D_ASSERT(aggregate.groups.size() == 1); - auto new_keys = extractor.Extract(*domain); - if (new_keys) { - auto &condition = existing.GetCondition(0); - LogicalComparisonJoin replacement(JoinType::SEMI); - replacement.conditions.emplace_back(condition.GetLHS().Copy(), DomainKey(*domain), - condition.GetComparisonType()); - auto restricted = EstimateRestrictionStats(replacement, *input, *new_keys); - auto distinct_key_rows = new_keys->cardinality.GetDouble(); - auto new_producer_work = - EstimateFixedDomainWork(key_input_rows, distinct_key_rows) + source_read_write_work; - auto new_key_work = distinct_key_rows + new_producer_work; - if (!old_input) { - // Containment can justify cheaper key production, but missing selectivity cannot justify removal. - if (!keys_may_expand && IsCheaper(new_key_work, old_key_rows + old_producer_work)) { - return {RestrictionAction::REPLACE, 0}; - } - return {}; - } - if (restricted) { - consider(EstimateAggregateWork(*restricted, group_bindings) + - EstimateSemiJoinWork(input_rows, restricted->cardinality.GetDouble(), distinct_key_rows) + - new_producer_work, - RestrictionAction::REPLACE); - } else if (!keys_may_expand) { - consider(best_work - old_key_rows - old_producer_work + new_key_work, RestrictionAction::REPLACE); - } - } - } - if (old_input && (keys_may_expand || existing.CanRemove())) { - // Charge each required NULL filter without taking credit for rows it removes. - consider(EstimateAggregateWork(*input, group_bindings) + - static_cast(existing.NullFilterCount()) * input_rows, - RestrictionAction::REMOVE); - } - return {action, action == RestrictionAction::REMOVE ? original_work - best_work : 0}; -} - -static bool HasSharedSource(LogicalOperator &op) { - if (op.type == LogicalOperatorType::LOGICAL_CTE_REF || op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { - return true; - } - for (auto &child : op.children) { - if (HasSharedSource(*child)) { - return true; - } - } - return false; -} - -static bool HasRuntimeFilterTargets(LogicalAggregate &aggregate) { - JoinFilterPushdownColumn column; - if (!JoinFilterPushdownUtil::PushdownJoinFilterExpression(*aggregate.groups[0], column)) { - return false; - } - vector columns; - columns.push_back(std::move(column)); - vector targets; - JoinFilterPushdownOptimizer::GetPushdownFilterTargets(*aggregate.children[0], columns, targets, - EqualityPropagation::ENABLED); - return !targets.empty(); -} - -static bool TryOptimizeRestriction(Optimizer &optimizer, LogicalAggregate &aggregate, - unique_ptr &domain, ExpressionType consumer_comparison, - const vector> &cte_scopes) { - DomainRestriction existing(optimizer.context, cte_scopes, aggregate, consumer_comparison); - auto restriction = existing.GetJoin(); - if (!restriction || HasSharedSource(*restriction->children[1])) { - return false; - } - auto &condition = restriction->conditions[0]; - auto key = ReferenceIndex(condition.GetRHS(), *restriction->children[1]).GetIndex(); - vector>> original_rows; - if (!CopyExactFixedKeys(*restriction->children[1], key, condition.GetRHS().GetReturnType(), original_rows)) { - return false; - } - expression_set_t original_keys; - for (auto &row : original_rows) { - original_keys.insert(*row[0]); - } - auto &fixed = domain->children[0]->Cast(); - for (auto &row : fixed.expressions) { - if (!original_keys.count(*row[0])) { - return false; - } - } - RelationStatsExtractor extractor(optimizer.context); - DomainCostModel costs(extractor, aggregate, static_cast(fixed.expressions.size()), 0); - auto action = costs.ChooseRestrictionAction(existing, *domain).action; - if (action == RestrictionAction::KEEP) { - return false; - } - existing.Apply(domain, action); - return true; -} - -static optional_ptr FindSharedKey(LogicalOperator &op, idx_t &key) { - if (op.type == LogicalOperatorType::LOGICAL_PROJECTION) { - auto index = ReferenceIndex(*op.expressions[key], *op.children[0]); - if (!index.IsValid()) { - return nullptr; - } - key = index.GetIndex(); - return FindSharedKey(*op.children[0], key); - } - if (op.type == LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { - auto &aggregate = op.Cast(); - auto index = GroupKeyIndex(aggregate, key); - if (!index.IsValid()) { - return nullptr; - } - key = index.GetIndex(); - return FindSharedKey(*op.children[0], key); - } - if (op.type != LogicalOperatorType::LOGICAL_CTE_REF) { - return nullptr; - } - auto &reference = op.Cast(); - return reference.is_recurring || reference.correlated_columns ? nullptr : &reference; -} - -struct RuntimeDomainSource { - optional_ptr input; - optional_ptr owner; - idx_t key = 0; -}; - -static bool ReferencesVisibleOwners(LogicalOperator &op, const vector> &cte_scopes) { - if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { - auto &cte = op.Cast(); - return !cte.is_recurring && !cte.correlated_columns && FindVisibleOwner(cte.cte_index, cte_scopes); - } - for (auto &child : op.children) { - if (!ReferencesVisibleOwners(*child, cte_scopes)) { - return false; - } - } - return true; -} - -static bool CanChangeRuntimeKeyReaders(LogicalOperator &op, const vector> &cte_scopes, - unordered_map &checked_owners) { - if (ClassifyLogicalOperatorRepeatability(op) != LogicalOperatorRepeatability::REPEATABLE) { - return false; - } - // A SINGLE join can throw when additional rows are evaluated. - if (op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN && - op.Cast().join_type == JoinType::SINGLE) { - return false; - } - // Reader changes and materialization can expose rows that later filters or limits would skip. - bool can_throw = false; - LogicalOperatorVisitor::EnumerateExpressions( - op, [&](unique_ptr *expression) { can_throw |= (*expression)->CanThrow(); }); - // Pushed-down scan predicates are not enumerated by the logical operator visitor. - if (op.type == LogicalOperatorType::LOGICAL_GET) { - for (auto &entry : op.Cast().table_filters) { - can_throw |= - ExpressionFilter::GetExpressionFilter(entry.Filter(), "CanChangeRuntimeKeyReaders").expr->CanThrow(); - } - } - if (can_throw) { - return false; - } - if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { - auto &cte = op.Cast(); - if (cte.is_recurring || cte.correlated_columns) { - return false; - } - auto checked = checked_owners.find(cte.cte_index); - if (checked != checked_owners.end()) { - return checked->second; - } - auto owner = FindVisibleOwner(cte.cte_index, cte_scopes); - if (!owner) { - return false; - } - checked_owners.emplace(cte.cte_index, false); - // Reader changes can expose or prevent producer filters and alter volatile payload evaluation. - auto repeatable = CanChangeRuntimeKeyReaders(*owner->children[0], cte_scopes, checked_owners); - checked_owners[cte.cte_index] = repeatable; - return repeatable; - } - if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { - // A materialized CTE inside the subtree is read by the subtree only: its definition is checked here, once, - // for all of its references. - if (!CanChangeRuntimeKeyReaders(*op.children[0], cte_scopes, checked_owners)) { - return false; - } - checked_owners[op.Cast().table_index] = true; - return CanChangeRuntimeKeyReaders(*op.children[1], cte_scopes, checked_owners); - } - for (auto &child : op.children) { - if (!CanChangeRuntimeKeyReaders(*child, cte_scopes, checked_owners)) { - return false; - } - } - return true; -} - -static bool TryGetRuntimeDomainSource(LogicalOperator &demand, idx_t demand_index, - const vector> &cte_scopes, - RuntimeDomainSource &source) { - source.key = demand_index; - auto shared = FindSharedKey(demand, source.key); - unordered_map checked_owners; - if (shared) { - auto owner = FindVisibleOwner(shared->cte_index, cte_scopes); - // Statistics can make the original reader filterable after this pass. - if (!owner || !CanChangeRuntimeKeyReaders(*shared, cte_scopes, checked_owners)) { - return false; - } - source.input = *owner->children[0]; - source.owner = owner; - } else { - if (!CanChangeRuntimeKeyReaders(demand, cte_scopes, checked_owners)) { - return false; - } - source.input = demand; - source.key = demand_index; - } - return true; -} - -using SharedKeyTuples = unordered_map>; - -static void TraceSharedKeys(LogicalOperator &op, vector keys, const vector &types, - const vector> &cte_scopes, bool allow_filters, - SharedKeyTuples &tuples) { - optional_ptr current = op; - while (true) { - auto bindings = current->GetColumnBindings(); - vector child_keys; - for (idx_t key = 0; key < keys.size(); key++) { - if (keys[key] >= bindings.size()) { - return; - } - optional_idx index; - switch (current->type) { - case LogicalOperatorType::LOGICAL_PROJECTION: - index = ReferenceIndex(*current->expressions[keys[key]], *current->children[0], types[key]); - break; - case LogicalOperatorType::LOGICAL_FILTER: { - if (!allow_filters) { - return; - } - BoundColumnRefExpression reference(types[key], bindings[keys[key]]); - index = ReferenceIndex(reference, *current->children[0]); - break; - } - case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: - index = GroupKeyIndex(current->Cast(), keys[key], types[key]); - break; - case LogicalOperatorType::LOGICAL_CTE_REF: { - auto &cte = current->Cast(); - if (keys[key] >= cte.chunk_types.size() || - !types[key].EqualsIncludingCollation(cte.chunk_types[keys[key]])) { - return; - } - index = keys[key]; - break; - } - default: - return; - } - if (!index.IsValid()) { - return; - } - child_keys.push_back(index.GetIndex()); - } - if (current->type == LogicalOperatorType::LOGICAL_CTE_REF) { - auto &cte = current->Cast(); - auto owner = FindVisibleOwner(cte.cte_index, cte_scopes); - if (!owner || cte.is_recurring || cte.correlated_columns || - !tuples.emplace(cte.cte_index, child_keys).second) { - return; - } - current = *owner->children[0]; - } else { - current = *current->children[0]; - } - keys = std::move(child_keys); - } -} - -static bool RuntimeRestrictionContainsDemand(const DomainRestriction &existing, LogicalOperator &demand, - const vector &demand_indices, - const vector> &cte_scopes) { - auto restriction = existing.GetJoin(); - if (!restriction || !existing.HasSimpleProjections()) { - return false; - } - unordered_map checked_owners; - if (!CanChangeRuntimeKeyReaders(*restriction->children[1], cte_scopes, checked_owners)) { - return false; - } - vector keys; - vector types; - for (idx_t key = 0; key < demand_indices.size(); key++) { - auto &condition = existing.GetCondition(key); - keys.push_back(ReferenceIndex(condition.GetRHS(), *restriction->children[1]).GetIndex()); - types.push_back(condition.GetRHS().GetReturnType()); - } - SharedKeyTuples demanded_keys, original_keys; - TraceSharedKeys(demand, demand_indices, types, cte_scopes, true, demanded_keys); - TraceSharedKeys(*restriction->children[1], std::move(keys), types, cte_scopes, false, original_keys); - bool contains_demand = false; - for (auto &entry : original_keys) { - auto found = demanded_keys.find(entry.first); - contains_demand |= found != demanded_keys.end() && found->second == entry.second; - } - return contains_demand; -} - -static RestrictionAction TryOptimizeRuntimeRestriction(ClientContext &context, DomainCostModel &costs, - LogicalAggregate &aggregate, LogicalOperator &demand, - idx_t demand_index, unique_ptr &domain, - ExpressionType consumer_comparison, - const vector> &cte_scopes, - bool keys_may_expand = false) { - DomainRestriction existing(context, cte_scopes, aggregate, consumer_comparison); - if (!RuntimeRestrictionContainsDemand(existing, demand, {demand_index}, cte_scopes)) { - return RestrictionAction::KEEP; - } - auto action = costs.ChooseRestrictionAction(existing, domain.get(), keys_may_expand).action; - if (action != RestrictionAction::KEEP) { - existing.Apply(domain, action); - } - return action; -} - -struct ScanKeySource { - optional_ptr> input; - idx_t key = 0; - double rows = 0; - double scan_rows = 0; -}; - -static optional_ptr FindClosedScan(LogicalOperator &input) { - if (input.type == LogicalOperatorType::LOGICAL_FILTER || input.type == LogicalOperatorType::LOGICAL_PROJECTION) { - return FindClosedScan(*input.children[0]); - } - if (input.type != LogicalOperatorType::LOGICAL_GET || !input.children.empty()) { - return nullptr; - } - auto &get = input.Cast(); - return get.GetTable() ? &get : nullptr; -} - -//! An INNER equality lets either input supply a superset of the joined key domain. -static void FindScanKeySource(const unique_ptr &input, idx_t key, const LogicalType &type, - RelationStatsExtractor &extractor, ClientContext &context, ScanKeySource &source) { - if (auto scan = FindClosedScan(*input)) { - auto stats = extractor.Extract(*input); - if (stats && (!source.input || stats->cardinality.GetDouble() < source.rows)) { - source.input = input; - source.key = key; - source.rows = stats->cardinality.GetDouble(); - source.scan_rows = static_cast(scan->EstimateSourceCardinality(context)); - } - return; - } - if (input->type == LogicalOperatorType::LOGICAL_PROJECTION) { - auto index = ReferenceIndex(*input->expressions[key], *input->children[0], type); - if (index.IsValid()) { - FindScanKeySource(input->children[0], index.GetIndex(), type, extractor, context, source); - } - return; - } - if (input->type == LogicalOperatorType::LOGICAL_FILTER) { - BoundColumnRefExpression reference(type, input->GetColumnBindings()[key]); - auto index = ReferenceIndex(reference, *input->children[0]); - if (index.IsValid()) { - FindScanKeySource(input->children[0], index.GetIndex(), type, extractor, context, source); - } - return; - } - if (input->type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { - return; - } - auto &join = input->Cast(); - if (join.join_type != JoinType::INNER || !join.duplicate_eliminated_columns.empty()) { - return; - } - BoundColumnRefExpression reference(type, join.GetColumnBindings()[key]); - for (idx_t side = 0; side < 2; side++) { - auto index = ReferenceIndex(reference, *join.children[side]); - for (auto &condition : join.conditions) { - if (index.IsValid()) { - break; - } - if (!condition.IsComparison() || condition.GetComparisonType() != ExpressionType::COMPARE_EQUAL) { - continue; - } - auto &other = side == 0 ? condition.GetRHS() : condition.GetLHS(); - auto &candidate = side == 0 ? condition.GetLHS() : condition.GetRHS(); - if (reference.Equals(other)) { - index = ReferenceIndex(candidate, *join.children[side], type); - } - } - if (index.IsValid()) { - FindScanKeySource(join.children[side], index.GetIndex(), type, extractor, context, source); - } - } -} - -//! A join whose RHS recovers the keys without a group of a correlated aggregate: a LEFT join of the -//! duplicate-eliminated keys of the join's own LHS against the grouped aggregate (FindOuterDomainJoin). -struct OuterDomainJoin { - //! The number of operators between the join and the LEFT join against the key domain - idx_t chain_length = 0; - //! The LEFT join against the key domain - optional_ptr domain_join; - //! Per key: the binding of the domain column and the binding of the LHS column it duplicates - vector> keys; - //! Demand indices and comparisons in aggregate grouping-key order - vector demand_indices; - vector comparisons; - //! The materialized CTE both the LHS and the key domain read - TableIndex source; - //! The aggregate, when the restriction decision can handle the operators above it - optional_ptr aggregate; -}; - -//! The (CTE, column) an output column reads from a materialized CTE through plain projections. With `distinct` the -//! column must pass exactly one duplicate elimination of `group_count` groups (inline or as a visible CTE); `group` -//! is the group of that duplicate elimination the column reads. -static bool TraceSourceColumn(LogicalOperator &op, idx_t column, - const vector> &cte_scopes, bool distinct, - idx_t group_count, TableIndex &source, idx_t &source_column, idx_t &group) { - reference current = op; - bool seen_distinct = false; - while (true) { - auto &node = current.get(); - switch (node.type) { - case LogicalOperatorType::LOGICAL_PROJECTION: { - if (column >= node.expressions.size()) { - return false; - } - auto index = ReferenceIndex(*node.expressions[column], *node.children[0]); - if (!index.IsValid()) { - return false; - } - column = index.GetIndex(); - current = *node.children[0]; - break; - } - case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { - auto &aggregate = node.Cast(); - if (!distinct || seen_distinct || !aggregate.expressions.empty() || - aggregate.groups.size() != group_count) { - return false; - } - auto index = GroupKeyIndex(aggregate, column); - if (!index.IsValid()) { - return false; - } - group = column; - column = index.GetIndex(); - seen_distinct = true; - current = *node.children[0]; - break; - } - case LogicalOperatorType::LOGICAL_CTE_REF: { - auto &reference = node.Cast(); - if (reference.is_recurring || reference.correlated_columns) { - return false; - } - if (distinct == seen_distinct) { - source = reference.cte_index; - source_column = column; - return true; - } - auto owner = FindVisibleOwner(reference.cte_index, cte_scopes); - if (!owner) { - return false; - } - current = *owner->children[0]; - break; - } - default: - return false; - } - } -} - -//! `depends` caches, for one walk, whether the definition of a visible CTE reads the source: every reference of such a -//! CTE counts, but its definition is walked once. -static idx_t CountSourceReaders(LogicalOperator &op, TableIndex source, - const vector> &cte_scopes, - unordered_map &depends) { - if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { - auto &reference = op.Cast(); - if (reference.cte_index == source) { - return 1; - } - auto known = depends.find(reference.cte_index); - if (known != depends.end()) { - return known->second ? 1 : 0; - } - // The owner is an ancestor of `op`: its definition cannot contain `op`. - auto owner = FindVisibleOwner(reference.cte_index, cte_scopes); - bool reads_source = owner && CountSourceReaders(*owner->children[0], source, cte_scopes, depends) > 0; - depends[reference.cte_index] = reads_source; - return reads_source ? 1 : 0; - } - idx_t count = 0; - for (auto &child : op.children) { - count += CountSourceReaders(*child, source, cte_scopes, depends); - } - return count; -} - -//! The number of references below `op` that read the materialized CTE `source`, directly or through a visible CTE -//! whose definition does. -static idx_t CountSourceReaders(LogicalOperator &op, TableIndex source, - const vector> &cte_scopes) { - unordered_map depends; - return CountSourceReaders(op, source, cte_scopes, depends); -} - -//! An aggregate without groups below plain projections. -static bool IsSingleRow(LogicalOperator &op) { - reference current = op; - while (current.get().type == LogicalOperatorType::LOGICAL_PROJECTION) { - current = *current.get().children[0]; - } - if (current.get().type != LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { - return false; - } - auto &aggregate = current.get().Cast(); - return aggregate.groups.empty() && aggregate.grouping_sets.size() <= 1; -} - -//! The RHS of the equality join is grouped by (a subset of) the join keys. -static bool JoinRHSIsDeduplicated(LogicalComparisonJoin &join) { - vector bindings; - for (auto &condition : join.conditions) { - if (!condition.IsComparison() || condition.GetRHS().GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF || - condition.GetRHS().Cast().Depth() != 0) { - return false; - } - bindings.push_back(condition.GetRHS().Cast().Binding()); - } - return LogicalAggregate::KeysAreUnique(*join.children[1], std::move(bindings)); -} - -static bool ProjectionOnlyPassesKey(LogicalOperator &op, idx_t passthrough, ColumnBinding key) { - for (idx_t index = 0; index < op.expressions.size(); index++) { - if (index == passthrough) { - continue; - } - bool observes_key = false; - ExpressionIterator::EnumerateExpression(op.expressions[index], [&](const Expression &child) { - switch (child.GetExpressionClass()) { - case ExpressionClass::BOUND_COLUMN_REF: { - auto &column = child.Cast(); - observes_key |= column.Depth() != 0 || column.Binding() == key; - break; - } - case ExpressionClass::BOUND_LAMBDA: - case ExpressionClass::BOUND_LAMBDA_REF: - case ExpressionClass::BOUND_SUBQUERY: - case ExpressionClass::BOUND_REF: - observes_key = true; - break; - default: - break; - } - }); - if (observes_key) { - return false; - } - } - return true; -} - -//! Matches, at an INNER / LEFT / SINGLE join, -//! -//! JOIN (l.k IS NOT DISTINCT FROM p.k) -//! L: a reference of a materialized CTE -//! PROJECTION p (.., d.k) the empty-input substitution -//! LEFT JOIN (no condition) one row of empty-input aggregate values -//! LEFT JOIN (d.k = a.k) -//! d: the distinct keys of the CTE L reads -//! a: an aggregate grouped by the keys -//! -//! Only operators that compute one row from one row of the inner LEFT join may sit above it. -static bool FindOuterDomainJoin(LogicalOperator &op, const vector> &cte_scopes, - OuterDomainJoin &result) { - auto &join = op.Cast(); - if ((join.join_type != JoinType::SINGLE && join.join_type != JoinType::LEFT && join.join_type != JoinType::INNER) || - !join.left_projection_map.empty() || !join.expressions.empty() || !join.duplicate_eliminated_columns.empty() || - join.filter_pushdown || join.children[1]->type != LogicalOperatorType::LOGICAL_PROJECTION) { - return false; - } - vector> chain; - reference current = *join.children[1]; - while (true) { - auto &node = current.get(); - if (node.type == LogicalOperatorType::LOGICAL_PROJECTION) { - for (auto &expression : node.expressions) { - if (expression->CanThrow() || expression->IsVolatile()) { - return false; - } - } - } else if (node.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { - auto &inner = node.Cast(); - if (inner.join_type != JoinType::LEFT || inner.HasProjectionMap() || !inner.expressions.empty() || - !inner.duplicate_eliminated_columns.empty() || inner.filter_pushdown) { - return false; - } - if (!inner.conditions.empty()) { - break; - } - if (!IsSingleRow(*inner.children[1])) { - return false; - } - } else { - return false; - } - chain.push_back(node); - current = *node.children[0]; - } - auto &domain_join = current.get().Cast(); - auto &domain = *domain_join.children[0]; - auto domain_bindings = domain.GetColumnBindings(); - auto key_count = domain_bindings.size(); - if (key_count == 0 || domain_join.conditions.size() != key_count || join.conditions.size() != key_count || - !JoinRHSIsDeduplicated(domain_join)) { - return false; - } - - // The inner LEFT join compares every domain column with a group of the aggregate. The domain columns are the - // groups of the duplicate elimination, each of them exactly once: a group that is not output, or one that is output - // twice in place of another, leaves several domain rows per key and would multiply the rows of the LHS. - vector sources; - vector domain_groups(key_count, false); - for (idx_t index = 0; index < key_count; index++) { - idx_t compared = 0; - for (auto &condition : domain_join.conditions) { - if (!condition.IsComparison() || - (condition.GetComparisonType() != ExpressionType::COMPARE_EQUAL && - condition.GetComparisonType() != ExpressionType::COMPARE_NOT_DISTINCT_FROM)) { - continue; - } - auto &left = condition.GetLHS(); - if (left.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF && - left.Cast().Depth() == 0 && - left.Cast().Binding() == domain_bindings[index]) { - compared++; - } - } - TableIndex cte; - idx_t column; - idx_t group = 0; - if (compared != 1 || !TraceSourceColumn(domain, index, cte_scopes, true, key_count, cte, column, group) || - group >= key_count || domain_groups[group]) { - return false; - } - domain_groups[group] = true; - if (index == 0) { - result.source = cte; - } else if (result.source != cte) { - return false; - } - sources.push_back(column); - } - - // The outer join compares the LHS column each domain column duplicates with that column, passed through. - vector matched(key_count, false); - result.keys.resize(key_count); - vector demand_indices(key_count); - for (auto &condition : join.conditions) { - if (!condition.IsComparison() || condition.GetComparisonType() != ExpressionType::COMPARE_NOT_DISTINCT_FROM || - condition.GetLHS().GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF || - condition.GetRHS().GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF || - condition.GetRHS().Cast().Depth() != 0) { - return false; - } - auto left_index = ReferenceIndex(condition.GetLHS(), *join.children[0]); - TableIndex cte; - idx_t column; - idx_t group = 0; - if (!left_index.IsValid() || - !TraceSourceColumn(*join.children[0], left_index.GetIndex(), cte_scopes, false, 0, cte, column, group)) { - return false; - } - auto binding = condition.GetRHS().Cast().Binding(); - auto &type = condition.GetLHS().GetReturnType(); - const auto sensitive_key = !BoundComparisonExpression::EqualityPreservesValueRepresentation(type); - if (sensitive_key) { - auto outputs = join.GetColumnBindings(); - if (!type.IsFloating() || std::find(outputs.begin(), outputs.end(), binding) != outputs.end()) { - return false; - } - } - for (auto &above : chain) { - if (above.get().type != LogicalOperatorType::LOGICAL_PROJECTION) { - continue; - } - auto outputs = above.get().GetColumnBindings(); - auto entry = std::find(outputs.begin(), outputs.end(), binding); - if (entry == outputs.end()) { - return false; - } - auto projection_index = NumericCast(entry - outputs.begin()); - auto &expression = *above.get().expressions[projection_index]; - if (expression.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF || - expression.Cast().Depth() != 0) { - return false; - } - binding = expression.Cast().Binding(); - if (sensitive_key && !ProjectionOnlyPassesKey(above.get(), projection_index, binding)) { - return false; - } - } - auto entry = std::find(domain_bindings.begin(), domain_bindings.end(), binding); - if (entry == domain_bindings.end()) { - return false; - } - auto index = NumericCast(entry - domain_bindings.begin()); - if (cte != result.source || column != sources[index] || matched[index]) { - return false; - } - matched[index] = true; - result.keys[index] = make_pair(binding, condition.GetLHS().Cast().Binding()); - demand_indices[index] = left_index.GetIndex(); - } - - auto &aggregate_side = *domain_join.children[1]; - result.chain_length = chain.size(); - result.domain_join = &domain_join; - vector aggregate_indices, domain_indices; - for (auto &condition : domain_join.conditions) { - auto index = ReferenceIndex(condition.GetRHS(), aggregate_side); - auto domain_index = ReferenceIndex(condition.GetLHS(), domain); - if (!index.IsValid() || !domain_index.IsValid()) { - return true; - } - aggregate_indices.push_back(index.GetIndex()); - domain_indices.push_back(domain_index.GetIndex()); - } - auto aggregate_match = FindAggregate(aggregate_side, std::move(aggregate_indices)); - if (aggregate_match) { - result.aggregate = aggregate_match->aggregate.get(); - result.demand_indices.resize(key_count); - result.comparisons.resize(key_count); - for (idx_t index = 0; index < key_count; index++) { - auto group = aggregate_match->group_indices[index]; - result.demand_indices[group] = demand_indices[domain_indices[index]]; - result.comparisons[group] = domain_join.conditions[index].GetComparisonType(); - } - } - return true; -} - -static BindingReplacementGraph MaterializeRuntimeDomain(Optimizer &optimizer, unique_ptr &op, - idx_t demand_side, const LogicalCTERef &domain) { - BindingReplacementGraph replacements; - unique_ptr definition; - ColumnBindingRewrite::RewriteChild( - op, demand_side, [&](unique_ptr &child, BindingReplacementGraph &bindings) { - auto reference = make_uniq(optimizer.binder.GenerateTableIndex(), domain.cte_index, - domain.chunk_types, domain.bound_columns); - auto old_bindings = child->GetColumnBindings(); - auto new_bindings = reference->GetColumnBindings(); - for (idx_t index = 0; index < old_bindings.size(); index++) { - if (!bindings.Find(old_bindings[index])) { - bindings.Add(old_bindings[index], new_bindings[index]); - } - } - replacements.Merge(bindings); - definition = std::move(child); - child = std::move(reference); - }); - op = - make_uniq("domain_source", domain.cte_index, domain.chunk_types.size(), - std::move(definition), std::move(op), CTEMaterialize::CTE_MATERIALIZE_ALWAYS); - return replacements; -} - -bool DuplicateEliminatedDomainOptimizer::TryOptimizeRuntimeDomain(unique_ptr &op, - LogicalAggregate &aggregate, idx_t aggregate_side, - idx_t demand_index, ExpressionType comparison) { - auto &join = op->Cast(); - auto &demand = *join.children[1 - aggregate_side]; - if (!ReferencesVisibleOwners(demand, cte_scopes) || !ReferencesVisibleOwners(aggregate, cte_scopes)) { - return false; - } - RuntimeDomainSource source; - if (!TryGetRuntimeDomainSource(demand, demand_index, cte_scopes, source)) { - return false; - } - // The extractor caches by operator address: retain rejected candidates through fallback costing. - unique_ptr scan_domain; - auto owner_index = source.owner ? source.owner->table_index : optimizer.binder.GenerateTableIndex(); - RelationStatsExtractor extractor(optimizer.context, [&](TableIndex index) -> optional_ptr { - if (index == owner_index) { - return source.input; - } - auto owner = FindVisibleOwner(index, cte_scopes); - return owner ? owner->children[0].get() : nullptr; - }); - auto source_stats = extractor.Extract(*source.input); - if (!source_stats) { - return false; - } - if (source.owner) { - ScanKeySource scan_source; - auto &type = aggregate.groups[0]->GetReturnType(); - FindScanKeySource(source.owner->children[0], source.key, type, extractor, optimizer.context, scan_source); - if (scan_source.input) { - auto parameters = optimizer.binder.GetParameters(); - LogicalOperatorDeepCopy copier(optimizer.binder, parameters ? parameters->GetParametersPtr() : nullptr); - auto scan = copier.DeepCopy(*scan_source.input); - auto key = make_uniq(type, scan->GetColumnBindings()[scan_source.key]); - scan_domain = CreateKeyDomain(optimizer, std::move(scan), std::move(key)); - DomainCostModel costs(extractor, aggregate, scan_source.rows, scan_source.scan_rows); - // A scan supplies the keys: the demand's source is released either way. - if (TryOptimizeRuntimeRestriction(optimizer.context, costs, aggregate, demand, demand_index, scan_domain, - comparison, cte_scopes, true) != RestrictionAction::KEEP) { - return true; - } - } - } - source.input->ResolveOperatorTypes(); - auto &source_types = source.input->types; - auto key_reference = - make_uniq(optimizer.binder.GenerateTableIndex(), owner_index, source_types, - AggregateRewriteHelper::GenerateColumnNames("domain", source_types.size())); - auto &domain_reference = *key_reference; - auto key_expression = - make_uniq(source_types[source.key], key_reference->GetColumnBindings()[source.key]); - auto domain = CreateKeyDomain(optimizer, std::move(key_reference), std::move(key_expression)); - auto restriction = make_uniq(JoinType::SEMI); - restriction->conditions.emplace_back(aggregate.groups[0]->Copy(), DomainKey(*domain), comparison); - auto source_rows = source_stats->cardinality.GetDouble(); - // CTE readers scan the full row. A new owner also writes it and replaces the consumer with another reader. - auto source_read_write_work = (source.owner ? 1 : 3) * source_rows * static_cast(source_types.size()); - DomainCostModel costs(extractor, aggregate, source_rows, source_read_write_work); - auto action = TryOptimizeRuntimeRestriction(optimizer.context, costs, aggregate, demand, demand_index, domain, - comparison, cte_scopes); - if (action != RestrictionAction::KEEP) { - if (action == RestrictionAction::REPLACE && !source.owner) { - replacements.Merge(MaterializeRuntimeDomain(optimizer, op, 1 - aggregate_side, domain_reference)); - } - return true; - } - if (join.join_type != JoinType::SINGLE && HasRuntimeFilterTargets(aggregate)) { - return false; - } - if (!costs.IsProfitable(*restriction, *domain)) { - return false; - } - restriction->children.push_back(std::move(aggregate.children[0])); - restriction->children.push_back(std::move(domain)); - aggregate.children[0] = std::move(restriction); - if (!source.owner) { - replacements.Merge(MaterializeRuntimeDomain(optimizer, op, 1 - aggregate_side, domain_reference)); - } - return true; -} - -//! The number of references of the materialized CTE `cte` below `op`, nested CTE definitions included. -static idx_t CountReferences(LogicalOperator &op, TableIndex cte) { - if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { - return op.Cast().cte_index == cte ? 1 : 0; - } - idx_t count = 0; - for (auto &child : op.children) { - count += CountReferences(*child, cte); - } - return count; -} - -//! Which producers stop when the restriction of the aggregate input to the keys of `domain` is removed and the outer -//! side `demand` takes the place of the domain. The restriction keys and the domain go away with the rewrite; their -//! producers only stop when nothing else reads them: -//! - the duplicate elimination behind the domain, when it is inline or a CTE that only the domain and the restriction -//! keys reference; -//! - the materialization of the source, when the demand is its only remaining reference and the CTE is not -//! materialized on request (it is then inlined). -static ReleasedDomainWork FindReleasedDomainWork(LogicalOperator &demand, LogicalOperator &domain, - optional_ptr restriction_keys, TableIndex source, - const vector> &cte_scopes) { - ReleasedDomainWork released; - reference production = domain; - while (production.get().type == LogicalOperatorType::LOGICAL_PROJECTION) { - production = *production.get().children[0]; - } - auto released_source_references = - CountReferences(domain, source) + (restriction_keys ? CountReferences(*restriction_keys, source) : 0); - bool production_stops = true; - if (production.get().type == LogicalOperatorType::LOGICAL_CTE_REF) { - auto index = production.get().Cast().cte_index; - auto owner = FindVisibleOwner(index, cte_scopes); - production_stops = - owner && index != source && - CountReferences(*owner->children[1], index) == - CountReferences(domain, index) + (restriction_keys ? CountReferences(*restriction_keys, index) : 0); - if (production_stops) { - production = *owner->children[0]; - released_source_references += CountReferences(production, source); - } - } - if (production_stops) { - released.production = production.get(); - } - auto owner = FindVisibleOwner(source, cte_scopes); - if (owner && owner->materialize != CTEMaterialize::CTE_MATERIALIZE_ALWAYS && CountReferences(demand, source) == 1 && - CountReferences(*owner->children[1], source) == 1 + released_source_references) { - released.source = *owner->children[0]; - } - return released; -} - -static bool RecoveryIsProfitable(LogicalComparisonJoin &join, const OuterDomainJoin &matched, - RelationStatsExtractor &extractor, const ReleasedDomainWork &released, - double restriction_savings) { - double expression_work = 0; - idx_t single_row_joins = 0; - optional_ptr current = *join.children[1]; - for (idx_t depth = 0; depth < matched.chain_length; depth++) { - if (current->type == LogicalOperatorType::LOGICAL_PROJECTION) { - for (auto &expression : current->expressions) { - if (!IsWorkReference(*expression)) { - expression_work += static_cast(ExpressionHeuristics::Cost(*expression)); - } - } - } else { - single_row_joins++; - } - current = *current->children[0]; - } - if (expression_work == 0 && single_row_joins == 0) { - return true; - } - auto outer = extractor.Extract(*join.children[0]); - auto domain = extractor.Extract(*matched.domain_join->children[0]); - if (!outer || !domain) { - return false; - } - auto outer_rows = outer->cardinality.GetDouble(); - return DomainCostModel::IsRecoveryProfitable(outer_rows, *domain, expression_work, single_row_joins, - DomainCostModel::EstimateReleasedWork(extractor, released), - restriction_savings); -} - -//! Replace the recovery domain by the outer rows when the saved join pays for additional evaluation. -bool DuplicateEliminatedDomainOptimizer::TryPullUpOuterDomainJoin(unique_ptr &op) { - OuterDomainJoin matched; - if (!FindOuterDomainJoin(*op, cte_scopes, matched)) { - return false; - } - RelationStatsExtractor extractor(optimizer.context, [&](TableIndex index) -> optional_ptr { - auto owner = FindVisibleOwner(index, cte_scopes); - return owner ? owner->children[0].get() : nullptr; - }); - auto collapse_released = FindReleasedDomainWork(*op->children[0], *matched.domain_join->children[0], nullptr, - matched.source, cte_scopes); - optional restriction; - RestrictionDecision decision; - if (matched.aggregate) { - restriction.emplace(optimizer.context, cte_scopes, *matched.aggregate, matched.comparisons); - auto restriction_join = restriction->GetJoin(); - auto &aggregate_side = *matched.domain_join->children[1]; - if (restriction_join && - CountSourceReaders(aggregate_side, matched.source, cte_scopes) == - CountSourceReaders(*restriction_join->children[1], matched.source, cte_scopes) && - RuntimeRestrictionContainsDemand(*restriction, *op->children[0], matched.demand_indices, cte_scopes)) { - auto released = FindReleasedDomainWork(*op->children[0], *matched.domain_join->children[0], - *restriction_join->children[1], matched.source, cte_scopes); - // Only credit work that survives collapse with the restriction kept. - if (collapse_released.production) { - released.production = nullptr; - } - if (collapse_released.source) { - released.source = nullptr; - } - DomainCostModel costs(extractor, *matched.aggregate); - costs.SetReleasedWork(released); - decision = costs.ChooseRestrictionAction(*restriction, nullptr); - } - } - if (!RecoveryIsProfitable(op->Cast(), matched, extractor, collapse_released, - decision.removal_savings)) { - return false; - } - if (restriction && decision.action == RestrictionAction::REMOVE) { - restriction->Remove(); - } - - auto old_bindings = op->GetColumnBindings(); - auto &join = op->Cast(); - join.children[0]->ResolveOperatorTypes(); - auto left_types = join.children[0]->types; - auto left_bindings = join.children[0]->GetColumnBindings(); - auto right_projection_map = std::move(join.right_projection_map); - join.right_projection_map.clear(); - - // The join takes the place of the LEFT join against the key domain. - ColumnBindingReplacer replacer; - for (auto &key : matched.keys) { - replacer.replacement_bindings.emplace_back(key.first, key.second); - } - auto chain_top = std::move(join.children[1]); - vector> chain; - reference> slot = chain_top; - for (idx_t depth = 0; depth < matched.chain_length; depth++) { - chain.push_back(*slot.get()); - slot = slot.get()->children[0]; - } - auto &domain_join = slot.get()->Cast(); - join.children[1] = std::move(domain_join.children[1]); - join.conditions = std::move(domain_join.conditions); - for (auto &condition : join.conditions) { - replacer.VisitExpression(&condition.LeftReference()); - } - join.join_type = JoinType::LEFT; - slot.get() = std::move(op); - - // The operators above read the LHS keys instead of the domain and pass the LHS through. - auto current_left = left_bindings; - idx_t top_column_count = 0; - for (idx_t depth = chain.size(); depth-- > 0;) { - auto &node = chain[depth].get(); - if (node.type != LogicalOperatorType::LOGICAL_PROJECTION) { - continue; - } - auto table_index = node.Cast().table_index; - for (auto &expression : node.expressions) { - replacer.VisitExpression(&expression); - } - top_column_count = node.expressions.size(); - for (idx_t column = 0; column < current_left.size(); column++) { - auto passed = ColumnBinding::PushExpression( - node.expressions, make_uniq(left_types[column], current_left[column])); - current_left[column] = ColumnBinding(table_index, passed); - } - } - - // Restore the column order of the join: its LHS, then its RHS. - auto projection = LogicalProjection::CreateIdentity(optimizer.binder.GenerateTableIndex(), std::move(chain_top)); - auto right_expressions = std::move(projection->expressions); - projection->expressions.clear(); - for (idx_t column = top_column_count; column < right_expressions.size(); column++) { - projection->expressions.push_back(std::move(right_expressions[column])); - } - if (right_projection_map.empty()) { - for (idx_t column = 0; column < top_column_count; column++) { - projection->expressions.push_back(std::move(right_expressions[column])); - } - } else { - for (auto &index : right_projection_map) { - projection->expressions.push_back(right_expressions[index.GetIndex()]->Copy()); - } - } - projection->ResolveOperatorTypes(); - auto new_bindings = projection->GetColumnBindings(); - op = std::move(projection); - for (idx_t column = 0; column < old_bindings.size(); column++) { - if (old_bindings[column] != new_bindings[column] && !replacements.Find(old_bindings[column])) { - replacements.Add(old_bindings[column], new_bindings[column]); - } - } - return true; -} - -bool DuplicateEliminatedDomainOptimizer::TryOptimizeDomain(unique_ptr &op, idx_t aggregate_side, - idx_t condition_index) { - auto &join = op->Cast(); - auto &condition = join.conditions[condition_index]; - auto &aggregate_key = aggregate_side == 0 ? condition.GetLHS() : condition.GetRHS(); - auto &demand_key = aggregate_side == 0 ? condition.GetRHS() : condition.GetLHS(); - auto aggregate_index = ReferenceIndex(aggregate_key, *join.children[aggregate_side]); - auto demand_index = ReferenceIndex(demand_key, *join.children[1 - aggregate_side]); - if (!aggregate_index.IsValid() || !demand_index.IsValid() || - !aggregate_key.GetReturnType().EqualsIncludingCollation(demand_key.GetReturnType())) { - return false; - } - auto aggregate = FindAggregate(*join.children[aggregate_side], aggregate_index.GetIndex()); - if (!aggregate) { - return false; - } - vector>> rows; - if (!CopyFixedKeys(*join.children[1 - aggregate_side], demand_index.GetIndex(), demand_key.GetReturnType(), rows)) { - return TryOptimizeRuntimeDomain(op, *aggregate, aggregate_side, demand_index.GetIndex(), - condition.GetComparisonType()); - } - auto key_index = optimizer.binder.GenerateTableIndex(); - auto fixed = - make_uniq(key_index, vector {demand_key.GetReturnType()}, std::move(rows)); - fixed->children.push_back(make_uniq(optimizer.binder.GenerateTableIndex())); - auto key_expression = - make_uniq(demand_key.GetReturnType(), ColumnBinding(key_index, ProjectionIndex(0))); - auto domain = CreateKeyDomain(optimizer, std::move(fixed), std::move(key_expression)); - if (TryOptimizeRestriction(optimizer, *aggregate, domain, condition.GetComparisonType(), cte_scopes)) { - return true; - } - // Replacing an existing restriction keeps its filter opportunity. A new one may duplicate the consumer's work. - if (join.join_type != JoinType::SINGLE && HasRuntimeFilterTargets(*aggregate)) { - return false; - } - auto restriction = make_uniq(JoinType::SEMI); - restriction->conditions.emplace_back(aggregate->groups[0]->Copy(), DomainKey(*domain), - condition.GetComparisonType()); - RelationStatsExtractor extractor(optimizer.context); - auto key_input_rows = static_cast(domain->children[0]->Cast().expressions.size()); - DomainCostModel costs(extractor, *aggregate, key_input_rows, 0); - if (!costs.IsProfitable(*restriction, *domain)) { - return false; - } - // All analysis borrows have expired. Preserve every original binding and payload column. - restriction->children.push_back(std::move(aggregate->children[0])); - restriction->children.push_back(std::move(domain)); - aggregate->children[0] = std::move(restriction); - return true; -} - -void DuplicateEliminatedDomainOptimizer::VisitOperator(unique_ptr &op) { - replacements = BindingReplacementGraph(); - if (op->type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) { - return; - } - BindingReplacementGraph child_replacements; - // Visit only original children; generated domain operators are never reconsidered. - for (idx_t child_index = 0; child_index < op->children.size(); child_index++) { - auto publish_owner = op->type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE && child_index == 1; - if (publish_owner) { - cte_scopes.push_back(op->Cast()); - } - ColumnBindingRewrite::RewriteChild(op, child_index, - [&](unique_ptr &child, BindingReplacementGraph &bindings) { - VisitOperator(child); - bindings = std::move(replacements); - child_replacements.Merge(bindings); - }); - if (publish_owner) { - cte_scopes.pop_back(); - } - } - replacements = std::move(child_replacements); - if (op->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN && !TryPullUpOuterDomainJoin(op)) { - auto &join = op->Cast(); - bool safe_conditions = true; - LogicalOperatorVisitor::EnumerateExpressions(join, [&](const unique_ptr *expression) { - safe_conditions &= !(*expression)->CanThrow() && !(*expression)->IsVolatile(); - }); - if (safe_conditions && join.expressions.empty() && join.duplicate_eliminated_columns.empty()) { - for (idx_t condition_index = 0; condition_index < join.conditions.size(); condition_index++) { - auto &condition = join.conditions[condition_index]; - if (condition.IsComparison() && - (condition.GetComparisonType() == ExpressionType::COMPARE_EQUAL || - condition.GetComparisonType() == ExpressionType::COMPARE_NOT_DISTINCT_FROM)) { - auto join_type = join.join_type; - auto rewritten = join_type == JoinType::INNER && TryOptimizeDomain(op, 0, condition_index); - if (!rewritten && (join_type == JoinType::INNER || join_type == JoinType::LEFT || - join_type == JoinType::SINGLE)) { - rewritten = TryOptimizeDomain(op, 1, condition_index); - } - if (rewritten) { - break; - } - } - } - } - } - if (!replacements.Empty()) { - replacements = replacements.ScopedToBoundary(op->GetColumnBindings()); - } -} - -} // namespace duckdb diff --git a/src/duckdb/src/optimizer/expression_heuristics.cpp b/src/duckdb/src/optimizer/expression_heuristics.cpp index 05967ff00..89632a7eb 100644 --- a/src/duckdb/src/optimizer/expression_heuristics.cpp +++ b/src/duckdb/src/optimizer/expression_heuristics.cpp @@ -1,4 +1,5 @@ #include "duckdb/optimizer/expression_heuristics.hpp" +#include "duckdb/common/no_destructor.hpp" #include "duckdb/planner/table_filter_set.hpp" #include "duckdb/planner/expression/bound_between_expression.hpp" #include "duckdb/planner/expression/bound_comparison_expression.hpp" @@ -139,23 +140,33 @@ idx_t ExpressionHeuristics::ExpressionCost(const BoundFunctionExpression &expr) auto child = ExpressionFilter::GetOptionalFilterChild(expr); return child ? Cost(*child) : 0; } - identifier_map_t function_costs = {{"+", 5}, {"-", 5}, - {"&", 5}, {"#", 5}, - {">>", 5}, {"<<", 5}, - {"abs", 5}, {"*", 10}, - {"%", 10}, {"/", 15}, - {"date_part", 20}, {"year", 20}, - {"round", 100}, {"~~", 200}, - {"!~~", 200}, {"regexp_matches", 200}, - {"||", 200}, {PrefixRangeScalarFun::NAME, 20}}; + static const NoDestructor> function_costs( + identifier_map_t {{"+", 5}, + {"-", 5}, + {"&", 5}, + {"#", 5}, + {">>", 5}, + {"<<", 5}, + {"abs", 5}, + {"*", 10}, + {"%", 10}, + {"/", 15}, + {"date_part", 20}, + {"year", 20}, + {"round", 100}, + {"~~", 200}, + {"!~~", 200}, + {"regexp_matches", 200}, + {"||", 200}, + {PrefixRangeScalarFun::NAME, 20}}); idx_t cost_children = 0; for (auto &child : expr.GetChildren()) { cost_children += Cost(*child); } - auto cost_function = function_costs.find(expr.Function().GetName()); - if (cost_function != function_costs.end()) { + auto cost_function = function_costs->find(expr.Function().GetName()); + if (cost_function != function_costs->end()) { return cost_children + cost_function->second; } else { return cost_children + 1000; diff --git a/src/duckdb/src/optimizer/filter_combiner.cpp b/src/duckdb/src/optimizer/filter_combiner.cpp index c8ea8943c..9023360c8 100644 --- a/src/duckdb/src/optimizer/filter_combiner.cpp +++ b/src/duckdb/src/optimizer/filter_combiner.cpp @@ -16,6 +16,7 @@ #include "duckdb/planner/expression/bound_function_expression.hpp" #include "duckdb/planner/expression/bound_operator_expression.hpp" #include "duckdb/planner/expression/bound_reference_expression.hpp" +#include "duckdb/planner/expression/expression_barrier.hpp" #include "duckdb/planner/filter/expression_filter.hpp" #include "duckdb/planner/filter/table_filter_functions.hpp" #include "duckdb/planner/table_filter.hpp" @@ -129,8 +130,8 @@ void FilterCombiner::DeduplicateFilters(vector> &filters) expression_set_t seen; vector> unique_filters; for (auto &filter : filters) { - if (!filter->IsVolatile() && !filter->CanThrow() && CanMatchExpression(*filter) && - !seen.insert(*filter).second) { + if (!filter->IsVolatile() && !filter->CanThrow() && !ExpressionBarrier::Contains(*filter) && + CanMatchExpression(*filter) && !seen.insert(*filter).second) { continue; } unique_filters.push_back(std::move(filter)); @@ -412,6 +413,7 @@ void FilterCombiner::GenerateEquivalentKeyFilters(const Expression &filter, } void FilterCombiner::GenerateFilters(const std::function filter)> &callback) { + DeduplicateFilters(remaining_filters); vector> inferred; { expression_set_t seen; @@ -704,8 +706,8 @@ void ReplaceWithBoundReference(unique_ptr &root_expr) { }); } -static unique_ptr TryCreateMultiColumnExpressionFilter(LogicalGet &get, const Expression &expr, - const vector &bindings) { +static unique_ptr TryCreateMultiColumnPruningFilter(LogicalGet &get, const Expression &expr, + const vector &bindings) { vector distinct_bindings; distinct_bindings.reserve(bindings.size()); // Maps column bindings to dense BoundReference indexes. @@ -734,19 +736,28 @@ static unique_ptr TryCreateMultiColumnExpressionFilter(Logical } auto filter_expr = expr.Copy(); + bool valid = true; ExpressionIterator::VisitExpressionMutable( filter_expr, [&](BoundColumnRefExpression &column_ref, unique_ptr &child) { const auto entry = binding_indexes.find(column_ref.Binding()); - D_ASSERT(entry != binding_indexes.end()); + if (entry == binding_indexes.end() || column_ref.Depth() || + column_ref.GetReturnType() != + get.GetColumnType(get.GetColumnIndex(column_ref.Binding().column_index))) { + valid = false; + return; + } child = make_uniq(column_ref.GetAlias(), column_ref.GetReturnType(), entry->second); }); + if (!valid) { + return nullptr; + } // Remove query-specific metadata so equivalent filters serialize identically for common-subplan matching. ExpressionIterator::EnumerateExpression(filter_expr, [](Expression &expr) { expr.ClearAlias(); expr.SetQueryLocation(optional_idx()); }); - return make_uniq(std::move(filter_expr), std::move(column_indexes)); + return ExpressionFilter::CreateOptionalFilter(std::move(filter_expr), std::move(column_indexes)); } FilterPushdownResult FilterCombiner::TryPushdownGenericExpression(LogicalGet &get, Expression &expr) { @@ -770,7 +781,7 @@ FilterPushdownResult FilterCombiner::TryPushdownGenericExpression(LogicalGet &ge if (has_multiple_bindings) { auto table = get.GetTable(); if (table && table->IsDuckTable() && ExpressionFilter::CanPropagateExpressionStatistics(expr)) { - auto filter = TryCreateMultiColumnExpressionFilter(get, expr, bindings); + auto filter = TryCreateMultiColumnPruningFilter(get, expr, bindings); if (filter) { get.table_filters.PushMultiColumnFilter(std::move(filter)); return FilterPushdownResult::PUSHED_DOWN_PARTIALLY; diff --git a/src/duckdb/src/optimizer/filter_pushdown.cpp b/src/duckdb/src/optimizer/filter_pushdown.cpp index fb0cc1ca1..52bbc54aa 100644 --- a/src/duckdb/src/optimizer/filter_pushdown.cpp +++ b/src/duckdb/src/optimizer/filter_pushdown.cpp @@ -18,6 +18,19 @@ FilterPushdown::FilterPushdown(Optimizer &optimizer, ProjectionMode projection_m : optimizer(optimizer), combiner(optimizer.context), projection_mode(projection_mode) { } +FilterPushdown::FilterPushdown(const FilterPushdown &parent, ProjectionMode projection_mode) + : FilterPushdown(parent.optimizer, projection_mode) { + cte_state = parent.cte_state; +} + +FilterPushdown FilterPushdown::CreateChildPushdown() const { + return CreateChildPushdown(projection_mode); +} + +FilterPushdown FilterPushdown::CreateChildPushdown(ProjectionMode mode) const { + return FilterPushdown(*this, mode); +} + bool FilterPushdown::BarrierCanPassThrough(LogicalOperatorType type) { switch (type) { case LogicalOperatorType::LOGICAL_FILTER: @@ -76,14 +89,8 @@ unique_ptr FilterPushdown::Rewrite(unique_ptr // we can just push directly through these operations without any rewriting RewriteChild(*op, 0); return op; - case LogicalOperatorType::LOGICAL_MATERIALIZED_CTE: { - // we can't push filters into the materialized CTE (LHS), but we do want to recurse into it - FilterPushdown pushdown(optimizer, projection_mode); - op->children[0] = pushdown.Rewrite(std::move(op->children[0])); - // we can push filters into the rest of the query plan (RHS) - op->children[1] = Rewrite(std::move(op->children[1])); - return op; - } + case LogicalOperatorType::LOGICAL_MATERIALIZED_CTE: + return PushdownMaterializedCTE(std::move(op)); case LogicalOperatorType::LOGICAL_GET: return PushdownGet(std::move(op)); case LogicalOperatorType::LOGICAL_LIMIT: @@ -146,7 +153,7 @@ unique_ptr FilterPushdown::PushdownJoin(unique_ptr FilterPushdown::AddLogicalFilter(unique_ptr FilterPushdown::PushFiltersIntoDelimJoin(unique_ptr< for (idx_t i = 0; i < filters.size(); i++) { auto &f = *filters[i]; for (idx_t child_idx = 0; child_idx < op->children.size(); child_idx++) { - FilterPushdown pushdown(optimizer, projection_mode); + auto pushdown = CreateChildPushdown(); // check if filter bindings can be applied to the child bindings. auto child_bindings = op->children[child_idx]->GetColumnBindings(); @@ -268,7 +276,7 @@ unique_ptr FilterPushdown::PushFiltersIntoDelimJoin(unique_ptr< unique_ptr FilterPushdown::FinishPushdown(unique_ptr op) { // unhandled type, first perform filter pushdown in its children for (idx_t child_idx = 0; child_idx < op->children.size(); child_idx++) { - FilterPushdown pushdown(optimizer, projection_mode); + auto pushdown = CreateChildPushdown(); pushdown.RewriteChild(*op, child_idx); } // now push any existing filters diff --git a/src/duckdb/src/optimizer/filter_pushdown_guarantees.cpp b/src/duckdb/src/optimizer/filter_pushdown_guarantees.cpp new file mode 100644 index 000000000..731ebdb0d --- /dev/null +++ b/src/duckdb/src/optimizer/filter_pushdown_guarantees.cpp @@ -0,0 +1,272 @@ +#include "duckdb/optimizer/filter_pushdown.hpp" + +#include "duckdb/optimizer/filter_combiner.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression/bound_conjunction_expression.hpp" +#include "duckdb/planner/expression_iterator.hpp" +#include "duckdb/planner/filter/expression_filter.hpp" +#include "duckdb/planner/operator/logical_aggregate.hpp" +#include "duckdb/planner/operator/logical_comparison_join.hpp" +#include "duckdb/planner/operator/logical_get.hpp" +#include "duckdb/planner/operator/logical_projection.hpp" +#include "duckdb/planner/subquery/has_volatile_expressions.hpp" + +namespace duckdb { + +namespace { + +static optional_ptr PlainColumn(const Expression &expr) { + if (expr.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { + return nullptr; + } + auto &column_ref = expr.Cast(); + if (column_ref.Depth() != 0) { + return nullptr; + } + return &column_ref; +} + +static bool IsEquality(const JoinCondition &condition) { + return condition.IsComparison() && (condition.GetComparisonType() == ExpressionType::COMPARE_EQUAL || + condition.GetComparisonType() == ExpressionType::COMPARE_NOT_DISTINCT_FROM); +} + +static bool HasBinding(LogicalOperator &op, const ColumnBinding &binding) { + for (auto &op_binding : op.GetColumnBindings()) { + if (op_binding == binding) { + return true; + } + } + return false; +} + +//! Adds safe constraints on the whole key; optional scan hints are not constraints +static void AddColumnFilters(const Expression &filter, const BoundColumnRefExpression &column, + vector> &result) { + if (filter.GetExpressionType() == ExpressionType::CONJUNCTION_AND) { + for (auto &child : filter.Cast().GetChildren()) { + AddColumnFilters(*child, column, result); + } + return; + } + if (FilterCombiner::IsKeyConstraint(filter, {column})) { + result.push_back(filter.Copy()); + } +} + +class GuaranteedFilterSearch { +public: + //! Adds constraints on `column` that every row of `op` passes + void Collect(LogicalOperator &op, const BoundColumnRefExpression &column, vector> &result); + +private: + void FollowColumn(LogicalOperator &child, const BoundColumnRefExpression &source, + const BoundColumnRefExpression &target, vector> &result); + void CollectJoinFilters(LogicalComparisonJoin &join, const BoundColumnRefExpression &column, + vector> &result); + +private: + //! Limit operator visits per key: equality paths may revisit subtrees. Exhaustion only skips further inference. + static constexpr idx_t MAX_SEARCH_STEPS = 256; + idx_t steps = 0; +}; + +void GuaranteedFilterSearch::FollowColumn(LogicalOperator &child, const BoundColumnRefExpression &source, + const BoundColumnRefExpression &target, + vector> &result) { + if (source.Binding() == target.Binding()) { + Collect(child, target, result); + return; + } + if (source.GetReturnType() != target.GetReturnType()) { + return; + } + vector> source_filters; + Collect(child, source, source_filters); + for (auto &filter : source_filters) { + result.push_back(ExpressionIterator::ReplaceExpression(*filter, source, target)); + } +} + +void GuaranteedFilterSearch::Collect(LogicalOperator &op, const BoundColumnRefExpression &column, + vector> &result) { + if (++steps > MAX_SEARCH_STEPS) { + return; + } + auto &binding = column.Binding(); + switch (op.type) { + case LogicalOperatorType::LOGICAL_FILTER: + for (auto &expr : op.expressions) { + AddColumnFilters(*expr, column, result); + } + Collect(*op.children[0], column, result); + break; + case LogicalOperatorType::LOGICAL_PROJECTION: { + auto &projection = op.Cast(); + if (binding.table_index != projection.table_index || binding.column_index.GetIndex() >= op.expressions.size()) { + break; + } + auto source = PlainColumn(*op.expressions[binding.column_index.GetIndex()]); + if (source) { + FollowColumn(*op.children[0], *source, column, result); + } + break; + } + case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { + // grouping sets add NULL groups that the filters below do not describe + auto &aggregate = op.Cast(); + if (binding.table_index != aggregate.group_index || aggregate.grouping_sets.size() > 1 || + binding.column_index.GetIndex() >= aggregate.groups.size()) { + break; + } + auto source = PlainColumn(*aggregate.groups[binding.column_index.GetIndex()]); + if (source) { + FollowColumn(*op.children[0], *source, column, result); + } + break; + } + case LogicalOperatorType::LOGICAL_GET: { + auto &get = op.Cast(); + if (binding.table_index != get.table_index || !op.children.empty()) { + break; + } + auto filter = get.table_filters.TryGetFilterByColumnIndex(binding.column_index); + // an optional filter is a hint the scan may ignore + if (!filter || ExpressionFilter::IsOptionalFilter(*filter)) { + break; + } + AddColumnFilters(*filter->ToExpression(column), column, result); + break; + } + case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: + CollectJoinFilters(op.Cast(), column, result); + break; + case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: + for (auto &child : op.children) { + if (HasBinding(*child, binding)) { + Collect(*child, column, result); + break; + } + } + break; + case LogicalOperatorType::LOGICAL_ORDER_BY: + case LogicalOperatorType::LOGICAL_LIMIT: + case LogicalOperatorType::LOGICAL_TOP_N: + case LogicalOperatorType::LOGICAL_DISTINCT: + case LogicalOperatorType::LOGICAL_WINDOW: + // rows are removed, reordered or kept, the columns of the child pass through under their own bindings + if (op.children.size() == 1 && HasBinding(*op.children[0], binding)) { + Collect(*op.children[0], column, result); + } + break; + default: + // set operations and CTE references end the search + break; + } +} + +void GuaranteedFilterSearch::CollectJoinFilters(LogicalComparisonJoin &join, const BoundColumnRefExpression &column, + vector> &result) { + if (join.children.size() != 2) { + return; + } + auto &binding = column.Binding(); + optional_idx side; + for (idx_t child_idx = 0; child_idx < 2; child_idx++) { + if (HasBinding(*join.children[child_idx], binding)) { + side = child_idx; + break; + } + } + if (!side.IsValid()) { + return; + } + // The side that an outer join extends with NULLs does not retain its input's guarantees. + const auto side_idx = side.GetIndex(); + switch (join.join_type) { + case JoinType::INNER: + break; + case JoinType::LEFT: + case JoinType::SEMI: + case JoinType::ANTI: + case JoinType::MARK: + if (side_idx != 0) { + return; + } + break; + case JoinType::RIGHT: + if (side_idx != 1) { + return; + } + break; + default: + return; + } + Collect(*join.children[side_idx], column, result); + if (join.join_type != JoinType::INNER) { + return; + } + // INNER join rows also satisfy constraints implied by equalities with the other side. + auto &other_child = *join.children[1 - side_idx]; + vector> other_filters; + for (auto &condition : join.conditions) { + if (!IsEquality(condition)) { + continue; + } + auto own = PlainColumn(side_idx == 0 ? condition.GetLHS() : condition.GetRHS()); + auto other = PlainColumn(side_idx == 0 ? condition.GetRHS() : condition.GetLHS()); + if (own && other && own->Binding() == binding && HasBinding(other_child, other->Binding())) { + Collect(other_child, *other, other_filters); + } + } + vector> filters; + for (auto &filter : other_filters) { + filters.push_back(*filter); + } + FilterCombiner::GenerateJoinFilters( + join.conditions, filters, side_idx == 0 ? JoinSide::LEFT : JoinSide::RIGHT, + [&](unique_ptr filter) { AddColumnFilters(*filter, column, result); }); +} + +} // namespace + +bool FilterPushdown::IsMarkFilter(const LogicalComparisonJoin &join, const Expression &filter) { + auto column = PlainColumn(filter); + return join.join_type == JoinType::MARK && join.children.size() == 2 && column && + column->Binding() == ColumnBinding(join.mark_index, ProjectionIndex(0)); +} + +vector> FilterPushdown::GenerateJoinFilters(LogicalComparisonJoin &join) { + D_ASSERT(join.children.size() == 2); + // the filters on the join keys that every right row passes + vector> right_filters; + for (auto &condition : join.conditions) { + if (!IsEquality(condition)) { + continue; + } + auto right_key = PlainColumn(condition.GetRHS()); + if (right_key && HasBinding(*join.children[1], right_key->Binding())) { + GuaranteedFilterSearch search; + search.Collect(*join.children[1], *right_key, right_filters); + } + } + + // Inferred pruning must not change which left rows reach volatile expressions. + if (right_filters.empty() || (!input_is_nonvolatile && HasVolatileExpressionsIgnoringError(*join.children[0]))) { + return {}; + } + + // a left row with a match passes what they imply for the left side + vector> filters; + for (auto &filter : right_filters) { + filters.push_back(*filter); + } + vector> left_filters; + FilterCombiner::GenerateJoinFilters( + join.conditions, filters, JoinSide::LEFT, + [&](unique_ptr left_filter) { left_filters.push_back(std::move(left_filter)); }); + FilterCombiner::DeduplicateFilters(left_filters); + return left_filters; +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/filter_statistics.cpp b/src/duckdb/src/optimizer/filter_statistics.cpp index 97b941895..444aef710 100644 --- a/src/duckdb/src/optimizer/filter_statistics.cpp +++ b/src/duckdb/src/optimizer/filter_statistics.cpp @@ -1,6 +1,5 @@ #include "duckdb/optimizer/filter_statistics.hpp" -#include "duckdb/optimizer/filter_pushdown.hpp" #include "duckdb/optimizer/optimizer.hpp" #include "duckdb/optimizer/statistics_propagator.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" @@ -197,14 +196,14 @@ bool FilterStatisticsOptimizer::ComparesAllNullColumn(LogicalOperator &plan) con return ScansAllNullBinding(optimizer.context, plan, bindings); } -void FilterStatisticsOptimizer::Optimize(unique_ptr &plan) { +bool FilterStatisticsOptimizer::Optimize(unique_ptr &plan) { if (ContainsDelimJoin(*plan)) { - return; + return false; } // a comparison with a column that holds only NULLs never passes: propagating the statistics here removes // the filters and joins on it before the join order is chosen if (!HasMultiBindingFilter(*plan) && !ComparesAllNullColumn(*plan)) { - return; + return false; } bool filter_bindings_changed = false; @@ -213,14 +212,7 @@ void FilterStatisticsOptimizer::Optimize(unique_ptr &plan) { propagator.PropagateStatistics(plan); filter_bindings_changed = propagator.FilterBindingsChanged(); }); - if (!filter_bindings_changed) { - return; - } - - optimizer.RunOptimizer(OptimizerType::FILTER_PUSHDOWN, [&]() { - FilterPushdown filter_pushdown(optimizer); - plan = filter_pushdown.Rewrite(std::move(plan)); - }); + return filter_bindings_changed; } } // namespace duckdb diff --git a/src/duckdb/src/optimizer/join_elimination.cpp b/src/duckdb/src/optimizer/join_elimination.cpp index 9be6f09c6..d6cfe7ca2 100644 --- a/src/duckdb/src/optimizer/join_elimination.cpp +++ b/src/duckdb/src/optimizer/join_elimination.cpp @@ -10,9 +10,6 @@ #include "duckdb/planner/logical_operator.hpp" #include "duckdb/planner/operator/logical_aggregate.hpp" #include "duckdb/planner/operator/logical_comparison_join.hpp" -#include "duckdb/planner/operator/logical_cte.hpp" -#include "duckdb/planner/operator/logical_cteref.hpp" -#include "duckdb/planner/operator/logical_get.hpp" #include namespace duckdb { @@ -28,70 +25,6 @@ static bool AnyVolatile(const LogicalOperator &op) { return is_volatile; } -RemovedSubtreeEffects::RemovedSubtreeEffects(LogicalOperator &plan) { - CollectDefinitions(plan); -} - -void RemovedSubtreeEffects::CollectDefinitions(LogicalOperator &op) { - if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { - materialized_ctes.emplace(op.Cast().table_index, op); - } else if (op.type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) { - recursive_ctes.insert(op.Cast().table_index); - } - for (auto &child : op.children) { - CollectDefinitions(*child); - } -} - -bool RemovedSubtreeEffects::DefinitionHasEffect(TableIndex cte_index) { - auto known = definition_has_effect.find(cte_index); - if (known != definition_has_effect.end()) { - return known->second; - } - auto cte = materialized_ctes.find(cte_index); - if (cte == materialized_ctes.end()) { - // a reference to something that is not defined in this plan: assume the worst - return true; - } - // a materialized CTE cannot reference itself, so the definition is known before it is asked about again - const bool has_effect = HasEffect(*cte->second.get().children[0]); - definition_has_effect.emplace(cte_index, has_effect); - return has_effect; -} - -bool RemovedSubtreeEffects::HasEffect(LogicalOperator &subtree) { - if (AnyVolatile(subtree)) { - return true; - } - switch (subtree.type) { - case LogicalOperatorType::LOGICAL_INSERT: - case LogicalOperatorType::LOGICAL_DELETE: - case LogicalOperatorType::LOGICAL_UPDATE: - case LogicalOperatorType::LOGICAL_MERGE_INTO: - return true; - case LogicalOperatorType::LOGICAL_GET: - if (subtree.Cast().function.stability == FunctionStability::VOLATILE) { - return true; - } - break; - case LogicalOperatorType::LOGICAL_CTE_REF: { - auto cte_index = subtree.Cast().cte_index; - if (recursive_ctes.find(cte_index) == recursive_ctes.end() && DefinitionHasEffect(cte_index)) { - return true; - } - break; - } - default: - break; - } - for (auto &child : subtree.children) { - if (HasEffect(*child)) { - return true; - } - } - return false; -} - void JoinElimination::OptimizeChild(LogicalOperator &op, idx_t child_idx, JoinElimination &child_optimizer, bool replaceable) { // `op` may select the columns of its child by position: when a join is removed below, the selection is remapped diff --git a/src/duckdb/src/optimizer/join_filter_pushdown_optimizer.cpp b/src/duckdb/src/optimizer/join_filter_pushdown_optimizer.cpp index d8fb43835..6bfb21c99 100644 --- a/src/duckdb/src/optimizer/join_filter_pushdown_optimizer.cpp +++ b/src/duckdb/src/optimizer/join_filter_pushdown_optimizer.cpp @@ -10,6 +10,7 @@ #include "duckdb/function/scalar/struct_utils.hpp" #include "duckdb/optimizer/filter_combiner.hpp" #include "duckdb/optimizer/optimizer.hpp" +#include "duckdb/optimizer/statistics_propagator.hpp" #include "duckdb/planner/expression/bound_aggregate_expression.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/expression/bound_cast_expression.hpp" @@ -28,6 +29,7 @@ #include "duckdb/planner/operator/logical_set_operation.hpp" #include "duckdb/planner/operator/logical_unnest.hpp" #include "duckdb/planner/operator/logical_window.hpp" +#include "duckdb/storage/statistics/numeric_stats.hpp" namespace duckdb { @@ -39,6 +41,33 @@ struct FilterTarget { vector columns; }; +struct FilterTargets { + explicit FilterTargets(bool collect_p) : collect(collect_p) { + } + + void Add(LogicalOperator &op, vector columns) { + found = true; + if (collect) { + targets.emplace_back(op, std::move(columns)); + } + } + + void Merge(FilterTargets &other) { + found |= other.found; + for (auto &target : other.targets) { + targets.push_back(std::move(target)); + } + } + + bool Complete() const { + return found && !collect; + } + + const bool collect; + bool found = false; + vector targets; +}; + JoinFilterPushdownOptimizer::JoinFilterPushdownOptimizer(Optimizer &optimizer) : optimizer(optimizer) { } @@ -234,18 +263,27 @@ using filter_equality_graph_t = column_binding_map_t>; enum class FilterTargetMode : uint8_t { SCANS, SCANS_AND_CTE_REFERENCES }; +class FilterTargetCacheState { +public: + using group_targets_t = unordered_map; + reference_map_t grouped_targets; + reference_map_t skippable_subtrees; +}; + class FilterTargetFinder { public: explicit FilterTargetFinder(FilterTargetMode mode, EqualityPropagation equality_propagation = EqualityPropagation::DISABLED, - bool cross_secure_views = false) - : mode(mode), equality_propagation(equality_propagation), cross_secure_views(cross_secure_views) { + bool cross_secure_views = false, optional_ptr cache = nullptr) + : mode(mode), equality_propagation(equality_propagation), cross_secure_views(cross_secure_views), cache(cache) { } - void Find(LogicalOperator &op, const vector &columns, vector &targets) { + void Find(LogicalOperator &op, const vector &columns, FilterTargets &targets) { FindTargets(op, FilterColumns(columns), targets); } + bool HasGroupTargets(LogicalAggregate &aggregate, vector &group_columns); + private: //! Borrowed for synchronous traversal; remapped columns start without an expansion region. struct FilterColumns { @@ -258,14 +296,14 @@ class FilterTargetFinder { const optional_ptr expanded_for; }; - void FindTargets(LogicalOperator &op, const FilterColumns &state, vector &targets); - void FindJoinFilterTargets(LogicalOperator &op, const FilterColumns &state, vector &targets); + void FindTargets(LogicalOperator &op, const FilterColumns &state, FilterTargets &targets); + void FindJoinFilterTargets(LogicalOperator &op, const FilterColumns &state, FilterTargets &targets); void FindSetOperationFilterTargets(LogicalSetOperation &setop, const vector &columns, - vector &targets); + FilterTargets &targets); void FindWindowFilterTargets(LogicalWindow &window, const vector &columns, - vector &targets); + FilterTargets &targets); static void FindScanFilterTargets(LogicalGet &get, const vector &columns, - vector &targets); + FilterTargets &targets); static void PushdownProjectionColumns(LogicalProjection &proj, const vector &columns, vector &projected_columns); static void PushdownAggregateColumns(LogicalAggregate &aggr, const vector &columns, @@ -277,6 +315,7 @@ class FilterTargetFinder { static void CollectJoinFilterEqualities(const LogicalComparisonJoin &join, filter_equality_graph_t &equalities); static bool OperatorHasVolatileExpressions(const LogicalOperator &op); static bool FilterTargetPreservesLeftInput(JoinType type); + static bool FilterTargetPreservesRightInput(JoinType type); const filter_equality_graph_t &GetEqualities(const LogicalOperator &op); void CollectEqualities(const LogicalOperator &op, const shared_ptr &graph); @@ -287,6 +326,7 @@ class FilterTargetFinder { const FilterTargetMode mode; const EqualityPropagation equality_propagation; const bool cross_secure_views; + optional_ptr cache; reference_map_t skippable_subtrees; reference_map_t> equality_graphs; }; @@ -353,7 +393,7 @@ void FilterTargetFinder::CollectJoinFilterEqualities(const LogicalComparisonJoin } void FilterTargetFinder::FindScanFilterTargets(LogicalGet &get, const vector &columns, - vector &targets) { + FilterTargets &targets) { if (!get.function.filter_pushdown || get.ordinality_idx.IsValid() || get.extra_info.sample_options) { return; } @@ -393,7 +433,7 @@ void FilterTargetFinder::FindScanFilterTargets(LogicalGet &get, const vector &columns, - vector &targets) { + FilterTargets &targets) { for (auto &child : setop.children) { vector child_columns; const auto child_bindings = child->GetColumnBindings(); @@ -419,7 +459,7 @@ void FilterTargetFinder::FindSetOperationFilterTargets(LogicalSetOperation &seto child_columns.push_back(std::move(candidate)); } FindTargets(*child, FilterColumns(child_columns), targets); - if (setop.type == LogicalOperatorType::LOGICAL_EXCEPT) { + if (targets.Complete() || setop.type == LogicalOperatorType::LOGICAL_EXCEPT) { break; } } @@ -440,6 +480,17 @@ bool FilterTargetFinder::FilterTargetPreservesLeftInput(JoinType type) { } } +bool FilterTargetFinder::FilterTargetPreservesRightInput(JoinType type) { + switch (type) { + case JoinType::RIGHT: + case JoinType::RIGHT_SEMI: + case JoinType::RIGHT_ANTI: + return true; + default: + return false; + } +} + const filter_equality_graph_t &FilterTargetFinder::GetEqualities(const LogicalOperator &op) { auto entry = equality_graphs.find(op); if (entry != equality_graphs.end()) { @@ -451,12 +502,13 @@ const filter_equality_graph_t &FilterTargetFinder::GetEqualities(const LogicalOp } bool FilterTargetFinder::CanSkipSubtree(const LogicalOperator &op) { - auto entry = skippable_subtrees.find(op); - if (entry != skippable_subtrees.end()) { + auto &skippable = cache ? cache->skippable_subtrees : skippable_subtrees; + auto entry = skippable.find(op); + if (entry != skippable.end()) { return entry->second; } const auto result = CanSkipSubtreeInternal(op); - skippable_subtrees.emplace(op, result); + skippable.emplace(op, result); return result; } @@ -575,14 +627,26 @@ FilterTargetFinder::ExpandEquivalentFilterColumns(const filter_equality_graph_t } void FilterTargetFinder::FindJoinFilterTargets(LogicalOperator &op, const FilterColumns &state, - vector &targets) { + FilterTargets &targets) { if (OperatorHasVolatileExpressions(op)) { return; } const auto inner = op.type == LogicalOperatorType::LOGICAL_CROSS_PRODUCT || op.Cast().join_type == JoinType::INNER; - if (!inner && !FilterTargetPreservesLeftInput(op.Cast().join_type)) { - return; + if (!inner) { + const auto join_type = op.Cast().join_type; + if (FilterTargetPreservesRightInput(join_type)) { + FilterTargets right_targets(targets.collect); + FindTargets(*op.children[1], state, right_targets); + // An empty build can skip the probe input, including expressions outside the filtered branch. + if (right_targets.found && CanSkipSubtree(*op.children[0])) { + targets.Merge(right_targets); + } + return; + } + if (!FilterTargetPreservesLeftInput(join_type)) { + return; + } } optional_ptr equalities; if (inner && equality_propagation == EqualityPropagation::ENABLED) { @@ -596,21 +660,19 @@ void FilterTargetFinder::FindJoinFilterTargets(LogicalOperator &op, const Filter // Remapping creates fresh state; unchanged columns share their expansion within the same equality region. const FilterColumns child_state(needs_expansion ? expanded_columns : state.columns, equalities); FindTargets(*op.children[0], child_state, targets); - if (!inner) { + if (!inner || targets.Complete()) { return; } - vector right_targets; + FilterTargets right_targets(targets.collect); FindTargets(*op.children[1], child_state, right_targets); // An empty build can skip the probe input, including expressions outside the filtered branch. - if (!right_targets.empty() && CanSkipSubtree(*op.children[0])) { - for (auto &target : right_targets) { - targets.push_back(std::move(target)); - } + if (right_targets.found && CanSkipSubtree(*op.children[0])) { + targets.Merge(right_targets); } } void FilterTargetFinder::FindWindowFilterTargets(LogicalWindow &window, const vector &columns, - vector &targets) { + FilterTargets &targets) { vector partition_columns; for (auto &filter : columns) { bool shared_partition = filter.probe_column_index.table_index != window.window_index; @@ -632,7 +694,7 @@ void FilterTargetFinder::FindWindowFilterTargets(LogicalWindow &window, const ve FindTargets(*window.children[0], FilterColumns(partition_columns), targets); } -void FilterTargetFinder::FindTargets(LogicalOperator &op, const FilterColumns &state, vector &targets) { +void FilterTargetFinder::FindTargets(LogicalOperator &op, const FilterColumns &state, FilterTargets &targets) { const auto &columns = state.columns; if (columns.empty() || OperatorHasVolatileExpressions(op)) { return; @@ -667,7 +729,7 @@ void FilterTargetFinder::FindTargets(LogicalOperator &op, const FilterColumns &s accepted.push_back(std::move(column)); } if (!accepted.empty()) { - targets.emplace_back(ref, std::move(accepted)); + targets.Add(ref, std::move(accepted)); } break; } @@ -679,8 +741,13 @@ void FilterTargetFinder::FindTargets(LogicalOperator &op, const FilterColumns &s } case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: { vector group_columns; - PushdownAggregateColumns(op.Cast(), columns, group_columns); - FindTargets(*op.children[0], FilterColumns(group_columns), targets); + auto &aggregate = op.Cast(); + PushdownAggregateColumns(aggregate, columns, group_columns); + if (cache) { + targets.found |= HasGroupTargets(aggregate, group_columns); + } else { + FindTargets(*op.children[0], FilterColumns(group_columns), targets); + } break; } case LogicalOperatorType::LOGICAL_ANY_JOIN: { @@ -737,15 +804,60 @@ void FilterTargetFinder::FindTargets(LogicalOperator &op, const FilterColumns &s } } +bool FilterTargetFinder::HasGroupTargets(LogicalAggregate &aggregate, vector &group_columns) { + // Group remapping starts a new equality region, independent of the path used to reach the aggregate. + auto &answers = cache->grouped_targets[aggregate]; + for (auto &column : group_columns) { + auto entry = answers.find(column); + if (entry != answers.end()) { + if (entry->second) { + return true; + } + continue; + } + vector input; + input.push_back(std::move(column)); + FilterTargets result(false); + FindTargets(*aggregate.children[0], FilterColumns(input), result); + answers.emplace(std::move(input[0]), result.found); + if (result.found) { + return true; + } + } + return false; +} + +JoinFilterTargetCache::JoinFilterTargetCache() : state(make_uniq()) { +} + +JoinFilterTargetCache::~JoinFilterTargetCache() = default; + +bool JoinFilterTargetCache::HasTargets(LogicalAggregate &aggregate) { + D_ASSERT(aggregate.groups.size() == 1); + JoinFilterPushdownColumn column; + if (!JoinFilterPushdownUtil::PushdownJoinFilterExpression(*aggregate.groups[0], column)) { + return false; + } + vector group_columns; + group_columns.push_back(std::move(column)); + FilterTargetFinder finder(FilterTargetMode::SCANS, EqualityPropagation::ENABLED, false, state.get()); + return finder.HasGroupTargets(aggregate, group_columns); +} + +void JoinFilterTargetCache::Invalidate(const LogicalOperator &op) { + state->grouped_targets.erase(op); + state->skippable_subtrees.erase(op); +} + void JoinFilterPushdownOptimizer::GetPushdownFilterTargets(LogicalOperator &op, const vector &columns, vector &targets, EqualityPropagation equality_propagation, bool cross_secure_views) { FilterTargetFinder finder(FilterTargetMode::SCANS, equality_propagation, cross_secure_views); - vector result; + FilterTargets result(true); finder.Find(op, columns, result); - for (auto &target : result) { + for (auto &target : result.targets) { targets.emplace_back(target.op.Cast(), std::move(target.columns)); } } @@ -754,9 +866,9 @@ void JoinFilterPushdownOptimizer::GetCTEFilterTargets( LogicalOperator &op, const vector &columns, reference_map_t> &targets) { FilterTargetFinder finder(FilterTargetMode::SCANS_AND_CTE_REFERENCES); - vector result; + FilterTargets result(true); finder.Find(op, columns, result); - for (auto &target : result) { + for (auto &target : result.targets) { if (target.op.type != LogicalOperatorType::LOGICAL_CTE_REF) { continue; } @@ -789,15 +901,11 @@ bool JoinFilterPushdownOptimizer::IsFiltering(const unique_ptr } } -static void SimplifyJoinFilterCastChain(ClientContext &context, JoinFilterPushdownColumn &column, - ExpressionType comparison) { - if (comparison != ExpressionType::COMPARE_EQUAL || column.mode != JoinFilterPushdownMode::RECONSTRUCT_EXPRESSION || - !IsJoinFilterPushdownIntegralType(column.storage_type) || !column.input_expression) { - return; - } +//! Collect the casts of input (outermost first) when it is a chain of built-in integral casts over the scan value +static bool GetIntegralCastChain(ClientContext &context, const Expression &input, + vector> &casts) { auto &cast_functions = CastFunctionSet::Get(context); - optional_ptr current = column.input_expression.get(); - idx_t cast_count = 0; + optional_ptr current = &input; while (BoundCastExpression::IsCast(*current)) { auto &cast = current->Cast(); const auto &source_type = BoundCastExpression::Child(cast).GetReturnType(); @@ -805,12 +913,70 @@ static void SimplifyJoinFilterCastChain(ClientContext &context, JoinFilterPushdo if (!IsJoinFilterPushdownIntegralType(source_type) || !IsJoinFilterPushdownIntegralType(target_type) || !RuntimeFilterCastUtil::IsBuiltinCast(cast) || cast_functions.CanOverrideDefaultCast(source_type, target_type)) { - return; + return false; } - cast_count++; + casts.push_back(cast); current = BoundCastExpression::Child(cast); } - if (cast_count < 2 || current->GetExpressionClass() != ExpressionClass::BOUND_REF || + return current->GetExpressionClass() == ExpressionClass::BOUND_REF; +} + +//! Prove from the statistics of the scanned column that every cast of the filter input succeeds and returns its +//! input value. A built-in integral cast returns the value of every input its target type can represent, and the +//! represented values of an integral type are a contiguous range, so the column's min/max decide it. +static void ProveValuePreservingInput(ClientContext &context, LogicalGet &get, JoinFilterPushdownColumn &column) { + if (column.mode != JoinFilterPushdownMode::RECONSTRUCT_EXPRESSION || !column.input_expression || + !IsJoinFilterPushdownIntegralType(column.storage_type)) { + return; + } + vector> casts; + if (!GetIntegralCastChain(context, *column.input_expression, casts) || casts.empty()) { + return; + } + // the filter values have the outermost target type and are compared in the storage type + auto &filter_type = column.input_expression->GetReturnType(); + if (!Value::MinimumValue(filter_type).DefaultTryCastAs(column.storage_type, nullptr, true) || + !Value::MaximumValue(filter_type).DefaultTryCastAs(column.storage_type, nullptr, true)) { + return; + } + auto &column_index = column.probe_column_index.column_index; + auto stats = StatisticsPropagator::GetColumnStatistics(context, get, get.GetColumnIndex(column_index)); + if (!stats) { + return; + } + // optional filters are wrapped in a function and do not narrow the statistics + auto filter = get.table_filters.TryGetFilterByColumnIndex(column_index); + if (filter) { + StatisticsPropagator::UpdateFilterStatistics(*stats, *filter); + } + if (!NumericStats::HasMinMax(*stats)) { + return; + } + auto min = NumericStats::Min(*stats); + auto max = NumericStats::Max(*stats); + for (idx_t i = casts.size(); i > 0; i--) { + auto &target_type = casts[i - 1].get().GetReturnType(); + auto cast_min = min.DefaultTryCastAs(target_type, nullptr, true); + auto cast_max = max.DefaultTryCastAs(target_type, nullptr, true); + if (!cast_min || !cast_max) { + return; + } + min = std::move(*cast_min); + max = std::move(*cast_max); + } + column.value_preserving_input = true; +} + +static void SimplifyJoinFilterCastChain(ClientContext &context, JoinFilterPushdownColumn &column, + ExpressionType comparison) { + if (comparison != ExpressionType::COMPARE_EQUAL || column.mode != JoinFilterPushdownMode::RECONSTRUCT_EXPRESSION || + !IsJoinFilterPushdownIntegralType(column.storage_type) || !column.input_expression || + column.value_preserving_input) { + return; + } + auto &cast_functions = CastFunctionSet::Get(context); + vector> casts; + if (!GetIntegralCastChain(context, *column.input_expression, casts) || casts.size() < 2 || cast_functions.CanOverrideDefaultCast(column.storage_type, column.input_expression->GetReturnType())) { return; } @@ -919,10 +1085,27 @@ static void MakeRedundantProbeFiltersAdaptive(LogicalComparisonJoin &join) { } void JoinFilterPushdownOptimizer::GenerateJoinFilters(LogicalComparisonJoin &join) { - if (!CanGenerateJoinFilters(join)) { + const auto can_pushdown = CanGenerateJoinFilters(join); + const auto collect_probe_filter_min_max = + !can_pushdown && join.conditions.size() == 1 && join.conditions[0].IsComparison() && + join.conditions[0].GetComparisonType() == ExpressionType::COMPARE_EQUAL && + !join.conditions[0].GetLHS().IsVolatile() && + PrefixRangeFilter::SupportedType(join.conditions[0].GetRHS().GetReturnType()); + if (!can_pushdown && !collect_probe_filter_min_max) { return; } - MakeRedundantProbeFiltersAdaptive(join); + if (collect_probe_filter_min_max) { + // Avoid min/max collection when estimates already rule out a join-local filter. + // Finalize checks the same cost guards again using the actual build count. + const auto build_estimate = join.children[1]->EstimateCardinality(optimizer.GetContext()); + const auto probe_estimate = join.children[0]->EstimateCardinality(optimizer.GetContext()); + if (!JoinFilterPushdownUtil::CanBuildProbeFilter(build_estimate, probe_estimate)) { + return; + } + } + if (can_pushdown) { + MakeRedundantProbeFiltersAdaptive(join); + } // re-order conditions here - otherwise this will happen later on and invalidate the indexes we generate PhysicalComparisonJoin::ReorderConditions(join.conditions); auto pushdown_info = make_uniq(); @@ -945,23 +1128,26 @@ void JoinFilterPushdownOptimizer::GenerateJoinFilters(LogicalComparisonJoin &joi continue; } - JoinFilterPushdownColumn pushdown_col; - if (!JoinFilterPushdownUtil::PushdownJoinFilterExpression(cond.GetLHS(), pushdown_col)) { - continue; + if (can_pushdown) { + JoinFilterPushdownColumn pushdown_col; + if (!JoinFilterPushdownUtil::PushdownJoinFilterExpression(cond.GetLHS(), pushdown_col)) { + continue; + } + pushdown_col.join_filter_idx = pushdown_info->join_condition.size(); + pushdown_columns.push_back(std::move(pushdown_col)); } - - pushdown_col.join_filter_idx = pushdown_info->join_condition.size(); - pushdown_columns.push_back(std::move(pushdown_col)); pushdown_info->join_condition.push_back(cond_idx); } - if (pushdown_columns.empty()) { + if (pushdown_info->join_condition.empty()) { // could not generate any filters - bail-out return; } // recurse the query tree to find the LogicalGets in which we can push the filter info vector pushdown_filter_targets; - GetPushdownFilterTargets(*join.children[0], pushdown_columns, pushdown_filter_targets, EqualityPropagation::ENABLED, - true); + if (can_pushdown) { + GetPushdownFilterTargets(*join.children[0], pushdown_columns, pushdown_filter_targets, + EqualityPropagation::ENABLED, true); + } for (auto &target : pushdown_filter_targets) { vector get_columns; for (auto &column : target.columns) { @@ -971,6 +1157,9 @@ void JoinFilterPushdownOptimizer::GenerateJoinFilters(LogicalComparisonJoin &joi column.mode != JoinFilterPushdownMode::RECONSTRUCT_EXPRESSION) { continue; } + if (use_scan_statistics) { + ProveValuePreservingInput(optimizer.GetContext(), target.get, column); + } SimplifyJoinFilterCastChain(optimizer.GetContext(), column, comparison); get_columns.push_back(std::move(column)); } @@ -1007,7 +1196,7 @@ void JoinFilterPushdownOptimizer::GenerateJoinFilters(LogicalComparisonJoin &joi } } - if (pushdown_info->probe_info.empty()) { + if (pushdown_info->probe_info.empty() && !collect_probe_filter_min_max) { // no table sources found in which we can push down filters return; } diff --git a/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp b/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp index 78901ff79..10a03b4dc 100644 --- a/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp +++ b/src/duckdb/src/optimizer/join_order/cardinality_estimator.cpp @@ -1213,6 +1213,9 @@ optional CardinalityEstimator::ColumnProjection::ProjectInp if (op.type == JoinOrderOperatorType::LEFT) { join_rows = estimator.EstimateLeftJoinCardinality(*boundary, left, right); result->semi_anti_join_domain_evidence.Invalidate(); + if (!on_left) { + result->base_stats = nullptr; + } } else if (op.type == JoinOrderOperatorType::MARK) { join_rows = left_rows; } else { @@ -1315,6 +1318,36 @@ optional CardinalityEstimator::ColumnProjection::ProjectCol return result; } +CardinalityValue CardinalityEstimator::EstimateValueRows(JoinRelationSet &set, ColumnBinding binding) { + auto rows = EstimateCardinality(set); + optional_ptr region; + auto boundary = FindBoundary(set, region); + if (!boundary) { + return rows; + } + // rows holding the binding's values, and the input whose rows they duplicate + CardinalityValue holder_rows = rows; + optional_ptr input; + if (region->count < set.count) { + input = ContainsBinding(*region, binding) ? *region : set_manager.Difference(set, *region); + } else { + auto &op = boundary->op.get(); + auto &left = set_manager.Intersection(set, op.left_relations); + auto &right = set_manager.Intersection(set, op.right_relations); + input = ContainsBinding(left, binding) ? left : right; + if (op.type == JoinOrderOperatorType::LEFT && input.get() == &right) { + // only matched rows hold right-side values, the NULL-extended rows hold none + holder_rows = MinValue(rows, EstimateCardinality(left) * EstimateCardinality(right) * + boundary->selectivity * GetJoinSelectivity(set, left, right)); + } + } + auto input_rows = EstimateCardinality(*input); + if (input_rows.IsZero()) { + return CardinalityValue(0); + } + return EstimateValueRows(*input, binding) * (holder_rows / input_rows); +} + optional CardinalityEstimator::ColumnProjection::ProjectStats(const vector &bindings) { RelationStats result; result.cardinality = estimator.EstimateCardinality(set); @@ -1329,6 +1362,15 @@ optional CardinalityEstimator::ColumnProjection::ProjectStats(con return {}; } result.columns.push_back(*column); + // list totals scale with the duplication of their leaf rows, the MARK slot carries none + auto &leaf = estimator.state->leaves[binding.table_index.index]; + auto column_index = binding.column_index.GetIndex(); + if (column_index >= leaf.columns.size() || !leaf.columns[column_index].list_stats) { + continue; + } + // NULL-extended rows hold no lists: scale by the rows that hold the leaf's values + result.columns.back().list_stats = RelationStatisticsHelper::ScaleListStats( + leaf.columns[column_index].list_stats, leaf.cardinality, estimator.EstimateValueRows(set, binding)); } result.stats_initialized = true; result.Verify(bindings); diff --git a/src/duckdb/src/optimizer/join_order/join_order_optimizer.cpp b/src/duckdb/src/optimizer/join_order/join_order_optimizer.cpp index 724f2157b..8da840dc4 100644 --- a/src/duckdb/src/optimizer/join_order/join_order_optimizer.cpp +++ b/src/duckdb/src/optimizer/join_order/join_order_optimizer.cpp @@ -128,8 +128,9 @@ unique_ptr JoinOrderOptimizer::Optimize(unique_ptr definition) { + materialized_cte_stats.emplace(index, MaterializedCTEStats(std::move(stats), definition)); } RelationStats JoinOrderOptimizer::GetMaterializedCTEStats(TableIndex index) { @@ -137,7 +138,12 @@ RelationStats JoinOrderOptimizer::GetMaterializedCTEStats(TableIndex index) { if (it == materialized_cte_stats.end()) { throw InternalException("Unable to find materialized CTE stats with index %llu", index.index); } - return it->second; + return it->second.stats; +} + +optional_ptr JoinOrderOptimizer::GetMaterializedCTEDefinition(TableIndex index) const { + auto it = materialized_cte_stats.find(index); + return it == materialized_cte_stats.end() ? nullptr : it->second.definition; } void JoinOrderOptimizer::AddDelimScanStats(RelationStats &stats) { diff --git a/src/duckdb/src/optimizer/join_order/query_graph.cpp b/src/duckdb/src/optimizer/join_order/query_graph.cpp index ddef03b7c..fe45484ac 100644 --- a/src/duckdb/src/optimizer/join_order/query_graph.cpp +++ b/src/duckdb/src/optimizer/join_order/query_graph.cpp @@ -14,28 +14,33 @@ NeighborInfo::NeighborInfo(optional_ptr neighbor, optional_ptr< } // LCOV_EXCL_START -static string QueryEdgeToString(const QueryEdge *info, vector prefix) { - string result = ""; - string source = "["; - for (idx_t i = 0; i < prefix.size(); i++) { - source += StringUtil::Format("%llu%s", prefix[i].index, i < prefix.size() - 1 ? ", " : ""); - } - source += "]"; - for (auto &entry : info->neighbors) { - result += StringUtil::Format("%s -> %s\n", source.c_str(), entry->neighbor->ToString().c_str()); - } - for (auto &entry : info->children) { - vector new_prefix = prefix; - new_prefix.push_back(entry.first); - result += QueryEdgeToString(entry.second.get(), new_prefix); +string QueryGraphEdges::ToString() const { + struct EdgeTraversal { + reference edge; + unordered_map>::const_iterator next_child; + }; + vector pending {{root, root.children.begin()}}; + string result; + while (!pending.empty()) { + auto &frame = pending.back(); + if (frame.next_child == frame.edge.get().children.end()) { + pending.pop_back(); + continue; + } + auto &edge = *frame.next_child->second; + ++frame.next_child; + if (!edge.neighbors.empty()) { + D_ASSERT(edge.relations); + auto source = edge.relations->ToString(); + for (auto &neighbor : edge.neighbors) { + result += StringUtil::Format("%s -> %s\n", source.c_str(), neighbor->neighbor->ToString().c_str()); + } + } + pending.push_back({edge, edge.children.begin()}); } return result; } -string QueryGraphEdges::ToString() const { - return QueryEdgeToString(&root, {}); -} - void QueryGraphEdges::Print() { Printer::Print(ToString()); } @@ -49,7 +54,8 @@ optional_ptr QueryGraphEdges::GetQueryEdge(JoinRelationSet &left) { auto entry = info.get()->children.find(left.relations[i]); if (entry == info.get()->children.end()) { // node not found, create it - auto insert_it = info.get()->children.insert(make_pair(left.relations[i], make_uniq())); + owned_edges.push_back(make_uniq()); + auto insert_it = info.get()->children.emplace(left.relations[i], owned_edges.back().get()); entry = insert_it.first; } // move to the next node @@ -100,30 +106,40 @@ void QueryGraphEdges::EnumerateEdges(const std::function info, idx_t index, - const std::function &callback) const { - for (auto &neighbor : info.get().neighbors) { - if (callback(*neighbor)) { - return; - } - } - - for (idx_t node_index = index; node_index < node.count; ++node_index) { - auto iter = info.get().children.find(node.relations[node_index]); - if (iter != info.get().children.end()) { - reference new_info = *iter->second; - EnumerateNeighborsDFS(node, new_info, node_index + 1, callback); - } - } -} - void QueryGraphEdges::EnumerateNeighbors(JoinRelationSet &node, const std::function &callback) const { - for (idx_t j = 0; j < node.count; j++) { - auto iter = root.children.find(node.relations[j]); - if (iter != root.children.end()) { - reference new_info = *iter->second; - EnumerateNeighborsDFS(node, new_info, j + 1, callback); + struct NeighborTraversal { + reference edge; + idx_t next_relation; + }; + vector pending; + NeighborTraversal frame {root, 0}; + while (true) { + if (frame.next_relation == node.count) { + if (pending.empty()) { + break; + } + frame = pending.back(); + pending.pop_back(); + continue; + } + auto index = frame.next_relation++; + auto iter = frame.edge.get().children.find(node.relations[index]); + if (iter == frame.edge.get().children.end()) { + continue; + } + auto &edge = *iter->second; + bool descend = true; + for (auto &neighbor : edge.neighbors) { + if (callback(*neighbor)) { + // Preserve the recursive traversal's pruning of this prefix, not its siblings. + descend = false; + break; + } + } + if (descend && !edge.children.empty()) { + pending.push_back(frame); + frame = {edge, index + 1}; } } } diff --git a/src/duckdb/src/optimizer/join_order/query_graph_manager.cpp b/src/duckdb/src/optimizer/join_order/query_graph_manager.cpp index 1a9bb336b..4439ba814 100644 --- a/src/duckdb/src/optimizer/join_order/query_graph_manager.cpp +++ b/src/duckdb/src/optimizer/join_order/query_graph_manager.cpp @@ -818,22 +818,56 @@ static void OrientInnerConditions(RelationManager &relation_manager, JoinRelatio GenerateJoinRelation QueryGraphManager::GenerateJoins(vector> &extracted_relations, JoinRelationSet &set, CardinalityEstimator &estimator, const vector> &pending_filters) { + enum class TraversalStage { CHILDREN, NODE }; + struct JoinTraversal { + reference node; + TraversalStage stage; + }; + auto find_plan = [&](JoinRelationSet &relation) -> DPJoinNode & { + auto entry = plans->find(relation); + if (entry == plans->end()) { + throw InternalException("Join Order Optimizer Error: No full plan was created"); + } + return *entry->second; + }; + vector pending {{find_plan(set), TraversalStage::CHILDREN}}; + vector children; + while (!pending.empty()) { + auto &frame = pending.back(); + auto &node = frame.node.get(); + if (!node.is_leaf && frame.stage == TraversalStage::CHILDREN) { + frame.stage = TraversalStage::NODE; + // Complete the left subtree before the right subtree: both consume pending filters. + pending.push_back({find_plan(node.right_set), TraversalStage::CHILDREN}); + pending.push_back({find_plan(node.left_set), TraversalStage::CHILDREN}); + continue; + } + pending.pop_back(); + auto result = ReconstructJoinNode(node, extracted_relations, children, estimator, pending_filters); + children.push_back(std::move(result)); + } + D_ASSERT(children.size() == 1); + return std::move(children.back()); +} + +GenerateJoinRelation QueryGraphManager::ReconstructJoinNode(DPJoinNode &node, + vector> &extracted_relations, + vector &children, + CardinalityEstimator &estimator, + const vector> &pending_filters) { optional_ptr left_node; optional_ptr right_node; optional_ptr result_relation; unique_ptr result_operator; optional result_stats; - auto dp_entry = plans->find(set); - if (dp_entry == plans->end()) { - throw InternalException("Join Order Optimizer Error: No full plan was created"); - } - auto &node = dp_entry->second; - if (!dp_entry->second->is_leaf) { - // generate the left and right children - auto left = GenerateJoins(extracted_relations, node->left_set, estimator, pending_filters); - auto right = GenerateJoins(extracted_relations, node->right_set, estimator, pending_filters); - auto descriptor = node->join_operator; + if (!node.is_leaf) { + D_ASSERT(children.size() >= 2); + auto right = std::move(children.back()); + children.pop_back(); + auto left = std::move(children.back()); + children.pop_back(); + auto descriptor = node.join_operator; if (descriptor) { D_ASSERT(descriptor->type == JoinOrderOperatorType::CROSS_PRODUCT || JoinOrderConflictDetector::MustApplyAsOperator(*descriptor)); @@ -884,7 +918,7 @@ GenerateJoinRelation QueryGraphManager::GenerateJoins(vectorpredicates.empty()) { + } else if (node.predicates.empty()) { // no filters, create a cross product result_operator = LogicalCrossProduct::Create(std::move(left.op), std::move(right.op)); } else { @@ -896,7 +930,7 @@ GenerateJoinRelation QueryGraphManager::GenerateJoins(vectorchildren.push_back(std::move(right.op)); // set the join conditions from the join node - for (auto predicate_ref : node->predicates) { + for (auto predicate_ref : node.predicates) { auto f = &predicate_ref.get().GetFilter(); // extract the filter from the operator it originally belonged to auto &filter_and_binding = filters_and_bindings.at(f->filter_index); @@ -939,9 +973,9 @@ GenerateJoinRelation QueryGraphManager::GenerateJoins(vectorset.count == 1); - D_ASSERT(extracted_relations[node->set.relations[0].index]); - result_relation = &node->set; + D_ASSERT(node.set.count == 1); + D_ASSERT(extracted_relations[node.set.relations[0].index]); + result_relation = &node.set; result_operator = std::move(extracted_relations[result_relation->relations[0].index]); } @@ -1073,15 +1107,15 @@ GenerateJoinRelation QueryGraphManager::GenerateJoins(vectorGetColumnBindings()); + result_stats = ProjectStats(estimator, node.set, result_operator->GetColumnBindings()); RelationStats output_stats; if (result_stats) { output_stats = std::move(*result_stats); output_stats.Verify(result_operator->GetColumnBindings()); } else { - output_stats.cardinality = node->cardinality; + output_stats.cardinality = node.cardinality; } - D_ASSERT(output_stats.GetCardinality() == node->cardinality); + D_ASSERT(output_stats.GetCardinality() == node.cardinality); result_operator->SetEstimatedCardinality(output_stats.GetCardinalityForPlan()); return GenerateJoinRelation(result_relation, std::move(result_operator), std::move(output_stats)); } diff --git a/src/duckdb/src/optimizer/join_order/relation_manager.cpp b/src/duckdb/src/optimizer/join_order/relation_manager.cpp index 2a90dee47..957643c0b 100644 --- a/src/duckdb/src/optimizer/join_order/relation_manager.cpp +++ b/src/duckdb/src/optimizer/join_order/relation_manager.cpp @@ -43,18 +43,6 @@ const join_column_sources_t &RelationManager::GetColumnSources() const { static bool OperatorNeedsRelation(LogicalOperatorType op_type); static bool OperatorIsNonReorderable(const LogicalOperator &op); -static RelationStats RecursiveReferenceStats(const RelationStats &input, CardinalityValue rows) { - // The seed and one term do not constrain values, keys or NULLs in later iterations. - RelationStats result; - result.cardinality = rows; - result.stats_initialized = input.stats_initialized; - result.table_name = input.table_name; - for (auto &column : input.columns) { - result.columns.emplace_back(column.binding, DistinctCount(rows, DistinctCountSource::CARDINALITY), column.name); - } - return result; -} - static bool CanReuseAlignedStats(const LogicalOperator &op) { if (OperatorNeedsRelation(op.type) || OperatorIsNonReorderable(op)) { return true; @@ -106,7 +94,8 @@ const SingleJoinRelation &RelationManager::GetRelation(RelationIndex index) cons return *relations.at(index.index); } -bool RelationManager::RegisterRelation(LogicalOperator &op, optional_ptr parent, RelationStats stats) { +bool RelationManager::RegisterRelation(LogicalOperator &op, optional_ptr parent, RelationStats stats, + optional_ptr published_distinctness) { D_ASSERT(!parent || parent->children.size() >= 2); if (!stats.stats_initialized || !stats.MatchesBindings(op.GetColumnBindings())) { stats_complete = false; @@ -118,8 +107,10 @@ bool RelationManager::RegisterRelation(LogicalOperator &op, optional_ptrrecursive_properties.depends_on_recursive_input; } RelationIndex relation_id(relations.size()); - Distinctness distinctness(DistinctnessPropagation::UNARY_OPERATORS_AND_JOINS, context); - auto &unique_sets = distinctness.GetUniqueSets(op); + Distinctness distinctness(DistinctnessPropagation::UNARY_OPERATORS_AND_JOINS, context, + cte_scope ? &*cte_scope : nullptr); + auto &unique_sets = + published_distinctness ? published_distinctness->GetUniqueSets(op) : distinctness.GetUniqueSets(op); auto &unique_keys = relation->stats.unique_keys; unique_keys.clear(); unique_keys.reserve(MinValue(unique_sets.size(), Distinctness::MAX_UNIQUE_SETS)); @@ -234,43 +225,51 @@ static bool HasVisibleEstimationInputs(LogicalOperator &op) { } bool RelationManager::ExtractJoinRelationsForEstimation(RelationStatsExtractor &extractor, LogicalOperator &op, - vector> &filter_operators, - optional_ptr parent) { - // Filters within a region remain part of their leaf's statistics. Root filters can supply join predicates. - if (!parent && op.type == LogicalOperatorType::LOGICAL_FILTER) { - if (!HasVisibleEstimationInputs(op)) { - return false; - } - filter_operators.push_back(op); - return ExtractJoinRelationsForEstimation(extractor, *op.children[0], filter_operators); - } - auto is_inner = op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN && - op.Cast().join_type == JoinType::INNER; - auto is_left = op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN && - op.Cast().join_type == JoinType::LEFT; - if (is_inner || is_left || op.type == LogicalOperatorType::LOGICAL_CROSS_PRODUCT) { - if (!HasVisibleEstimationInputs(op)) { - return false; - } - if (is_left && !HasStableJoinInputs(op.Cast())) { - return false; + vector> &filter_operators) { + struct PendingEstimation { + public: + //! A LEFT join's RHS is one leaf even when it contains further joins. + reference op; + optional_ptr parent; + bool leaf; + }; + cte_scope.emplace(&extractor.GetCTEScope()); + vector pending {{op, nullptr, false}}; + while (!pending.empty()) { + auto item = pending.back(); + pending.pop_back(); + auto ¤t = item.op.get(); + // Filters within a region remain part of their leaf's statistics. + if (!item.leaf && !item.parent && current.type == LogicalOperatorType::LOGICAL_FILTER) { + if (!HasVisibleEstimationInputs(current)) { + return false; + } + filter_operators.push_back(current); + pending.push_back({*current.children[0], nullptr, false}); + continue; } - if (is_inner || is_left) { - filter_operators.push_back(op); + auto is_inner = current.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN && + current.Cast().join_type == JoinType::INNER; + auto is_left = current.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN && + current.Cast().join_type == JoinType::LEFT; + if (!item.leaf && (is_inner || is_left || current.type == LogicalOperatorType::LOGICAL_CROSS_PRODUCT)) { + if (!HasVisibleEstimationInputs(current) || + (is_left && !HasStableJoinInputs(current.Cast()))) { + return false; + } + if (is_inner || is_left) { + filter_operators.push_back(current); + } + pending.push_back({*current.children[1], ¤t, is_left}); + pending.push_back({*current.children[0], ¤t, false}); + continue; } - if (!ExtractJoinRelationsForEstimation(extractor, *op.children[0], filter_operators, op)) { + auto stats = extractor.Extract(current); + if (!stats || !RegisterRelation(current, item.parent, *stats, extractor.GetPublishedDistinctness())) { return false; } - if (is_left) { - // A non-inner boundary owns its entire RHS, including any joins within that subtree. - auto &right = *op.children[1]; - auto stats = extractor.Extract(right); - return stats && RegisterRelation(right, op, *stats); - } - return ExtractJoinRelationsForEstimation(extractor, *op.children[1], filter_operators, op); } - auto stats = extractor.Extract(op); - return stats && RegisterRelation(op, parent, *stats); + return true; } optional RelationManager::AlignStatsWithRelationRoot(LogicalOperator &op, const RelationStats &stats) { @@ -580,6 +579,10 @@ bool RelationManager::AddRelationWithChildren(JoinOrderOptimizer &optimizer, Log stats_complete = false; return false; } + if (op.type == LogicalOperatorType::LOGICAL_UNNEST) { + // a LogicalGet keeps its own source estimate, which can be better than the child cardinality + op.SetEstimatedCardinality(operator_stats->GetCardinalityForPlan()); + } return AddRelation(input_op, parent, *operator_stats); } @@ -587,6 +590,7 @@ bool RelationManager::ExtractJoinRelations(JoinOrderOptimizer &optimizer, Logica vector> &filter_operators, optional_ptr parent) { active_recursive_ctes = optimizer.recursive_cte_indexes; + cte_scope.emplace([&optimizer](TableIndex index) { return optimizer.GetMaterializedCTEDefinition(index); }); // Keep the join-region walk off the call stack: leaf extraction has a substantial frame, and generated // plans (e.g. many DISTINCT aggregates) can contain hundreds of nested binary joins. vector pending_relations {{input_op, parent, false, false}}; @@ -693,7 +697,9 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending auto child_optimizer = optimizer.CreateChildOptimizer(); OptimizeChild(child_optimizer, *op, 0, &child_stats); auto &aggr = op->Cast(); - RelationStatsExtractor extractor(context, optimizer.GetSourceStats()); + RelationStatsExtractor extractor(context, optimizer.GetSourceStats(), [&optimizer](TableIndex index) { + return optimizer.GetMaterializedCTEDefinition(index); + }); auto operator_stats = RelationStatisticsHelper::ExtractAggregationStats(aggr, child_stats, extractor); if (!operator_stats) { stats_complete = false; @@ -815,7 +821,7 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending OptimizeChild(child_optimizer, *op, 0, &child_stats); auto &proj = op->Cast(); // Projection can create columns so we need to add them here - auto proj_stats = RelationStatisticsHelper::ExtractProjectionStats(proj, child_stats); + auto proj_stats = RelationStatisticsHelper::ExtractProjectionStats(proj, child_stats, context); if (!proj_stats) { stats_complete = false; return false; @@ -850,9 +856,13 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending auto child_1_card = lhs_stats.stats_initialized ? lhs_stats.cardinality : 0; if (op->type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) { - lhs_stats = RecursiveReferenceStats(lhs_stats, child_1_card); + lhs_stats = RelationStatisticsHelper::RecursiveReferenceStats(lhs_stats, child_1_card); + } + optional_ptr definition; + if (op->type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { + definition = *op->children[0]; } - rhs_optimizer.AddMaterializedCTEStats(table_index, std::move(lhs_stats)); + rhs_optimizer.AddMaterializedCTEStats(table_index, std::move(lhs_stats), definition); if (op->type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) { rhs_optimizer.recursive_cte_indexes.insert(op->Cast().table_index); } @@ -879,7 +889,7 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending output_stats = RelationStatisticsHelper::RebindOutputStats(rhs_stats, input_op); } if (output_stats && op->type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) { - output_stats = RecursiveReferenceStats(*output_stats, cte_cardinality); + output_stats = RelationStatisticsHelper::RecursiveReferenceStats(*output_stats, cte_cardinality); } op->SetEstimatedCardinality(output_stats ? output_stats->GetCardinalityForPlan() : cte_cardinality.GetIndex()); if (!output_stats || !AddRelation(input_op, parent, *output_stats)) { @@ -966,6 +976,9 @@ bool RelationManager::ExtractJoinRelation(JoinOrderOptimizer &optimizer, Pending } else { for (auto &column : dj_stats.columns) { column.semi_anti_join_domain_evidence.Invalidate(); + if (delim_join.join_type == JoinType::OUTER) { + column.base_stats = nullptr; + } } } diff --git a/src/duckdb/src/optimizer/mark_join_simplifier.cpp b/src/duckdb/src/optimizer/mark_join_simplifier.cpp index 7f1c16dc1..f307b2344 100644 --- a/src/duckdb/src/optimizer/mark_join_simplifier.cpp +++ b/src/duckdb/src/optimizer/mark_join_simplifier.cpp @@ -147,12 +147,9 @@ bool MarkJoinSimplifier::TrySimplifyConstantInput(unique_ptr &o std::move(comparison_right))); auto projection = make_uniq(optimizer.binder.GenerateTableIndex(), std::move(expressions)); projection->children.push_back(std::move(join.children[0])); - projection->ResolveOperatorTypes(); - const auto new_bindings = projection->GetColumnBindings(); - for (idx_t i = 0; i < old_bindings.size(); ++i) { - replacements.Add(old_bindings[i], new_bindings[i]); - } + projection->ResolveOperatorTypesFromChildren(); op = std::move(projection); + ColumnBindingRewrite::ReplaceOutputBindings(op, old_bindings, replacements); return true; } @@ -287,7 +284,6 @@ static void ApplyMarkJoinConversion(Optimizer &optimizer, unique_ptr &)> &rewrite_join) { auto &filter = op->Cast(); auto &original = *filter.children[0]; - original.ResolveOperatorTypes(); const auto old_bindings = original.GetColumnBindings(); vector> expressions; for (idx_t i = 0; i < old_bindings.size(); i++) { @@ -300,26 +296,22 @@ static void ApplyMarkJoinConversion(Optimizer &optimizer, unique_ptr(optimizer.binder.GenerateTableIndex(), std::move(expressions)); BindingReplacementGraph local_replacements; - auto new_bindings = projection->GetColumnBindings(); - for (idx_t i = 0; i < old_bindings.size(); i++) { - if (!local_replacements.Find(old_bindings[i])) { - local_replacements.Add(old_bindings[i], new_bindings[i]); - } - } filter.expressions.erase_at(predicate_index); - ColumnBindingRewrite::RewriteChild( - op, 0, [&](unique_ptr &child, BindingReplacementGraph &child_replacements) { - rewrite_join(child); - auto &join = child->Cast(); - D_ASSERT(join.join_type == JoinType::SEMI || join.join_type == JoinType::ANTI); - projection->children.push_back(std::move(child)); - child = std::move(projection); - child_replacements.Merge(local_replacements); - // CTE nullability analysis needs the replacement attached to the complete plan. - if (join.join_type == JoinType::SEMI) { - SimplifyNullSafeSemiJoinConditions(nullability, join); - } - }); + auto &child = filter.children[0]; + rewrite_join(child); + auto &join = child->Cast(); + D_ASSERT(join.join_type == JoinType::SEMI || join.join_type == JoinType::ANTI); + join.ResolveOperatorTypesFromChildren(); + projection->children.push_back(std::move(child)); + projection->ResolveOperatorTypesFromChildren(); + child = std::move(projection); + ColumnBindingRewrite::ReplaceOutputBindings(child, old_bindings, local_replacements); + ColumnBindingRewrite::ApplyToOperatorBindings(filter, local_replacements); + filter.ResolveOperatorTypesFromChildren(); + // CTE nullability analysis needs the replacement attached to the complete plan. + if (join.join_type == JoinType::SEMI) { + SimplifyNullSafeSemiJoinConditions(nullability, join); + } replacements.Merge(local_replacements); } @@ -367,6 +359,7 @@ bool MarkJoinSimplifier::TrySimplify(unique_ptr &op, NotNullExp nullability, replacements, [&](unique_ptr &child) { auto &converted_join = child->Cast(); converted_join.join_type = target_type; + converted_join.mark_index = TableIndex(); converted_join.mark_types.clear(); }); return true; @@ -557,10 +550,12 @@ bool MarkJoinSimplifier::TrySimplifyDisjunction(unique_ptr &op, } auto build = make_uniq(optimizer.binder.GenerateTableIndex(), std::move(keys)); build->children.push_back(std::move(join.children[1])); + build->ResolveOperatorTypesFromChildren(); builds.push_back(std::move(build)); } auto union_op = make_uniq(union_index, semi->conditions.size(), std::move(builds), LogicalOperatorType::LOGICAL_UNION, true); + union_op->ResolveOperatorTypesFromChildren(); semi->children.push_back(std::move(joins.back().get().children[0])); semi->children.push_back(std::move(union_op)); child = std::move(semi); @@ -570,47 +565,48 @@ bool MarkJoinSimplifier::TrySimplifyDisjunction(unique_ptr &op, return false; } -void MarkJoinSimplifier::Rewrite(unique_ptr &op, NotNullExpressionAnalyzer &nullability, - BindingReplacementGraph &replacements, vector> &ancestors, - bool constant_input_only) { - ancestors.push_back(*op); - for (idx_t child_idx = 0; child_idx < op->children.size(); ++child_idx) { - ColumnBindingRewrite::RewriteChild( - op, child_idx, - [this, &nullability, &replacements, &ancestors, - constant_input_only](unique_ptr &child, BindingReplacementGraph &child_replacements) { - Rewrite(child, nullability, child_replacements, ancestors, constant_input_only); - replacements.Merge(child_replacements); - }); +class MarkJoinSimplifier::RewriteState : public LayoutPreservingRewriter { +public: + RewriteState(MarkJoinSimplifier &simplifier_p, LogicalOperator &plan, bool constant_input_only_p) + : simplifier(simplifier_p), nullability(simplifier.optimizer.context, plan), + constant_input_only(constant_input_only_p) { } - ancestors.pop_back(); - // Visit original consumers before adding their enclosing conversion's replacement edges. - ColumnBindingRewrite::ApplyToOperatorBindings(*op, replacements); - if (constant_input_only) { - TrySimplifyConstantInput(op, replacements); - } else if (op->type == LogicalOperatorType::LOGICAL_FILTER && - (TrySimplify(op, nullability, replacements) || - TrySimplifyDisjunction(op, nullability, ancestors, replacements))) { - auto &filter = op->Cast(); - if (filter.expressions.empty() && !filter.HasProjectionMap()) { - op = std::move(filter.children[0]); + +private: + bool EnterOperator(LogicalOperator &op) override { + ancestors.push_back(op); + return true; + } + + void RewriteOperator(unique_ptr &op, BindingReplacementGraph &replacements) override { + ancestors.pop_back(); + if (constant_input_only) { + simplifier.TrySimplifyConstantInput(op, replacements); + } else if (op->type == LogicalOperatorType::LOGICAL_FILTER && + (simplifier.TrySimplify(op, nullability, replacements) || + simplifier.TrySimplifyDisjunction(op, nullability, ancestors, replacements))) { + auto &filter = op->Cast(); + if (filter.expressions.empty() && !filter.HasProjectionMap()) { + op = std::move(filter.children[0]); + } } } -} -void MarkJoinSimplifier::OptimizeConstantInput(unique_ptr &plan) { - plan->ResolveOperatorTypes(); - NotNullExpressionAnalyzer nullability(optimizer.context, *plan); - BindingReplacementGraph replacements; +private: + MarkJoinSimplifier &simplifier; + NotNullExpressionAnalyzer nullability; + const bool constant_input_only; vector> ancestors; - Rewrite(plan, nullability, replacements, ancestors, true); +}; + +void MarkJoinSimplifier::OptimizeConstantInput(unique_ptr &plan) { + RewriteState state(*this, *plan, true); + state.RewritePlan(plan); } void MarkJoinSimplifier::Optimize(unique_ptr &plan) { - NotNullExpressionAnalyzer nullability(optimizer.context, *plan); - BindingReplacementGraph replacements; - vector> ancestors; - Rewrite(plan, nullability, replacements, ancestors, false); + RewriteState state(*this, *plan, false); + state.RewritePlan(plan); } } // namespace duckdb diff --git a/src/duckdb/src/optimizer/materialized_aggregate_reuse.cpp b/src/duckdb/src/optimizer/materialized_aggregate_reuse.cpp index 5f2eae3ed..b6cd68420 100644 --- a/src/duckdb/src/optimizer/materialized_aggregate_reuse.cpp +++ b/src/duckdb/src/optimizer/materialized_aggregate_reuse.cpp @@ -6,6 +6,7 @@ #include "duckdb/planner/filter/expression_filter.hpp" #include "duckdb/planner/expression/bound_aggregate_expression.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression/bound_operator_expression.hpp" #include "duckdb/planner/expression/bound_reference_expression.hpp" #include "duckdb/planner/expression_iterator.hpp" #include "duckdb/planner/operator/logical_aggregate.hpp" @@ -130,22 +131,29 @@ static bool CollectInnerGraph(LogicalOperator &op, optional_ptr GetDomainCTERef(LogicalOperator &op) { +static optional_ptr GetDomainCTERef(LogicalOperator &op, optional_ptr grouped, + vector> &filters) { reference current(op); - while (current.get().type == LogicalOperatorType::LOGICAL_PROJECTION && current.get().children.size() == 1) { - auto &projection = current.get().Cast(); - for (auto &expression : projection.expressions) { - if (expression->IsVolatile()) { - return nullptr; + while (current.get().children.size() == 1) { + if (current.get().type == LogicalOperatorType::LOGICAL_PROJECTION) { + for (auto &expression : current.get().expressions) { + if (expression->IsVolatile()) { + return nullptr; + } } + } else if (current.get().type == LogicalOperatorType::LOGICAL_FILTER) { + filters.push_back(current.get().Cast()); + } else if (!grouped || !RefersToSameObject(current.get(), *grouped)) { + return nullptr; } - current = *projection.children[0]; + current = *current.get().children[0]; } return current.get().type == LogicalOperatorType::LOGICAL_CTE_REF ? current.get().Cast() : optional_ptr(); } -static optional_idx TraceDomainOutput(LogicalOperator &op, idx_t output_idx, TableIndex cte_index) { +static optional_idx TraceDomainOutput(LogicalOperator &op, idx_t output_idx, TableIndex cte_index, + bool allow_casts = true) { if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { auto &ref = op.Cast(); return ref.cte_index == cte_index ? optional_idx(output_idx) : optional_idx(); @@ -153,14 +161,26 @@ static optional_idx TraceDomainOutput(LogicalOperator &op, idx_t output_idx, Tab if (op.children.size() != 1) { return optional_idx(); } + if (op.type == LogicalOperatorType::LOGICAL_FILTER) { + auto &projection_map = op.Cast().projection_map; + if (!projection_map.empty()) { + if (output_idx >= projection_map.size()) { + return optional_idx(); + } + output_idx = projection_map[output_idx].GetIndex(); + } + return TraceDomainOutput(*op.children[0], output_idx, cte_index, allow_casts); + } if (op.type == LogicalOperatorType::LOGICAL_PROJECTION) { auto &projection = op.Cast(); if (output_idx >= projection.expressions.size()) { return optional_idx(); } auto child_idx = - ColumnOriginHelper::GetInvertibleReferenceIndex(*projection.expressions[output_idx], *op.children[0]); - return child_idx.IsValid() ? TraceDomainOutput(*op.children[0], child_idx.GetIndex(), cte_index) + allow_casts + ? ColumnOriginHelper::GetInvertibleReferenceIndex(*projection.expressions[output_idx], *op.children[0]) + : ColumnOriginHelper::GetDirectReferenceIndex(*projection.expressions[output_idx], *op.children[0]); + return child_idx.IsValid() ? TraceDomainOutput(*op.children[0], child_idx.GetIndex(), cte_index, allow_casts) : optional_idx(); } if (op.type == LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY) { @@ -169,8 +189,10 @@ static optional_idx TraceDomainOutput(LogicalOperator &op, idx_t output_idx, Tab return optional_idx(); } auto child_idx = - ColumnOriginHelper::GetInvertibleReferenceIndex(*aggregate.groups[output_idx], *op.children[0]); - return child_idx.IsValid() ? TraceDomainOutput(*op.children[0], child_idx.GetIndex(), cte_index) + allow_casts + ? ColumnOriginHelper::GetInvertibleReferenceIndex(*aggregate.groups[output_idx], *op.children[0]) + : ColumnOriginHelper::GetDirectReferenceIndex(*aggregate.groups[output_idx], *op.children[0]); + return child_idx.IsValid() ? TraceDomainOutput(*op.children[0], child_idx.GetIndex(), cte_index, allow_casts) : optional_idx(); } return optional_idx(); @@ -183,6 +205,37 @@ struct DomainSemiInfo { vector cte_columns; }; +static optional_ptr GetNotNullSubject(const Expression &expression) { + if (expression.GetExpressionType() != ExpressionType::OPERATOR_IS_NOT_NULL || + expression.GetExpressionClass() != ExpressionClass::BOUND_OPERATOR) { + return nullptr; + } + auto &children = expression.Cast().GetChildren(); + return children.size() == 1 ? children[0].get() : nullptr; +} + +static bool IsRedundantDomainFilter(LogicalFilter &filter, const DomainSemiInfo &domain) { + for (auto &expression : filter.expressions) { + auto subject = GetNotNullSubject(*expression); + if (!subject) { + return false; + } + auto child_idx = ColumnOriginHelper::GetDirectReferenceIndex(*subject, *filter.children[0]); + if (!child_idx.IsValid()) { + return false; + } + // A cast may throw or produce NULL even when its input key is non-NULL. + auto cte_col = + TraceDomainOutput(*filter.children[0], child_idx.GetIndex(), domain.cte_ref.get().cte_index, false); + // Ordinary equality already rejects NULL values in each domain key. + if (!cte_col.IsValid() || std::find(domain.cte_columns.begin(), domain.cte_columns.end(), cte_col.GetIndex()) == + domain.cte_columns.end()) { + return false; + } + } + return true; +} + static optional FindDomainSemi(LogicalOperator &op) { if (op.type == LogicalOperatorType::LOGICAL_PROJECTION || op.type == LogicalOperatorType::LOGICAL_FILTER) { return op.children.size() == 1 ? FindDomainSemi(*op.children[0]) : nullopt; @@ -203,18 +256,15 @@ static optional FindDomainSemi(LogicalOperator &op) { const auto core_child = join.join_type == JoinType::RIGHT_SEMI ? idx_t(1) : idx_t(0); const auto domain_child = 1 - core_child; auto grouped = FindUnaryAggregate(*join.children[domain_child]); - optional_ptr domain_input; if (grouped) { if (!grouped->expressions.empty() || grouped->groups.size() != join.conditions.size() || grouped->children.size() != 1 || grouped->grouping_sets.size() > 1 || !grouped->grouping_functions.empty()) { return nullopt; } - domain_input = grouped->children[0].get(); - } else { - domain_input = join.children[domain_child].get(); } - auto cte_ref = GetDomainCTERef(*domain_input); + vector> filters; + auto cte_ref = GetDomainCTERef(*join.children[domain_child], grouped, filters); if (!cte_ref) { return nullopt; } @@ -237,6 +287,11 @@ static optional FindDomainSemi(LogicalOperator &op) { result.core_keys.push_back(*core_key); result.cte_columns.push_back(cte_col.GetIndex()); } + for (auto &filter : filters) { + if (!IsRedundantDomainFilter(filter, result)) { + return nullopt; + } + } return result; } @@ -276,16 +331,16 @@ static bool IsDomainCorrelationFilter(const TableFilter &filter, const TableColu if (expression.IsVolatile()) { return false; } - vector> children; - ExpressionIterator::EnumerateChildren(expression, [&](const Expression &child) { children.push_back(child); }); // The ordinary equality in the domain SEMI already rejects NULL core keys. - if (expression.GetExpressionType() == ExpressionType::OPERATOR_IS_NOT_NULL && children.size() == 1 && - children[0].get().GetExpressionClass() == ExpressionClass::BOUND_REF) { + auto subject_expression = GetNotNullSubject(expression); + if (subject_expression && subject_expression->GetExpressionClass() == ExpressionClass::BOUND_REF) { return true; } if (expression.GetExpressionType() != ExpressionType::COMPARE_NOT_DISTINCT_FROM) { return false; } + vector> children; + ExpressionIterator::EnumerateChildren(expression, [&](const Expression &child) { children.push_back(child); }); if (children.size() == 2 && Expression::Equals(children[0].get(), children[1].get())) { return true; } diff --git a/src/duckdb/src/optimizer/multi_stage_aggregate_rewriter.cpp b/src/duckdb/src/optimizer/multi_stage_aggregate_rewriter.cpp index 5ca4e5455..0d7fbbe63 100644 --- a/src/duckdb/src/optimizer/multi_stage_aggregate_rewriter.cpp +++ b/src/duckdb/src/optimizer/multi_stage_aggregate_rewriter.cpp @@ -3,6 +3,7 @@ #include "duckdb/common/string_util.hpp" #include "duckdb/function/aggregate/distributive_function_utils.hpp" #include "duckdb/function/function_binder.hpp" +#include "duckdb/optimizer/aggregate_filter_extractor.hpp" #include "duckdb/optimizer/aggregate_rewrite_helper.hpp" #include "duckdb/optimizer/aggregate_rewrite.hpp" #include "duckdb/optimizer/optimizer.hpp" @@ -16,6 +17,7 @@ #include "duckdb/planner/operator/logical_aggregate.hpp" #include "duckdb/planner/operator/logical_comparison_join.hpp" #include "duckdb/planner/operator/logical_cross_product.hpp" +#include "duckdb/planner/operator/logical_filter.hpp" #include "duckdb/planner/operator/logical_materialized_cte.hpp" #include "duckdb/planner/operator/logical_projection.hpp" @@ -43,12 +45,15 @@ struct DistinctAggregateSet { }; struct AggregateRewriteSet { - AggregateRewriteSet(idx_t source_index, unique_ptr plan_p) : plan(std::move(plan_p)) { + AggregateRewriteSet(idx_t source_index, unique_ptr plan_p, + unique_ptr input_filter_p) + : plan(std::move(plan_p)), input_filter(std::move(input_filter_p)) { aggregate_indices.push_back(source_index); results.push_back(std::move(plan->result)); } unique_ptr plan; + unique_ptr input_filter; vector aggregate_indices; vector> results; }; @@ -117,11 +122,10 @@ static bool OrderExpressionsEqual(const vector> &lhs, return true; } -static unique_ptr CreateFinalAggregate(const BoundAggregateExpression &source, - const DistinctAggregateSet &set, - TableIndex input_table, idx_t order_column_offset, - const vector &value_columns, - optional_idx filter_column_offset = optional_idx()) { +static unique_ptr +CreateFinalAggregate(const LogicalAggregate &aggr, const BoundAggregateExpression &source, + const DistinctAggregateSet &set, TableIndex input_table, idx_t order_column_offset, + const vector &value_columns, optional_idx filter_column_offset = optional_idx()) { auto result = unique_ptr_cast(source.Copy()); result->GetAggregateTypeMutable() = AggregateType::NON_DISTINCT; result->GetChildrenMutable().clear(); @@ -152,8 +156,9 @@ static unique_ptr CreateFinalAggregate(const BoundAggr result->GetOrderBysMutable().reset(); } if (filter_column_offset.IsValid()) { - result->GetFilterMutable() = make_uniq( + unique_ptr filter = make_uniq( LogicalType::BOOLEAN, ColumnBinding(input_table, ProjectionIndex(filter_column_offset.GetIndex()))); + result->GetFilterMutable() = AggregateFilterExtractor::GuardDeferredFilter(aggr, source, std::move(filter)); } else { result->GetFilterMutable().reset(); } @@ -248,7 +253,7 @@ static BranchResult CreateDistinctBranch(Optimizer &optimizer, LogicalAggregate const auto order_column_offset = group_count + source_aggregate.GetChildren().size(); for (auto aggregate_idx : set.aggregate_indices) { auto &aggregate = aggr.expressions[aggregate_idx]->Cast(); - final_aggregates.push_back(CreateFinalAggregate(aggregate, set, distinct_group_index, order_column_offset, + final_aggregates.push_back(CreateFinalAggregate(aggr, aggregate, set, distinct_group_index, order_column_offset, value_columns, filter_column_offset)); } @@ -297,8 +302,10 @@ static optional_idx FindExpression(const vector> &express return optional_idx(); } -static bool TryMergeRewrite(AggregateRewriteSet &target, idx_t source_index, AggregateRewritePlan &candidate) { - if (target.plan->stages.size() != candidate.stages.size() || target.plan->result_stage != candidate.result_stage) { +static bool TryMergeRewrite(AggregateRewriteSet &target, idx_t source_index, AggregateRewritePlan &candidate, + const unique_ptr &input_filter) { + if (target.plan->stages.size() != candidate.stages.size() || target.plan->result_stage != candidate.result_stage || + !Expression::Equals(target.input_filter, input_filter)) { return false; } @@ -722,6 +729,7 @@ bool MultiStageAggregateRewriter::TryRewrite(unique_ptr &op) { } AggregateRewriteHelper::StageVolatileAggregateInputs(optimizer, aggr, op->children[0]); + AggregateFilterExtractor filter_extractor(optimizer, aggr); vector distinct_sets; vector rewrite_sets; @@ -730,6 +738,7 @@ bool MultiStageAggregateRewriter::TryRewrite(unique_ptr &op) { auto &expr = aggr.expressions[aggregate_idx]; auto &aggregate = expr->Cast(); if (rewrite_candidates[aggregate_idx]) { + auto input_filter = filter_extractor.Extract({aggregate_idx}); AggregateRewriteInput rewrite_input(optimizer, aggr, aggregate); auto rewrite = aggregate.Function().GetRewriteCallback()(rewrite_input); if (!rewrite) { @@ -737,13 +746,13 @@ bool MultiStageAggregateRewriter::TryRewrite(unique_ptr &op) { } bool merged = false; for (auto &set : rewrite_sets) { - if (TryMergeRewrite(set, aggregate_idx, *rewrite)) { + if (TryMergeRewrite(set, aggregate_idx, *rewrite, input_filter)) { merged = true; break; } } if (!merged) { - rewrite_sets.emplace_back(aggregate_idx, std::move(rewrite)); + rewrite_sets.emplace_back(aggregate_idx, std::move(rewrite), std::move(input_filter)); } continue; } @@ -799,32 +808,45 @@ bool MultiStageAggregateRewriter::TryRewrite(unique_ptr &op) { vector branches; vector> branch_plans; - auto CreateBranchInput = [&](column_binding_map_t &input_replacements) { + auto CreateBranchInput = [&](column_binding_map_t &input_replacements, + unique_ptr input_filter) { + unique_ptr input; if (!needs_cte) { - return std::move(op->children[0]); - } - return AggregateRewriteHelper::CreateCTERef(optimizer, cte_index, input_types, input_names, input_bindings, - input_replacements); + input = std::move(op->children[0]); + } else { + input = AggregateRewriteHelper::CreateCTERef(optimizer, cte_index, input_types, input_names, input_bindings, + input_replacements); + } + if (input_filter) { + RebindRewriteExpression(input_filter, input_replacements); + auto filter = make_uniq(std::move(input_filter)); + filter->AddChild(std::move(input)); + input = std::move(filter); + has_new_filters = true; + } + return input; }; for (auto &set : distinct_sets) { column_binding_map_t input_replacements; - auto branch = - CreateDistinctBranch(optimizer, aggr, set, CreateBranchInput(input_replacements), input_replacements); + auto input_filter = filter_extractor.Extract(set.aggregate_indices); + auto input = CreateBranchInput(input_replacements, std::move(input_filter)); + auto branch = CreateDistinctBranch(optimizer, aggr, set, std::move(input), input_replacements); branch_plans.push_back(std::move(branch.plan)); branches.push_back(std::move(branch)); } for (auto &set : rewrite_sets) { column_binding_map_t input_replacements; - auto branch = - CreateRewriteBranch(optimizer, aggr, set, CreateBranchInput(input_replacements), input_replacements); + auto input = CreateBranchInput(input_replacements, std::move(set.input_filter)); + auto branch = CreateRewriteBranch(optimizer, aggr, set, std::move(input), input_replacements); branch_plans.push_back(std::move(branch.plan)); branches.push_back(std::move(branch)); } if (!regular_aggregates.empty()) { column_binding_map_t input_replacements; - auto branch = CreateRegularBranch(optimizer, aggr, regular_aggregates, CreateBranchInput(input_replacements), - input_replacements); + auto input_filter = filter_extractor.Extract(regular_aggregates); + auto input = CreateBranchInput(input_replacements, std::move(input_filter)); + auto branch = CreateRegularBranch(optimizer, aggr, regular_aggregates, std::move(input), input_replacements); branch_plans.push_back(std::move(branch.plan)); branches.push_back(std::move(branch)); } @@ -894,6 +916,10 @@ bool MultiStageAggregateRewriter::WasChanged() const { return changed; } +bool MultiStageAggregateRewriter::HasNewFilters() const { + return has_new_filters; +} + unique_ptr MultiStageAggregateRewriter::VisitReplace(BoundColumnRefExpression &expr, unique_ptr *expr_ptr) { auto entry = replacement_map.find(expr.Binding()); diff --git a/src/duckdb/src/optimizer/optimizer.cpp b/src/duckdb/src/optimizer/optimizer.cpp index 7f9c79028..bd31527e7 100644 --- a/src/duckdb/src/optimizer/optimizer.cpp +++ b/src/duckdb/src/optimizer/optimizer.cpp @@ -10,9 +10,10 @@ #include "duckdb/optimizer/column_lifetime_analyzer.hpp" #include "duckdb/optimizer/common_aggregate_optimizer.hpp" #include "duckdb/optimizer/constant_or_null_simplification.hpp" +#include "duckdb/optimizer/constant_propagation.hpp" #include "duckdb/optimizer/cse_optimizer.hpp" #include "duckdb/optimizer/cte_inlining.hpp" -#include "duckdb/optimizer/cte_filter_pusher.hpp" +#include "duckdb/optimizer/cte_join_filter_pusher.hpp" #include "duckdb/optimizer/deliminator.hpp" #include "duckdb/optimizer/multi_stage_aggregate_rewriter.hpp" #include "duckdb/optimizer/empty_result_pullup.hpp" @@ -63,6 +64,7 @@ #include "duckdb/planner/logical_plan_verifier.hpp" #include "duckdb/planner/planner.hpp" #include "duckdb/planner/operator/logical_prepare.hpp" +#include "duckdb/planner/operator/logical_materialized_cte.hpp" #include "duckdb/planner/operator/logical_secure_view.hpp" #include "duckdb/optimizer/remote_pushdown_optimizer.hpp" #include "duckdb/main/database_manager.hpp" @@ -142,6 +144,22 @@ static bool ContainsDataSource(const LogicalOperator &op) { return false; } +// Optimizers can embed the current database state in the plan, so a reused plan can miss later changes. +static void RequireRebindOfDataDependentPrepares(LogicalOperator &op) { + if (op.type == LogicalOperatorType::LOGICAL_PREPARE) { + auto &prepared = op.Cast().prepared; + if (!prepared->properties.read_databases.empty() && ContainsDataSource(op)) { + prepared->properties.always_require_rebind = true; + // every EXECUTE binds and optimizes the statement again, so the plan is never used + op.children.clear(); + return; + } + } + for (auto &child : op.children) { + RequireRebindOfDataDependentPrepares(*child); + } +} + void Optimizer::OptimizeStatement(unique_ptr &statement) { if (!Settings::Get(context)) { return; @@ -155,6 +173,18 @@ void Optimizer::OptimizeStatement(unique_ptr &statement) { } } +static bool HasMaterializedCTE(const LogicalOperator &op) { + if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { + return true; + } + for (auto &child : op.children) { + if (HasMaterializedCTE(*child)) { + return true; + } + } + return false; +} + void Optimizer::RunBuiltInOptimizers() { switch (plan->type) { case LogicalOperatorType::LOGICAL_TRANSACTION: @@ -224,6 +254,11 @@ void Optimizer::RunBuiltInOptimizers() { remove_redundant_order.Optimize(plan); }); + RunOptimizer(OptimizerType::CONSTANT_PROPAGATION, [&]() { + ConstantPropagation constant_propagation(context); + constant_propagation.Optimize(*plan); + }); + // perform filter pullup RunOptimizer(OptimizerType::FILTER_PULLUP, [&]() { FilterPullup filter_pullup(context); @@ -248,6 +283,7 @@ void Optimizer::RunBuiltInOptimizers() { mark_simplifier.Optimize(plan); }); + bool filter_bindings_changed = false; if (!plan->CTEContainsDML()) { RunOptimizer(OptimizerType::DUPLICATE_ELIMINATED_DOMAIN, [&]() { DuplicateEliminatedDomainOptimizer domain_optimizer(*this); @@ -255,15 +291,20 @@ void Optimizer::RunBuiltInOptimizers() { }); FilterStatisticsOptimizer filter_statistics(*this); - filter_statistics.Optimize(plan); + filter_bindings_changed = filter_statistics.Optimize(plan); + } + if (filter_bindings_changed || + (!OptimizerDisabled(OptimizerType::CTE_FILTER_PUSHER) && HasMaterializedCTE(*plan))) { + RunOptimizer(OptimizerType::FILTER_PUSHDOWN, + [&]() { plan = FilterPushdown::RewriteAndRestrictCTEs(*this, std::move(plan)); }); } - // derive and push filters into materialized CTEs + // Add costed correlation-domain joins after scalar restrictions have reached the CTE producers. RunOptimizer(OptimizerType::CTE_FILTER_PUSHER, [&]() { - CTEFilterPusher cte_filter_pusher(*this); - plan = cte_filter_pusher.Optimize(std::move(plan)); + CTEJoinFilterPusher cte_join_filter_pusher(*this); + cte_join_filter_pusher.Optimize(*plan); }); - CTEFilterPusher::ClearDependencies(*plan); + CTEFilterDependency::Clear(*plan); RunOptimizer(OptimizerType::REGEX_RANGE, [&]() { RegexRangeFilter regex_opt(context); @@ -292,6 +333,17 @@ void Optimizer::RunBuiltInOptimizers() { !OptimizerDisabled(OptimizerType::DISTINCT_AGGREGATE_REWRITE)); aggregate_rewriter.VisitOperator(plan); + if (aggregate_rewriter.HasNewFilters()) { + // Branching exposes filters shared by all aggregates in each branch. + RunOptimizer(OptimizerType::FILTER_PUSHDOWN, + [&]() { plan = FilterPushdown::RewriteAndRestrictCTEs(*this, std::move(plan)); }); + RunOptimizer(OptimizerType::CTE_FILTER_PUSHER, [&]() { + CTEJoinFilterPusher cte_join_filter_pusher(*this); + cte_join_filter_pusher.Optimize(*plan); + }); + CTEFilterDependency::Clear(*plan); + } + RunOptimizer(OptimizerType::DISJUNCTIVE_JOIN_REWRITER, [&]() { DisjunctiveJoinRewriter disjunctive_join_rewriter(binder); plan = disjunctive_join_rewriter.Optimize(std::move(plan)); @@ -613,25 +665,22 @@ unique_ptr Optimizer::LowerMandatoryAggregateRewrites(unique_pt unique_ptr Optimizer::Optimize(unique_ptr plan_p) { plan_p = LowerMandatoryAggregateRewrites(std::move(plan_p)); if (!Settings::Get(context)) { - CTEFilterPusher::ClearDependencies(*plan_p); + CTEFilterDependency::Clear(*plan_p); return plan_p; } Verify(*plan_p); this->plan = std::move(plan_p); - if (plan->type == LogicalOperatorType::LOGICAL_PREPARE) { - auto &prepared = plan->Cast().prepared; - // Optimizers can embed the current database state in the executable plan. - if (!prepared->properties.read_databases.empty() && ContainsDataSource(*plan)) { - prepared->properties.always_require_rebind = true; - } + RequireRebindOfDataDependentPrepares(*plan); + if (plan->type == LogicalOperatorType::LOGICAL_PREPARE && plan->children.empty()) { + return std::move(plan); } for (auto &pre_optimizer_extension : OptimizerExtension::Iterate(context)) { RunOptimizer(OptimizerType::EXTENSION, [&]() { OptimizerExtensionInput input {GetContext(), *this, pre_optimizer_extension.optimizer_info.get()}; if (pre_optimizer_extension.pre_optimize_function) { - CTEFilterPusher::ClearDependencies(*plan); + CTEFilterDependency::Clear(*plan); pre_optimizer_extension.pre_optimize_function(input, plan); } }); diff --git a/src/duckdb/src/optimizer/projection_pullup.cpp b/src/duckdb/src/optimizer/projection_pullup.cpp index 13c9a5591..c226bb70d 100644 --- a/src/duckdb/src/optimizer/projection_pullup.cpp +++ b/src/duckdb/src/optimizer/projection_pullup.cpp @@ -177,6 +177,23 @@ void ProjectionPullup::PullUpNonColrefProjection(unique_ptr &op next.VisitOperator(op); } +static bool HasComputedExpression(const column_binding_map_t> &projection_map) { + for (auto &entry : projection_map) { + auto type = entry.second->GetExpressionType(); + if (type != ExpressionType::BOUND_COLUMN_REF && type != ExpressionType::VALUE_CONSTANT) { + return true; + } + } + return false; +} + +static bool IsInnerJoin(const LogicalOperator &op) { + if (op.type != LogicalOperatorType::LOGICAL_COMPARISON_JOIN && op.type != LogicalOperatorType::LOGICAL_ANY_JOIN) { + return false; + } + return op.Cast().join_type == JoinType::INNER; +} + static bool HasJoinBelow(const LogicalOperator &op) { reference current = op; while (current.get().children.size() == 1) { @@ -203,7 +220,10 @@ static bool IsThrowingProjectionFilter(const Expression &expr, void ProjectionPullup::CanPullThrough(column_binding_map_t> &projection_map, const LogicalProjection &proj, bool &can_pull_through) { - const auto keep_throwing_filters_above = HasJoinBelow(proj); + const auto has_join_below = HasJoinBelow(proj); + // Without a join below, the projection is already a single join-order relation, so pulling its computations + // through an inner join only moves them away from their inputs. + const auto keep_below_inner_joins = !has_join_below && HasComputedExpression(projection_map); // if expressions in the projections are colrefs, we can always pull it up // if it's not a colref, we can pull it up only if it does not appear in the operator enumerate expressions for (idx_t i = parents.size(); i > 0; i--) { @@ -222,17 +242,18 @@ void ProjectionPullup::CanPullThrough(column_binding_map_tGetExpressionType(); - if (type != ExpressionType::BOUND_COLUMN_REF && type != ExpressionType::VALUE_CONSTANT) { - can_pull_through = false; - return; - } + if (HasComputedExpression(projection_map)) { + can_pull_through = false; + return; } } + if (keep_below_inner_joins && IsInnerJoin(parent_op)) { + can_pull_through = false; + return; + } LogicalOperatorVisitor::EnumerateExpressions(parent_op, [&](unique_ptr *expr) { - if (keep_throwing_filters_above && IsThrowingProjectionFilter(**expr, projection_map)) { + if (has_join_below && IsThrowingProjectionFilter(**expr, projection_map)) { can_pull_through = false; return; } diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_aggregate.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_aggregate.cpp index 99dacd1e3..e7bbf8f31 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_aggregate.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_aggregate.cpp @@ -1,4 +1,5 @@ #include "duckdb/optimizer/filter_pushdown.hpp" +#include "duckdb/optimizer/aggregate_filter_extractor.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/expression_iterator.hpp" #include "duckdb/planner/operator/logical_aggregate.hpp" @@ -42,7 +43,18 @@ unique_ptr FilterPushdown::PushdownAggregate(unique_ptr aggregate_indices; + for (idx_t i = 0; i < aggr.expressions.size(); i++) { + aggregate_indices.push_back(i); + } + AggregateFilterExtractor filter_extractor(optimizer, aggr); + auto aggregate_filter = filter_extractor.Extract(aggregate_indices); + if (aggregate_filter && child_pushdown.AddFilter(std::move(aggregate_filter)) == FilterResult::UNSATISFIABLE) { + // An empty input still produces the scalar aggregate's one output row. + op->children[0] = make_uniq(std::move(op->children[0])); + return PushFinalFilters(std::move(op)); + } for (idx_t i = 0; i < filters.size(); i++) { auto &f = *filters[i]; if (f.bindings.find(aggr.aggregate_index) != f.bindings.end()) { diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_cross_product.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_cross_product.cpp index f2ee21c63..c9bb9bd93 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_cross_product.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_cross_product.cpp @@ -57,8 +57,8 @@ static bool HasTransitiveJoinBounds(const vector> &filters) { unique_ptr FilterPushdown::PushdownCrossProduct(unique_ptr op) { D_ASSERT(op->children.size() > 1); - FilterPushdown left_pushdown(optimizer, projection_mode); - FilterPushdown right_pushdown(optimizer, projection_mode); + auto left_pushdown = CreateChildPushdown(); + auto right_pushdown = CreateChildPushdown(); vector> join_expressions; vector> deferred_filters; auto join_ref_type = JoinRefType::REGULAR; diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_semi_anti_join.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_filter_join.cpp similarity index 51% rename from src/duckdb/src/optimizer/pushdown/pushdown_semi_anti_join.cpp rename to src/duckdb/src/optimizer/pushdown/pushdown_filter_join.cpp index 66e69f92c..ebbd2fa61 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_semi_anti_join.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_filter_join.cpp @@ -4,29 +4,52 @@ #include "duckdb/planner/operator/logical_cross_product.hpp" #include "duckdb/planner/operator/logical_empty_result.hpp" #include "duckdb/planner/operator/logical_projection.hpp" +#include "duckdb/planner/subquery/has_volatile_expressions.hpp" namespace duckdb { using Filter = FilterPushdown::Filter; -unique_ptr FilterPushdown::PushdownSemiAntiJoin(unique_ptr op) { +unique_ptr FilterPushdown::PushdownFilterJoin(unique_ptr op) { auto &join = op->Cast(); - FilterPushdown right_pushdown(optimizer, projection_mode); + auto right_pushdown = CreateChildPushdown(); + bool has_volatile_filter = false; if (op->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN && !filters.empty()) { // a right row that matches a left row passes what the filters imply for the right side vector> left_filters; for (auto &filter : filters) { left_filters.push_back(*filter->filter); + has_volatile_filter = has_volatile_filter || filter->filter->IsVolatile(); } + vector> right_filters; FilterCombiner::GenerateJoinFilters( op->Cast().conditions, left_filters, JoinSide::RIGHT, - [&](unique_ptr right_filter) { right_pushdown.AddFilter(std::move(right_filter)); }); - right_pushdown.GenerateFilters(); + [&](unique_ptr right_filter) { right_filters.push_back(std::move(right_filter)); }); + // The filtering MARK path must not prune the input to volatile right-side expressions. + if (!right_filters.empty() && + (join.join_type != JoinType::MARK || !HasVolatileExpressionsIgnoringError(*op->children[1]))) { + op->children[1] = AddLogicalFilter(std::move(op->children[1]), std::move(right_filters)); + } } - // push all current filters down the left side - RewriteChild(*op, 0); right_pushdown.RewriteChild(*op, 1); + // Keep the proof local to this left input and all of its pending filters. + bool left_is_nonvolatile = + op->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN && input_is_nonvolatile && !has_volatile_filter; + // A SEMI join or a required TRUE marker keeps only left rows with a match. + // Pending left filters are not yet part of the child inspected by GenerateJoinFilters. + if (op->type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN && join.join_type != JoinType::ANTI && + !has_volatile_filter) { + auto left_filters = GenerateJoinFilters(op->Cast()); + // Only a nonempty result certifies that inference checked the entire left input. + left_is_nonvolatile = left_is_nonvolatile || !left_filters.empty(); + op->children[0] = AddLogicalFilter(std::move(op->children[0]), std::move(left_filters)); + } + D_ASSERT(!combiner.HasFilters()); + auto left_pushdown = CreateChildPushdown(); + left_pushdown.filters = std::move(filters); + left_pushdown.input_is_nonvolatile = left_is_nonvolatile; + left_pushdown.RewriteChild(*op, 0); bool left_empty = op->children[0]->type == LogicalOperatorType::LOGICAL_EMPTY_RESULT; bool right_empty = op->children[1]->type == LogicalOperatorType::LOGICAL_EMPTY_RESULT; diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_left_join.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_left_join.cpp index 351690036..0782884bb 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_left_join.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_left_join.cpp @@ -1,16 +1,14 @@ -#include "duckdb/common/assert.hpp" #include "duckdb/common/enums/join_type.hpp" #include "duckdb/common/helper.hpp" #include "duckdb/common/typedefs.hpp" #include "duckdb/common/types.hpp" #include "duckdb/common/types/value.hpp" #include "duckdb/common/unique_ptr.hpp" -#include "duckdb/common/unordered_map.hpp" +#include "duckdb/common/unordered_set.hpp" #include "duckdb/common/vector.hpp" #include "duckdb/execution/expression_executor.hpp" #include "duckdb/optimizer/filter_pushdown.hpp" #include "duckdb/optimizer/optimizer.hpp" -#include "duckdb/planner/binder.hpp" #include "duckdb/planner/column_binding.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" #include "duckdb/planner/expression/bound_comparison_expression.hpp" @@ -20,10 +18,8 @@ #include "duckdb/planner/logical_operator.hpp" #include "duckdb/planner/operator/logical_any_join.hpp" #include "duckdb/planner/operator/logical_comparison_join.hpp" -#include "duckdb/planner/operator/logical_cross_product.hpp" -#include "duckdb/planner/operator/logical_dummy_scan.hpp" +#include "duckdb/planner/operator/logical_empty_result.hpp" #include "duckdb/planner/operator/logical_filter.hpp" -#include "duckdb/planner/operator/logical_projection.hpp" #include namespace duckdb { @@ -43,37 +39,6 @@ static unique_ptr ReplaceColRefWithNull(unique_ptr root_ return root_expr; } -static unique_ptr CreateDummyRHS(Optimizer &optimizer, unique_ptr &rhs_op) { - unordered_map>> projections_groups; - auto column_bindings = rhs_op->GetColumnBindings(); - rhs_op->ResolveOperatorTypes(); - auto &types = rhs_op->types; - - for (idx_t i = 0; i < column_bindings.size(); i++) { - projections_groups[column_bindings[i].table_index].emplace_back( - make_uniq(Value(types[i]))); - } - - auto create_proj_dummy_scan = [&](TableIndex table_index) { - auto dummy_scan = make_uniq(optimizer.binder.GenerateTableIndex()); - auto proj = make_uniq(table_index, std::move(projections_groups[table_index])); - proj->AddChild(std::move(dummy_scan)); - return proj; - }; - - auto begin = projections_groups.begin(); - D_ASSERT(begin != projections_groups.end()); - unique_ptr rhs = create_proj_dummy_scan(begin->first); - projections_groups.erase(begin); - - for (auto &group : projections_groups) { - auto proj = create_proj_dummy_scan(group.first); - rhs = LogicalCrossProduct::Create(std::move(rhs), std::move(proj)); - } - - return rhs; -} - static bool FilterRemovesNull(ClientContext &context, ExpressionRewriter &rewriter, Expression *expr, unordered_set &right_bindings) { // make a copy of the expression @@ -112,8 +77,8 @@ unique_ptr FilterPushdown::PushdownLeftJoin(unique_ptr &left_bindings, unordered_set &right_bindings) { auto &join = op->Cast(); - FilterPushdown left_pushdown(optimizer, projection_mode); - FilterPushdown right_pushdown(optimizer, projection_mode); + auto left_pushdown = CreateChildPushdown(); + auto right_pushdown = CreateChildPushdown(); // for a comparison join we create a FilterCombiner that checks if we can push conditions on LHS join conditions // into the RHS of the join FilterCombiner filter_combiner(optimizer); @@ -188,7 +153,6 @@ unique_ptr FilterPushdown::PushdownLeftJoin(unique_ptrtype == LogicalOperatorType::LOGICAL_COMPARISON_JOIN) { @@ -208,14 +172,13 @@ unique_ptr FilterPushdown::PushdownLeftJoin(unique_ptrchildren[1]); - op = LogicalCrossProduct::Create(std::move(op->children[0]), std::move(dummy_rhs)); - rewrite_right = false; - } - - if (rewrite_right) { + // Keep the join so its NULL-extended rows retain the original column bindings. + auto &right = op->children[1]; + if (right->type != LogicalOperatorType::LOGICAL_EMPTY_RESULT) { + right = make_uniq(std::move(right)); + } + } else { right_pushdown.RewriteChild(*op, 1); } diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_mark_join.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_mark_join.cpp index 44ef8c5c2..aeb39aa60 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_mark_join.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_mark_join.cpp @@ -9,12 +9,21 @@ unique_ptr FilterPushdown::PushdownMarkJoin(unique_ptrCast(); D_ASSERT(join.join_type == JoinType::MARK); right_bindings.insert(join.mark_index); - FilterPushdown left_pushdown(optimizer, projection_mode); - FilterPushdown right_pushdown(optimizer, projection_mode); + auto left_pushdown = CreateChildPushdown(); + auto right_pushdown = CreateChildPushdown(); + bool has_volatile_filter = false; for (idx_t i = 0; i < filters.size(); i++) { if (JoinSide::GetJoinSide(filters[i]->bindings, left_bindings, right_bindings) == JoinSide::LEFT) { left_pushdown.filters.push_back(std::move(filters[i])); filters.erase_at(i--); + } else { + has_volatile_filter = has_volatile_filter || filters[i]->filter->IsVolatile(); + } + } + for (auto &filter : filters) { + if (!has_volatile_filter && IsMarkFilter(join, *filter->filter)) { + // Use the SEMI filtering semantics, retaining the MARK operator and its output layout. + return PushFinalFilters(left_pushdown.PushdownFilterJoin(std::move(op))); } } left_pushdown.RewriteChild(*op, 0); diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_materialized_cte.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_materialized_cte.cpp new file mode 100644 index 000000000..2f3281fa5 --- /dev/null +++ b/src/duckdb/src/optimizer/pushdown/pushdown_materialized_cte.cpp @@ -0,0 +1,279 @@ +#include "duckdb/optimizer/filter_pushdown.hpp" + +#include "duckdb/common/reference_map.hpp" +#include "duckdb/optimizer/column_binding_replacer.hpp" +#include "duckdb/optimizer/cte_filter_helpers.hpp" +#include "duckdb/optimizer/optimizer.hpp" +#include "duckdb/planner/expression/bound_conjunction_expression.hpp" +#include "duckdb/planner/expression/expression_barrier.hpp" +#include "duckdb/planner/filter/expression_filter.hpp" +#include "duckdb/planner/logical_operator_visitor.hpp" +#include "duckdb/planner/operator/logical_cteref.hpp" +#include "duckdb/planner/operator/logical_filter.hpp" +#include "duckdb/planner/operator/logical_materialized_cte.hpp" +#include "duckdb/planner/subquery/has_volatile_expressions.hpp" + +namespace duckdb { + +using CTEConsumer = CTEFilterInfo::Consumer; + +static bool ConsumersPermitRestriction(const LogicalMaterializedCTE &cte, const vector &consumers) { + if (consumers.empty()) { + return false; + } + idx_t filtered_count = 0; + optional_ptr filtered_ref; + vector> references; + for (auto &consumer : consumers) { + references.push_back(consumer.ref); + if (consumer.filter) { + filtered_count++; + filtered_ref = consumer.ref; + } + } + if (filtered_count == consumers.size()) { + return true; + } + return filtered_count == 1 && cte.filter_dependency && cte.filter_dependency->MatchesConsumers(references) && + filtered_ref->table_index == cte.filter_dependency->row_scan; +} + +static unique_ptr CopyConsumerFilter(const CTEConsumer &consumer, + const vector &producer_bindings, bool may_skip) { + D_ASSERT(consumer.filter); + auto consumer_bindings = consumer.ref.GetColumnBindings(); + D_ASSERT(consumer_bindings.size() == producer_bindings.size()); + ColumnBindingReplacer replacer; + for (idx_t i = 0; i < consumer_bindings.size(); i++) { + replacer.replacement_bindings.emplace_back(consumer_bindings[i], producer_bindings[i]); + } + + replacer.BuildIndex(); + + bool all_repeatable = true; + for (auto &expr : consumer.filter->expressions) { + all_repeatable &= !expr->IsVolatile() && !ExpressionBarrier::Contains(*expr); + } + auto conjunction = make_uniq(ExpressionType::CONJUNCTION_AND); + for (auto &expr : consumer.filter->expressions) { + if (ExpressionFilter::IsOptionalExpression(*expr)) { + continue; + } + // Dropping a guard must not expose errors it previously short-circuited. + if (expr->IsVolatile() || ExpressionBarrier::Contains(*expr) || + ((!all_repeatable || may_skip) && expr->CanThrow())) { + continue; + } + auto copy = expr->Copy(); + replacer.VisitExpression(©); + conjunction->GetChildrenMutable().push_back(std::move(copy)); + } + if (conjunction->GetChildren().empty()) { + return nullptr; + } + if (conjunction->GetChildren().size() == 1) { + return std::move(conjunction->GetChildrenMutable()[0]); + } + return std::move(conjunction); +} + +static unique_ptr GetConsumerRestriction(CTEFilterInfo &info, + const reference_set_t &conditional_consumers) { + if (!ConsumersPermitRestriction(info.cte, info.consumers) || !info.ValidateProducerBindings()) { + return nullptr; + } + auto disjunction = make_uniq(ExpressionType::CONJUNCTION_OR); + // The coordination walk visits children in reverse order; restore the original OR-arm order. + for (auto it = info.consumers.rbegin(); it != info.consumers.rend(); ++it) { + auto &consumer = *it; + if (!consumer.filter) { + // ConsumersPermitRestriction validated this consumer's dependency on the filtered row scan. + continue; + } + auto conjunction = + CopyConsumerFilter(consumer, info.producer_bindings, conditional_consumers.count(consumer.ref) != 0); + if (!conjunction) { + return nullptr; + } + disjunction->GetChildrenMutable().push_back(std::move(conjunction)); + } + if (disjunction->GetChildren().size() == 1) { + return std::move(disjunction->GetChildrenMutable()[0]); + } + return std::move(disjunction); +} + +struct FilterPushdown::CTEFilterState { + unordered_map deferred_producers; +}; + +//! Ordinary pushdown has settled each consumer region before this walk records its references. +//! Rewrite deferred producers and producers with a new restriction; collected consumer regions remain untouched. +class FilterPushdown::CTEFilterRewriter { + struct Properties { + bool side_effects = false; + bool volatile_expressions = false; + + void Combine(const Properties &other) { + side_effects |= other.side_effects; + volatile_expressions |= other.volatile_expressions; + } + }; + + struct CTEContext { + CTEContext(LogicalMaterializedCTE &cte, idx_t recursive_depth) : info(cte), recursive_depth(recursive_depth) { + } + + CTEFilterInfo info; + idx_t recursive_depth; + reference_set_t conditional_consumers; + }; + +public: + explicit CTEFilterRewriter(FilterPushdown &pushdown) : pushdown(pushdown) { + } + + void Rewrite(LogicalOperator &op) { + Initialize(op); + Visit(op, nullptr); +#ifdef DEBUG + VerifyComplete(op); +#endif + } + +private: + FilterPushdown &pushdown; + unordered_map producer_properties; + unordered_map> active_ctes; + idx_t recursive_depth = 0; + +#ifdef DEBUG + void VerifyComplete(const LogicalOperator &op) const { + // Deferred entries from eliminated branches can remain, but every surviving producer must be visited. + if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { + D_ASSERT(!pushdown.cte_state->deferred_producers.count(op.Cast().table_index)); + } + for (auto &child : op.children) { + VerifyComplete(*child); + } + } +#endif + + static Properties LocalProperties(const LogicalOperator &op) { + Properties result; + result.side_effects = op.HasLocalSideEffects(); + LogicalOperatorVisitor::EnumerateExpressions(op, [&](optional_ptr> expr) { + result.volatile_expressions |= HasVolatileExpressionsIgnoringError(**expr); + }); + return result; + } + + Properties Initialize(LogicalOperator &op) { + auto properties = LocalProperties(op); + for (idx_t i = 0; i < op.children.size(); i++) { + auto child_properties = Initialize(*op.children[i]); + if (i == 0 && op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { + // Producer deferral keeps this subtree untouched until its owner's turn. + auto inserted = + producer_properties.emplace(op.Cast().table_index, child_properties); + D_ASSERT(inserted.second); + } + properties.Combine(child_properties); + } + op.ResolveOperatorTypesFromChildren(); + return properties; + } + + void Visit(LogicalOperator &op, optional_ptr parent) { + if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { + VisitCTE(op.Cast()); + return; + } + if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { + auto &ref = op.Cast(); + auto owner = active_ctes.find(ref.cte_index); + if (owner != active_ctes.end()) { + auto &context = owner->second.get(); + context.info.consumers.emplace_back(ref, parent); + if (recursive_depth > context.recursive_depth) { + // An empty recursive frontier can skip this reader even though its producer runs. + context.conditional_consumers.insert(ref); + } + } + } + for (idx_t i = op.children.size(); i > 0; i--) { + const bool recursive_step = op.type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE && i == 2; + recursive_depth += recursive_step; + Visit(*op.children[i - 1], op); + recursive_depth -= recursive_step; + } + } + + void VisitCTE(LogicalMaterializedCTE &cte) { + CTEContext context(cte, recursive_depth); + auto inserted = active_ctes.emplace(cte.table_index, context); + D_ASSERT(inserted.second); + Visit(*cte.children[1], cte); + auto &producer = producer_properties.at(cte.table_index); + unique_ptr restriction; + if (!producer.side_effects && !producer.volatile_expressions) { + restriction = GetConsumerRestriction(context.info, context.conditional_consumers); + } + active_ctes.erase(cte.table_index); + auto &deferred = pushdown.cte_state->deferred_producers; + auto entry = deferred.find(cte.table_index); + const bool rewrite_producer = restriction || entry != deferred.end(); + // Copied consumer predicates refer to materialized values; do not duplicate their computations. + auto mode = ProjectionMode::PRESERVE_COMPUTED_EXPRESSIONS; + if (entry != deferred.end()) { + if (!restriction) { + mode = entry->second; + } + deferred.erase(entry); + } + if (restriction) { + auto filter = make_uniq(std::move(restriction)); + LogicalFilter::SplitPredicates(filter->expressions); + pushdown.optimizer.rewriter.VisitOperator(*filter); + filter->children.push_back(std::move(cte.children[0])); + filter->ResolveOperatorTypesFromChildren(); + cte.children[0] = std::move(filter); + } + if (rewrite_producer) { + auto producer_pushdown = pushdown.CreateChildPushdown(mode); + cte.children[0] = producer_pushdown.Rewrite(std::move(cte.children[0])); + } + Visit(*cte.children[0], cte); + } +}; + +unique_ptr FilterPushdown::RewriteAndRestrictCTEs(Optimizer &optimizer, + unique_ptr op) { + if (optimizer.OptimizerDisabled(OptimizerType::FILTER_PUSHDOWN)) { + return op; + } + FilterPushdown pushdown(optimizer); + if (optimizer.OptimizerDisabled(OptimizerType::CTE_FILTER_PUSHER)) { + return pushdown.Rewrite(std::move(op)); + } + CTEFilterState state; + pushdown.cte_state = state; + op = pushdown.Rewrite(std::move(op)); + CTEFilterRewriter rewriter(pushdown); + rewriter.Rewrite(*op); + return op; +} + +unique_ptr FilterPushdown::PushdownMaterializedCTE(unique_ptr op) { + if (cte_state) { + // The later entrypoint settles consumers before rewriting their producers. + cte_state->deferred_producers[op->Cast().table_index] = projection_mode; + } else { + auto producer_pushdown = CreateChildPushdown(); + op->children[0] = producer_pushdown.Rewrite(std::move(op->children[0])); + } + op->children[1] = Rewrite(std::move(op->children[1])); + return op; +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_projection.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_projection.cpp index 20eae1a73..892d16c43 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_projection.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_projection.cpp @@ -170,7 +170,7 @@ unique_ptr FilterPushdown::PushdownProjection(unique_ptr> remain_expressions; diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_secure_view.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_secure_view.cpp index 72fa75a5b..ad9e337fd 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_secure_view.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_secure_view.cpp @@ -42,7 +42,7 @@ unique_ptr FilterPushdown::PushdownSecureView(unique_ptrSetEstimatedCardinality(op->children[0]->EstimateCardinality(optimizer.GetContext())); } - FilterPushdown child_pushdown(optimizer, projection_mode); + auto child_pushdown = CreateChildPushdown(); for (auto &f : filters) { auto expr = std::move(f->filter); if (secure_view.has_source) { diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_set_operation.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_set_operation.cpp index d974ce756..a85956df6 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_set_operation.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_set_operation.cpp @@ -71,8 +71,8 @@ unique_ptr FilterPushdown::PushdownSetOperation(unique_ptrchildren.size() == 2); auto comparisons = setop.GetComparisons(optimizer.context); auto left_bindings = op->children[0]->GetColumnBindings(); - FilterPushdown left_pushdown(optimizer, projection_mode); - FilterPushdown right_pushdown(optimizer, projection_mode); + auto left_pushdown = CreateChildPushdown(); + auto right_pushdown = CreateChildPushdown(); for (auto &original_filter : filters) { auto filter = make_uniq(); filter->filter = original_filter->filter->Copy(); @@ -105,7 +105,7 @@ unique_ptr FilterPushdown::PushdownSetOperation(unique_ptrchildren[child_idx]; auto child_bindings = child->GetColumnBindings(); - FilterPushdown child_pushdown(optimizer, projection_mode); + auto child_pushdown = CreateChildPushdown(); for (auto &original_filter : filters) { // first create a copy of the filter auto filter = make_uniq(); diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_single_join.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_single_join.cpp index f04401fc0..4cbad6769 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_single_join.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_single_join.cpp @@ -9,8 +9,8 @@ unique_ptr FilterPushdown::PushdownSingleJoin(unique_ptr &left_bindings, unordered_set &right_bindings) { D_ASSERT(op->Cast().join_type == JoinType::SINGLE); - FilterPushdown left_pushdown(optimizer, projection_mode); - FilterPushdown right_pushdown(optimizer, projection_mode); + auto left_pushdown = CreateChildPushdown(); + auto right_pushdown = CreateChildPushdown(); // now check the set of filters for (idx_t i = 0; i < filters.size(); i++) { auto side = JoinSide::GetJoinSide(filters[i]->bindings, left_bindings, right_bindings); diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_unnest.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_unnest.cpp index 2f6b53577..e65c71c31 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_unnest.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_unnest.cpp @@ -12,7 +12,7 @@ unique_ptr FilterPushdown::PushdownUnnest(unique_ptr> remain_expressions; diff --git a/src/duckdb/src/optimizer/pushdown/pushdown_window.cpp b/src/duckdb/src/optimizer/pushdown/pushdown_window.cpp index e34615fc9..e956d6872 100644 --- a/src/duckdb/src/optimizer/pushdown/pushdown_window.cpp +++ b/src/duckdb/src/optimizer/pushdown/pushdown_window.cpp @@ -176,7 +176,7 @@ bool FilterPushdown::OnlyRanksWithoutArguments(const LogicalWindow &window) { unique_ptr FilterPushdown::PushdownWindow(unique_ptr op) { D_ASSERT(op->type == LogicalOperatorType::LOGICAL_WINDOW); auto &window = op->Cast(); - FilterPushdown pushdown(optimizer, projection_mode); + auto pushdown = CreateChildPushdown(); // 1. Loop through the expressions, find the window expressions and investigate the partitions // if a filter applies to a partition in each window expression then you can push the filter diff --git a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_aggregate.cpp b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_aggregate.cpp new file mode 100644 index 000000000..10c1d48f7 --- /dev/null +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_aggregate.cpp @@ -0,0 +1,495 @@ +#include "duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp" +#include "duckdb/optimizer/relation_statistics/relation_statistics_extractor.hpp" + +#include "duckdb/common/unordered_map.hpp" +#include "duckdb/function/aggregate/distributive_function_utils.hpp" +#include "duckdb/optimizer/distinctness.hpp" +#include "duckdb/planner/column_binding_map.hpp" +#include "duckdb/planner/expression/list.hpp" +#include "duckdb/planner/operator/list.hpp" + +namespace duckdb { + +class GroupingColumnMapper { +public: + explicit GroupingColumnMapper(LogicalOperator &child) { + auto child_bindings = child.GetColumnBindings(); + child_indexes.reserve(child_bindings.size()); + for (idx_t i = 0; i < child_bindings.size(); i++) { + child_indexes.emplace(child_bindings[i], i); + } + } + +public: + optional_idx GetChildIndex(LogicalOperator &projection, idx_t index) const { + if (index >= projection.expressions.size()) { + return {}; + } + auto &expr = *projection.expressions[index]; + if (expr.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { + return {}; + } + auto &column = expr.Cast(); + if (column.Depth() != 0) { + return {}; + } + return GetChildIndex(column.Binding()); + } + + optional_idx GetChildIndex(const ColumnBinding &binding) const { + auto match = child_indexes.find(binding); + if (match == child_indexes.end()) { + return {}; + } + return match->second; + } + +private: + column_binding_map_t child_indexes; +}; + +CardinalityValue RelationStatisticsHelper::EstimateGroupCardinality(LogicalOperator &input, + const RelationStats &input_stats, + vector groups, + RelationStatsExtractor &extractor) { + vector counts; + for (auto index : groups) { + auto count = input_stats.columns[index].current_domain; + if (count.distinct_count.IsZero()) { + count.distinct_count = CardinalityValue(1); + } + counts.push_back(count); + } + auto estimate = EstimateDistinctCardinality(counts, input_stats.cardinality); + auto union_groups = extractor.EstimateUnionGroups(input, std::move(groups)); + if (union_groups) { + // Per-arm domain products avoid inventing cross-arm combinations of grouping keys. + estimate = MinValue(estimate, *union_groups); + } + return estimate; +} + +struct GroupingAlias { + idx_t group_index; + optional_idx mapped_index; +}; + +static optional_ptr TryMapJoinAliases(LogicalOperator &join, vector &aliases) { + auto bindings = join.GetColumnBindings(); + for (auto &child : join.children) { + GroupingColumnMapper mapper(*child); + vector mapped; + mapped.reserve(aliases.size()); + for (auto alias : aliases) { + if (alias.mapped_index.IsValid()) { + if (alias.mapped_index.GetIndex() >= bindings.size()) { + return nullptr; + } + alias.mapped_index = mapper.GetChildIndex(bindings[alias.mapped_index.GetIndex()]); + if (!alias.mapped_index.IsValid()) { + break; + } + } + mapped.push_back(alias); + } + if (mapped.size() == aliases.size()) { + // Stay on one input: separate references to the same CTE are separate row streams. + aliases = std::move(mapped); + return child.get(); + } + } + return nullptr; +} + +static void MergeGroupingAliases(vector &aliases, const RelationStats &input_stats) { + unordered_map factors; + factors.reserve(aliases.size()); + auto domain = [&](idx_t index) { + auto count = input_stats.columns[index].current_domain.distinct_count; + return count.IsZero() ? CardinalityValue(1) : count; + }; + idx_t distinct_count = 0; + for (auto &alias : aliases) { + if (!alias.mapped_index.IsValid()) { + aliases[distinct_count++] = alias; + continue; + } + auto entry = factors.emplace(alias.mapped_index.GetIndex(), distinct_count); + if (entry.second) { + aliases[distinct_count++] = alias; + } else { + auto &existing = aliases[entry.first->second].group_index; + if (domain(existing) > domain(alias.group_index)) { + existing = alias.group_index; + } + } + } + aliases.resize(distinct_count); +} + +static void DeduplicateGroupingAliases(LogicalOperator &input, const RelationStats &input_stats, vector &groups, + RelationStatsExtractor &extractor) { + if (groups.size() < 2) { + return; + } + // Keep aliases proved along this row stream, even if traversal stops; retain the filtered input's domains. + vector aliases; + aliases.reserve(groups.size()); + for (auto index : groups) { + aliases.push_back({index, optional_idx(index)}); + } + MergeGroupingAliases(aliases, input_stats); + optional_ptr current = input; + unordered_map> local_definitions; + static constexpr idx_t MAX_VISITED_OPERATORS = 1024; + for (idx_t visited = 0; visited < MAX_VISITED_OPERATORS; visited++) { + auto &op = *current; + idx_t mapped_count = 0; + for (auto &alias : aliases) { + mapped_count += alias.mapped_index.IsValid(); + } + if (mapped_count < 2) { + break; + } + if (op.type == LogicalOperatorType::LOGICAL_PROJECTION && op.children.size() == 1) { + GroupingColumnMapper mapper(*op.children[0]); + for (auto &alias : aliases) { + if (alias.mapped_index.IsValid()) { + alias.mapped_index = mapper.GetChildIndex(op, alias.mapped_index.GetIndex()); + } + } + // Unresolved expressions remain independent; keep aliases proved before they became unresolved. + MergeGroupingAliases(aliases, input_stats); + current = *op.children[0]; + continue; + } + if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { + auto &ref = op.Cast(); + auto local = local_definitions.find(ref.cte_index); + auto definition = local == local_definitions.end() ? extractor.GetCTEDefinition(ref) : local->second.get(); + if (definition && definition->GetColumnBindings().size() == ref.chunk_types.size()) { + current = definition; + continue; + } + } + if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE && op.children.size() == 2) { + local_definitions.emplace(op.Cast().table_index, *op.children[0]); + current = *op.children[1]; + continue; + } + if ((op.type == LogicalOperatorType::LOGICAL_FILTER || op.type == LogicalOperatorType::LOGICAL_ORDER_BY) && + op.children.size() == 1) { + const auto &projection_map = op.type == LogicalOperatorType::LOGICAL_FILTER + ? op.Cast().projection_map + : op.Cast().projection_map; + if (!projection_map.empty()) { + for (auto &alias : aliases) { + if (alias.mapped_index.IsValid()) { + alias.mapped_index = projection_map[alias.mapped_index.GetIndex()].GetIndex(); + } + } + MergeGroupingAliases(aliases, input_stats); + } + current = *op.children[0]; + continue; + } + if (op.type == LogicalOperatorType::LOGICAL_LIMIT && op.children.size() == 1) { + current = *op.children[0]; + continue; + } + if (op.type == LogicalOperatorType::LOGICAL_COMPARISON_JOIN || + op.type == LogicalOperatorType::LOGICAL_CROSS_PRODUCT) { + auto child = TryMapJoinAliases(op, aliases); + if (child) { + MergeGroupingAliases(aliases, input_stats); + current = child; + continue; + } + } + break; + } + groups.clear(); + for (auto &alias : aliases) { + groups.push_back(alias.group_index); + } +} + +static optional_ptr GetSelectedValueStats(const Expression &expression, + const RelationColumnStatsLookup &child_columns) { + if (expression.GetExpressionClass() != ExpressionClass::BOUND_AGGREGATE) { + return nullptr; + } + const auto &aggregate = expression.Cast(); + if (aggregate.StateExportMode() != AggregateStateExportMode::NONE || aggregate.GetChildren().size() != 1 || + !IsFirstLastOrAnyValue(aggregate.Function())) { + return nullptr; + } + // The selected value has a known domain only for a direct, type-preserving column reference. + const auto &argument = *aggregate.GetChildren()[0]; + if (argument.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF || + !argument.GetReturnType().EqualsIncludingCollation(aggregate.GetReturnType())) { + return nullptr; + } + return child_columns.Find(argument.Cast().Binding()); +} + +static optional ExtractAggregationStatsInternal(LogicalAggregate &aggregate, + const RelationStats &child_stats, + RelationStatsExtractor &extractor) { + RelationColumnStatsLookup child_columns(child_stats); + Distinctness distinctness(DistinctnessPropagation::UNARY_OPERATORS_AND_JOINS, extractor.GetContext(), + &extractor.GetCTEScope()); + vector cardinality_counts; + const auto has_multiple_grouping_sets = aggregate.grouping_sets.size() > 1; + CardinalityValue grouping_sets_cardinality(0); + auto add_group = [&](const Expression &group, vector &counts) { + if (group.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { + return true; + } + auto column = child_columns.Find(group.Cast().Binding()); + if (!column) { + return false; + } + auto count = column->current_domain; + if (count.distinct_count.IsZero()) { + count.distinct_count = CardinalityValue(1); + } + counts.push_back(count); + return true; + }; + // An absent grouping-set list denotes the single set containing all groups. + if (aggregate.grouping_sets.empty()) { + for (auto &group : aggregate.groups) { + if (!add_group(*group, cardinality_counts)) { + return {}; + } + } + } + for (auto &grouping_set : aggregate.grouping_sets) { + vector set_counts; + column_binding_set_t set_keys; + for (auto group_idx : grouping_set) { + auto &group = aggregate.GetGroupExpression(group_idx); + if (!add_group(group, set_counts)) { + return {}; + } + if (has_multiple_grouping_sets && group.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { + set_keys.insert(group.Cast().Binding()); + } + } + if (has_multiple_grouping_sets) { + if (grouping_set.empty()) { + grouping_sets_cardinality += CardinalityValue(1); + } else if (aggregate.children.size() == 1 && distinctness.IsDistinctOn(*aggregate.children[0], set_keys)) { + grouping_sets_cardinality += child_stats.cardinality; + } else { + grouping_sets_cardinality += + RelationStatisticsHelper::EstimateDistinctCardinality(set_counts, child_stats.cardinality); + } + } else { + cardinality_counts = std::move(set_counts); + } + } + + RelationStats result; + result.table_name = Identifier(aggregate.GetName()); + result.stats_initialized = true; + if (aggregate.grouping_sets.empty()) { + result.max_cardinality = aggregate.groups.empty() ? optional_idx(1) : child_stats.max_cardinality; + } else { + result.max_cardinality = optional_idx(0); + for (auto &grouping_set : aggregate.grouping_sets) { + result.max_cardinality = RelationStatisticsHelper::AddCardinalityBounds( + result.max_cardinality, grouping_set.empty() ? optional_idx(1) : child_stats.max_cardinality); + } + } + auto bindings = aggregate.GetColumnBindings(); + auto preserves_group_evidence = + aggregate.grouping_sets.empty() || + (aggregate.grouping_sets.size() == 1 && aggregate.grouping_sets[0].size() == aggregate.groups.size()); + if (has_multiple_grouping_sets) { + result.cardinality = grouping_sets_cardinality; + } else if (preserves_group_evidence && !aggregate.groups.empty() && aggregate.children.size() == 1 && + cardinality_counts.size() == aggregate.groups.size()) { + column_binding_map_t positions; + for (idx_t index = 0; index < child_stats.columns.size(); index++) { + positions.emplace(child_stats.columns[index].binding, index); + } + vector groups; + for (auto &group : aggregate.groups) { + groups.push_back(positions.at(group->Cast().Binding())); + } + DeduplicateGroupingAliases(*aggregate.children[0], child_stats, groups, extractor); + result.cardinality = RelationStatisticsHelper::EstimateGroupCardinality(*aggregate.children[0], child_stats, + std::move(groups), extractor); + } else { + result.cardinality = + aggregate.groups.empty() + ? 1 + : RelationStatisticsHelper::EstimateDistinctCardinality(cardinality_counts, child_stats.cardinality); + } + bool has_unique_groups = false; + if (preserves_group_evidence && !aggregate.groups.empty() && aggregate.children.size() == 1) { + has_unique_groups = distinctness.IsDistinctOn(*aggregate.children[0], aggregate.groups); + if (has_unique_groups) { + result.cardinality = child_stats.cardinality; + } + } + for (idx_t group_idx = 0; group_idx < aggregate.groups.size(); group_idx++) { + auto &group = *aggregate.groups[group_idx]; + DistinctCount distinct_count(result.cardinality, DistinctCountSource::CARDINALITY); + auto current_domain = distinct_count; + SemiAntiJoinDomainEvidence semi_anti_join_domain_evidence; + if (group.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { + auto child_column = child_columns.Find(group.Cast().Binding()); + if (!child_column) { + return {}; + } + distinct_count = child_column->total_domain; + current_domain = child_column->current_domain; + if (preserves_group_evidence) { + semi_anti_join_domain_evidence = child_column->semi_anti_join_domain_evidence; + } + } + if (aggregate.groups.size() == 1 && preserves_group_evidence) { + semi_anti_join_domain_evidence.MarkUnique(); + } + // a name would render the group as SQL, which can cost more than running the query + result.columns.emplace_back(bindings[result.columns.size()], distinct_count, current_domain, Identifier(), + semi_anti_join_domain_evidence); + } + for (auto &expression : aggregate.expressions) { + DistinctCount total_domain(result.cardinality, DistinctCountSource::CARDINALITY); + DistinctCount current_domain = total_domain; + bool forwards_input_domain = false; + if (has_unique_groups && expression->GetExpressionClass() == ExpressionClass::BOUND_AGGREGATE) { + auto &bound_aggregate = expression->Cast(); + auto &agg_children = bound_aggregate.GetChildren(); + if (bound_aggregate.CanForwardSingletonInputDomain() && !bound_aggregate.GetFilter() && + !agg_children.empty() && expression->GetReturnType() == agg_children[0]->GetReturnType() && + agg_children[0]->GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { + auto binding = agg_children[0]->Cast().Binding(); + auto child_column = child_columns.Find(binding); + if (child_column) { + total_domain = child_column->total_domain; + current_domain = child_column->current_domain; + forwards_input_domain = true; + } + } + } + // A selector can bias which values survive. Only the total domain keeps the + // source confidence; the common cardinality cap below bounds the current domain. + if (!forwards_input_domain) { + if (auto source = GetSelectedValueStats(*expression, child_columns)) { + total_domain = source->total_domain; + current_domain.distinct_count = + MinValue(source->current_domain.distinct_count, total_domain.distinct_count); + } + } + result.columns.emplace_back(bindings[result.columns.size()], total_domain, current_domain, Identifier()); + if (expression->GetExpressionClass() != ExpressionClass::BOUND_AGGREGATE) { + continue; + } + auto &bound_aggr = expression->Cast(); + auto &aggr_function = bound_aggr.Function(); + if (expression->GetReturnType().id() != LogicalTypeId::LIST || !aggr_function.HasStatisticsCallback() || + !RelationStatisticsHelper::ExpressionTypesResolved(*expression)) { + continue; + } + // invoke the aggregate's statistics callback with the extraction's cardinality estimate + vector callback_child_stats; + for (auto &aggr_child : bound_aggr.GetChildren()) { + optional_ptr child_column; + if (aggr_child->GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { + child_column = child_columns.Find(aggr_child->Cast().Binding()); + } + auto derived_stats = + RelationStatisticsHelper::DeriveListStats(*aggr_child, child_columns, extractor.GetContext()); + if (derived_stats) { + callback_child_stats.push_back(derived_stats->Copy()); + } else { + auto unknown_stats = BaseStatistics::CreateUnknown(aggr_child->GetReturnType()); + if (child_column && (child_column->total_domain.source == DistinctCountSource::HLL || + child_column->total_domain.source == DistinctCountSource::EXACT)) { + // the input domain bounds the distinct list elements + unknown_stats.SetDistinctCount(child_column->total_domain.distinct_count.GetIndex()); + } + callback_child_stats.push_back(std::move(unknown_stats)); + } + } + auto input_cardinality = child_stats.GetCardinality(); + NodeStatistics node_stats(input_cardinality.GetIndex()); + // a shared copy: a callback that writes its bind data detaches it instead of mutating the plan + auto callback_bind_data = bound_aggr.BindInfo(); + AggregateStatisticsInput callback_input(callback_bind_data, callback_child_stats, &node_stats); + auto callback_stats = aggr_function.GetStatisticsCallback()(extractor.GetContext(), bound_aggr, callback_input); + if (!callback_stats || callback_stats->GetStatsType() != StatisticsType::LIST_STATS) { + continue; + } + auto element_count = ListStats::TotalListLength(*callback_stats); + if (aggr_function.HasSingleValueIdentity()) { + // identity aggregates forward one input value: the input total only describes + // the output when a single row reaches a single group. A point estimate below one + // does not establish that, so require the structural bound. An aggregate FILTER can + // reject the row. The callback resets additive statistics, so restore the total + // from the carried input statistics. + element_count = optional_idx(); + auto &input_bound = child_stats.max_cardinality; + if (input_bound.IsValid() && input_bound.GetIndex() <= 1 && !bound_aggr.GetFilter() && + aggregate.grouping_sets.size() <= 1 && !callback_child_stats.empty() && + callback_child_stats[0].GetStatsType() == StatisticsType::LIST_STATS) { + element_count = ListStats::TotalListLength(callback_child_stats[0]); + } + } + if (element_count.IsValid()) { + if (aggr_function.HasSingleValueIdentity()) { + // restored from the single-row input above: no adjustment + } else { + // assumed callback contract: the returned total counts one element per input row + // (list/array_agg), so grouping-set replication and FILTER selectivity apply here + CardinalityValue total(element_count.GetIndex()); + total *= CardinalityValue(MaxValue(aggregate.grouping_sets.size(), 1)); + if (bound_aggr.GetFilter()) { + // an aggregate FILTER keeps only part of the input in the lists + total *= CardinalityValue(RelationStatisticsHelper::DEFAULT_SELECTIVITY); + } + element_count = MaxValue(total.GetIndex(), 1); + } + } + if (element_count.IsValid()) { + auto length_data = ListStats::GetLengthData(*callback_stats); + length_data.has_total_list_length = true; + length_data.total_list_length = element_count.GetIndex(); + ListStats::SetLengthData(*callback_stats, length_data); + } else if (callback_stats->GetStatsType() == StatisticsType::LIST_STATS) { + // no reliable total for this column: keep the value statistics and length bounds + ListStats::ResetTotalListLength(*callback_stats); + } + result.columns.back().list_stats = shared_ptr(callback_stats.release()); + } + for (idx_t grouping_idx = 0; grouping_idx < aggregate.grouping_functions.size(); grouping_idx++) { + auto grouping_count = + MinValue(result.cardinality, CardinalityValue(MaxValue(aggregate.grouping_sets.size(), 1))); + result.columns.emplace_back(bindings[result.columns.size()], + DistinctCount(grouping_count, DistinctCountSource::CARDINALITY), + Identifier("grouping")); + } + result.CapCurrentDomainsToCardinality(); + result.Verify(bindings); + return result; +} + +optional RelationStatisticsHelper::ExtractAggregationStats(LogicalAggregate &aggregate, + const RelationStats &child_stats, + ClientContext &context) { + RelationStatsExtractor extractor(context); + return ExtractAggregationStatsInternal(aggregate, child_stats, extractor); +} + +optional RelationStatisticsHelper::ExtractAggregationStats(LogicalAggregate &aggregate, + const RelationStats &child_stats, + RelationStatsExtractor &extractor) { + return ExtractAggregationStatsInternal(aggregate, child_stats, extractor); +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_extractor.cpp b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_extractor.cpp index ce743f35b..559f2436f 100644 --- a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_extractor.cpp +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_extractor.cpp @@ -7,22 +7,337 @@ #include "duckdb/planner/operator/logical_materialized_cte.hpp" #include "duckdb/optimizer/join_order/query_graph_manager.hpp" #include "duckdb/planner/operator/logical_get.hpp" +#include "duckdb/planner/operator/logical_projection.hpp" +#include "duckdb/planner/operator/logical_set_operation.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/subquery/column_binding_layout.hpp" +#include "duckdb/common/types/hash.hpp" namespace duckdb { +class GroupingCTEScope { +public: + GroupingCTEScope(optional_ptr &active_scope, const CTEDefinitionScope &outer) + : active_scope(active_scope), previous_scope(active_scope), outer(outer), scope([this](TableIndex index) { + auto entry = definitions.find(index); + return entry == definitions.end() ? this->outer.Find(index) + : optional_ptr(entry->second); + }) { + active_scope = scope; + } + ~GroupingCTEScope() { + active_scope = previous_scope; + } + +public: + optional_ptr Push(LogicalOperator &op) { + if (op.type != LogicalOperatorType::LOGICAL_MATERIALIZED_CTE || op.children.size() != 2) { + return nullptr; + } + auto index = op.Cast().table_index; + auto entry = definitions.find(index); + optional_ptr previous = entry == definitions.end() ? nullptr : &entry->second.get(); + definitions.insert_or_assign(index, *op.children[0]); + return previous; + } + void Pop(LogicalOperator &op, optional_ptr previous) { + if (op.type != LogicalOperatorType::LOGICAL_MATERIALIZED_CTE || op.children.size() != 2) { + return; + } + auto index = op.Cast().table_index; + if (previous) { + definitions.insert_or_assign(index, *previous); + } else { + definitions.erase(index); + } + } + +private: + //! Restore the caller's scope after this grouping walk, including on failure. + optional_ptr &active_scope; + optional_ptr previous_scope; + const CTEDefinitionScope &outer; + CTEDefinitionScope scope; + + //! A flat map keeps local lookups independent of materialized CTE nesting depth. + unordered_map> definitions; +}; + RelationStatsExtractor::RelationStatsExtractor(ClientContext &context) : context(context) { } -RelationStatsExtractor::RelationStatsExtractor(ClientContext &context, relation_stats_cte_callback_t cte_callback) - : context(context), cte_callback(std::move(cte_callback)) { +RelationStatsExtractor::RelationStatsExtractor(ClientContext &context, CTEDefinitionScope::lookup_t cte_lookup) + : context(context), cte_scope(std::move(cte_lookup)) { } RelationStatsExtractor::RelationStatsExtractor(ClientContext &context, - shared_ptr source_stats) - : context(context), inherited_source_stats(std::move(source_stats)) { + shared_ptr source_stats, + CTEDefinitionScope::lookup_t cte_lookup) + : context(context), cte_scope(std::move(cte_lookup)), inherited_source_stats(std::move(source_stats)) { +} + +RelationStatsExtractor::RelationStatsExtractor(ClientContext &context, relation_stats_lookup_t lookup_p, + CTEDefinitionScope::lookup_t cte_lookup, + optional_ptr distinctness_p) + : context(context), cte_scope(std::move(cte_lookup)), lookup(std::move(lookup_p)), distinctness(distinctness_p) { + D_ASSERT(lookup); +} + +Distinctness &RelationStatsExtractor::GetDistinctness() { + if (!distinctness) { + owned_distinctness = make_uniq(DistinctnessPropagation::UNARY_OPERATORS, context); + distinctness = owned_distinctness.get(); + } + return *distinctness; +} + +void RelationStatsExtractor::Invalidate(LogicalOperator &op) { + cache.erase(op); + failed_operators.erase(op); + group_estimates.erase(op); + union_group_inputs.erase(op); + group_input_layouts.erase(op); + projection_groups.erase(op); + if (distinctness) { + distinctness->Invalidate(op); + } +} + +uint64_t RelationStatsExtractor::GroupHash::operator()(const vector &groups) const { + hash_t result = 0; + for (auto index : groups) { + result = CombineHash(result, Hash(index)); + } + return result; +} + +bool RelationStatsExtractor::CanRefineUnionGroups(LogicalOperator &op) { + GroupingCTEScope scope(local_cte_scope, GetCTEScope()); + vector> path; + optional_ptr current = op; + bool result = false; + while (current) { + auto entry = union_group_inputs.emplace(*current, false); + if (!entry.second) { + result = entry.first->second; + break; + } + path.push_back(*current); + if (current->type == LogicalOperatorType::LOGICAL_UNION) { + result = true; + break; + } + if (current->type == LogicalOperatorType::LOGICAL_PROJECTION && current->children.size() == 1) { + current = *current->children[0]; + } else if (current->type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE && current->children.size() == 2) { + scope.Push(*current); + current = *current->children[1]; + } else if (current->type == LogicalOperatorType::LOGICAL_CTE_REF) { + current = GetCTEDefinition(current->Cast()); + } else { + break; + } + } + for (auto &node : path) { + union_group_inputs.at(node) = result; + } + return result; +} + +const ColumnBindingLayout &RelationStatsExtractor::GetGroupInputLayout(LogicalOperator &op) { + vector> path; + reference current = op; + shared_ptr layout; + while (true) { + auto entry = group_input_layouts.find(current); + if (entry != group_input_layouts.end()) { + layout = entry->second; + break; + } + auto &node = current.get(); + path.push_back(node); + if (node.type != LogicalOperatorType::LOGICAL_MATERIALIZED_CTE || node.children.size() != 2) { + layout = make_shared_ptr(node.GetColumnBindings()); + break; + } + current = *node.children[1]; + } + for (auto &node : path) { + group_input_layouts.emplace(node, layout); + } + return *layout; +} + +bool RelationStatsExtractor::MapProjectionGroups(LogicalOperator &op, vector &groups) { + auto entry = projection_groups.find(op); + if (entry == projection_groups.end()) { + vector mapping(op.expressions.size()); + auto &columns = GetGroupInputLayout(*op.children[0]).positions; + for (idx_t index = 0; index < op.expressions.size(); index++) { + auto &expression = *op.expressions[index]; + if (expression.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { + continue; + } + auto &column = expression.Cast(); + auto match = columns.find(column.Binding()); + if (column.Depth() == 0 && match != columns.end()) { + mapping[index] = match->second; + } + } + entry = projection_groups.emplace(op, std::move(mapping)).first; + } + vector mapped; + for (auto index : groups) { + if (index >= entry->second.size() || !entry->second[index].IsValid()) { + return false; + } + mapped.push_back(entry->second[index].GetIndex()); + } + groups = std::move(mapped); + return true; +} + +static optional EstimateLeafGroups(const RelationStats &stats, const vector &groups) { + auto estimate = MinValue(stats.cardinality, CardinalityValue(1)); + for (auto index : groups) { + if (index >= stats.columns.size()) { + return {}; + } + auto domain = stats.columns[index].current_domain.distinct_count; + if (domain.IsZero()) { + domain = CardinalityValue(1); + } + if (estimate > stats.cardinality / domain) { + return stats.cardinality; + } + estimate *= domain; + } + return estimate; +} + +vector +RelationStatsExtractor::PrepareGroupEstimate(LogicalOperator &op, vector groups, GroupEstimate &estimate) { + vector inputs; + estimate.cardinality = CardinalityValue(0); + if (op.type == LogicalOperatorType::LOGICAL_PROJECTION && op.children.size() == 1 && + MapProjectionGroups(op, groups)) { + inputs.emplace_back(*op.children[0], std::move(groups)); + } else if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { + auto &ref = op.Cast(); + auto definition = GetCTEDefinition(ref); + if (!definition || GetGroupInputLayout(*definition).bindings.size() != ref.chunk_types.size()) { + estimate.cardinality = {}; + } else { + inputs.emplace_back(*definition, std::move(groups)); + } + } else if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE && op.children.size() == 2) { + inputs.emplace_back(*op.children[1], std::move(groups)); + } else if (op.type == LogicalOperatorType::LOGICAL_UNION) { + estimate.has_union = true; + for (auto &child : op.children) { + if (GetGroupInputLayout(*child).bindings.size() != op.Cast().column_count) { + estimate.cardinality = {}; + inputs.clear(); + break; + } + inputs.emplace_back(*child, groups); + } + } else { + auto stats = Extract(op); + estimate.cardinality = stats ? EstimateLeafGroups(*stats, groups) : optional(); + } + return inputs; +} + +optional RelationStatsExtractor::EstimateUnionGroups(LogicalOperator &input, vector groups) { + if (!CanRefineUnionGroups(input)) { + return {}; + } + struct Frame { + public: + Frame(LogicalOperator &op_p, GroupEstimate &estimate_p, vector inputs_p, + optional_ptr previous_definition_p) + : op(op_p), estimate(estimate_p), inputs(std::move(inputs_p)), previous_definition(previous_definition_p) { + } + + public: + //! The cached estimate and the next input that contributes to it. + reference op; + reference estimate; + vector inputs; + idx_t child = 0; + + //! Restore a shadowed local CTE definition when leaving this frame. + optional_ptr previous_definition; + }; + auto find_estimate = [&](LogicalOperator &op, vector &keys) -> pair, bool> { + std::sort(keys.begin(), keys.end()); + keys.erase(std::unique(keys.begin(), keys.end()), keys.end()); + auto &estimates = group_estimates[op]; + auto entry = estimates.find(keys); + if (entry != estimates.end()) { + return {entry->second, false}; + } + // Different projections through shared CTEs can generate exponentially many key sets. + if (estimates.size() >= 64) { + return {nullptr, false}; + } + return {estimates.emplace(keys, GroupEstimate()).first->second, true}; + }; + auto root = find_estimate(input, groups); + if (!root.first) { + return {}; + } + auto &root_estimate = *root.first; + GroupingCTEScope scope(local_cte_scope, GetCTEScope()); + vector stack; + auto push_frame = [&](LogicalOperator &op, vector keys, GroupEstimate &estimate) { + auto previous = scope.Push(op); + auto inputs = PrepareGroupEstimate(op, std::move(keys), estimate); + stack.emplace_back(op, estimate, std::move(inputs), previous); + }; + if (root.second) { + push_frame(input, std::move(groups), root_estimate); + } + while (!stack.empty()) { + auto &frame = stack.back(); + auto &estimate = frame.estimate.get(); + if (!estimate.cardinality || frame.child == frame.inputs.size()) { + estimate.state = GroupEstimateState::COMPLETE; + scope.Pop(frame.op, frame.previous_definition); + stack.pop_back(); + continue; + } + auto &child = frame.inputs[frame.child]; + auto entry = find_estimate(child.first, child.second); + if (!entry.first) { + estimate.cardinality = {}; + continue; + } + auto &child_estimate = *entry.first; + if (entry.second) { + push_frame(child.first, child.second, child_estimate); + continue; + } + // Recursive definitions do not provide finite per-arm domain evidence. + if (child_estimate.state == GroupEstimateState::ACTIVE || !child_estimate.cardinality) { + estimate.cardinality = {}; + } else { + estimate.cardinality = *estimate.cardinality + *child_estimate.cardinality; + estimate.has_union |= child_estimate.has_union; + } + frame.child++; + } + if (root_estimate.state == GroupEstimateState::COMPLETE && root_estimate.has_union) { + return root_estimate.cardinality; + } + return {}; } optional_ptr RelationStatsExtractor::Extract(LogicalOperator &op) { + if (lookup) { + return lookup(op); + } auto cache_entry = cache.find(op); if (cache_entry != cache.end()) { return cache_entry->second; @@ -45,6 +360,9 @@ optional_ptr RelationStatsExtractor::Extract(LogicalOperato } shared_ptr RelationStatsExtractor::GetSourceStats(LogicalOperator &root) { + if (lookup) { + return nullptr; + } if (inherited_source_stats) { return inherited_source_stats; } @@ -57,6 +375,7 @@ shared_ptr RelationStatsExtractor::GetSourceStats(Lo } idx_t RelationStatsExtractor::ExtractedOperatorCount() const { + D_ASSERT(!lookup); return extracted_operator_count; } @@ -89,20 +408,16 @@ optional RelationStatsExtractor::ExtractInternal(LogicalOperator return {}; } auto &cte = op.Cast(); - // An extraction exception invalidates this extractor; restore the outer lookup on normal return. - auto outer_callback = cte_callback; - cte_callback = [&cte, outer_callback](TableIndex index) -> optional_ptr { - if (index == cte.table_index) { - return cte.children[0].get(); - } - return outer_callback ? outer_callback(index) : nullptr; - }; + // An extraction exception invalidates this extractor; restore the outer scope on normal return. + auto outer = local_cte_scope; + CTEDefinitionScope local(GetCTEScope(), cte.table_index, *cte.children[0]); + local_cte_scope = local; optional result; auto stats = Extract(*cte.children[1]); if (stats) { result = RelationStatisticsHelper::ProjectOutputStats(*stats, cte); } - cte_callback = std::move(outer_callback); + local_cte_scope = outer; return result; } if (op.type == LogicalOperatorType::LOGICAL_EXPLAIN) { @@ -147,11 +462,12 @@ optional RelationStatsExtractor::ExtractJoinStats(LogicalOperator return graph.ProjectRetainedStats(estimator, set, op); } +const CTEDefinitionScope &RelationStatsExtractor::GetCTEScope() const { + return local_cte_scope ? *local_cte_scope : cte_scope; +} + optional_ptr RelationStatsExtractor::GetCTEDefinition(const LogicalCTERef &cte_ref) const { - if (cte_ref.is_recurring || !cte_callback) { - return nullptr; - } - return cte_callback(cte_ref.cte_index); + return cte_ref.is_recurring ? nullptr : GetCTEScope().Find(cte_ref.cte_index); } optional RelationStatsExtractor::ExtractCTERef(LogicalCTERef &cte_ref) { diff --git a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_helper.cpp b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_helper.cpp index 5e78d33cb..737313b69 100644 --- a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_helper.cpp +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_helper.cpp @@ -1,22 +1,35 @@ #include "duckdb/optimizer/relation_statistics/relation_statistics_helper.hpp" -#include "duckdb/optimizer/relation_statistics/relation_statistics_extractor.hpp" +#include "duckdb/common/types/hugeint.hpp" +#include "duckdb/common/type_visitor.hpp" #include "duckdb/common/types/value_map.hpp" -#include "duckdb/function/aggregate/distributive_function_utils.hpp" #include "duckdb/common/operator/add.hpp" #include "duckdb/common/operator/multiply.hpp" -#include "duckdb/optimizer/distinctness.hpp" #include "duckdb/planner/expression/bound_comparison_expression.hpp" #include "duckdb/planner/expression/bound_constant_expression.hpp" +#include "duckdb/planner/expression/bound_reference_expression.hpp" #include "duckdb/planner/expression/list.hpp" #include "duckdb/planner/expression_iterator.hpp" -#include "duckdb/planner/column_binding_map.hpp" #include "duckdb/planner/operator/list.hpp" +#include "duckdb/storage/statistics/base_statistics.hpp" +#include "duckdb/storage/statistics/numeric_stats.hpp" +#include #include namespace duckdb { +RelationStats RelationStatisticsHelper::RecursiveReferenceStats(const RelationStats &input, CardinalityValue rows) { + RelationStats result; + result.cardinality = rows; + result.stats_initialized = input.stats_initialized; + result.table_name = input.table_name; + for (auto &column : input.columns) { + result.columns.emplace_back(column.binding, DistinctCount(rows, DistinctCountSource::CARDINALITY), column.name); + } + return result; +} + optional RelationStatisticsHelper::SelectTotalDomain(const vector &domains) { optional reliable; optional min_max; @@ -61,6 +74,65 @@ idx_t RelationStatisticsHelper::CardinalityFromDouble(double cardinality) { return LossyNumericCast(cardinality); } +template +static optional_idx SignedRangeCount(const BaseStatistics &stats) { + auto min_value = NumericStats::Min(stats).GetValueUnsafe(); + auto max_value = NumericStats::Max(stats).GetValueUnsafe(); + if (max_value < min_value) { + return optional_idx(); + } + // a full int64 range does not fit in int64_t + auto span = hugeint_t(static_cast(max_value)) - hugeint_t(static_cast(min_value)); + idx_t count; + if (!Hugeint::TryCast(span + hugeint_t(1), count)) { + return optional_idx(); + } + return optional_idx(count); +} + +template +static optional_idx UnsignedRangeCount(const BaseStatistics &stats) { + auto min_value = NumericStats::Min(stats).GetValueUnsafe(); + auto max_value = NumericStats::Max(stats).GetValueUnsafe(); + if (max_value < min_value) { + return optional_idx(); + } + idx_t span = static_cast(max_value) - static_cast(min_value); + if (span == NumericLimits::Maximum()) { + return optional_idx(); + } + return optional_idx(span + 1); +} + +optional_idx RelationStatisticsHelper::NumericStatsDistinctCount(const BaseStatistics &stats) { + if (stats.GetStatsType() != StatisticsType::NUMERIC_STATS || !NumericStats::HasMinMax(stats)) { + return optional_idx(); + } + switch (stats.GetType().InternalType()) { + case PhysicalType::BOOL: + return optional_idx( + NumericStats::Min(stats).GetValueUnsafe() == NumericStats::Max(stats).GetValueUnsafe() ? 1 : 2); + case PhysicalType::INT8: + return SignedRangeCount(stats); + case PhysicalType::INT16: + return SignedRangeCount(stats); + case PhysicalType::INT32: + return SignedRangeCount(stats); + case PhysicalType::INT64: + return SignedRangeCount(stats); + case PhysicalType::UINT8: + return UnsignedRangeCount(stats); + case PhysicalType::UINT16: + return UnsignedRangeCount(stats); + case PhysicalType::UINT32: + return UnsignedRangeCount(stats); + case PhysicalType::UINT64: + return UnsignedRangeCount(stats); + default: + return optional_idx(); + } +} + static bool MatchesTargetColumn(const Expression &expression, optional target_binding) { if (expression.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { return !target_binding || expression.Cast().Binding() == *target_binding; @@ -183,8 +255,121 @@ static ExpressionBinding GetChildColumnBinding(Expression &expr) { return result; } +static bool IsMultiColumnExpression(const Expression &expression) { + column_binding_set_t bindings; + std::function collect = [&](const Expression &expr) { + if (expr.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { + bindings.insert(expr.Cast().Binding()); + return; + } + ExpressionIterator::EnumerateChildren(expr, [&](const Expression &child) { collect(child); }); + }; + collect(expression); + return bindings.size() > 1; +} + +//! Number of values a key computed from base columns (e.g. ts::DATE, year(ts)) can take, from its derived range +static optional_idx DeriveExpressionDomain(const Expression &expression, const RelationColumnStatsLookup &child_columns, + ClientContext &context) { + if (expression.IsVolatile()) { + return optional_idx(); + } + auto expr_copy = expression.Copy(); + vector input_stats; + column_binding_map_t indexes; + bool usable = true; + // column refs become positional refs into input_stats, so the expression's statistics callbacks can run + std::function &)> rewrite = [&](unique_ptr &child) { + if (!usable) { + return; + } + if (child->GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { + auto &ref = child->Cast(); + auto entry = indexes.find(ref.Binding()); + if (entry == indexes.end()) { + auto column = child_columns.Find(ref.Binding()); + if (!column || !column->base_stats) { + usable = false; + return; + } + auto index = input_stats.size(); + indexes.emplace(ref.Binding(), index); + input_stats.push_back(column->base_stats->Copy()); + child = make_uniq(ref.GetReturnType(), index); + } else { + child = make_uniq(ref.GetReturnType(), entry->second); + } + return; + } + ExpressionIterator::EnumerateChildren(*child, rewrite); + }; + ExpressionIterator::EnumerateChildren(*expr_copy, rewrite); + if (!usable || input_stats.empty()) { + return optional_idx(); + } + auto derived = ExpressionFilter::TryGetExpressionStatistics( + context, *expr_copy, array_ptr(input_stats.data(), input_stats.size())); + if (!derived) { + return optional_idx(); + } + return RelationStatisticsHelper::NumericStatsDistinctCount(*derived); +} + +static bool TypeIsResolved(const LogicalType &type) { + return !TypeVisitor::Contains(type, [](const LogicalType &entry) { + return entry.id() == LogicalTypeId::UNKNOWN || entry.id() == LogicalTypeId::ANY; + }); +} + +bool RelationStatisticsHelper::ExpressionTypesResolved(const Expression &expr) { + if (!TypeIsResolved(expr.GetReturnType())) { + return false; + } + bool resolved = true; + ExpressionIterator::EnumerateChildren(expr, [&](const Expression &child) { + if (!TypeIsResolved(child.GetReturnType())) { + resolved = false; + } + }); + return resolved; +} + +shared_ptr RelationStatisticsHelper::DeriveListStats(Expression &expr, + const RelationColumnStatsLookup &columns, + ClientContext &context) { + if (expr.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { + auto column = columns.Find(expr.Cast().Binding()); + return column ? column->list_stats : nullptr; + } + // callbacks run outside the statistics propagator (expr_ptr is null): keep to LIST-returning functions, + // e.g. list_sort forwards its input statistics unchanged + if (expr.GetExpressionClass() != ExpressionClass::BOUND_FUNCTION || + expr.GetReturnType().id() != LogicalTypeId::LIST) { + return nullptr; + } + auto &bound_function = expr.Cast(); + if (!bound_function.Function().HasStatisticsCallback() || !ExpressionTypesResolved(expr)) { + return nullptr; + } + vector callback_child_stats; + for (auto &function_child : bound_function.GetChildren()) { + auto child_stats = DeriveListStats(*function_child, columns, context); + callback_child_stats.push_back(child_stats ? child_stats->Copy() + : BaseStatistics::CreateUnknown(function_child->GetReturnType())); + } + // a shared copy: a callback that writes its bind data detaches it instead of mutating the plan + auto callback_bind_data = bound_function.BindInfo(); + FunctionStatisticsInput callback_input(bound_function, callback_bind_data, callback_child_stats, nullptr); + auto callback_stats = bound_function.Function().GetStatisticsCallback()(context, callback_input); + if (!callback_stats || callback_stats->GetStatsType() != StatisticsType::LIST_STATS) { + return nullptr; + } + return shared_ptr(callback_stats.release()); +} + optional RelationStatisticsHelper::ExtractProjectionStats(LogicalProjection &projection, - const RelationStats &child_stats) { + const RelationStats &child_stats, + ClientContext &context) { RelationStats result; result.cardinality = child_stats.cardinality; result.max_cardinality = child_stats.max_cardinality; @@ -215,16 +400,78 @@ optional RelationStatisticsHelper::ExtractProjectionStats(Logical current_domain = child_column->current_domain; if (expression.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { semi_anti_join_domain_evidence = child_column->semi_anti_join_domain_evidence; + } else { + // cap a derived key (cast or function) by the range of the expression + auto bound = DeriveExpressionDomain(expression, child_columns, context); + if (bound.IsValid()) { + if (bound.GetIndex() < distinct_count.distinct_count) { + // keep HLL/EXACT sources, SelectTotalDomain ranks them above MIN_MAX + auto source = distinct_count.source == DistinctCountSource::CARDINALITY + ? DistinctCountSource::MIN_MAX + : distinct_count.source; + distinct_count = DistinctCount(bound.GetIndex(), source); + } + current_domain.distinct_count = + MinValue(current_domain.distinct_count, CardinalityValue(bound.GetIndex())); + } else if (IsMultiColumnExpression(expression)) { + // no expression-derived bound and multiple input columns (e.g. COALESCE after + // a LEFT join drops base_stats): the single-column estimate is unreliable, + // fall back to the projection cardinality + distinct_count = DistinctCount(result.cardinality, DistinctCountSource::CARDINALITY); + current_domain = distinct_count; + } } } // a name would render the expression as SQL, which can cost more than running the query result.columns.emplace_back(bindings[expression_idx], distinct_count, current_domain, Identifier(), semi_anti_join_domain_evidence); + if (child_column && expression.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { + // keep base stats for a projection on top of this one + result.columns.back().base_stats = child_column->base_stats; + } + result.columns.back().list_stats = DeriveListStats(expression, child_columns, context); + if (child_column && expression.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF && + expression.Cast().Depth() == 0) { + result.columns.back().value_bounds = child_column->value_bounds; + } } result.Verify(bindings); return result; } +//! Scale the total list lengths of every list level by the row-duplication factor. +//! Duplicating rows leaves the per-list length bounds unchanged. +static bool ScaleListTotals(BaseStatistics &stats, CardinalityValue factor) { + bool scaled_any = false; + if (stats.GetStatsType() == StatisticsType::LIST_STATS) { + auto element_count = ListStats::TotalListLength(stats); + if (element_count.IsValid()) { + auto length_data = ListStats::GetLengthData(stats); + length_data.has_total_list_length = true; + length_data.total_list_length = (CardinalityValue(element_count.GetIndex()) * factor).GetIndex(); + ListStats::SetLengthData(stats, length_data); + scaled_any = true; + } + scaled_any = ScaleListTotals(ListStats::GetChildStats(stats), factor) || scaled_any; + } + return scaled_any; +} + +shared_ptr RelationStatisticsHelper::ScaleListStats(const shared_ptr &list_stats, + CardinalityValue source_cardinality, + CardinalityValue result_cardinality) { + if (!list_stats || result_cardinality <= source_cardinality || source_cardinality.IsZero()) { + // keep the source totals when rows are removed: the overestimate protects against degenerate seeds + return list_stats; + } + // the rows holding the lists are duplicated: scale the element totals of every nesting level along + auto rescaled = list_stats->ToUnique(); + if (!ScaleListTotals(*rescaled, result_cardinality / source_cardinality)) { + return list_stats; + } + return shared_ptr(rescaled.release()); +} + CardinalityValue RelationStatisticsHelper::EstimateDistinctCardinality(const vector &distinct_counts, CardinalityValue input_cardinality) { if (distinct_counts.empty()) { @@ -454,299 +701,6 @@ RelationStatisticsHelper::EstimateTupleDomainRestriction(LogicalComparisonJoin & return TupleDomainRestrictionEstimate {rows.GetDouble(), groups.GetDouble()}; } -static bool TryMapProjectionGroups(LogicalOperator &op, vector &groups) { - auto child_bindings = op.children[0]->GetColumnBindings(); - vector mapped; - for (auto index : groups) { - if (index >= op.expressions.size()) { - return false; - } - auto &expr = *op.expressions[index]; - if (expr.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { - return false; - } - auto binding = expr.Cast().Binding(); - auto match = std::find(child_bindings.begin(), child_bindings.end(), binding); - if (match == child_bindings.end()) { - return false; - } - mapped.push_back(idx_t(match - child_bindings.begin())); - } - groups = std::move(mapped); - return true; -} - -static optional EstimateUnionGroups(LogicalOperator &input, vector groups, - CardinalityValue maximum, RelationStatsExtractor &extractor) { - static constexpr idx_t MAX_VISITED_OPERATORS = 1024; - vector, vector>> pending; - pending.emplace_back(input, std::move(groups)); - idx_t visited = 0; - CardinalityValue result(0); - bool found_union = false; - while (!pending.empty()) { - if (visited++ == MAX_VISITED_OPERATORS) { - // Abandon the whole refinement when shared CTE expansion exceeds the work budget. - return {}; - } - auto entry = std::move(pending.back()); - pending.pop_back(); - auto &op = entry.first.get(); - if (op.type == LogicalOperatorType::LOGICAL_PROJECTION && op.children.size() == 1 && - TryMapProjectionGroups(op, entry.second)) { - pending.emplace_back(*op.children[0], std::move(entry.second)); - continue; - } - if (op.type == LogicalOperatorType::LOGICAL_CTE_REF) { - auto &ref = op.Cast(); - auto definition = extractor.GetCTEDefinition(ref); - if (!definition || definition->GetColumnBindings().size() != ref.chunk_types.size()) { - return {}; - } - pending.emplace_back(*definition, std::move(entry.second)); - continue; - } - if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { - if (op.children.size() != 2) { - return {}; - } - pending.emplace_back(*op.children[1], std::move(entry.second)); - continue; - } - if (op.type == LogicalOperatorType::LOGICAL_UNION) { - found_union = true; - for (auto &child : op.children) { - if (child->GetColumnBindings().size() != op.Cast().column_count) { - return {}; - } - pending.emplace_back(*child, entry.second); - } - continue; - } - if (!found_union) { - return {}; - } - auto stats = extractor.Extract(op); - if (!stats) { - return {}; - } - auto cardinality = stats->cardinality; - auto estimate = MinValue(cardinality, CardinalityValue(1)); - for (auto index : entry.second) { - if (index >= stats->columns.size()) { - return {}; - } - auto domain = stats->columns[index].current_domain.distinct_count; - if (domain.IsZero()) { - domain = CardinalityValue(1); - } - if (estimate > cardinality / domain) { - estimate = cardinality; - break; - } - estimate *= domain; - } - result += MinValue(estimate, maximum - result); - } - return result; -} - -CardinalityValue RelationStatisticsHelper::EstimateGroupCardinality(LogicalOperator &input, - const RelationStats &input_stats, - vector groups, - RelationStatsExtractor &extractor) { - vector counts; - for (auto index : groups) { - auto count = input_stats.columns[index].current_domain; - if (count.distinct_count.IsZero()) { - count.distinct_count = CardinalityValue(1); - } - counts.push_back(count); - } - auto estimate = EstimateDistinctCardinality(counts, input_stats.cardinality); - auto union_groups = EstimateUnionGroups(input, std::move(groups), input_stats.cardinality, extractor); - if (union_groups) { - // Per-arm domain products avoid inventing cross-arm combinations of grouping keys. - estimate = MinValue(estimate, *union_groups); - } - return estimate; -} - -static optional_ptr GetSelectedValueStats(const Expression &expression, - const RelationColumnStatsLookup &child_columns) { - if (expression.GetExpressionClass() != ExpressionClass::BOUND_AGGREGATE) { - return nullptr; - } - const auto &aggregate = expression.Cast(); - if (aggregate.StateExportMode() != AggregateStateExportMode::NONE || aggregate.GetChildren().size() != 1 || - !IsFirstLastOrAnyValue(aggregate.Function())) { - return nullptr; - } - // The selected value has a known domain only for a direct, type-preserving column reference. - const auto &argument = *aggregate.GetChildren()[0]; - if (argument.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF || - !argument.GetReturnType().EqualsIncludingCollation(aggregate.GetReturnType())) { - return nullptr; - } - return child_columns.Find(argument.Cast().Binding()); -} - -static optional ExtractAggregationStatsInternal(LogicalAggregate &aggregate, - const RelationStats &child_stats, - RelationStatsExtractor &extractor) { - RelationColumnStatsLookup child_columns(child_stats); - vector cardinality_counts; - auto add_group = [&](const Expression &group, vector &counts) { - if (group.GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { - return true; - } - auto column = child_columns.Find(group.Cast().Binding()); - if (!column) { - return false; - } - auto count = column->current_domain; - if (count.distinct_count.IsZero()) { - count.distinct_count = CardinalityValue(1); - } - counts.push_back(count); - return true; - }; - // An absent grouping-set list denotes the single set containing all groups. - if (aggregate.grouping_sets.empty()) { - for (auto &group : aggregate.groups) { - if (!add_group(*group, cardinality_counts)) { - return {}; - } - } - } - for (auto &grouping_set : aggregate.grouping_sets) { - vector set_counts; - for (auto group_idx : grouping_set) { - if (!add_group(aggregate.GetGroupExpression(group_idx), set_counts)) { - return {}; - } - } - if (set_counts.size() > cardinality_counts.size()) { - cardinality_counts = std::move(set_counts); - } - } - - RelationStats result; - result.table_name = Identifier(aggregate.GetName()); - result.stats_initialized = true; - if (aggregate.grouping_sets.empty()) { - result.max_cardinality = aggregate.groups.empty() ? optional_idx(1) : child_stats.max_cardinality; - } else { - result.max_cardinality = optional_idx(0); - for (auto &grouping_set : aggregate.grouping_sets) { - result.max_cardinality = RelationStatisticsHelper::AddCardinalityBounds( - result.max_cardinality, grouping_set.empty() ? optional_idx(1) : child_stats.max_cardinality); - } - } - auto bindings = aggregate.GetColumnBindings(); - auto preserves_group_evidence = - aggregate.grouping_sets.empty() || - (aggregate.grouping_sets.size() == 1 && aggregate.grouping_sets[0].size() == aggregate.groups.size()); - if (preserves_group_evidence && !aggregate.groups.empty() && aggregate.children.size() == 1 && - cardinality_counts.size() == aggregate.groups.size()) { - vector groups; - for (auto &group : aggregate.groups) { - groups.push_back(child_stats.FindColumn(group->Cast().Binding()).GetIndex()); - } - result.cardinality = RelationStatisticsHelper::EstimateGroupCardinality(*aggregate.children[0], child_stats, - std::move(groups), extractor); - } else { - result.cardinality = - aggregate.groups.empty() - ? 1 - : RelationStatisticsHelper::EstimateDistinctCardinality(cardinality_counts, child_stats.cardinality); - } - bool has_unique_groups = false; - if (preserves_group_evidence && !aggregate.groups.empty() && aggregate.children.size() == 1) { - Distinctness distinctness(DistinctnessPropagation::UNARY_OPERATORS, extractor.GetContext()); - has_unique_groups = distinctness.IsDistinctOn(*aggregate.children[0], aggregate.groups); - if (has_unique_groups) { - result.cardinality = child_stats.cardinality; - } - } - for (idx_t group_idx = 0; group_idx < aggregate.groups.size(); group_idx++) { - auto &group = *aggregate.groups[group_idx]; - DistinctCount distinct_count(result.cardinality, DistinctCountSource::CARDINALITY); - SemiAntiJoinDomainEvidence semi_anti_join_domain_evidence; - if (group.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { - auto child_column = child_columns.Find(group.Cast().Binding()); - if (!child_column) { - return {}; - } - distinct_count = child_column->total_domain; - if (preserves_group_evidence) { - semi_anti_join_domain_evidence = child_column->semi_anti_join_domain_evidence; - } - } - auto current_domain = distinct_count; - if (group.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { - current_domain = - child_stats.GetColumnStats(group.Cast().Binding())->current_domain; - } - if (aggregate.groups.size() == 1 && preserves_group_evidence) { - semi_anti_join_domain_evidence.MarkUnique(); - } - // a name would render the group as SQL, which can cost more than running the query - result.columns.emplace_back(bindings[result.columns.size()], distinct_count, current_domain, Identifier(), - semi_anti_join_domain_evidence); - } - for (auto &expression : aggregate.expressions) { - DistinctCount total_domain(result.cardinality, DistinctCountSource::CARDINALITY); - DistinctCount current_domain = total_domain; - if (has_unique_groups && expression->GetExpressionClass() == ExpressionClass::BOUND_AGGREGATE) { - auto &bound_aggregate = expression->Cast(); - auto &agg_children = bound_aggregate.GetChildren(); - if (bound_aggregate.CanForwardSingletonInputDomain() && !bound_aggregate.GetFilter() && - !agg_children.empty() && expression->GetReturnType() == agg_children[0]->GetReturnType() && - agg_children[0]->GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { - auto binding = agg_children[0]->Cast().Binding(); - auto child_column = child_columns.Find(binding); - if (child_column) { - result.columns.emplace_back(bindings[result.columns.size()], child_column->total_domain, - child_column->current_domain, Identifier()); - continue; - } - } - } - // A selector can bias which values survive. Only the total domain keeps the - // source confidence; the common cardinality cap below bounds the current domain. - if (auto source = GetSelectedValueStats(*expression, child_columns)) { - total_domain = source->total_domain; - current_domain.distinct_count = - MinValue(source->current_domain.distinct_count, total_domain.distinct_count); - } - result.columns.emplace_back(bindings[result.columns.size()], total_domain, current_domain, Identifier()); - } - for (idx_t grouping_idx = 0; grouping_idx < aggregate.grouping_functions.size(); grouping_idx++) { - auto grouping_count = - MinValue(result.cardinality, CardinalityValue(MaxValue(aggregate.grouping_sets.size(), 1))); - result.columns.emplace_back(bindings[result.columns.size()], - DistinctCount(grouping_count, DistinctCountSource::CARDINALITY), - Identifier("grouping")); - } - result.CapCurrentDomainsToCardinality(); - result.Verify(bindings); - return result; -} - -optional RelationStatisticsHelper::ExtractAggregationStats(LogicalAggregate &aggregate, - const RelationStats &child_stats, - ClientContext &context) { - RelationStatsExtractor extractor(context); - return ExtractAggregationStatsInternal(aggregate, child_stats, extractor); -} - -optional RelationStatisticsHelper::ExtractAggregationStats(LogicalAggregate &aggregate, - const RelationStats &child_stats, - RelationStatsExtractor &extractor) { - return ExtractAggregationStatsInternal(aggregate, child_stats, extractor); -} - optional RelationStatisticsHelper::ExtractWindowStats(LogicalWindow &window, const RelationStats &child_stats) { RelationStats result; @@ -761,6 +715,7 @@ optional RelationStatisticsHelper::ExtractWindowStats(LogicalWind if (child_column) { result.columns.emplace_back(binding, child_column->total_domain, child_column->current_domain, child_column->name, child_column->semi_anti_join_domain_evidence); + result.columns.back().list_stats = child_column->list_stats; } else if (binding.table_index == window.window_index) { result.columns.emplace_back(binding, DistinctCount(result.cardinality, DistinctCountSource::CARDINALITY), Identifier("window")); @@ -841,6 +796,14 @@ optional RelationStatisticsHelper::ProjectOutputStats(const Relat if (!stats.stats_initialized) { return {}; } + return ProjectOutputStats(stats, op.GetColumnBindings()); +} + +optional RelationStatisticsHelper::ProjectOutputStats(const RelationStats &stats, + const vector &bindings) { + if (!stats.stats_initialized) { + return {}; + } RelationStats result; result.cardinality = stats.cardinality; result.max_cardinality = stats.max_cardinality; @@ -848,7 +811,6 @@ optional RelationStatisticsHelper::ProjectOutputStats(const Relat result.stats_initialized = true; result.table_name = stats.table_name; RelationColumnStatsLookup lookup(stats); - auto bindings = op.GetColumnBindings(); for (auto &binding : bindings) { auto column = lookup.Find(binding); if (!column) { diff --git a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_operator.cpp b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_operator.cpp index 828139295..2444244e6 100644 --- a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_operator.cpp +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_operator.cpp @@ -4,13 +4,17 @@ #include "duckdb/common/operator/multiply.hpp" #include "duckdb/optimizer/column_origin.hpp" #include "duckdb/optimizer/join_order/join_predicate.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression/bound_unnest_expression.hpp" #include "duckdb/planner/operator/list.hpp" namespace duckdb { static optional ProjectChildStats(LogicalOperator &op, const vector> &children, - CardinalityValue cardinality, optional_idx maximum = {}) { + const vector &bindings, CardinalityValue cardinality, + optional_idx maximum = {}, + const vector &null_extended_children = {}) { RelationStats result; result.cardinality = cardinality; result.max_cardinality = maximum; @@ -20,15 +24,37 @@ static optional ProjectChildStats(LogicalOperator &op, for (auto &child : children) { child_columns.AddRelation(child.get()); } - for (auto &binding : op.GetColumnBindings()) { + for (auto &binding : bindings) { auto source = child_columns.Find(binding); if (!source) { return {}; } result.columns.emplace_back(binding, source->total_domain, source->current_domain, source->name); + CardinalityValue source_cardinality = 0; + bool null_extended = false; + for (idx_t child_idx = 0; child_idx < children.size(); child_idx++) { + if (children[child_idx].get().GetColumnStats(binding)) { + source_cardinality = children[child_idx].get().cardinality; + null_extended = child_idx < null_extended_children.size() && null_extended_children[child_idx]; + break; + } + } + // base stats do not account for NULLs added by an outer join + if (!null_extended) { + result.columns.back().base_stats = source->base_stats; + } + if (source->list_stats) { + if (null_extended) { + // null-extended join sides grow through rows that hold no lists: keep the source total + result.columns.back().list_stats = source->list_stats; + } else { + result.columns.back().list_stats = + RelationStatisticsHelper::ScaleListStats(source->list_stats, source_cardinality, cardinality); + } + } } result.CapCurrentDomainsToCardinality(); - result.Verify(op.GetColumnBindings()); + result.Verify(bindings); return result; } @@ -199,21 +225,54 @@ static optional ExtractGetWithChildStats(LogicalGet &get, ClientC return result; } -static optional ExtractUnnestStats(LogicalOperator &op, const RelationStats &child_stats) { +static optional ExtractUnnestStats(LogicalOperator &op, const RelationStats &child_stats, + ClientContext &context) { auto &unnest = op.Cast(); + RelationColumnStatsLookup child_columns(child_stats); + // UNNEST multiplies its input by the list lengths, which plain child cardinality cannot capture: + // unnest((SELECT list(x) FROM tbl)) collapses to a single-row estimate and derails join ordering. + // When the unnested column carries list statistics with an element count, use it as the estimate. + CardinalityValue element_cardinality = 0; + // distinct element counts of the unnested lists, zero when unknown + vector element_domains(op.expressions.size(), 0); + for (idx_t expr_idx = 0; expr_idx < op.expressions.size(); expr_idx++) { + auto &expr = op.expressions[expr_idx]; + if (expr->GetExpressionClass() != ExpressionClass::BOUND_UNNEST) { + continue; + } + auto &unnest_child = *expr->Cast().Child(); + auto list_stats = RelationStatisticsHelper::DeriveListStats(unnest_child, child_columns, context); + if (!list_stats) { + continue; + } + auto element_count = ListStats::TotalListLength(*list_stats); + if (element_count.IsValid()) { + element_cardinality = MaxValue(element_cardinality, CardinalityValue(element_count.GetIndex())); + } + auto element_stats = ListStats::GetChildStats(*list_stats).Copy(); + element_domains[expr_idx] = element_stats.GetDistinctCount(); + } RelationStats result; - result.cardinality = child_stats.cardinality; + result.cardinality = MaxValue(child_stats.cardinality, element_cardinality); result.stats_initialized = true; result.table_name = Identifier(op.GetName()); - RelationColumnStatsLookup child_columns(child_stats); for (auto &binding : op.GetColumnBindings()) { auto child_column = child_columns.Find(binding); if (child_column) { result.columns.emplace_back(binding, child_column->total_domain, child_column->current_domain, child_column->name); + result.columns.back().list_stats = RelationStatisticsHelper::ScaleListStats( + child_column->list_stats, child_stats.cardinality, result.cardinality); } else if (binding.table_index == unnest.unnest_index) { - result.columns.emplace_back(binding, DistinctCount(result.cardinality, DistinctCountSource::CARDINALITY), - Identifier("unnest")); + auto element_domain = element_domains[binding.column_index.GetIndex()]; + if (element_domain > 0) { + DistinctCount domain(MinValue(CardinalityValue(element_domain), result.cardinality), + DistinctCountSource::HLL); + result.columns.emplace_back(binding, domain, Identifier("unnest")); + } else { + result.columns.emplace_back( + binding, DistinctCount(result.cardinality, DistinctCountSource::CARDINALITY), Identifier("unnest")); + } } else { return {}; } @@ -223,27 +282,42 @@ static optional ExtractUnnestStats(LogicalOperator &op, const Rel } static optional ExtractComparisonJoinStats(LogicalComparisonJoin &join, - const vector> &child_stats) { - if (child_stats.size() != 2) { - return {}; - } + const vector> &child_stats, + const vector &bindings) { if (join.join_type == JoinType::SEMI || join.join_type == JoinType::ANTI || join.join_type == JoinType::RIGHT_SEMI || join.join_type == JoinType::RIGHT_ANTI) { auto preserve_right = join.join_type == JoinType::RIGHT_SEMI || join.join_type == JoinType::RIGHT_ANTI; auto &preserved = child_stats[preserve_right ? 1 : 0].get(); - auto result = ProjectChildStats(join, child_stats, preserved.cardinality); + auto result = ProjectChildStats(join, child_stats, bindings, preserved.cardinality); if (!result) { return {}; } RelationStatisticsHelper::ApplySemiAntiJoinStats(join, child_stats[0], child_stats[1], *result); - result->Verify(join.GetColumnBindings()); + result->Verify(bindings); return result; } auto cardinality = JoinCardinality(join, child_stats[0], child_stats[1]); auto maximum = RelationStatisticsHelper::JoinCardinalityBound(join.join_type, child_stats[0].get().max_cardinality, child_stats[1].get().max_cardinality); if (join.join_type != JoinType::MARK) { - return ProjectChildStats(join, child_stats, cardinality, maximum); + // join sides that can be null-extended must not scale their list element counts + vector null_extended_children(2, false); + switch (join.join_type) { + case JoinType::LEFT: + case JoinType::SINGLE: + null_extended_children[1] = true; + break; + case JoinType::RIGHT: + null_extended_children[0] = true; + break; + case JoinType::OUTER: + null_extended_children[0] = true; + null_extended_children[1] = true; + break; + default: + break; + } + return ProjectChildStats(join, child_stats, bindings, cardinality, maximum, null_extended_children); } RelationStats mark_result; @@ -253,10 +327,12 @@ static optional ExtractComparisonJoinStats(LogicalComparisonJoin mark_result.stats_initialized = true; mark_result.table_name = Identifier(join.GetName()); RelationColumnStatsLookup left_columns(child_stats[0].get()); - for (auto &binding : join.GetColumnBindings()) { + for (auto &binding : bindings) { auto column = left_columns.Find(binding); if (column) { mark_result.columns.push_back(*column); + mark_result.columns.back().list_stats = RelationStatisticsHelper::ScaleListStats( + column->list_stats, child_stats[0].get().cardinality, cardinality); } else if (binding.table_index == join.mark_index) { mark_result.columns.emplace_back(binding, DistinctCount(3, DistinctCountSource::CARDINALITY), Identifier("mark")); @@ -265,20 +341,18 @@ static optional ExtractComparisonJoinStats(LogicalComparisonJoin } } mark_result.CapCurrentDomainsToCardinality(); - mark_result.Verify(join.GetColumnBindings()); + mark_result.Verify(bindings); return mark_result; } static optional ExtractCrossProductStats(LogicalOperator &op, - const vector> &child_stats) { - if (child_stats.size() != 2) { - return {}; - } + const vector> &child_stats, + const vector &bindings) { auto &left = child_stats[0].get(); auto &right = child_stats[1].get(); auto cardinality = left.GetCardinality() * right.GetCardinality(); auto maximum = RelationStatisticsHelper::MultiplyCardinalityBounds(left.max_cardinality, right.max_cardinality); - return ProjectChildStats(op, child_stats, cardinality, maximum); + return ProjectChildStats(op, child_stats, bindings, cardinality, maximum); } static optional @@ -429,6 +503,25 @@ RelationStatisticsHelper::ExtractOperatorStats(LogicalOperator &op, ClientContex return {}; } } + return ExtractValidatedOperatorStats(op, context, child_stats, [&] { return op.GetColumnBindings(); }); +} + +optional +RelationStatisticsHelper::ExtractOperatorStats(LogicalOperator &op, ClientContext &context, + const vector> &child_stats, + const vector &bindings) { + if (child_stats.size() != op.children.size()) { + return {}; + } + return ExtractValidatedOperatorStats(op, context, child_stats, + [&]() -> const vector & { return bindings; }); +} + +template +optional +RelationStatisticsHelper::ExtractValidatedOperatorStats(LogicalOperator &op, ClientContext &context, + const vector> &child_stats, + GET_BINDINGS get_bindings) { switch (op.type) { case LogicalOperatorType::LOGICAL_GET: if (child_stats.empty()) { @@ -445,7 +538,7 @@ RelationStatisticsHelper::ExtractOperatorStats(LogicalOperator &op, ClientContex case LogicalOperatorType::LOGICAL_CHUNK_GET: return ExtractColumnDataGetStats(op.Cast(), context); case LogicalOperatorType::LOGICAL_PROJECTION: - return ExtractProjectionStats(op.Cast(), child_stats[0].get()); + return ExtractProjectionStats(op.Cast(), child_stats[0].get(), context); case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY: return ExtractAggregationStats(op.Cast(), child_stats[0].get(), context); case LogicalOperatorType::LOGICAL_WINDOW: @@ -454,14 +547,21 @@ RelationStatisticsHelper::ExtractOperatorStats(LogicalOperator &op, ClientContex if (child_stats.size() != 1) { return {}; } - return ExtractFilterStats(op.Cast(), child_stats[0].get()); + vector child_bindings; + child_bindings.reserve(child_stats[0].get().columns.size()); + for (auto &column : child_stats[0].get().columns) { + child_bindings.push_back(column.binding); + } + return ExtractFilterStats(child_stats[0], op.expressions, child_bindings, get_bindings()); } case LogicalOperatorType::LOGICAL_ORDER_BY: - return child_stats.size() == 1 ? ProjectOutputStats(child_stats[0].get(), op) : optional(); + return child_stats.size() == 1 ? ProjectOutputStats(child_stats[0].get(), get_bindings()) + : optional(); case LogicalOperatorType::LOGICAL_MATERIALIZED_CTE: - return child_stats.size() == 2 ? ProjectOutputStats(child_stats[1].get(), op) : optional(); + return child_stats.size() == 2 ? ProjectOutputStats(child_stats[1].get(), get_bindings()) + : optional(); case LogicalOperatorType::LOGICAL_UNNEST: - return ExtractUnnestStats(op, child_stats[0].get()); + return ExtractUnnestStats(op, child_stats[0].get(), context); case LogicalOperatorType::LOGICAL_LIMIT: { if (child_stats.size() != 1) { return {}; @@ -469,9 +569,15 @@ RelationStatisticsHelper::ExtractOperatorStats(LogicalOperator &op, ClientContex return ExtractLimitStats(op.Cast(), child_stats[0].get()); } case LogicalOperatorType::LOGICAL_COMPARISON_JOIN: - return ExtractComparisonJoinStats(op.Cast(), child_stats); + if (child_stats.size() != 2) { + return {}; + } + return ExtractComparisonJoinStats(op.Cast(), child_stats, get_bindings()); case LogicalOperatorType::LOGICAL_CROSS_PRODUCT: - return ExtractCrossProductStats(op, child_stats); + if (child_stats.size() != 2) { + return {}; + } + return ExtractCrossProductStats(op, child_stats, get_bindings()); case LogicalOperatorType::LOGICAL_UNION: case LogicalOperatorType::LOGICAL_INTERSECT: case LogicalOperatorType::LOGICAL_EXCEPT: diff --git a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_scan.cpp b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_scan.cpp index 0f1e5c8df..d8ecbd61d 100644 --- a/src/duckdb/src/optimizer/relation_statistics/relation_statistics_scan.cpp +++ b/src/duckdb/src/optimizer/relation_statistics/relation_statistics_scan.cpp @@ -4,8 +4,10 @@ #include "duckdb/catalog/catalog_entry/table_catalog_entry.hpp" #include "duckdb/common/operator/add.hpp" #include "duckdb/common/operator/subtract.hpp" +#include "duckdb/common/shared_ptr.hpp" #include "duckdb/common/string_util.hpp" #include "duckdb/common/types/hugeint.hpp" +#include "duckdb/common/types/value_map.hpp" #include "duckdb/function/partition_stats.hpp" #include "duckdb/function/table/table_scan.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" @@ -36,78 +38,15 @@ static idx_t CapMinMaxDistinctCount(uint64_t distinct_count, idx_t base_table_ca return capped_distinct_count == NumericLimits::Maximum() ? 0 : capped_distinct_count; } -static idx_t GetMinMaxSpanDistinctCount(uint64_t span, idx_t base_table_cardinality) { - uint64_t distinct_count; - if (!TryAddOperator::Operation(span, 1, distinct_count)) { - return 0; - } - return CapMinMaxDistinctCount(distinct_count, base_table_cardinality); -} - -template -static idx_t GetSignedMinMaxDistinctCount(const BaseStatistics &base_stats, idx_t base_table_cardinality) { - auto min_value = NumericStats::Min(base_stats).GetValueUnsafe(); - auto max_value = NumericStats::Max(base_stats).GetValueUnsafe(); - if (max_value < min_value) { - return 0; - } - hugeint_t span; - if (!TrySubtractOperator::Operation(hugeint_t(static_cast(max_value)), - hugeint_t(static_cast(min_value)), span)) { - return 0; - } - uint64_t unsigned_span; - if (!Hugeint::TryCast(span, unsigned_span)) { - return 0; - } - return GetMinMaxSpanDistinctCount(unsigned_span, base_table_cardinality); -} - -template -static idx_t GetUnsignedMinMaxDistinctCount(const BaseStatistics &base_stats, idx_t base_table_cardinality) { - auto min_value = NumericStats::Min(base_stats).GetValueUnsafe(); - auto max_value = NumericStats::Max(base_stats).GetValueUnsafe(); - T span; - if (!TrySubtractOperator::Operation(max_value, min_value, span)) { - return 0; - } - return GetMinMaxSpanDistinctCount(static_cast(span), base_table_cardinality); -} - -static idx_t GetBooleanMinMaxDistinctCount(const BaseStatistics &base_stats, idx_t base_table_cardinality) { - auto min_value = NumericStats::Min(base_stats).GetValueUnsafe(); - auto max_value = NumericStats::Max(base_stats).GetValueUnsafe(); - return CapMinMaxDistinctCount(min_value == max_value ? idx_t(1) : idx_t(2), base_table_cardinality); -} - static idx_t GetMinMaxDistinctCount(const BaseStatistics &base_stats, idx_t base_table_cardinality) { - if (base_table_cardinality == 0 || base_stats.GetStatsType() != StatisticsType::NUMERIC_STATS || - !NumericStats::HasMinMax(base_stats)) { + if (base_table_cardinality == 0) { return 0; } - - switch (base_stats.GetType().InternalType()) { - case PhysicalType::BOOL: - return GetBooleanMinMaxDistinctCount(base_stats, base_table_cardinality); - case PhysicalType::INT8: - return GetSignedMinMaxDistinctCount(base_stats, base_table_cardinality); - case PhysicalType::INT16: - return GetSignedMinMaxDistinctCount(base_stats, base_table_cardinality); - case PhysicalType::INT32: - return GetSignedMinMaxDistinctCount(base_stats, base_table_cardinality); - case PhysicalType::INT64: - return GetSignedMinMaxDistinctCount(base_stats, base_table_cardinality); - case PhysicalType::UINT8: - return GetUnsignedMinMaxDistinctCount(base_stats, base_table_cardinality); - case PhysicalType::UINT16: - return GetUnsignedMinMaxDistinctCount(base_stats, base_table_cardinality); - case PhysicalType::UINT32: - return GetUnsignedMinMaxDistinctCount(base_stats, base_table_cardinality); - case PhysicalType::UINT64: - return GetUnsignedMinMaxDistinctCount(base_stats, base_table_cardinality); - default: + auto distinct_count = RelationStatisticsHelper::NumericStatsDistinctCount(base_stats); + if (!distinct_count.IsValid()) { return 0; } + return CapMinMaxDistinctCount(distinct_count.GetIndex(), base_table_cardinality); } static DistinctCount GetDistinctCountFromStats(BaseStatistics &base_stats, idx_t base_table_cardinality) { @@ -223,6 +162,120 @@ static optional_ptr FilterColumn(const Expression &ex return nullptr; } +//! Literal alternatives for one direct column; this is local to one filter, not retained statistics. +struct ConstantFilterValues { +public: + bool Extract(const Expression &expression) { + vector> pending {expression}; + while (!pending.empty()) { + auto &expr = pending.back().get(); + pending.pop_back(); + if (expr.GetExpressionType() == ExpressionType::CONJUNCTION_OR) { + for (auto &child : expr.Cast().GetChildren()) { + pending.emplace_back(*child); + } + } else if (expr.GetExpressionType() == ExpressionType::COMPARE_IN && + expr.GetExpressionClass() == ExpressionClass::BOUND_OPERATOR) { + auto &children = expr.Cast().GetChildren(); + if (children.size() < 2) { + return false; + } + for (idx_t i = 1; i < children.size(); i++) { + if (!Add(*children[0], *children[i])) { + return false; + } + } + } else if (BoundComparisonExpression::IsComparison(expr) && + expr.GetExpressionType() == ExpressionType::COMPARE_EQUAL) { + auto &comparison = expr.Cast(); + auto &left = BoundComparisonExpression::Left(comparison); + auto &right = BoundComparisonExpression::Right(comparison); + if (ExpressionFilter::IsSimpleFilterColumnRef(left) ? !Add(left, right) : !Add(right, left)) { + return false; + } + } else { + return false; + } + } + return column; + } + + void ExcludeImpossibleValues(optional_ptr statistics) { + if (!statistics || !statistics->GetType().EqualsIncludingCollation(column->GetReturnType())) { + return; + } + if (!statistics->CanHaveNoNull()) { + values.clear(); + return; + } + for (auto it = values.begin(); it != values.end();) { + auto pruning = ExpressionFilter::CheckZonemapAgainstConstants(*statistics, ExpressionType::COMPARE_EQUAL, + array_ptr(&*it, 1)); + if (pruning == FilterPropagateResult::FILTER_ALWAYS_FALSE || + pruning == FilterPropagateResult::FILTER_FALSE_OR_NULL) { + it = values.erase(it); + } else { + ++it; + } + } + } + +private: + bool Add(const Expression &ref, const Expression &constant) { + if (!ExpressionFilter::IsSimpleFilterColumnRef(ref) || + constant.GetExpressionClass() != ExpressionClass::BOUND_CONSTANT || + (ref.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF && + ref.Cast().Depth() != 0) || + (column && !column->Equals(ref))) { + return false; + } + auto &value = constant.Cast().GetValue(); + if (!ref.GetReturnType().EqualsIncludingCollation(value.type()) || + (value.type().id() == LogicalTypeId::VARCHAR && !StringType::GetCollation(value.type()).empty())) { + return false; + } + column = ref; + if (!value.IsNull()) { + values.insert(value); + } + return true; + } + +public: + optional_ptr column; + value_set_t values; +}; + +static FilterEstimate EstimateConstantFilterRows(CardinalityValue cardinality, const Expression &expression, + const RelationColumnStatsLookup &columns, + const vector &positional_bindings, + optional_ptr scan_statistics) { + ConstantFilterValues filter; + if (!filter.Extract(expression)) { + return {cardinality, false}; + } + auto column = FilterColumn(*filter.column, columns, positional_bindings); + if (!column) { + return {cardinality, false}; + } + filter.ExcludeImpossibleValues(scan_statistics ? scan_statistics : column->value_bounds.get()); + if (filter.values.empty()) { + return {0, true, true}; + } + if (!column->total_domain.CanEstimateCoverage()) { + return {cardinality, false}; + } + auto domain = MinValue(cardinality, column->current_domain.distinct_count); + if (domain == 0) { + return {cardinality, false}; + } + auto fraction = MinValue(CardinalityValue(1), CardinalityValue(filter.values.size()) / domain); + // Distinct counts do not describe literal frequencies; retain the existing fallback for selective lists. + return { + MaxValue(cardinality * fraction, FilterFraction(cardinality, RelationStatisticsHelper::DEFAULT_SELECTIVITY)), + true}; +} + static FilterEstimate EstimateNullCheckRows(CardinalityValue cardinality, const BoundOperatorExpression &expr, const RelationColumnStatsLookup &columns, const vector &positional_bindings) { @@ -372,6 +425,10 @@ static FilterEstimate EstimateFilterRows(CardinalityValue cardinality, const Exp return EstimateComparisonRows(cardinality, expr.Cast(), columns, positional_bindings, pruning, range, !scan_statistics || scan_statistics->CanHaveNull()); } + if (expr.GetExpressionType() == ExpressionType::COMPARE_IN || + expr.GetExpressionType() == ExpressionType::CONJUNCTION_OR) { + return EstimateConstantFilterRows(cardinality, expr, columns, positional_bindings, scan_statistics); + } return {cardinality, false}; } @@ -397,12 +454,57 @@ static void ApplyFilterDomainCap(RelationColumnStats &column, optional_idx cap) column.semi_anti_join_domain_evidence.TightenDomainBound(cap.GetIndex()); } -static void ApplyDirectFilterDomain(RelationColumnStats &column, const Expression &expression, - optional binding) { - auto bound = column.semi_anti_join_domain_evidence.GetDomainBound(); - ApplyFilterDomainCap( - column, RelationStatisticsHelper::EstimateDirectFilterDomain( - expression, binding, bound.IsValid() ? bound.GetIndex() : NumericLimits::Maximum())); +static void ApplyDirectFilterDomain(RelationStats &stats, const Expression &expression, + optional scan_binding, + optional_ptr scan_statistics) { + // Collect literals once, rather than once per output column. + ConstantFilterValues filter; + if ((expression.GetExpressionType() == ExpressionType::COMPARE_IN || + expression.GetExpressionType() == ExpressionType::CONJUNCTION_OR) && + filter.Extract(expression)) { + if (!scan_binding && filter.column->GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) { + return; + } + auto binding = scan_binding ? *scan_binding : filter.column->Cast().Binding(); + auto index = stats.FindColumn(binding); + if (index.IsValid()) { + auto &column = stats.columns[index.GetIndex()]; + filter.ExcludeImpossibleValues(scan_statistics ? scan_statistics : column.value_bounds.get()); + ApplyFilterDomainCap(column, optional_idx(filter.values.size())); + } + return; + } + // A conservative bound admits more expressions than a finite row estimate, including bounded conjunctions. + for (auto &column : stats.columns) { + if (scan_binding && column.binding != *scan_binding) { + continue; + } + auto bound = column.semi_anti_join_domain_evidence.GetDomainBound(); + ApplyFilterDomainCap(column, RelationStatisticsHelper::EstimateDirectFilterDomain( + expression, scan_binding ? optional() : column.binding, + bound.IsValid() ? bound.GetIndex() : NumericLimits::Maximum())); + } +} + +static void ApplyDirectFilterDomains(RelationStats &stats, const Expression &expression, + optional scan_binding = {}, + optional_ptr scan_statistics = nullptr) { + if (expression.GetExpressionType() != ExpressionType::CONJUNCTION_AND) { + ApplyDirectFilterDomain(stats, expression, scan_binding, scan_statistics); + return; + } + vector> pending {expression}; + while (!pending.empty()) { + auto &expr = pending.back().get(); + pending.pop_back(); + if (expr.GetExpressionType() == ExpressionType::CONJUNCTION_AND) { + for (auto &child : expr.Cast().GetChildren()) { + pending.emplace_back(*child); + } + } else { + ApplyDirectFilterDomain(stats, expr, scan_binding, scan_statistics); + } + } } //===--------------------------------------------------------------------===// @@ -552,6 +654,8 @@ RelationStats RelationStatisticsHelper::ExtractGetStats(LogicalGet &get, ClientC Identifier(get.GetName() + "." + get.GetColumnName(column_id))); if (column_statistics && column_statistics->GetType().EqualsIncludingCollation(get.GetColumnType(column_id))) { scan_statistics.push_back(std::move(*column_statistics)); + // kept so a projection above the scan can bound keys derived from this column + result.columns.back().base_stats = make_shared_ptr(scan_statistics.back().Copy()); } else { scan_statistics.push_back(BaseStatistics::CreateUnknown(get.GetColumnType(column_id))); } @@ -590,19 +694,23 @@ RelationStats RelationStatisticsHelper::ExtractGetStats(LogicalGet &get, ClientC } } ApplyFilterEstimate(result, estimate); - for (auto &column : result.columns) { - for (auto &entry : get.table_filters) { - if (ExpressionFilter::IsOptionalFilter(entry.Filter()) || entry.GetIndex() != column.binding.column_index) { - continue; - } - auto &filter = ExpressionFilter::GetExpressionFilter(entry.Filter(), "ExtractGetStats"); - ApplyDirectFilterDomain(column, *filter.expr, {}); + for (auto &entry : get.table_filters) { + if (ExpressionFilter::IsOptionalFilter(entry.Filter())) { + continue; } + auto &filter = ExpressionFilter::GetExpressionFilter(entry.Filter(), "ExtractGetStats"); + ApplyDirectFilterDomains(result, *filter.expr, ColumnBinding(get.table_index, entry.GetIndex()), + scan_statistics[entry.GetIndex().GetIndex()]); } vector output_columns; for (auto binding : get.GetColumnBindings()) { if (binding.table_index == get.table_index) { - output_columns.push_back(result.columns[binding.column_index.GetIndex()]); + auto &column = result.columns[binding.column_index.GetIndex()]; + if (!column.value_bounds) { + column.value_bounds = + make_shared_ptr(std::move(scan_statistics[binding.column_index.GetIndex()])); + } + output_columns.push_back(column); } } result.columns = std::move(output_columns); @@ -619,8 +727,16 @@ optional RelationStatisticsHelper::ExtractFilterStats(LogicalFilt optional RelationStatisticsHelper::ExtractFilterStats(LogicalFilter &filter, const RelationStats &child_stats, const vector> &expressions) { - auto result = ConditionFilterStats(child_stats, expressions, filter.children[0]->GetColumnBindings()); - return ProjectOutputStats(result, filter); + return ExtractFilterStats(child_stats, expressions, filter.children[0]->GetColumnBindings(), + filter.GetColumnBindings()); +} + +optional RelationStatisticsHelper::ExtractFilterStats(const RelationStats &child_stats, + const vector> &expressions, + const vector &input_bindings, + const vector &output_bindings) { + auto conditioned = ConditionFilterStats(child_stats, expressions, input_bindings); + return ProjectOutputStats(conditioned, output_bindings); } RelationStats RelationStatisticsHelper::ConditionFilterStats(const RelationStats &child_stats, @@ -633,10 +749,8 @@ RelationStats RelationStatisticsHelper::ConditionFilterStats(const RelationStats estimate.Combine(EstimateFilterRows(child_stats.cardinality, *expression, columns, bindings)); } ApplyFilterEstimate(result, estimate); - for (auto &column : result.columns) { - for (auto &expression : expressions) { - ApplyDirectFilterDomain(column, *expression, column.binding); - } + for (auto &expression : expressions) { + ApplyDirectFilterDomains(result, *expression); } return result; } diff --git a/src/duckdb/src/optimizer/remove_unused_columns.cpp b/src/duckdb/src/optimizer/remove_unused_columns.cpp index dfb2a7dd7..5c90cb1ea 100644 --- a/src/duckdb/src/optimizer/remove_unused_columns.cpp +++ b/src/duckdb/src/optimizer/remove_unused_columns.cpp @@ -15,6 +15,7 @@ #include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/planner/expression/bound_cast_expression.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/expression/bound_unnest_expression.hpp" #include "duckdb/planner/filter/expression_filter.hpp" #include "duckdb/planner/operator/logical_aggregate.hpp" #include "duckdb/planner/operator/logical_column_data_get.hpp" @@ -25,6 +26,7 @@ #include "duckdb/planner/operator/logical_projection.hpp" #include "duckdb/planner/operator/logical_recursive_cte.hpp" #include "duckdb/planner/operator/logical_set_operation.hpp" +#include "duckdb/planner/operator/logical_unnest.hpp" #include "duckdb/planner/operator/logical_secure_view.hpp" #include "duckdb/planner/operator/logical_cte.hpp" #include "duckdb/planner/operator/logical_cteref.hpp" @@ -492,6 +494,83 @@ void RemoveUnusedColumns::VisitSecureView(LogicalSecureView &view) { view.output_expressions = std::move(new_expressions); } +//! Whether the function builds a list with exactly one entry per argument, and never returns NULL +static bool IsListValue(const BoundScalarFunction &function) { + if (function.GetCatalogName() != SYSTEM_CATALOG) { + return false; + } + auto &name = function.GetName(); + return name == "list_value" || name == "list_pack"; +} + +//! Returns the number of entries of the list an UNNEST expression expands if that number is the same for every input +//! row, or an invalid index if it is not known. A NULL list expands to zero entries. +static optional_idx GetConstantUnnestLength(const Expression &unnest_expr) { + if (unnest_expr.GetExpressionClass() != ExpressionClass::BOUND_UNNEST) { + return optional_idx(); + } + auto &list = *unnest_expr.Cast().Child(); + if (list.GetReturnType().id() != LogicalTypeId::LIST) { + return optional_idx(); + } + if (list.GetExpressionClass() == ExpressionClass::BOUND_CONSTANT) { + auto &value = list.Cast().GetValue(); + return value.IsNull() ? 0 : ListValue::GetChildren(value).size(); + } + if (list.GetExpressionClass() == ExpressionClass::BOUND_FUNCTION) { + // list_value never returns NULL and has one entry per argument + auto &function = list.Cast(); + if (IsListValue(function.Function())) { + return function.GetChildren().size(); + } + } + return optional_idx(); +} + +void RemoveUnusedColumns::MarkRequiredUnnestExpressions(LogicalUnnest &unnest) { + // An UNNEST emits as many rows per input row as its longest list has entries, shorter lists are padded with NULL. + // An expression that is not referenced can therefore only be removed if a remaining expression is known to + // expand to at least as many rows for every input row. We only know this for lists with a constant length. + // Expressions that have to stay are marked as referenced. + auto mark_required = [&](idx_t expr_idx) { + column_references.emplace(ColumnBinding(unnest.unnest_index, ProjectionIndex(expr_idx)), ReferencedColumn()); + }; + bool has_required = false; + idx_t required_length = 0; + // the longest expression that is a candidate for removal + optional_idx longest_candidate; + idx_t longest_candidate_length = 0; + for (idx_t i = 0; i < unnest.expressions.size(); i++) { + auto &expr = *unnest.expressions[i]; + auto length = GetConstantUnnestLength(expr); + bool referenced = + column_references.find(ColumnBinding(unnest.unnest_index, ProjectionIndex(i))) != column_references.end(); + if (!referenced && length.IsValid() && !expr.IsVolatile()) { + if (!longest_candidate.IsValid() || length.GetIndex() > longest_candidate_length) { + longest_candidate = i; + longest_candidate_length = length.GetIndex(); + } + continue; + } + // referenced, of unknown length, or volatile: this expression stays + if (!referenced) { + mark_required(i); + } + has_required = true; + if (length.IsValid()) { + required_length = MaxValue(required_length, length.GetIndex()); + } + } + if (!longest_candidate.IsValid()) { + return; + } + // The longest candidate stays if the expressions that stay are not known to be at least as long. + // It also stays if it would otherwise leave the UNNEST without any expression. + if (!has_required || longest_candidate_length > required_length) { + mark_required(longest_candidate.GetIndex()); + } +} + static bool IsDuplicateCondition(const vector &conditions, const JoinCondition &cond) { // two equal volatile conditions are two evaluations, so neither is a duplicate of the other if (cond.IsComparison() ? (cond.GetLHS().IsVolatile() || cond.GetRHS().IsVolatile()) @@ -556,6 +635,27 @@ void RemoveUnusedColumns::VisitOperator(unique_ptr &op_ref) { VisitPrunableChildren(window); return; } + case LogicalOperatorType::LOGICAL_UNNEST: { + auto &unnest = op.Cast(); + if (everything_referenced) { + break; + } + MarkRequiredUnnestExpressions(unnest); + if (analyze) { + // The UNNEST also passes through child columns, so retain the existing references. + for (idx_t i = 0; i < unnest.expressions.size(); i++) { + auto binding = ColumnBinding(unnest.unnest_index, ProjectionIndex(i)); + if (column_references.find(binding) != column_references.end()) { + VisitExpression(&unnest.expressions[i]); + } + } + VisitOperator(unnest.children[0]); + return; + } + ClearUnusedExpressions(unnest.expressions, unnest.unnest_index); + ApplySecureViewReplacements(); + break; + } case LogicalOperatorType::LOGICAL_SECURE_VIEW: { auto &view = op.Cast(); if (!analyze && !everything_referenced && view.has_source && @@ -823,16 +923,16 @@ void RemoveUnusedColumns::VisitOperator(unique_ptr &op_ref) { } case LogicalOperatorType::LOGICAL_GET: { LogicalOperatorVisitor::VisitOperatorExpressions(op); - if (!analyze) { - auto &get = op.Cast(); - RemoveColumnsFromLogicalGet(get, op_ref); - } if (!op.children.empty()) { - // Some LOGICAL_GET operators (e.g., table in out functions) may have a - // child operator. So we recurse into it if it exists. + // Some LOGICAL_GET operators (e.g., table in out functions) have an input child. RemoveUnusedColumns remove(*this, true); remove.VisitOperator(op.children[0]); } + if (!analyze) { + // Re-admitting a scalar filter can replace and destroy this GET. + auto &get = op.Cast(); + RemoveColumnsFromLogicalGet(get, op_ref); + } return; } case LogicalOperatorType::LOGICAL_CHUNK_GET: { @@ -1339,41 +1439,35 @@ void RemoveUnusedColumns::RemoveColumnsFromLogicalGet(LogicalGet &get, unique_pt // Clear unused ids, exclude filter columns that are projected out immediately ClearUnusedExpressions(proj_sel, get.table_index, false); - //! for each filter that was pushed down - convert them into an expression + // Keep these expressions alive while column_references refers to them. vector> filter_expressions; - for (auto &entry : get.table_filters) { - auto filter_idx = entry.GetIndex(); - auto &filter = entry.Filter(); - auto &col_id = get.GetColumnIndex(filter_idx); - auto column_type = get.GetColumnType(col_id); - - ColumnBinding filter_binding(get.table_index, filter_idx); - auto column_ref = make_uniq(std::move(column_type), filter_binding); - //! Convert the filter to an expression, so we can visit it + vector> retained_columns; + get.table_filters.VisitFilters([&](const TableFilter &filter, array_ptr columns) { auto &expr_filter = ExpressionFilter::GetExpressionFilter(filter, "RemoveUnusedColumns::VisitGet"); - auto filter_expr = expr_filter.ToExpression(*column_ref); - if (filter_expr->IsScalar()) { - filter_expr = std::move(column_ref); + const bool optional = ExpressionFilter::IsPruningOnlyExpression(*expr_filter.expr); + for (const auto &filter_idx : columns) { + auto column_type = get.GetColumnType(get.GetColumnIndex(filter_idx)); + ColumnBinding filter_binding(get.table_index, filter_idx); + auto column_ref = make_uniq(std::move(column_type), filter_binding); + if (optional) { + // Optional predicates retain their declared inputs without introducing a row filter. + retained_columns.push_back(std::move(column_ref)); + continue; + } + D_ASSERT(columns.size() == 1); + auto filter_expr = expr_filter.ToExpression(*column_ref); + if (filter_expr->IsScalar()) { + retained_columns.push_back(std::move(column_ref)); + } + filter_expressions.push_back(std::move(filter_expr)); } - filter_expressions.push_back(std::move(filter_expr)); - } + }); for (auto &filter_expression : filter_expressions) { //! Now visit the filter to add to the 'column_references' VisitExpression(&filter_expression); } - //! The 'column_references' hold references to these expressions, so they have to stay alive - vector> multi_filter_columns; - for (const auto &filter : get.table_filters.GetMultiColumnFilters()) { - const auto &expression_filter = ExpressionFilter::GetExpressionFilter(*filter, "RemoveUnusedColumns::VisitGet"); - for (const auto &filter_idx : expression_filter.column_indexes) { - const auto &col_id = get.GetColumnIndex(filter_idx); - auto column_type = get.GetColumnType(col_id); - ColumnBinding filter_binding(get.table_index, filter_idx); - multi_filter_columns.push_back(make_uniq(std::move(column_type), filter_binding)); - } - } - for (auto &column_ref : multi_filter_columns) { - VisitExpression(&column_ref); + for (auto &column : retained_columns) { + VisitExpression(&column); } //! Check with the LogicalGet whether pushdown-extract is supported @@ -1441,35 +1535,20 @@ void RemoveUnusedColumns::RemoveColumnsFromLogicalGet(LogicalGet &get, unique_pt get.SetColumnIds(std::move(new_column_ids)); // remap table filters so they point towards the new set of ids - if (get.table_filters.HasFilters() || get.table_filters.HasMultiColumnFilters()) { + if (get.table_filters.HasAnyFilters()) { // Build a mapping from old ProjectionIndex -> new ProjectionIndex using original_ids unordered_map old_to_new_pos; old_to_new_pos.reserve(original_ids.size()); for (idx_t new_pos = 0; new_pos < original_ids.size(); new_pos++) { old_to_new_pos[original_ids[new_pos]] = ProjectionIndex(new_pos); } - TableFilterSet remapped_filters; - for (auto &entry : get.table_filters) { - auto it = old_to_new_pos.find(entry.GetIndex()); + get.table_filters.RemapColumns([&](ProjectionIndex column) { + auto it = old_to_new_pos.find(column); if (it == old_to_new_pos.end()) { throw InternalException("RemoveUnusedColumns: removed a filter column"); } - remapped_filters.PushFilter(it->second, entry.TakeFilter()); - } - for (const auto &filter : get.table_filters.GetMultiColumnFilters()) { - auto remapped_filter = - ExpressionFilter::GetExpressionFilter(*filter, "RemoveUnusedColumns::RemoveColumnsFromLogicalGet") - .Copy(); - for (auto &column_index : remapped_filter->column_indexes) { - auto it = old_to_new_pos.find(column_index); - if (it == old_to_new_pos.end()) { - throw InternalException("RemoveUnusedColumns: removed a multi-column filter column"); - } - column_index = it->second; - } - remapped_filters.PushMultiColumnFilter(std::move(remapped_filter)); - } - get.table_filters = std::move(remapped_filters); + return it->second; + }); } if (get.function.filter_prune) { @@ -1506,7 +1585,22 @@ void RemoveUnusedColumns::RemoveColumnsFromLogicalGet(LogicalGet &get, unique_pt auto filter = make_uniq_base(); filter->expressions = std::move(filter_expressions); filter->children.push_back(std::move(op_ref)); - get.table_filters.ClearFilters(); + // The optional predicates keep whole inputs, so only their dependency indexes changed. Preserve them while + // the existing pushdown path reconstructs row filters over the extracted fields. + TableFilterSet optional_filters; + get.table_filters.VisitFilters([&](const TableFilter &table_filter, array_ptr columns) { + auto &expression_filter = + ExpressionFilter::GetExpressionFilter(table_filter, "RemoveUnusedColumns::VisitGet"); + if (!ExpressionFilter::IsPruningOnlyExpression(*expression_filter.expr)) { + return; + } + if (expression_filter.column_indexes.empty()) { + optional_filters.PushFilter(columns[0], expression_filter.Copy()); + } else { + optional_filters.PushMultiColumnFilter(expression_filter.Copy()); + } + }); + get.table_filters = std::move(optional_filters); // try to push filters back into the table scan FilterPushdown pushdown(optimizer); diff --git a/src/duckdb/src/optimizer/removed_subtree_effects.cpp b/src/duckdb/src/optimizer/removed_subtree_effects.cpp new file mode 100644 index 000000000..08b4d61ac --- /dev/null +++ b/src/duckdb/src/optimizer/removed_subtree_effects.cpp @@ -0,0 +1,77 @@ +#include "duckdb/optimizer/removed_subtree_effects.hpp" + +#include "duckdb/planner/logical_operator_visitor.hpp" +#include "duckdb/planner/operator/logical_cte.hpp" +#include "duckdb/planner/operator/logical_cteref.hpp" +#include "duckdb/planner/operator/logical_get.hpp" + +namespace duckdb { + +RemovedSubtreeEffects::RemovedSubtreeEffects(LogicalOperator &plan) { + CollectDefinitions(plan); +} + +void RemovedSubtreeEffects::CollectDefinitions(LogicalOperator &op) { + if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { + materialized_ctes.emplace(op.Cast().table_index, op); + } else if (op.type == LogicalOperatorType::LOGICAL_RECURSIVE_CTE) { + recursive_ctes.insert(op.Cast().table_index); + } + for (auto &child : op.children) { + CollectDefinitions(*child); + } +} + +bool RemovedSubtreeEffects::DefinitionHasEffect(TableIndex cte_index) { + auto known = definition_has_effect.find(cte_index); + if (known != definition_has_effect.end()) { + return known->second; + } + auto cte = materialized_ctes.find(cte_index); + if (cte == materialized_ctes.end()) { + // A reference to something not defined in this plan may have effects. + return true; + } + // Materialized CTE definitions cannot reference themselves. + const bool has_effect = HasEffect(*cte->second.get().children[0]); + definition_has_effect.emplace(cte_index, has_effect); + return has_effect; +} + +bool RemovedSubtreeEffects::HasEffect(LogicalOperator &subtree) { + bool is_volatile = false; + LogicalOperatorVisitor::EnumerateExpressions( + subtree, [&](const unique_ptr *expr) { is_volatile |= (*expr)->IsVolatile(); }); + if (is_volatile) { + return true; + } + switch (subtree.type) { + case LogicalOperatorType::LOGICAL_INSERT: + case LogicalOperatorType::LOGICAL_DELETE: + case LogicalOperatorType::LOGICAL_UPDATE: + case LogicalOperatorType::LOGICAL_MERGE_INTO: + return true; + case LogicalOperatorType::LOGICAL_GET: + if (subtree.Cast().function.stability == FunctionStability::VOLATILE) { + return true; + } + break; + case LogicalOperatorType::LOGICAL_CTE_REF: { + auto cte_index = subtree.Cast().cte_index; + if (recursive_ctes.find(cte_index) == recursive_ctes.end() && DefinitionHasEffect(cte_index)) { + return true; + } + break; + } + default: + break; + } + for (auto &child : subtree.children) { + if (HasEffect(*child)) { + return true; + } + } + return false; +} + +} // namespace duckdb diff --git a/src/duckdb/src/optimizer/rule/constant_folding.cpp b/src/duckdb/src/optimizer/rule/constant_folding.cpp index b8b14022e..5749946b9 100644 --- a/src/duckdb/src/optimizer/rule/constant_folding.cpp +++ b/src/duckdb/src/optimizer/rule/constant_folding.cpp @@ -25,20 +25,26 @@ ConstantFoldingRule::ConstantFoldingRule(ExpressionRewriter &rewriter) : Rule(re root = std::move(op); } -unique_ptr ConstantFoldingRule::Apply(LogicalOperator &op, vector> &bindings, - bool &changes_made, bool is_root) { - auto &root = bindings[0].get(); - // the root is a scalar expression that we have to fold - D_ASSERT(root.IsFoldable() && root.GetExpressionType() != ExpressionType::VALUE_CONSTANT); +unique_ptr ConstantFoldingRule::TryFold(ClientContext &context, Expression &expr) { + ConstantFoldingExpressionMatcher matcher; + vector> bindings; + if (!matcher.Match(expr, bindings)) { + return nullptr; + } // use an ExpressionExecutor to execute the expression Value result_value; - if (!ExpressionExecutor::TryEvaluateScalar(GetContext(), root, result_value)) { + if (!ExpressionExecutor::TryEvaluateScalar(context, expr, result_value)) { return nullptr; } - D_ASSERT(result_value.type().InternalType() == root.GetReturnType().InternalType()); + D_ASSERT(result_value.type().InternalType() == expr.GetReturnType().InternalType()); // now get the value from the result vector and insert it back into the plan as a constant expression return make_uniq(result_value); } +unique_ptr ConstantFoldingRule::Apply(LogicalOperator &op, vector> &bindings, + bool &changes_made, bool is_root) { + return TryFold(GetContext(), bindings[0].get()); +} + } // namespace duckdb diff --git a/src/duckdb/src/optimizer/rule/date_trunc_simplification.cpp b/src/duckdb/src/optimizer/rule/date_trunc_simplification.cpp index e4b61908d..41a58e5c4 100644 --- a/src/duckdb/src/optimizer/rule/date_trunc_simplification.cpp +++ b/src/duckdb/src/optimizer/rule/date_trunc_simplification.cpp @@ -82,6 +82,16 @@ static bool TruncatesToSecondOrFiner(DatePartSpecifier part) { } } +static unique_ptr CopyColumnWithType(ExpressionRewriter &rewriter, + const BoundColumnRefExpression &column_part, + const LogicalType &return_type) { + auto column = column_part.Copy(); + if (column->GetReturnType().id() != return_type.id()) { + column = BoundCastExpression::AddCastToType(rewriter.context, std::move(column), return_type, true); + } + return column; +} + static bool IsAfterFirstYear(const Value &value) { if (value.IsNull()) { return true; @@ -112,6 +122,11 @@ unique_ptr DateTruncSimplificationRule::Apply(LogicalOperator &op, v } auto &column_part = bindings[3].get().Cast(); + auto return_type = column_part.GetReturnType(); + // Bounds finer than a day must retain their time for DATE columns. + if (return_type.id() == LogicalTypeId::DATE && !TruncatesToDays(part)) { + return_type = LogicalType::TIMESTAMP; + } auto &rhs = bindings[4].get().Cast(); // Determine whether or not the column name is on the lhs or rhs. @@ -130,22 +145,18 @@ unique_ptr DateTruncSimplificationRule::Apply(LogicalOperator &op, v // the rewrites rely on built-in casts inverting date_trunc - a registered cast need not if (CastFunctionSet::Get(rewriter.context) .CanOverrideDefaultCast(rhs.GetReturnType(), column_part.GetReturnType()) || + CastFunctionSet::Get(rewriter.context).CanOverrideDefaultCast(column_part.GetReturnType(), return_type) || !CreateTrunc(date_part, rhs, rhs.GetReturnType())) { return nullptr; } // date_trunc preserves temporal infinities, so only remove the function call. if (IsInfinity(rhs.GetValue())) { - ReplaceDateTruncWithColumn(column_side, constant_side, column_part); + ReplaceDateTruncWithColumn(column_side, constant_side, column_part, return_type); changes_made = true; return nullptr; } - // Bounds finer than a day lose their time when cast to DATE, so keep the comparison. - if (column_part.GetReturnType().id() == LogicalTypeId::DATE && !TruncatesToDays(part)) { - return nullptr; - } - // Truncating a time zone aware timestamp to a minute or longer can cross a UTC offset change, so keep the // comparison. if (TruncatesInSessionTimeZone(column_part.GetReturnType().id()) && !TruncatesToSecondOrFiner(part)) { @@ -201,19 +212,21 @@ unique_ptr DateTruncSimplificationRule::Apply(LogicalOperator &op, v return ExpressionRewriter::ConstantOrNull(GetContext(), column_part.Copy(), Value::BOOLEAN(false)); } - auto trunc = CreateTrunc(date_part, rhs, column_part.GetReturnType()); + auto trunc = CreateTrunc(date_part, rhs, return_type); if (!trunc) { return nullptr; } - auto trunc_add = CreateTruncAdd(date_part, rhs, column_part.GetReturnType()); + auto trunc_add = CreateTruncAdd(date_part, rhs, return_type); if (!trunc_add) { return nullptr; } auto gteq = BoundComparisonExpression::Create(ExpressionType::COMPARE_GREATERTHANOREQUALTO, - column_part.Copy(), std::move(trunc)); - auto lt = BoundComparisonExpression::Create(ExpressionType::COMPARE_LESSTHAN, column_part.Copy(), + CopyColumnWithType(rewriter, column_part, return_type), + std::move(trunc)); + auto lt = BoundComparisonExpression::Create(ExpressionType::COMPARE_LESSTHAN, + CopyColumnWithType(rewriter, column_part, return_type), std::move(trunc_add)); // For IS NOT DISTINCT FROM, we also have to add the extra NULL term. @@ -272,20 +285,22 @@ unique_ptr DateTruncSimplificationRule::Apply(LogicalOperator &op, v return ExpressionRewriter::ConstantOrNull(GetContext(), column_part.Copy(), Value::BOOLEAN(true)); } - auto trunc = CreateTrunc(date_part, rhs, column_part.GetReturnType()); + auto trunc = CreateTrunc(date_part, rhs, return_type); if (!trunc) { return nullptr; } - auto trunc_add = CreateTruncAdd(date_part, rhs, column_part.GetReturnType()); + auto trunc_add = CreateTruncAdd(date_part, rhs, return_type); if (!trunc_add) { return nullptr; } - auto lt = BoundComparisonExpression::Create(ExpressionType::COMPARE_LESSTHAN, column_part.Copy(), + auto lt = BoundComparisonExpression::Create(ExpressionType::COMPARE_LESSTHAN, + CopyColumnWithType(rewriter, column_part, return_type), std::move(trunc)); auto gteq = BoundComparisonExpression::Create(ExpressionType::COMPARE_GREATERTHANOREQUALTO, - column_part.Copy(), std::move(trunc_add)); + CopyColumnWithType(rewriter, column_part, return_type), + std::move(trunc_add)); // If this is a DISTINCT FROM, we need to add the 'column IS NULL' term. if (rhs_comparison_type == ExpressionType::COMPARE_DISTINCT_FROM) { @@ -316,17 +331,17 @@ unique_ptr DateTruncSimplificationRule::Apply(LogicalOperator &op, v // use the rhs as-is, instead of using trunc(rhs + 1 date_part). if (!is_truncated) { // Create date_trunc(part, date_add(rhs, INTERVAL 1 part)) and fold the constant. - auto trunc = CreateTruncAdd(date_part, rhs, column_part.GetReturnType()); + auto trunc = CreateTruncAdd(date_part, rhs, return_type); if (!trunc) { return nullptr; // Something went wrong---don't do the optimization. } - column_side = column_part.Copy(); + column_side = CopyColumnWithType(rewriter, column_part, return_type); constant_side = std::move(trunc); } else { // If the RHS is already truncated (i.e. date_trunc(part, rhs) = rhs), then we can use // it as-is. - ReplaceDateTruncWithColumn(column_side, constant_side, column_part); + ReplaceDateTruncWithColumn(column_side, constant_side, column_part, return_type); } changes_made = true; @@ -341,12 +356,12 @@ unique_ptr DateTruncSimplificationRule::Apply(LogicalOperator &op, v // INTERVAL 1 part)) { // Create date_trunc(part, date_add(rhs, INTERVAL 1 part)) and fold the constant. - auto trunc = CreateTruncAdd(date_part, rhs, column_part.GetReturnType()); + auto trunc = CreateTruncAdd(date_part, rhs, return_type); if (!trunc) { return nullptr; // Something went wrong---don't do the optimization. } - column_side = column_part.Copy(); + column_side = CopyColumnWithType(rewriter, column_part, return_type); constant_side = std::move(trunc); // > needs to become >=, and <= needs to become <. @@ -384,7 +399,7 @@ unique_ptr DateTruncSimplificationRule::CreateTrunc(const BoundConst args.emplace_back(rhs.Copy()); auto trunc = binder.BindScalarFunction(Identifier::DefaultSchema(), "date_trunc", std::move(args), error); - // Ensure that the RHS type matches the column type. + // Ensure that the RHS type matches the requested return type. if (trunc->GetReturnType().id() != return_type.id()) { if (CastFunctionSet::Get(rewriter.context).CanOverrideDefaultCast(trunc->GetReturnType(), return_type)) { return nullptr; @@ -438,7 +453,7 @@ unique_ptr DateTruncSimplificationRule::CreateTruncAdd(const BoundCo args3.emplace_back(std::move(add)); auto trunc = binder.BindScalarFunction(Identifier::DefaultSchema(), "date_trunc", std::move(args3), error); - // Ensure that the RHS type matches the column type. + // Ensure that the RHS type matches the requested return type. if (trunc->GetReturnType().id() != return_type.id()) { if (CastFunctionSet::Get(rewriter.context).CanOverrideDefaultCast(trunc->GetReturnType(), return_type)) { return nullptr; @@ -498,10 +513,11 @@ bool DateTruncSimplificationRule::IsInfinity(const Value &value) { void DateTruncSimplificationRule::ReplaceDateTruncWithColumn(unique_ptr &column_side, unique_ptr &constant_side, - const BoundColumnRefExpression &column_part) { - column_side = column_part.Copy(); - if (constant_side->GetReturnType().id() != column_side->GetReturnType().id()) { - constant_side = CastAndEvaluate(std::move(constant_side), column_side->GetReturnType()); + const BoundColumnRefExpression &column_part, + const LogicalType &return_type) { + column_side = CopyColumnWithType(rewriter, column_part, return_type); + if (constant_side->GetReturnType().id() != return_type.id()) { + constant_side = CastAndEvaluate(std::move(constant_side), return_type); } } diff --git a/src/duckdb/src/optimizer/rule/list_comprehension_rewrite.cpp b/src/duckdb/src/optimizer/rule/list_comprehension_rewrite.cpp index 9b45def6d..d79dfc217 100644 --- a/src/duckdb/src/optimizer/rule/list_comprehension_rewrite.cpp +++ b/src/duckdb/src/optimizer/rule/list_comprehension_rewrite.cpp @@ -43,7 +43,8 @@ bool IsStructPack(const BoundFunctionExpression &expr) { return expr.Function().GetName() == "struct_pack"; } -optional_ptr FindStructPackChildByName(BoundFunctionExpression &struct_pack, const string &name) { +optional_ptr FindStructPackChildByName(const BoundFunctionExpression &struct_pack, + const string &name) { D_ASSERT(struct_pack.GetReturnType().id() == LogicalTypeId::STRUCT); for (auto &child : struct_pack.GetChildren()) { if (child->GetAlias() == name) { @@ -53,7 +54,7 @@ optional_ptr FindStructPackChildByName(BoundFunctionExpression &stru return nullptr; } -bool UsesIndexParameter(Expression &expr) { +bool UsesIndexParameter(const Expression &expr) { if (expr.GetExpressionClass() == ExpressionClass::BOUND_REF) { auto &ref = expr.Cast(); if (ref.Index() == 0) { @@ -61,20 +62,8 @@ bool UsesIndexParameter(Expression &expr) { } } bool uses_index = false; - ExpressionIterator::EnumerateChildren(expr, [&uses_index](unique_ptr &child) { - ExpressionIterator::EnumerateExpression(child, [&uses_index](Expression &child) { - if (uses_index) { - return; - } - if (child.GetExpressionClass() == ExpressionClass::BOUND_REF) { - auto &ref = child.Cast(); - if (ref.Index() == 0) { - uses_index = true; - return; - } - } - }); - }); + ExpressionIterator::EnumerateChildren( + expr, [&uses_index](const Expression &child) { uses_index = uses_index || UsesIndexParameter(child); }); return uses_index; } @@ -86,15 +75,15 @@ void RemoveIndexInputSlot(unique_ptr &expr) { }); } -bool MatchesStructFieldProjection(Expression &expr, const string &field_name, bool allow_boolean_cast = false) { - optional_ptr base = expr; +bool MatchesStructFieldProjection(const Expression &expr, const string &field_name, bool allow_boolean_cast = false) { + optional_ptr base = expr; if (allow_boolean_cast && BoundCastExpression::IsCast(*base) && base->GetReturnType() == LogicalType::BOOLEAN) { auto &cast_expr = base->Cast(); if (BoundCastExpression::IsTryCast(cast_expr)) { return false; } // The rewritten filter recreates this single BOOLEAN cast. - base = BoundCastExpression::ChildMutable(cast_expr).get(); + base = BoundCastExpression::Child(cast_expr); } if (base->GetExpressionClass() != ExpressionClass::BOUND_FUNCTION) { return false; @@ -130,8 +119,8 @@ struct ListComprehensionMatch { optional_ptr list_filter_expr; optional_ptr inner_apply; optional_ptr inner_bind; - optional_ptr filter_expr; - optional_ptr result_expr; + optional_ptr filter_expr; + optional_ptr result_expr; vector> captured_children; }; diff --git a/src/duckdb/src/optimizer/runtime_filter_cast.cpp b/src/duckdb/src/optimizer/runtime_filter_cast.cpp index a811507a9..984b18f76 100644 --- a/src/duckdb/src/optimizer/runtime_filter_cast.cpp +++ b/src/duckdb/src/optimizer/runtime_filter_cast.cpp @@ -83,7 +83,8 @@ static bool ExpressionPreservesStorageOrdering(const Expression &expr) { bool RuntimeFilterCastUtil::PreservesStorageOrdering(const JoinFilterPushdownColumn &column) { return column.mode == JoinFilterPushdownMode::RECONSTRUCT_EXPRESSION && - (!column.input_expression || ExpressionPreservesStorageOrdering(*column.input_expression)); + (!column.input_expression || column.value_preserving_input || + ExpressionPreservesStorageOrdering(*column.input_expression)); } LogicalType RuntimeFilterCastUtil::GetRuntimeFilterInputType(const JoinFilterPushdownColumn &column, @@ -100,9 +101,10 @@ bool RuntimeFilterCastUtil::RequiresRuntimeFilterExpressionReconstruction(const !PreservesStorageOrdering(column); } -static void PreserveRuntimeFilterCastErrors(unique_ptr &expr, bool &preserves_cast_errors) { - ExpressionIterator::EnumerateChildren( - *expr, [&](unique_ptr &child) { PreserveRuntimeFilterCastErrors(child, preserves_cast_errors); }); +static void PreserveRuntimeFilterCastErrors(unique_ptr &expr, bool can_fail, bool &preserves_cast_errors) { + ExpressionIterator::EnumerateChildren(*expr, [&](unique_ptr &child) { + PreserveRuntimeFilterCastErrors(child, can_fail, preserves_cast_errors); + }); if (!BoundCastExpression::IsCast(*expr)) { return; } @@ -117,7 +119,9 @@ static void PreserveRuntimeFilterCastErrors(unique_ptr &expr, bool & safe_cast->SetAlias(cast.GetAlias()); safe_cast->SetQueryLocation(cast.GetQueryLocation()); expr = std::move(safe_cast); - preserves_cast_errors = true; + // the scan can evaluate the filter before its other filters, so a cast that only cannot fail on the returned + // rows still becomes a try cast, but has no errors to retain + preserves_cast_errors |= can_fail; } unique_ptr RuntimeFilterCastUtil::CreateRuntimeFilterInputExpression(ClientContext &context, @@ -127,7 +131,7 @@ unique_ptr RuntimeFilterCastUtil::CreateRuntimeFilterInputExpression preserves_cast_errors = false; auto input = column.input_expression ? column.input_expression->Copy() : make_uniq(column.storage_type, idx_t(0)); - PreserveRuntimeFilterCastErrors(input, preserves_cast_errors); + PreserveRuntimeFilterCastErrors(input, !column.value_preserving_input, preserves_cast_errors); return input; } diff --git a/src/duckdb/src/optimizer/statistics/expression/propagate_conjunction.cpp b/src/duckdb/src/optimizer/statistics/expression/propagate_conjunction.cpp index 59f32c89e..80364c4ef 100644 --- a/src/duckdb/src/optimizer/statistics/expression/propagate_conjunction.cpp +++ b/src/duckdb/src/optimizer/statistics/expression/propagate_conjunction.cpp @@ -70,6 +70,10 @@ unique_ptr StatisticsPropagator::PropagateExpression(BoundConjun for (idx_t expr_idx = 0; expr_idx < expr.GetChildren().size(); expr_idx++) { auto &child = expr.GetChildrenMutable()[expr_idx]; auto stats = PropagateExpression(child); + if (!IsRemovable(*child)) { + // Later constants must not erase this effect. + break; + } if (!child->IsFoldable()) { continue; } diff --git a/src/duckdb/src/optimizer/statistics/operator/propagate_filter.cpp b/src/duckdb/src/optimizer/statistics/operator/propagate_filter.cpp index 446265b8b..fd8cfee8f 100644 --- a/src/duckdb/src/optimizer/statistics/operator/propagate_filter.cpp +++ b/src/duckdb/src/optimizer/statistics/operator/propagate_filter.cpp @@ -393,6 +393,9 @@ unique_ptr StatisticsPropagator::PropagateStatistics(LogicalFilt // filter is always false or null; this entire filter should be replaced by an empty result block ReplaceWithEmptyResult(node_ptr); return make_uniq(0U, 0U); + } else if (!IsRemovable(*condition)) { + // Later predicates must not erase this effect. + return std::move(node_stats); } } SimplifyConstantOrNull(filter.expressions); diff --git a/src/duckdb/src/optimizer/statistics/operator/propagate_join.cpp b/src/duckdb/src/optimizer/statistics/operator/propagate_join.cpp index 4fba090e1..447ad7f27 100644 --- a/src/duckdb/src/optimizer/statistics/operator/propagate_join.cpp +++ b/src/duckdb/src/optimizer/statistics/operator/propagate_join.cpp @@ -9,6 +9,7 @@ #include "duckdb/planner/operator/logical_any_join.hpp" #include "duckdb/planner/operator/logical_comparison_join.hpp" #include "duckdb/planner/operator/logical_cross_product.hpp" +#include "duckdb/planner/operator/logical_empty_result.hpp" #include "duckdb/planner/operator/logical_filter.hpp" #include "duckdb/planner/operator/logical_join.hpp" #include "duckdb/planner/operator/logical_limit.hpp" @@ -34,13 +35,16 @@ bool StatisticsPropagator::HandleJoinNeverMatches(LogicalJoin &join, unique_ptr< node_ptr = LogicalJoin::PromoteJoinSide(std::move(join.children[0]), std::move(join.left_projection_map)); return true; case JoinType::LEFT: - // anti/left outer join: replace right side with empty node - ReplaceWithEmptyResult(join.children[1]); - return true; - case JoinType::RIGHT: - // right outer join: replace left side with empty node - ReplaceWithEmptyResult(join.children[0]); + case JoinType::RIGHT: { + auto &child = join.children[join.join_type == JoinType::LEFT ? 1 : 0]; + ReplaceWithEmptyResult(child); + // Every output value from the pruned side is a typed NULL. + auto &empty = child->Cast(); + for (idx_t i = 0; i < empty.bindings.size(); i++) { + statistics_map[empty.bindings[i]] = BaseStatistics::FromConstant(Value(empty.return_types[i])).ToUnique(); + } return true; + } default: // other join types: can't do much meaningful with this information // full outer join requires both sides anyway; we can skip the execution of the actual join, but eh diff --git a/src/duckdb/src/parallel/async_result.cpp b/src/duckdb/src/parallel/async_result.cpp index 11f9aa2f4..7920aba8e 100644 --- a/src/duckdb/src/parallel/async_result.cpp +++ b/src/duckdb/src/parallel/async_result.cpp @@ -100,12 +100,14 @@ AsyncResult::AsyncResult(vector> &&tasks, TaskSchedulerTyp AsyncResult &AsyncResult::operator=(duckdb::SourceResultType t) { result_type = GetAsyncResultType(t); async_tasks.clear(); + prepared_io_size = 0; return *this; } AsyncResult &AsyncResult::operator=(duckdb::AsyncResultType t) { result_type = t; async_tasks.clear(); + prepared_io_size = 0; return *this; } @@ -113,6 +115,7 @@ AsyncResult &AsyncResult::operator=(AsyncResult &&other) noexcept { result_type = other.result_type; async_tasks = std::move(other.async_tasks); pool_type = other.pool_type; + prepared_io_size = other.prepared_io_size; return *this; } @@ -136,6 +139,7 @@ void AsyncResult::ScheduleTasks(InterruptState &interrupt_state, Executor &execu async_tasks.clear(); result_type = AsyncResultType::INVALID; + prepared_io_size = 0; } void AsyncResult::ExecuteTasksSynchronously() { @@ -154,6 +158,7 @@ void AsyncResult::ExecuteTasksSynchronously() { async_tasks.clear(); result_type = AsyncResultType::HAVE_MORE_OUTPUT; + prepared_io_size = 0; } //! Runs one AsyncTask as a task of a TaskExecutor @@ -196,6 +201,7 @@ void AsyncResult::ExecuteTasksSynchronously(ClientContext &context) { } async_tasks.clear(); result_type = AsyncResultType::HAVE_MORE_OUTPUT; + prepared_io_size = 0; } SourceResultType AsyncResult::ScheduleOrExecute(ExecutionContext &context, OperatorSourceInput &input, @@ -211,11 +217,12 @@ SourceResultType AsyncResult::ScheduleOrExecute(ExecutionContext &context, Opera return SourceResultType::HAVE_MORE_OUTPUT; } -AsyncResult AsyncResult::FromTasks(vector> &&tasks, TaskSchedulerType pool_type) { - if (tasks.empty()) { - return AsyncResult(SourceResultType::HAVE_MORE_OUTPUT); - } - return AsyncResult(std::move(tasks), pool_type); +AsyncResult AsyncResult::FromTasks(vector> &&tasks, TaskSchedulerType pool_type, + idx_t prepared_io_size) { + auto result = + tasks.empty() ? AsyncResult(SourceResultType::HAVE_MORE_OUTPUT) : AsyncResult(std::move(tasks), pool_type); + result.prepared_io_size = prepared_io_size; + return result; } AsyncResult AsyncResult::FromChunk(const DataChunk &chunk) { @@ -264,6 +271,7 @@ AsyncResultType AsyncResult::GetResultType() const { vector> &&AsyncResult::ExtractAsyncTasks() { D_ASSERT(result_type != AsyncResultType::INVALID); result_type = AsyncResultType::INVALID; + prepared_io_size = 0; return std::move(async_tasks); } diff --git a/src/duckdb/src/parallel/pipeline.cpp b/src/duckdb/src/parallel/pipeline.cpp index c78c01946..27069c549 100644 --- a/src/duckdb/src/parallel/pipeline.cpp +++ b/src/duckdb/src/parallel/pipeline.cpp @@ -145,6 +145,13 @@ void Pipeline::GetDetailedProgress(PipelineProgress &progress) { } progress.pipeline = progress.source; progress.pipeline.Normalize(double(source_cardinality)); + for (auto &op_ref : operators) { + auto &op = op_ref.get(); + lock_guard guard(op.lock); + if (op.op_state) { + progress.pipeline = op.GetOperatorProgress(client, *op.op_state, progress.pipeline); + } + } if (sink) { lock_guard guard(sink->lock); if (sink->sink_state) { diff --git a/src/duckdb/src/parallel/pipeline_broadcast_exchange.cpp b/src/duckdb/src/parallel/pipeline_broadcast_exchange.cpp index e10f427ee..e969028b7 100644 --- a/src/duckdb/src/parallel/pipeline_broadcast_exchange.cpp +++ b/src/duckdb/src/parallel/pipeline_broadcast_exchange.cpp @@ -787,7 +787,7 @@ void PipelineBroadcastExchange::Reset() { void PipelineBroadcastExchange::ResetExchangeStateLocked() { buffer->Reset(); - produced_rows.store(0, std::memory_order_relaxed); + produced_rows.Reset(); producer_state = ProducerState::ACTIVE; watermark_state = WatermarkState::BELOW_HIGH_WATERMARK; append_reservation_state = AppendReservationState::IDLE; @@ -1407,7 +1407,7 @@ PipelineBroadcastExchange::BufferedPushState PipelineBroadcastExchange::Append(D } void PipelineBroadcastExchange::RecordProducedRows(idx_t count) { - produced_rows.fetch_add(count, std::memory_order_relaxed); + produced_rows.Add(count); } void PipelineBroadcastExchange::Finish() { @@ -1787,7 +1787,7 @@ ProgressData PipelineBroadcastExchange::ScanProgress(idx_t consumer_idx, idx_t e progress.SetInvalid(); return progress; } - auto total = produced_rows.load(std::memory_order_relaxed); + auto total = produced_rows.GetTotal(); if (producer_state == ProducerState::ACTIVE) { static constexpr const idx_t MAX_PROGRESS_CARDINALITY = 1ULL << 48ULL; if (estimated_cardinality > 0 && estimated_cardinality < MAX_PROGRESS_CARDINALITY) { @@ -1815,7 +1815,7 @@ ProgressData PipelineBroadcastExchange::SinkProgress(const ProgressData &source_ // the producing pipeline is done once its source is exhausted return source_progress; } - auto produced_count = produced_rows.load(std::memory_order_relaxed); + auto produced_count = produced_rows.GetTotal(); auto produced = double(produced_count); progress.done = produced; static constexpr const idx_t MAX_PROGRESS_CARDINALITY = 1ULL << 48ULL; diff --git a/src/duckdb/src/parallel/runtime_filter_schedule.cpp b/src/duckdb/src/parallel/runtime_filter_schedule.cpp index 19eeba2eb..08334663c 100644 --- a/src/duckdb/src/parallel/runtime_filter_schedule.cpp +++ b/src/duckdb/src/parallel/runtime_filter_schedule.cpp @@ -167,8 +167,7 @@ static void ScheduleRuntimeFiltersInternal(PipelineSchedule &schedule, bool clea continue; } const auto small_build_only = - join_build_stages[stage_idx] || - (scan.table_filters && (scan.table_filters->HasFilters() || scan.table_filters->HasMultiColumnFilters())); + join_build_stages[stage_idx] || (scan.table_filters && scan.table_filters->HasAnyFilters()); sources[*scan.dynamic_filters].push_back({stage_idx, small_build_only}); for (auto &filters : scan.dynamic_filters->GetDisjunctionFilters()) { sources[filters.get()].push_back({stage_idx, false}); diff --git a/src/duckdb/src/parallel/scan_read_ahead.cpp b/src/duckdb/src/parallel/scan_read_ahead.cpp index 9d3e8a4b3..1a1c9af8b 100644 --- a/src/duckdb/src/parallel/scan_read_ahead.cpp +++ b/src/duckdb/src/parallel/scan_read_ahead.cpp @@ -304,15 +304,15 @@ bool ScanReadAhead::TryProduceBatch(const ProduceJobCallback &produce, idx_t loc try { for (idx_t i = 0; i < count; i++) { ThrowIfError(); - vector> io_tasks; - auto job = produce(io_tasks); + AsyncResult io(SourceResultType::HAVE_MORE_OUTPUT); + auto job = produce(io); if (!job) { ThrowIfError(); SetDone(); break; } job->producer_shard = local_shard; - ScheduleReadyJob(std::move(job), std::move(io_tasks), reservation); + ScheduleReadyJob(std::move(job), std::move(io), reservation); if (pending_budget_charge.load() >= backlog_budget.load()) { break; } @@ -329,15 +329,24 @@ bool ScanReadAhead::TryProduceBatch(const ProduceJobCallback &produce, idx_t loc return true; } -void ScanReadAhead::ScheduleReadyJob(unique_ptr job, vector> io_tasks, - ProducerReservation &reservation) { - const auto minimum = MinimumJobCharge(); - job->budget_charge = memory_governor ? MaxValue(minimum, job->GetMemoryUsage()) : 0; +vector> ScanReadAhead::TakeJobIO(ScanReadAheadJob &job, AsyncResult io) { + auto io_size = io.GetPreparedIOSize(); + auto io_tasks = io.ExtractAsyncTasks(); for (auto &task : io_tasks) { - if (memory_governor) { - job->budget_charge += task->GetIOSize(); - } + io_size += task->GetIOSize(); + } + if (affinity) { + job.budget_charge = memory_governor ? MaxValue(MinimumJobCharge(), job.GetMemoryUsage()) + io_size : 0; + } else { + job.budget_charge = MaxValue(MINIMUM_ORDERED_JOB_CHARGE, io_size); } + return io_tasks; +} + +void ScanReadAhead::ScheduleReadyJob(unique_ptr job, AsyncResult io, + ProducerReservation &reservation) { + const auto minimum = MinimumJobCharge(); + auto io_tasks = TakeJobIO(*job, std::move(io)); if (io_tasks.empty()) { if (job->budget_charge > minimum) { pending_budget_charge += job->budget_charge - minimum; @@ -478,15 +487,15 @@ bool ScanReadAhead::TryProduceJob(const ProduceJobCallback &claim_and_schedule) } ProducerReservation reservation(*this, 1); try { - vector> io_tasks; - auto job = claim_and_schedule(io_tasks); + AsyncResult io(SourceResultType::HAVE_MORE_OUTPUT); + auto job = claim_and_schedule(io); if (!job) { // an async open that failed while we were claiming must fail the scan, not quiet-finish it ThrowIfError(); SetDone(); return false; } - PushJob(std::move(job), std::move(io_tasks)); + PushJob(std::move(job), std::move(io)); reservation.Commit(); } catch (std::exception &ex) { PushError(ErrorData(ex)); @@ -632,17 +641,16 @@ bool ScanReadAhead::TryReserveSlot() { return true; } -void ScanReadAhead::PushJob(unique_ptr job, vector> io_tasks) { +void ScanReadAhead::PushJob(unique_ptr job, AsyncResult io) { + auto io_tasks = TakeJobIO(*job, std::move(io)); auto completion = make_shared_ptr(executor); job->io_completion = completion; // wrap all reads before scheduling any, a wrapped task settles the completion even when scheduling throws vector> read_tasks; read_tasks.reserve(io_tasks.size()); for (auto &task : io_tasks) { - job->budget_charge += task->GetIOSize(); read_tasks.push_back(make_uniq(*executor, std::move(task), completion)); } - job->budget_charge = MaxValue(job->budget_charge, MINIMUM_ORDERED_JOB_CHARGE); // the minimum charge was taken by TryReserveSlot, charge the remainder pending_budget_charge += job->budget_charge - MINIMUM_ORDERED_JOB_CHARGE; // schedule the reads detached on the async pool right away, logged under their own label diff --git a/src/duckdb/src/parallel/task_scheduler.cpp b/src/duckdb/src/parallel/task_scheduler.cpp index d4c6a0712..1b4faf1fd 100644 --- a/src/duckdb/src/parallel/task_scheduler.cpp +++ b/src/duckdb/src/parallel/task_scheduler.cpp @@ -1,4 +1,5 @@ #include "duckdb/parallel/task_scheduler.hpp" +#include "duckdb/common/no_destructor.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/numeric_utils.hpp" @@ -10,7 +11,10 @@ #include "duckdb/parallel/task_scheduler_queue.hpp" #include "duckdb/storage/block_allocator.hpp" #ifndef DUCKDB_NO_THREADS +// vendored code with statics we do not control +DUCKDB_ALLOW_STATIC_LIFETIME_BEGIN #include "concurrentqueue.h" +DUCKDB_ALLOW_STATIC_LIFETIME_END #include "duckdb/common/thread.hpp" #include diff --git a/src/duckdb/src/parallel/task_scheduler_queue.cpp b/src/duckdb/src/parallel/task_scheduler_queue.cpp index ef1d15112..de265b9ab 100644 --- a/src/duckdb/src/parallel/task_scheduler_queue.cpp +++ b/src/duckdb/src/parallel/task_scheduler_queue.cpp @@ -1,9 +1,13 @@ #include "duckdb/parallel/task_scheduler_queue.hpp" +#include "duckdb/common/no_destructor.hpp" #include "duckdb/parallel/task.hpp" #ifndef DUCKDB_NO_THREADS +// vendored code with statics we do not control +DUCKDB_ALLOW_STATIC_LIFETIME_BEGIN #include "concurrentqueue.h" +DUCKDB_ALLOW_STATIC_LIFETIME_END #endif namespace duckdb { diff --git a/src/duckdb/src/parser/expression/function_expression.cpp b/src/duckdb/src/parser/expression/function_expression.cpp index 2554b613d..213e2d53a 100644 --- a/src/duckdb/src/parser/expression/function_expression.cpp +++ b/src/duckdb/src/parser/expression/function_expression.cpp @@ -2,6 +2,7 @@ #include #include "duckdb/common/string_util.hpp" +#include "duckdb/parser/keyword_helper.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/types/hash.hpp" #include "duckdb/common/serializer/serializer.hpp" @@ -57,6 +58,25 @@ FunctionExpression::FunctionExpression(const Identifier &function_name, vector 3 || + (!catalog.empty() && catalog != Identifier(SYSTEM_CATALOG)) || + (!schema.empty() && schema != Identifier(DEFAULT_SCHEMA)) || distinct || filter || + (order_bys && !order_bys->orders.empty()) || export_state) { + return false; + } + bool has_empty_name = false; + for (auto &argument : arguments) { + if (!argument.HasName()) { + return false; + } + has_empty_name = has_empty_name || argument.GetName().empty(); + } + return has_empty_name; +} + string FunctionExpression::ToString() const { if (is_operator) { // built-in operator @@ -73,6 +93,16 @@ string FunctionExpression::ToString() const { arguments[1].ToString()); } } + if (RendersAsStructLiteral()) { + // HACK: `"" := x` does not parse (empty identifiers are rejected), so use a struct literal; remove once allowed + return "{" + + StringUtil::Join(arguments, arguments.size(), ", ", + [&](const FunctionArgument &child) { + return SQLString::ToString(child.GetName().GetIdentifierName()) + ": " + + child.GetExpression().ToString(); + }) + + "}"; + } // standard function call - render the full qualification, the schema path can be nested (e.g. s1.s2.s3.my_macro) string result = qualified_name.QualificationToString(); result += SQLIdentifier(qualified_name.Name()); @@ -137,7 +167,7 @@ void FunctionExpression::Serialize(Serializer &serializer) const { vector> children; for (auto &arg : arguments) { auto copy = arg.GetExpression().Copy(); - copy->SetAlias(arg.GetName()); + copy->SetAlias(Identifier(arg.GetName().GetSerializedName())); children.push_back(std::move(copy)); } serializer.WritePropertyWithDefault>>(202, "children", children); @@ -175,8 +205,9 @@ unique_ptr FunctionExpression::Deserialize(Deserializer &deser if (!children.empty()) { result->arguments.reserve(children.size()); for (auto &child : children) { - auto alias = child->GetAlias(); - result->arguments.emplace_back(alias, std::move(child)); + auto name = Identifier::FromSerializedName(child->GetAlias().GetIdentifierName()); + child->SetAlias(name); + result->arguments.emplace_back(std::move(name), std::move(child)); } // Mark this function expression as a legacy function call, so that the binder can handle it accordingly. @@ -217,7 +248,7 @@ unique_ptr FunctionExpression::Deserialize(Deserializer &deser } hash_t FunctionArgument::Hash() const { - hash_t result = duckdb::Hash(name.c_str()); + hash_t result = CombineHash(duckdb::Hash(name.c_str()), duckdb::Hash(name.IsSet())); if (expression) { result = CombineHash(result, expression->Hash()); } diff --git a/src/duckdb/src/parser/expression/type_expression.cpp b/src/duckdb/src/parser/expression/type_expression.cpp index 6bd7c33a2..7387a3173 100644 --- a/src/duckdb/src/parser/expression/type_expression.cpp +++ b/src/duckdb/src/parser/expression/type_expression.cpp @@ -1,4 +1,5 @@ #include "duckdb/parser/expression/type_expression.hpp" +#include #include "duckdb/common/types/geometry_crs.hpp" #include "duckdb/common/extension_type_info.hpp" #include "duckdb/common/exception.hpp" @@ -12,18 +13,37 @@ namespace duckdb { bool TypeExpression::IsSQLType(LogicalTypeId id) { - static const auto admitted_ids = [] { + static const std::bitset<256> admitted_ids = [] { // TYPE has SQL syntax but is not included in AllTypes. - unordered_set ids {LogicalTypeId::SQLNULL, LogicalTypeId::TYPE}; + std::bitset<256> ids; + ids.set(static_cast(LogicalTypeId::SQLNULL)); + ids.set(static_cast(LogicalTypeId::TYPE)); for (auto &type : LogicalType::AllTypes()) { - ids.insert(type.id()); + ids.set(static_cast(type.id())); } return ids; }(); - return admitted_ids.count(id) != 0; + return admitted_ids.test(static_cast(id)); +} + +bool TypeExpression::HasEmptyStructMemberName(const LogicalType &type) { + return TypeVisitor::Contains(type, [](const LogicalType &child) { + if (child.id() != LogicalTypeId::STRUCT || !child.HasParameters()) { + return false; + } + for (auto &entry : StructType::GetChildTypes(child)) { + if (entry.first.empty()) { + return true; + } + } + return false; + }); } bool TypeExpression::CanRepresent(const LogicalType &type) { + if (HasEmptyStructMemberName(type)) { + return false; + } return type.IsComplete() && !TypeVisitor::Contains(type, [](const LogicalType &child) { const bool empty_tuple = child.id() == LogicalTypeId::TUPLE && StructType::GetChildCount(child) == 0; const bool empty_enum = child.id() == LogicalTypeId::ENUM && EnumType::GetSize(child) == 0; diff --git a/src/duckdb/src/parser/expression/value_expression.cpp b/src/duckdb/src/parser/expression/value_expression.cpp index ddb1c343b..46efb2d2c 100644 --- a/src/duckdb/src/parser/expression/value_expression.cpp +++ b/src/duckdb/src/parser/expression/value_expression.cpp @@ -107,7 +107,7 @@ static unique_ptr StructExpression(const Value &value) { auto &name = StructType::GetChildName(type, i); auto child = ConstantExpression::FromValue(children[i]); child->SetAlias(name); - arguments.emplace_back(name, std::move(child)); + arguments.emplace_back(name.AsSet(), std::move(child)); } return make_uniq(QualifiedName("system", "main", "struct_pack"), std::move(arguments)); } @@ -202,7 +202,9 @@ static bool HasUnsupportedVariantKeys(const VariantNode &node) { bool ConstantExpression::RequiresTypeWitness(const LogicalType &type) { return TypeVisitor::Contains(type, [&](const LogicalType &child) { + // an empty TUPLE has no type name, only its constructor row() return child.IsAggregateState() || child.id() == LogicalTypeId::TYPE || + (child.id() == LogicalTypeId::TUPLE && StructType::GetChildCount(child) == 0) || ((child.id() == LogicalTypeId::GEOMETRY || child.id() == LogicalTypeId::GEOGRAPHY) && GeoType::HasCRS(child)) || (type.id() != LogicalTypeId::VARCHAR && child.id() == LogicalTypeId::VARCHAR && @@ -284,7 +286,7 @@ static unique_ptr NestedValueExpression(const LogicalType &typ auto child = NestedValueExpression(child_types[i].second, children ? &(*children)[i] : nullptr); auto name = function == "struct_pack" ? child_types[i].first : Identifier(); child->SetAlias(name); - arguments.emplace_back(name, std::move(child)); + arguments.emplace_back(function == "struct_pack" ? name.AsSet() : name, std::move(child)); } unique_ptr result = make_uniq(QualifiedName("system", "main", Identifier(function)), std::move(arguments)); @@ -328,7 +330,8 @@ unique_ptr ConstantExpression::FromValue(const Value &value) { })) { throw NotImplementedException("The nested value type has no SQL constructor"); } - if (RequiresTypeWitness(type) || type.id() == LogicalTypeId::TUPLE) { + if (RequiresTypeWitness(type) || type.id() == LogicalTypeId::TUPLE || + TypeExpression::HasEmptyStructMemberName(type)) { return NestedValueExpression(type, value); } if (!value.IsNull() && type.id() == LogicalTypeId::INTERVAL) { diff --git a/src/duckdb/src/parser/expression/window_expression.cpp b/src/duckdb/src/parser/expression/window_expression.cpp index 54219d59a..ad3a3bb3d 100644 --- a/src/duckdb/src/parser/expression/window_expression.cpp +++ b/src/duckdb/src/parser/expression/window_expression.cpp @@ -18,7 +18,7 @@ vector> WindowExpression::SerializedChildren(Serial for (idx_t i = 0; i < nargs; ++i) { auto copy = arguments[i].GetExpression().Copy(); - copy->SetAlias(arguments[i].GetName()); + copy->SetAlias(Identifier(arguments[i].GetSerializedName())); result.emplace_back(std::move(copy)); } @@ -160,8 +160,9 @@ unique_ptr WindowExpression::Deserialize(Deserializer &deseria if (!children.empty()) { result->arguments.reserve(children.size()); for (auto &child : children) { - auto alias = child->GetAlias(); - result->arguments.emplace_back(std::move(alias), std::move(child)); + auto name = Identifier::FromSerializedName(child->GetAlias().GetIdentifierName()); + child->SetAlias(name); + result->arguments.emplace_back(std::move(name), std::move(child)); } // Mark this function expression as a legacy function call, so that the binder can handle it accordingly. result->is_legacy_function_call = true; diff --git a/src/duckdb/src/parser/peg/compiled_grammar.cpp b/src/duckdb/src/parser/peg/compiled_grammar.cpp index 015cffc79..99f841907 100644 --- a/src/duckdb/src/parser/peg/compiled_grammar.cpp +++ b/src/duckdb/src/parser/peg/compiled_grammar.cpp @@ -1,4 +1,5 @@ #include "duckdb/parser/peg/compiled_grammar.hpp" +#include "duckdb/common/no_destructor.hpp" #include "duckdb/parser/peg/matcher_factory.hpp" #include "duckdb/parser/peg/keyword_helper/parsed_grammar_keyword_helper.hpp" #include "duckdb/common/string_util.hpp" @@ -179,8 +180,8 @@ shared_ptr CompiledGrammar::Create(const vector CompiledGrammar::DefaultGrammar() { - static auto grammar = Create(); - return grammar; + static const NoDestructor> grammar(Create()); + return *grammar; } shared_ptr CompiledGrammar::Create() { diff --git a/src/duckdb/src/parser/peg/keyword_helper/duckdb_keyword_helper.cpp b/src/duckdb/src/parser/peg/keyword_helper/duckdb_keyword_helper.cpp index 45f57c8cb..04c3f06ca 100644 --- a/src/duckdb/src/parser/peg/keyword_helper/duckdb_keyword_helper.cpp +++ b/src/duckdb/src/parser/peg/keyword_helper/duckdb_keyword_helper.cpp @@ -1,4 +1,5 @@ #include "duckdb/parser/peg/keyword_helper/duckdb_keyword_helper.hpp" +#include "duckdb/common/no_destructor.hpp" #include "duckdb/parser/peg/parsed_grammar.hpp" namespace duckdb { @@ -9,8 +10,8 @@ DuckDBKeywordHelper::DuckDBKeywordHelper() } const DuckDBKeywordHelper &DuckDBKeywordHelper::Instance() { - static DuckDBKeywordHelper instance; - return instance; + static const NoDestructor instance; + return *instance; } keyword_categories_t DuckDBKeywordHelper::GetIdentifierMask(SuggestionState type) const { diff --git a/src/duckdb/src/parser/peg/matcher_factory.cpp b/src/duckdb/src/parser/peg/matcher_factory.cpp index 6e691a813..ebbe5e683 100644 --- a/src/duckdb/src/parser/peg/matcher_factory.cpp +++ b/src/duckdb/src/parser/peg/matcher_factory.cpp @@ -237,6 +237,8 @@ Matcher &MatcherFactory::CreateRootMatcher(const string &root_rule) { AddPackratMemoizedRule("SchemaQualification"); AddPackratMemoizedRule("ReservedSchemaQualification"); AddPackratMemoizedRule("SelectParens"); + AddPackratMemoizedRule("WithClause"); + AddPackratMemoizedRule("JoinedTableRef"); //===--------------------------------------------------------------------===// // END GENERATED PACKRAT MEMOIZED RULES //===--------------------------------------------------------------------===// @@ -265,6 +267,7 @@ Matcher &MatcherFactory::CreateRootMatcher(const string &root_rule) { LabelRule("CollateExpression", "an expression"); LabelRule("AtTimeZoneExpression", "an expression"); LabelRule("PrefixExpression", "an expression"); + LabelRule("PrefixedCustomExpression", "an expression"); LabelRule("BaseExpression", "an expression"); LabelRule("SingleExpression", "an expression"); LabelRule("Type", "a type"); diff --git a/src/duckdb/src/parser/peg/matcher_stack.cpp b/src/duckdb/src/parser/peg/matcher_stack.cpp index 7d10fc9fc..b12208194 100644 --- a/src/duckdb/src/parser/peg/matcher_stack.cpp +++ b/src/duckdb/src/parser/peg/matcher_stack.cpp @@ -1,4 +1,5 @@ #include "duckdb/parser/peg/matcher_stack.hpp" +#include "duckdb/common/no_destructor.hpp" #include "duckdb/parser/peg/matcher/list_matcher.hpp" #include "duckdb/parser/peg/matcher/choice_matcher.hpp" #include "duckdb/parser/peg/matcher/optional_matcher.hpp" @@ -60,6 +61,19 @@ static idx_t FindChoiceChild(const ChoiceMatcher &matcher, MatchState &state, id return index; } +//! An optional that matched nothing carries no rule, name or position, so every anonymous optional shares one +//! immutable result; an optional with a rule of its own still gets a result naming that rule +static MatcherResult MakeEmptyOptionalResult(MatchState &state) { + if (!state.BuildParseResult()) { + return MatcherResult::Success(); + } + if (state.rule) { + return state.AllocateParseResult(); + } + static NoDestructor shared_empty; + return MatcherResult::Success(shared_empty.Get()); +} + static MatcherResult MakeChoiceResult(MatchState &state, const MatcherResult &child, idx_t index, optional_idx start_offset) { if (!child.HasParseResult()) { @@ -114,12 +128,9 @@ class ListMatchFrame final : public MatchStackFrame { if (chain && matcher.get().GetPreparedChainIndex() + 1 < chain->lists.size() && (!chain->has_optional_prefix || (allow_empty_prefix && !chain->prefix_first_set.MightMatch(list_state)))) { - auto &last = chain->lists.back().get(); - if (!last.first_set.MightMatch(list_state)) { - break; - } + // the dispatched list's lookahead covers its chain members, which fail on entry otherwise pending = state.context.process_allocator.Make(matcher.get(), pending); - matcher = last; + matcher = chain->lists.back().get(); continue; } @@ -130,7 +141,7 @@ class ListMatchFrame final : public MatchStackFrame { list_state))) { break; } - if (!child || !child->first_set.MightMatch(list_state)) { + if (!child) { break; } pending = state.context.process_allocator.Make(matcher.get(), pending); @@ -183,8 +194,7 @@ class ListMatchFrame final : public MatchStackFrame { auto choice = matcher.get().GetFirstChoice(); auto current = list_state.token_iterator.Current(); if (!choice || !state.BuildParseResult() || - (current && current->type == TokenType::END_OF_INPUT_AUTOCOMPLETE) || - !choice->first_set.MightMatch(list_state)) { + (current && current->type == TokenType::END_OF_INPUT_AUTOCOMPLETE)) { return; } first_choice = choice; @@ -524,17 +534,40 @@ class RepeatMatchFrame final : public MatchStackFrame { public: RepeatMatchFrame(const RepeatMatcher &matcher_p, MatchState &state_p, ArenaAllocator::Position mark = {}, const PackratMatchState &packrat = {}) - : MatchStackFrame(MatcherType::REPEAT, {matcher_p, state_p}, mark, packrat), matcher(matcher_p), - repeat_state(state_p), results(state_p.context.process_allocator) { + : RepeatMatchFrame(matcher_p, matcher_p, state_p, mark, packrat, false) { + } + //! A repetition inside an optional (zero or more) runs as one frame and produces the optional's result + RepeatMatchFrame(const OptionalMatcher &optional, const RepeatMatcher &matcher_p, MatchState &state_p, + ArenaAllocator::Position mark, const PackratMatchState &packrat) + : RepeatMatchFrame(optional, matcher_p, state_p, mark, packrat, true) { + } + +private: + RepeatMatchFrame(const Matcher &input_matcher, const RepeatMatcher &matcher_p, MatchState &state_p, + ArenaAllocator::Position mark, const PackratMatchState &packrat, bool optional_wrapper_p) + : MatchStackFrame(MatcherType::REPEAT, {input_matcher, state_p}, mark, packrat), matcher(matcher_p), + repeat_state(state_p), results(state_p.context.process_allocator), optional_wrapper(optional_wrapper_p) { if (auto current = repeat_state.token_iterator.Current()) { start_offset = optional_idx(current->offset); } } public: + //! The result of one or more repetitions MatcherResult CreateResult() { - return state.AllocateParseResult(state.context.allocator.MakeChildren(results), - start_offset); + auto repeat = + state.AllocateParseResult(state.context.allocator.MakeChildren(results), start_offset); + if (!optional_wrapper) { + return repeat; + } + if (!repeat.HasParseResult()) { + return MatcherResult::Success(); + } + return state.AllocateParseResult(repeat.GetParseResult(), start_offset); + } + //! The result when the first repetition does not match + MatcherResult NoMatch() { + return optional_wrapper ? MakeEmptyOptionalResult(state) : MatcherResult::Failure(); } public: @@ -544,6 +577,8 @@ class RepeatMatchFrame final : public MatchStackFrame { bool matched_once = false; optional_idx start_offset; bool awaiting_child = false; + //! the frame stands for the optional around the repetition + bool optional_wrapper; }; struct OpaqueMatchFrame final : MatchStackFrame { OpaqueMatchFrame(MatchInput input, ArenaAllocator::Position mark, const PackratMatchState &packrat) @@ -630,10 +665,19 @@ optional MatchStack::PushFrame(MatchInput input) { arena.Make(input.matcher.Cast(), input.state, mark, packrat)); break; - case MatcherType::OPTIONAL: - owned = arena_ptr( - arena.Make(input.matcher.Cast(), input.state, mark, packrat)); + case MatcherType::OPTIONAL: { + auto &optional = input.matcher.Cast(); + auto &child = optional.GetChildMatcher(); + if (child.IsStructural() && child.Type() == MatcherType::REPEAT && !child.IsPackratMemoized() && + !child.GetRule() && !optional.GetRule()) { + owned = arena_ptr( + arena.Make(optional, child.Cast(), input.state, mark, packrat)); + } else { + owned = + arena_ptr(arena.Make(optional, input.state, mark, packrat)); + } break; + } case MatcherType::REPEAT: owned = arena_ptr( @@ -668,6 +712,8 @@ template MatchStep MatchStack::ExecuteInternal(optional_ptr stack, MatchStackFrame &initial_frame, optional child_result) { reference current_frame(initial_frame); + // the next child was covered by a lookahead test of its parent already + bool child_checked = false; while (true) { auto &frame = current_frame.get(); optional next; @@ -730,11 +776,13 @@ MatchStep MatchStack::ExecuteInternal(optional_ptr stack, MatchStack f.awaiting_child = true; next.emplace(MatchInput {f.matcher.GetChildMatcher(), f.child_state}); has_child = true; + // the optional's fast-empty test already tested the child's FIRST set + child_checked = true; break; } f.awaiting_child = false; if (!child_result->IsSuccess()) { - completed = f.state.AllocateParseResult(); + completed = MakeEmptyOptionalResult(f.state); break; } f.state.token_iterator.SetPosition(f.child_state.token_iterator); @@ -752,9 +800,7 @@ MatchStep MatchStack::ExecuteInternal(optional_ptr stack, MatchStack if (child_result) { f.awaiting_child = false; if (!child_result->IsSuccess()) { - if (f.matched_once) { - completed = f.CreateResult(); - } + completed = f.matched_once ? f.CreateResult() : f.NoMatch(); break; } f.matched_once = true; @@ -772,6 +818,8 @@ MatchStep MatchStack::ExecuteInternal(optional_ptr stack, MatchStack f.awaiting_child = true; next.emplace(MatchInput {f.matcher.GetChildMatcher(), f.repeat_state}); has_child = true; + // the repetition's own test covers the first iteration + child_checked = !f.matched_once; break; } default: { @@ -792,15 +840,17 @@ MatchStep MatchStack::ExecuteInternal(optional_ptr stack, MatchStack return MatchStep::Child(*next); } auto &child = *next; + auto checked = child_checked; + child_checked = false; if (!child.matcher.IsStructural() && child.matcher.IsAtomic()) { child_result = stack->ExecuteAtomicMatcher(child); continue; } - if (child.state.BuildParseResult()) { + if (child.state.BuildParseResult() && !checked) { if (child.matcher.Type() == MatcherType::OPTIONAL && child.matcher.IsStructural() && !child.matcher.Cast().GetChildMatcher().first_set.MightMatch(child.state)) { child.state.rule = child.matcher.GetRule(); - child_result = child.state.AllocateParseResult(); + child_result = MakeEmptyOptionalResult(child.state); continue; } if (!child.matcher.first_set.MightMatch(child.state)) { diff --git a/src/duckdb/src/parser/peg/peg_rule_id.cpp b/src/duckdb/src/parser/peg/peg_rule_id.cpp index 0e4fd5f21..6fc4fe500 100644 --- a/src/duckdb/src/parser/peg/peg_rule_id.cpp +++ b/src/duckdb/src/parser/peg/peg_rule_id.cpp @@ -1,6 +1,7 @@ // AUTO-GENERATED by scripts/parser/generate_transformer_trampoline.py -- DO NOT EDIT #include "duckdb/parser/peg/peg_rule_id.hpp" +#include "duckdb/common/no_destructor.hpp" #include "duckdb/common/case_insensitive_map.hpp" namespace duckdb { @@ -743,7 +744,9 @@ static const char *const PEG_RULE_NAMES[] = { "AtTimeZoneOperator", "UnaryExpression", "PrefixExpression", + "PrefixedCustomExpression", "CustomPrefixExpression", + "CustomPrefixOperator", "PrefixOperator", "MinusPrefixOperator", "PlusPrefixOperator", @@ -1255,13 +1258,14 @@ const char *PEGRuleIdToString(PEGRuleId rule_id) { } PEGRuleId PEGRuleIdFromString(const string &rule_name) { - static const case_insensitive_map_t lookup = [] { + static const NoDestructor> lookup_storage([] { case_insensitive_map_t result; for (uint32_t i = 1; i < static_cast(PEGRuleId::BUILTIN_COUNT); i++) { result.emplace(PEG_RULE_NAMES[i], static_cast(i)); } return result; - }(); + }()); + const auto &lookup = *lookup_storage; auto entry = lookup.find(rule_name); return entry == lookup.end() ? PEGRuleId::INVALID : entry->second; } diff --git a/src/duckdb/src/parser/peg/sql_formatter.cpp b/src/duckdb/src/parser/peg/sql_formatter.cpp index 163317411..2ca0acc3b 100644 --- a/src/duckdb/src/parser/peg/sql_formatter.cpp +++ b/src/duckdb/src/parser/peg/sql_formatter.cpp @@ -8,6 +8,7 @@ //===----------------------------------------------------------------------===// #include "duckdb/parser/peg/sql_formatter.hpp" +#include "duckdb/common/static_string_table.hpp" #include "duckdb/parser/peg/keyword_helper/duckdb_keyword_helper.hpp" #include "duckdb/parser/peg/tokenizer/highlight_tokenizer.hpp" #include "duckdb/parser/peg/compiled_grammar.hpp" @@ -179,12 +180,13 @@ string SQLFormatter::Format(const string &sql) { //! Returns true if kw (already uppercased) is a structural clause keyword that //! starts a new line in the formatted output. bool SQLFormatter::IsClauseKeyword(const string &kw) { - static const std::unordered_set clause_keywords = { + static constexpr const char *const CLAUSE_KEYWORDS[] = { "SELECT", "FROM", "WHERE", "HAVING", "LIMIT", "OFFSET", "JOIN", "UNION", "INTERSECT", "EXCEPT", "WITH", "INSERT", "UPDATE", "DELETE", "SET", "RETURNING", "VALUES", "CREATE", "DROP", "ALTER", "TRUNCATE", "QUALIFY", "PIVOT", "UNPIVOT", "REFRESH", "INSTALL", "LOAD", "ATTACH", "DETACH", "CHECKPOINT", "FORCE", "COPY"}; - return clause_keywords.count(kw) > 0; + const StaticStringSet clause_keywords(CLAUSE_KEYWORDS); + return clause_keywords.Contains(kw); } bool SQLFormatter::IsJoinModifier(const string &kw) { @@ -194,7 +196,7 @@ bool SQLFormatter::IsJoinModifier(const string &kw) { //! Complete set of clause keyword *strings* as they appear in the formatted //! output (single words AND compound forms). Used by the post-processing pass. bool SQLFormatter::IsClauseKeywordLine(const string &trimmed) { - static const std::unordered_set all_clause_strings = { + static constexpr const char *const ALL_CLAUSE_STRINGS[] = { // Single-word clause starters "SELECT", "FROM", "WHERE", "HAVING", "LIMIT", "OFFSET", "JOIN", "UNION", "INTERSECT", "EXCEPT", "WITH", "INSERT", "UPDATE", "DELETE", "SET", "RETURNING", "VALUES", "CREATE", "DROP", "ALTER", "TRUNCATE", "QUALIFY", @@ -211,14 +213,15 @@ bool SQLFormatter::IsClauseKeywordLine(const string &trimmed) { "CREATE OR REPLACE INDEX", "CREATE OR REPLACE MACRO", "CREATE OR REPLACE FUNCTION", "CREATE OR REPLACE TYPE", "CREATE OR REPLACE TEMP TABLE", "CREATE OR REPLACE TEMP VIEW", "CREATE OR REPLACE TEMPORARY TABLE", "CREATE OR REPLACE TEMPORARY VIEW", "ALTER TABLE"}; - return all_clause_strings.count(StringUtil::Upper(trimmed)) > 0; + const StaticStringSet all_clause_strings(ALL_CLAUSE_STRINGS); + return all_clause_strings.Contains(StringUtil::Upper(trimmed)); } //! Structural keywords that are always uppercased. Unreserved keywords used //! as identifiers (e.g. "name", "value", "type") are excluded so their //! original casing is preserved. bool SQLFormatter::ShouldUppercase(const string &kw) { - static const std::unordered_set uppercase_set = { + static constexpr const char *const UPPERCASE_KEYWORDS[] = { "SELECT", "DISTINCT", "FROM", "WHERE", "HAVING", "LIMIT", "OFFSET", "GROUP", "BY", "ORDER", "UNION", "INTERSECT", "EXCEPT", "ALL", "JOIN", "INNER", "LEFT", "RIGHT", "FULL", "OUTER", "CROSS", @@ -241,7 +244,8 @@ bool SQLFormatter::ShouldUppercase(const string &kw) { "LOAD", "INSTALL", "FORCE", "POSITIONAL", "ASOF", "LATERAL", "TABLESAMPLE", "REPEATABLE", "USING", "SYSTEM", "BERNOULLI", "RESERVOIR", "NEAREST", "APPROX", "EXACT", "DISTANCE", "SIMILARITY"}; - return uppercase_set.count(kw) > 0; + const StaticStringSet uppercase_set(UPPERCASE_KEYWORDS); + return uppercase_set.Contains(kw); } // ───────────────────────────────────────────────────────────────────────────── @@ -256,6 +260,19 @@ string SQLFormatter::PeekKeyword(const vector &tokens, idx_t i, id return ""; } +//! A multi-word clause keyword; the words after the last one are null. Room for the longest CREATE form. +struct CompoundClause { + const char *words[5]; + + constexpr idx_t WordCount() const { + idx_t count = 0; + while (count < 5 && words[count]) { + count++; + } + return count; + } +}; + //! Detect a compound clause keyword starting at tokens[i]. //! Returns the number of *additional* tokens consumed (caller advances by 1+return). //! Returns static_cast(-1) if tokens[i] is NOT a clause keyword. @@ -265,89 +282,87 @@ idx_t SQLFormatter::DetectCompoundClause(const vector &tokens, idx string &original_text) { // clang-format off //! Fixed multi-word clause keyword patterns. - static const vector> kFixedCompounds = { + static constexpr CompoundClause kFixedCompounds[] = { // Two-word clauses - {"GROUP", "BY" }, - {"ORDER", "BY" }, - {"PARTITION", "BY" }, - {"ALTER", "TABLE" }, - {"INSERT", "INTO" }, - {"DELETE", "FROM" }, - {"ON", "CONFLICT"}, - {"FORCE", "CHECKPOINT"}, + {{"GROUP", "BY" }}, + {{"ORDER", "BY" }}, + {{"PARTITION", "BY" }}, + {{"ALTER", "TABLE" }}, + {{"INSERT", "INTO" }}, + {{"DELETE", "FROM" }}, + {{"ON", "CONFLICT"}}, + {{"FORCE", "CHECKPOINT"}}, // Set operations with qualifier - {"UNION", "ALL" }, {"UNION", "DISTINCT"}, - {"INTERSECT", "ALL" }, {"INTERSECT", "DISTINCT"}, - {"EXCEPT", "ALL" }, {"EXCEPT", "DISTINCT"}, + {{"UNION", "ALL" }}, {{"UNION", "DISTINCT"}}, + {{"INTERSECT", "ALL" }}, {{"INTERSECT", "DISTINCT"}}, + {{"EXCEPT", "ALL" }}, {{"EXCEPT", "DISTINCT"}}, // JOIN variants - {"INNER", "JOIN" }, - {"CROSS", "JOIN" }, - {"NATURAL", "JOIN" }, - {"LEFT", "JOIN" }, {"LEFT", "OUTER", "JOIN"}, - {"RIGHT", "JOIN" }, {"RIGHT", "OUTER", "JOIN"}, - {"FULL", "JOIN" }, {"FULL", "OUTER", "JOIN"}, + {{"INNER", "JOIN" }}, + {{"CROSS", "JOIN" }}, + {{"NATURAL", "JOIN" }}, + {{"LEFT", "JOIN" }}, {{"LEFT", "OUTER", "JOIN"}}, + {{"RIGHT", "JOIN" }}, {{"RIGHT", "OUTER", "JOIN"}}, + {{"FULL", "JOIN" }}, {{"FULL", "OUTER", "JOIN"}}, // WITH RECURSIVE - {"WITH", "RECURSIVE" }, + {{"WITH", "RECURSIVE" }}, // Special CREATE form - {"CREATE", "UNIQUE", "INDEX" }, + {{"CREATE", "UNIQUE", "INDEX" }}, }; - // CREATE [OR REPLACE] [TEMP | TEMPORARY] — generated from prefixes × objects. - static const vector> kCreatePrefixes = { - {"CREATE"}, - {"CREATE", "TEMP"}, - {"CREATE", "TEMPORARY"}, - {"CREATE", "OR", "REPLACE"}, - {"CREATE", "OR", "REPLACE", "TEMP"}, - {"CREATE", "OR", "REPLACE", "TEMPORARY"}, + // CREATE [OR REPLACE] [TEMP | TEMPORARY] - the prefixes combined with each of the objects. + static constexpr CompoundClause kCreatePrefixes[] = { + {{"CREATE"}}, + {{"CREATE", "TEMP"}}, + {{"CREATE", "TEMPORARY"}}, + {{"CREATE", "OR", "REPLACE"}}, + {{"CREATE", "OR", "REPLACE", "TEMP"}}, + {{"CREATE", "OR", "REPLACE", "TEMPORARY"}}, }; - static const vector kCreateObjects = { + static constexpr const char *const kCreateObjects[] = { "TABLE", "VIEW", "INDEX", "SCHEMA", "SEQUENCE", "MACRO", "FUNCTION", "TYPE", }; // clang-format on - static const vector> kCompoundKeywords = [&]() { - auto result = kFixedCompounds; - for (const auto &prefix : kCreatePrefixes) { - for (const char *obj : kCreateObjects) { - auto entry = prefix; - entry.push_back(obj); - result.push_back(std::move(entry)); - } - } - return result; - }(); const string kw = StringUtil::Upper(tokens[i].text); // Find the longest compound keyword pattern whose first word matches kw. idx_t best_extra = static_cast(-1); - const vector *best_match = nullptr; + CompoundClause best_match; + bool has_best_match = false; - for (const auto &entry : kCompoundKeywords) { - if (kw != entry[0]) { - continue; + auto consider = [&](const CompoundClause &entry) { + if (kw != entry.words[0]) { + return; } - bool matched = true; - for (idx_t k = 1; k < entry.size(); k++) { - if (PeekKeyword(tokens, i, k) != entry[k]) { - matched = false; - break; + const idx_t word_count = entry.WordCount(); + for (idx_t k = 1; k < word_count; k++) { + if (PeekKeyword(tokens, i, k) != entry.words[k]) { + return; } } - if (matched) { - idx_t extra = static_cast(entry.size()) - 1; - if (best_match == nullptr || extra > best_extra) { - best_extra = extra; - best_match = &entry; - } + idx_t extra = word_count - 1; + if (!has_best_match || extra > best_extra) { + best_extra = extra; + best_match = entry; + has_best_match = true; + } + }; + for (const auto &entry : kFixedCompounds) { + consider(entry); + } + for (const auto &prefix : kCreatePrefixes) { + for (const char *object : kCreateObjects) { + CompoundClause entry = prefix; + entry.words[prefix.WordCount()] = object; + consider(entry); } } - if (best_match != nullptr) { + if (has_best_match) { compound_text = kw; original_text = tokens[i].text; for (idx_t k = 1; k <= best_extra; k++) { compound_text += ' '; - compound_text += (*best_match)[k]; + compound_text += best_match.words[k]; original_text += ' '; original_text += tokens[i + k].text; } @@ -556,7 +571,7 @@ string SQLFormatter::FormatMultiline(const string &sql, const vector no_space_before_paren = { + static constexpr const char *const NO_SPACE_BEFORE_PAREN[] = { "COALESCE", "NULLIF", "CAST", "TRY_CAST", "EXTRACT", "OVERLAY", "POSITION", "SUBSTRING", "TRIM", "GROUPING", "GROUPING_ID", "TREAT", "XMLATTRIBUTES", "XMLCONCAT", "XMLELEMENT", "XMLFOREST", "XMLNAMESPACES", "XMLPARSE", "XMLPI", "XMLROOT", "XMLSERIALIZE", @@ -565,7 +580,8 @@ string SQLFormatter::FormatMultiline(const string &sql, const vector -PEGTransformerFactory::TransformCustomPrefixExpression(PEGTransformer &transformer, const string &operator_literal, - unique_ptr other_operator_expression) { +unique_ptr PEGTransformerFactory::TransformCustomPrefixExpression( + PEGTransformer &transformer, const string &custom_prefix_operator, unique_ptr tilde_expression) { vector> children; - children.push_back(std::move(other_operator_expression)); - return TransformOperatorFunction(operator_literal, std::move(children)); + children.push_back(std::move(tilde_expression)); + return TransformOperatorFunction(custom_prefix_operator, std::move(children)); } OtherOperatorTail PEGTransformerFactory::TransformAnyAllSubqueryTail(PEGTransformer &transformer, @@ -1791,15 +1790,13 @@ void PEGTransformerFactory::InitializePrefixExpressionTrampoline(PEGTransformer process.PushChild({list_pr.GetChild(1)}, 0); } -arena_ptr -PEGTransformerFactory::FinalizePrefixExpressionTrampoline(PEGTransformer &transformer, - GeneratedTransformProcess &process) { +//! Apply a PrefixOperator* run to the operand in slot 0 +static unique_ptr FinalizePrefixOperators(GeneratedTransformProcess &process, bool locate_operators) { auto &list_pr = process.parse_result.Cast(); auto &prefix_opt = list_pr.Child(0); auto expr = process.TakeResult>(0); - if (!prefix_opt.HasResult()) { - return transformer.MakeResult>(std::move(expr)); + return expr; } auto &prefix_repeat = prefix_opt.GetResult().Cast(); @@ -1809,8 +1806,9 @@ PEGTransformerFactory::FinalizePrefixExpressionTrampoline(PEGTransformer &transf prefixes.push_back(process.TakeResult(1 + i)); } - for (auto it = prefixes.rbegin(); it != prefixes.rend(); ++it) { - const string &prefix = *it; + auto rule_location = process.parse_result.GetLocation(); + for (idx_t i = prefixes.size(); i > 0; i--) { + const string &prefix = prefixes[i - 1]; if (prefix == "-" && expr->GetExpressionType() == ExpressionType::VALUE_CONSTANT) { // fold the sign into the number text so -9223372036854775808 stays exact auto &literal = expr->Cast().GetLiteral(); @@ -1823,10 +1821,28 @@ PEGTransformerFactory::FinalizePrefixExpressionTrampoline(PEGTransformer &transf children.push_back(std::move(expr)); auto func_expr = make_uniq(Identifier(prefix), std::move(children)); func_expr->IsOperatorMutable() = true; + auto operator_location = prefix_children[i - 1].get().GetLocation(); + if (locate_operators && rule_location.IsValid() && operator_location.IsValid()) { + auto start = operator_location.Start(); + func_expr->SetQueryLocation(QueryLocation(start, rule_location.End() - start)); + } expr = std::move(func_expr); } - return transformer.MakeResult>(std::move(expr)); + return expr; } + +arena_ptr +PEGTransformerFactory::FinalizePrefixExpressionTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + return transformer.MakeResult>(FinalizePrefixOperators(process, false)); +} + +arena_ptr +PEGTransformerFactory::FinalizePrefixedCustomExpressionTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + return transformer.MakeResult>(FinalizePrefixOperators(process, true)); +} + unique_ptr PEGTransformerFactory::TransformAnonymousParameter(PEGTransformer &transformer) { // AnonymousParameter <- '?' auto expr = make_uniq(); diff --git a/src/duckdb/src/parser/peg/transformer/transform_generated_trampoline.cpp b/src/duckdb/src/parser/peg/transformer/transform_generated_trampoline.cpp index 3aae38af0..6d22cd7ff 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_generated_trampoline.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_generated_trampoline.cpp @@ -3,6 +3,7 @@ #include "duckdb/parser/peg/transformer/peg_transformer.hpp" #include "duckdb/parser/expression/star_expression.hpp" #include "duckdb/parser/expression/columnref_expression.hpp" +#include "duckdb/common/no_destructor.hpp" namespace duckdb { @@ -4389,12 +4390,19 @@ static const TransformFramePlan FRAME_PLAN_AtTimeZoneExpressionTail = { static const TransformChildPlan FRAME_CHILDREN_CustomPrefixExpression[] = {{PEGRuleId::TildeExpression, TransformChildKind::REQUIRED, 1, + 1, + false, + {0, TRANSFORM_PATH_END, 0}, + {0, TRANSFORM_PATH_END, 0}}, + {PEGRuleId::CustomPrefixOperator, + TransformChildKind::REQUIRED, + 0, 0, false, {0, TRANSFORM_PATH_END, 0}, {0, TRANSFORM_PATH_END, 0}}}; static const TransformFramePlan FRAME_PLAN_CustomPrefixExpression = { - FRAME_CHILDREN_CustomPrefixExpression, 1, 1, false, 0, {}}; + FRAME_CHILDREN_CustomPrefixExpression, 2, 2, false, 0, {}}; static const TransformChildPlan FRAME_CHILDREN_BaseExpression[] = {{PEGRuleId::IndirectionList, TransformChildKind::OPTIONAL, 1, @@ -8700,8 +8708,13 @@ static const TransformFrameOps GENERATED_FRAME_OPS[] = { &PEGTransformerFactory::FinalizePassthroughTrampoline, &FRAME_PLAN_ChoiceThrow}, {"PrefixExpression", &PEGTransformerFactory::InitializePrefixExpressionTrampoline, &PEGTransformerFactory::FinalizePrefixExpressionTrampoline, nullptr}, + {"PrefixedCustomExpression", &PEGTransformerFactory::InitializePrefixExpressionTrampoline, + &PEGTransformerFactory::FinalizePrefixedCustomExpressionTrampoline, nullptr}, {"CustomPrefixExpression", &PEGTransformerFactory::InitializePlannedTrampoline, &PEGTransformerFactory::FinalizeCustomPrefixExpressionTrampoline, &FRAME_PLAN_CustomPrefixExpression}, + {"CustomPrefixOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, + &PEGTransformerFactory::FinalizeCustomPrefixOperatorTrampoline, + &FRAME_PLAN_ChoiceEarlyIdentifierKeywordStringOperatorThrow}, {"PrefixOperator", &PEGTransformerFactory::InitializePlannedChoiceTrampoline, &PEGTransformerFactory::FinalizePrefixOperatorTrampoline, &FRAME_PLAN_ChoiceEarlyIdentifierKeywordStringOperatorThrow}, @@ -9675,8 +9688,9 @@ static case_insensitive_map_t BuildGeneratedTransform } const case_insensitive_map_t &PEGTransformerFactory::GeneratedTransformFrameOps() { - static const case_insensitive_map_t result = BuildGeneratedTransformFrameOps(); - return result; + static const NoDestructor> result( + BuildGeneratedTransformFrameOps()); + return *result; } void PEGTransformerFactory::InitializeStatementTrampoline(PEGTransformer &transformer, @@ -16155,13 +16169,36 @@ PEGTransformerFactory::FinalizeAtTimeZoneExpressionTailTrampoline(PEGTransformer arena_ptr PEGTransformerFactory::FinalizeCustomPrefixExpressionTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { - auto &list_pr = process.parse_result.Cast(); - auto operator_literal = list_pr.GetChild(0).Cast().operator_token; - auto tilde_expression = process.TakeResult>(0); - auto result = TransformCustomPrefixExpression(transformer, operator_literal, std::move(tilde_expression)); + auto custom_prefix_operator = process.TakeResult(0); + auto tilde_expression = process.TakeResult>(1); + auto result = TransformCustomPrefixExpression(transformer, custom_prefix_operator, std::move(tilde_expression)); return transformer.MakeResult>(std::move(result)); } +arena_ptr +PEGTransformerFactory::FinalizeCustomPrefixOperatorTrampoline(PEGTransformer &transformer, + GeneratedTransformProcess &process) { + string result; + if (process.child_results[0]) { + result = process.TakeResult(0); + } else { + auto &list_pr = process.parse_result.Cast(); + auto &choice_result = list_pr.Child(0).GetResult(); + if (choice_result.type == ParseResultType::IDENTIFIER) { + result = choice_result.Cast().identifier.GetIdentifierName(); + } else if (choice_result.type == ParseResultType::KEYWORD) { + result = choice_result.Cast().keyword; + } else if (choice_result.type == ParseResultType::STRING) { + result = choice_result.Cast().result; + } else if (choice_result.type == ParseResultType::OPERATOR) { + result = choice_result.Cast().operator_token; + } else { + result = transformer.Transform(choice_result); + } + } + return transformer.MakeResult(result); +} + arena_ptr PEGTransformerFactory::FinalizePrefixOperatorTrampoline(PEGTransformer &transformer, GeneratedTransformProcess &process) { diff --git a/src/duckdb/src/parser/peg/transformer/transform_select.cpp b/src/duckdb/src/parser/peg/transformer/transform_select.cpp index b12cea5fc..15c7a4617 100644 --- a/src/duckdb/src/parser/peg/transformer/transform_select.cpp +++ b/src/duckdb/src/parser/peg/transformer/transform_select.cpp @@ -668,7 +668,9 @@ unique_ptr PEGTransformerFactory::TransformNearestJoinBare( unique_ptr PEGTransformerFactory::TransformNearestValuesRef(PEGTransformer &transformer, unique_ptr values_clause) { - return make_uniq(std::move(values_clause)); + auto subquery_ref = make_uniq(std::move(values_clause)); + subquery_ref->lateral = SubqueryLateralType::IMPLICIT; + return std::move(subquery_ref); } unique_ptr PEGTransformerFactory::TransformNearestTableFunction( @@ -684,6 +686,8 @@ unique_ptr PEGTransformerFactory::TransformNearestTableFunction( unique_ptr PEGTransformerFactory::TransformNearestTableSubquery(PEGTransformer &transformer, const optional &lateral, unique_ptr subquery_reference) { + subquery_reference->Cast().lateral = + lateral.value_or(false) ? SubqueryLateralType::EXPLICIT : SubqueryLateralType::IMPLICIT; return subquery_reference; } @@ -711,6 +715,7 @@ PEGTransformerFactory::TransformNearestParensTableRef(PEGTransformer &transforme select_node->from_table = std::move(table_ref); select_statement->node = std::move(select_node); auto subquery = make_uniq(std::move(select_statement)); + subquery->lateral = SubqueryLateralType::FROM_CLAUSE_WRAPPER; subquery->sample = std::move(*sample_clause); return std::move(subquery); } @@ -1393,6 +1398,8 @@ unique_ptr PEGTransformerFactory::TransformTableSubquery(PEGTransforme if (lateral.value_or(false) && sample_clause) { throw ParserException("TABLESAMPLE cannot be applied to a LATERAL subquery"); } + subquery_reference->Cast().lateral = + lateral.value_or(false) ? SubqueryLateralType::EXPLICIT : SubqueryLateralType::IMPLICIT; if (table_alias_colon) { subquery_reference->alias = *table_alias_colon; } @@ -1445,6 +1452,7 @@ unique_ptr PEGTransformerFactory::TransformValuesRef(PEGTransformer &t throw ParserException("Table reference cannot have two aliases"); } auto subquery_ref = make_uniq(std::move(values_clause)); + subquery_ref->lateral = SubqueryLateralType::IMPLICIT; if (table_alias_colon) { subquery_ref->alias = *table_alias_colon; } @@ -1475,6 +1483,7 @@ unique_ptr PEGTransformerFactory::TransformParensTableRef(PEGTransform select_node->from_table = std::move(table_ref); select_statement->node = std::move(select_node); auto subquery = make_uniq(std::move(select_statement)); + subquery->lateral = SubqueryLateralType::FROM_CLAUSE_WRAPPER; if (table_alias_colon) { subquery->alias = *table_alias_colon; } diff --git a/src/duckdb/src/parser/query_node/select_node.cpp b/src/duckdb/src/parser/query_node/select_node.cpp index addf992f3..219c581f9 100644 --- a/src/duckdb/src/parser/query_node/select_node.cpp +++ b/src/duckdb/src/parser/query_node/select_node.cpp @@ -1,6 +1,7 @@ #include "duckdb/parser/query_node/select_node.hpp" #include "duckdb/parser/expression_util.hpp" #include "duckdb/common/serializer/serializer.hpp" +#include "duckdb/parser/tableref/subqueryref.hpp" namespace duckdb { @@ -44,7 +45,11 @@ string SelectNode::ToString() const { } } if (from_table && from_table->type != TableReferenceType::EMPTY_FROM) { - result += " FROM " + from_table->ToString(); + if (from_table->type == TableReferenceType::SUBQUERY) { + result += " FROM " + from_table->Cast().ToString(true); + } else { + result += " FROM " + from_table->ToString(); + } } if (where_clause) { result += " WHERE " + where_clause->ToString(); diff --git a/src/duckdb/src/parser/tableref/subqueryref.cpp b/src/duckdb/src/parser/tableref/subqueryref.cpp index 20f03283c..00c05f232 100644 --- a/src/duckdb/src/parser/tableref/subqueryref.cpp +++ b/src/duckdb/src/parser/tableref/subqueryref.cpp @@ -1,11 +1,26 @@ #include "duckdb/parser/tableref/subqueryref.hpp" #include "duckdb/common/limits.hpp" +#include "duckdb/parser/query_node/select_node.hpp" namespace duckdb { string SubqueryRef::ToString() const { - string result = "(" + subquery->ToString() + ")"; + return ToString(false); +} + +string SubqueryRef::ToString(bool first_from_item) const { + if (lateral == SubqueryLateralType::FROM_CLAUSE_WRAPPER && subquery->node->type == QueryNodeType::SELECT_NODE) { + // print the parenthesized FROM item this wrapper was created for, so that it re-parses to the same wrapper + auto &node = subquery->node->Cast(); + if (node.from_table && !node.where_clause && node.modifiers.empty()) { + return BaseToString("(" + node.from_table->ToString() + ")", column_name_alias); + } + } + // an unrecorded subquery may have been written with LATERAL, which is a no-op if it is not correlated + bool print_lateral = lateral == SubqueryLateralType::EXPLICIT || + (lateral == SubqueryLateralType::UNRECORDED && !sample && !first_from_item); + string result = string(print_lateral ? "LATERAL " : "") + "(" + subquery->ToString() + ")"; return BaseToString(result, column_name_alias); } @@ -22,12 +37,13 @@ bool SubqueryRef::Equals(const TableRef &other_p) const { return false; } auto &other = other_p.Cast(); - return subquery->Equals(*other.subquery); + return lateral == other.lateral && subquery->Equals(*other.subquery); } unique_ptr SubqueryRef::Copy() { auto copy = make_uniq(unique_ptr_cast(subquery->Copy()), alias); copy->column_name_alias = column_name_alias; + copy->lateral = lateral; CopyProperties(*copy); return std::move(copy); } diff --git a/src/duckdb/src/planner/binder/expression/bind_aggregate_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_aggregate_expression.cpp index 96ab57732..49db688f2 100644 --- a/src/duckdb/src/planner/binder/expression/bind_aggregate_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_aggregate_expression.cpp @@ -120,7 +120,8 @@ static void NegatePercentileFractions(ClientContext &context, unique_ptr presence; + auto count_star = TryRewriteQualifiedCountStar(aggr, presence); if (count_star) { return BindAggregate(count_star->Cast(), func, depth); } @@ -188,13 +189,18 @@ BindResult BaseSelectBinder::BindAggregate(FunctionExpression &aggr, AggregateFu } vector> bound_arguments; - for (idx_t i = 0; i < aggr.GetArguments().size(); ++i) { - auto &child = aggr.GetArgumentsMutable()[i]; - // arguments are aliased by their name, if any (see BindFunction for the rationale) - bound_arguments.push_back(BindChild(child.GetExpressionMutable(), 0, error, child.GetName())); - // We have to negate the fractions for PERCENTILE_XXXX DESC - if (!error.HasError() && ordered_set_agg && i == aggr.GetArguments().size() - 1) { - NegatePercentileFractions(context, bound_arguments.back(), negate_fractions); + if (presence) { + D_ASSERT(aggr.GetArguments().size() == 1 && !ordered_set_agg); + bound_arguments.push_back(std::move(presence)); + } else { + for (idx_t i = 0; i < aggr.GetArguments().size(); ++i) { + auto &child = aggr.GetArgumentsMutable()[i]; + // arguments are aliased by their name, if any (see BindFunction for the rationale) + bound_arguments.push_back(BindChild(child.GetExpressionMutable(), 0, error, child.GetName())); + // We have to negate the fractions for PERCENTILE_XXXX DESC + if (!error.HasError() && ordered_set_agg && i == aggr.GetArguments().size() - 1) { + NegatePercentileFractions(context, bound_arguments.back(), negate_fractions); + } } } @@ -241,9 +247,9 @@ BindResult BaseSelectBinder::BindAggregate(FunctionExpression &aggr, AggregateFu if (aggr.GetArguments().size() < ordered_set_agg) { for (auto &bound_order : bound_orders) { if (order_sensitive) { - arguments.emplace_back(string(), bound_order->Copy()); + arguments.emplace_back(Identifier(), bound_order->Copy()); } else { - arguments.emplace_back(string(), std::move(bound_order)); + arguments.emplace_back(Identifier(), std::move(bound_order)); } } } @@ -256,7 +262,7 @@ BindResult BaseSelectBinder::BindAggregate(FunctionExpression &aggr, AggregateFu auto &arg = aggr.GetArgumentsMutable()[arg_idx]; auto bound_arg = std::move(bound_arguments[arg_idx]); if (aggr.IsLegacyFunctionCall()) { - arguments.emplace_back(string(), std::move(bound_arg)); + arguments.emplace_back(Identifier(), std::move(bound_arg)); } else { arguments.emplace_back(arg.GetName(), std::move(bound_arg)); } diff --git a/src/duckdb/src/planner/binder/expression/bind_function_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_function_expression.cpp index 65dca756a..7744943a4 100644 --- a/src/duckdb/src/planner/binder/expression/bind_function_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_function_expression.cpp @@ -389,7 +389,7 @@ BindResult ExpressionBinder::BindFunction(FunctionExpression &function, ScalarFu vector named_fallback; if (function.IsLegacyFunctionCall()) { for (auto &arg : function.GetArguments()) { - if (!arg.GetName().empty()) { + if (arg.HasName()) { for (auto &fallback_arg : function.GetArguments()) { named_fallback.push_back(fallback_arg.Copy()); } @@ -428,7 +428,7 @@ BindResult ExpressionBinder::BindFunction(FunctionExpression &function, ScalarFu auto &arg = function.GetArgumentsMutable()[i]; auto bound_arg = std::move(bound_children[i]); if (function.IsLegacyFunctionCall()) { - arguments.emplace_back(string(), std::move(bound_arg)); + arguments.emplace_back(Identifier(), std::move(bound_arg)); } else { arguments.emplace_back(arg.GetName(), std::move(bound_arg)); } diff --git a/src/duckdb/src/planner/binder/expression/bind_macro_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_macro_expression.cpp index aa7f56242..763c02457 100644 --- a/src/duckdb/src/planner/binder/expression/bind_macro_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_macro_expression.cpp @@ -86,7 +86,11 @@ void ExpressionBinder::ReplaceMacroParameters(unique_ptr &expr // Special-handling for lambdas, which are inside function expressions. auto &function = expr->Cast(); if (function.IsLambdaFunction()) { - return ReplaceMacroParametersInLambda(function, lambda_params); + EntryLookupInfo function_lookup(CatalogType::SCALAR_FUNCTION_ENTRY, function.GetQualifiedName()); + auto entry = GetCatalogEntry(function_lookup, OnEntryNotFound::RETURN_NULL); + if (!entry || entry->type != CatalogType::AGGREGATE_FUNCTION_ENTRY) { + return ReplaceMacroParametersInLambda(function, lambda_params); + } } break; } @@ -105,41 +109,37 @@ void ExpressionBinder::ReplaceMacroParameters(unique_ptr &expr } // Find aggregate expression children -void ExpressionBinder::FindAggregateExprs(unique_ptr &expr, - vector>> &exprs) { - if (expr->GetExpressionType() == ExpressionType::FUNCTION) { - auto &fn_expr = expr->Cast(); +void ExpressionBinder::FindAggregateExprs(ParsedExpression &expr, vector> &exprs) { + if (expr.GetExpressionType() == ExpressionType::FUNCTION) { + auto &fn_expr = expr.Cast(); // Look up the function in the catalog, check to see if it is actually an aggregate function EntryLookupInfo fn_entry(CatalogType::AGGREGATE_FUNCTION_ENTRY, fn_expr.GetQualifiedName()); auto entry = GetCatalogEntry(fn_entry, OnEntryNotFound::RETURN_NULL); if (entry && entry->type == CatalogType::AGGREGATE_FUNCTION_ENTRY) { - exprs.push_back(expr); + exprs.push_back(fn_expr); return; } } - ParsedExpressionIterator::EnumerateChildren( - *expr, [&](unique_ptr &child_expr) { FindAggregateExprs(child_expr, exprs); }); + ParsedExpressionIterator::EnumerateChildren(expr, + [&](ParsedExpression &child) { FindAggregateExprs(child, exprs); }); } -void ExpressionBinder::UnfoldWindowMacroExpression(unique_ptr &expr, ScalarMacroFunction ¯o_def) { - auto macro_copy = macro_def.expression->Copy(); - vector>> aggregate_exprs; - FindAggregateExprs(macro_copy, aggregate_exprs); - - // Only allowed if the macro body has a single aggregate expression - if (aggregate_exprs.size() != 1) { - throw BinderException("Window function macro bodies must contain exactly one aggregate function"); +static bool ApplyWindowToMacroAggregate(unique_ptr &expr, FunctionExpression &agg_fn_expr, + unique_ptr &window) { + if (expr.get() != &agg_fn_expr) { + for (auto &child : expr->ChildrenMutable()) { + if (ApplyWindowToMacroAggregate(child, agg_fn_expr, window)) { + return true; + } + } + return false; } - // The window spec is pushed down to the aggregate function target within the macro body - unique_ptr &agg_expr_ref = aggregate_exprs[0]; - auto &agg_fn_expr = agg_expr_ref->Cast(); - // Transfer the macro function attributes - auto &window_expr = expr->Cast(); + auto &window_expr = window->Cast(); window_expr.SetQualifiedName(agg_fn_expr.GetQualifiedName()); window_expr.GetArgumentsMutable().clear(); for (auto &arg : agg_fn_expr.GetArgumentsMutable()) { @@ -159,13 +159,12 @@ void ExpressionBinder::UnfoldWindowMacroExpression(unique_ptr } // Transfer argument ORDER BYs if (agg_fn_expr.OrderBy()) { - auto clone = agg_fn_expr.OrderBy()->Copy(); - window_expr.ArgOrdersMutable() = std::move(clone->Cast().orders); + window_expr.ArgOrdersMutable() = std::move(agg_fn_expr.OrderByMutable()->orders); } // Replace the aggregate expression with the new window expression - agg_expr_ref = std::move(expr); - expr = std::move(macro_copy); + expr = std::move(window); + return true; } MacroFunction &ExpressionBinder::UnfoldMacroExpression(FunctionExpression &function, @@ -184,25 +183,36 @@ MacroFunction &ExpressionBinder::UnfoldMacroExpression(FunctionExpression &funct auto new_macro_binding = MacroFunction::CreateDummyBinding(macro_def, macro_func.name, positional_arguments, named_arguments); - macro_binding = new_macro_binding.get(); - // replace current expression with stored macro expression - // special case: If this is a window function, then we need to return a window expression + auto macro_body = macro_def.expression->Copy(); + // Select the aggregate from the original body. Qualification can move its owning slot. + vector> aggregate_exprs; if (expr->GetExpressionClass() == ExpressionClass::WINDOW) { - UnfoldWindowMacroExpression(expr, macro_def); - } else { - expr = macro_def.expression->Copy(); + FindAggregateExprs(*macro_body, aggregate_exprs); + if (aggregate_exprs.size() != 1) { + throw BinderException("Window function macro bodies must contain exactly one aggregate function"); + } + } + + // Substitute before attaching the window so its clauses retain the caller's scope. + SubstituteMacroParameters(macro_body, *new_macro_binding); + if (!aggregate_exprs.empty() && !ApplyWindowToMacroAggregate(macro_body, aggregate_exprs[0], expr)) { + throw InternalException("Window macro aggregate missing after parameter substitution"); } + expr = std::move(macro_body); + return macro_def; +} +void ExpressionBinder::SubstituteMacroParameters(unique_ptr &expr, DummyBinding &binding) { + macro_binding = &binding; // qualify only the macro parameters with a new empty binder that only knows the macro binding auto dummy_binder = Binder::CreateBinder(context); - dummy_binder->macro_binding = new_macro_binding.get(); + dummy_binder->macro_binding = &binding; ExpressionBinder::QualifyColumnNames(*dummy_binder, expr); // now replace the parameters vector lambda_params; ReplaceMacroParameters(expr, lambda_params); - return macro_def; } BindResult ExpressionBinder::BindMacro(FunctionExpression &function, ScalarMacroCatalogEntry ¯o_func, idx_t depth, diff --git a/src/duckdb/src/planner/binder/expression/bind_operator_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_operator_expression.cpp index bb9bf0d2b..8983cd653 100644 --- a/src/duckdb/src/planner/binder/expression/bind_operator_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_operator_expression.cpp @@ -106,7 +106,7 @@ BindResult ExpressionBinder::BindGroupingFunction(OperatorExpression &op, idx_t //! step. Unlike BindFunction it accepts only a scalar function: a macro shadowing the operator's //! backing name (say, a user macro called struct_extract) cannot be handed already-bound children, so //! it is reported rather than invoked. -BindResult ExpressionBinder::BindOperatorAsFunction(OperatorExpression &op, const Identifier &function_name, +BindResult ExpressionBinder::BindOperatorAsFunction(OperatorExpression &op, const QualifiedName &function_name, vector> children) { if (binder.GetBindingMode() == BindingMode::EXTRACT_NAMES || binder.GetBindingMode() == BindingMode::EXTRACT_QUALIFIED_NAMES) { @@ -116,7 +116,7 @@ BindResult ExpressionBinder::BindOperatorAsFunction(OperatorExpression &op, cons lookup.SetQueryLocation(op.GetQueryLocation()); auto &func = BindFunction(lookup); if (func.type != CatalogType::SCALAR_FUNCTION_ENTRY) { - throw BinderException(op, "%s is not a scalar function", function_name.GetIdentifierName()); + throw BinderException(op, "%s is not a scalar function", function_name.Name().GetIdentifierName()); } ErrorData error; @@ -218,9 +218,15 @@ BindResult ExpressionBinder::BindExpression(OperatorExpression &op, idx_t depth) if (b_exp_type.id() == LogicalTypeId::MAP) { function_name = "map_extract_value"; } else if (b_exp_type.IsJSONType() && children.size() == 2) { + auto &i_exp = *children[1]; + const auto &key_type = i_exp.GetReturnType(); + if (key_type.id() == LogicalTypeId::VARCHAR && !key_type.IsJSONType()) { + QualifiedName subscript(Identifier::SystemCatalog(), Identifier::DefaultSchema(), + Identifier("__internal_json_subscript")); + return BindOperatorAsFunction(op, subscript, std::move(children)); + } function_name = "json_extract"; // Make sure we only extract array elements, not fields, by adding the $[] syntax - auto &i_exp = *children[1]; if (i_exp.GetExpressionClass() == ExpressionClass::BOUND_CONSTANT && !i_exp.Cast().GetValue().IsNull()) { auto &const_exp = i_exp.Cast(); @@ -231,8 +237,9 @@ BindResult ExpressionBinder::BindExpression(OperatorExpression &op, idx_t depth) children[1] = const_exp.WithValue(Value(StringUtil::Format("$[%lld]", index))); } else if (const_exp.GetReturnType().id() == LogicalType::VARCHAR) { // Field extraction - children[1] = - const_exp.WithValue(Value(StringUtil::Format("$.\"%s\"", const_exp.GetValue().ToString()))); + auto key = StringUtil::Replace(const_exp.GetValue().ToString(), "\\", "\\\\"); + key = StringUtil::Replace(key, "\"", "\\\""); + children[1] = const_exp.WithValue(Value("$.\"" + key + "\"")); } } } else if (b_exp_type.id() == LogicalTypeId::VARIANT && children.size() == 2) { @@ -288,8 +295,9 @@ BindResult ExpressionBinder::BindExpression(OperatorExpression &op, idx_t depth) if (name_exp.GetExpressionClass() == ExpressionClass::BOUND_CONSTANT) { auto &const_exp = name_exp.Cast(); if (!const_exp.GetValue().IsNull()) { - children[1] = - const_exp.WithValue(Value(StringUtil::Format("$.\"%s\"", const_exp.GetValue().ToString()))); + auto key = StringUtil::Replace(const_exp.GetValue().ToString(), "\\", "\\\\"); + key = StringUtil::Replace(key, "\"", "\\\""); + children[1] = const_exp.WithValue(Value("$.\"" + key + "\"")); } } } else if (extract_expr_type.id() == LogicalTypeId::GEOMETRY || diff --git a/src/duckdb/src/planner/binder/expression/bind_star_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_star_expression.cpp index 131dbce2a..00c2f91d3 100644 --- a/src/duckdb/src/planner/binder/expression/bind_star_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_star_expression.cpp @@ -10,6 +10,10 @@ #include "duckdb/function/scalar/regexp.hpp" #include "duckdb/parser/expression/function_expression.hpp" #include "duckdb/parser/expression/lambda_expression.hpp" +#include "duckdb/planner/expression_binder/base_select_binder.hpp" +#include "duckdb/planner/query_node/bound_select_node.hpp" +#include "duckdb/planner/operator/logical_projection.hpp" +#include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/parser/expression/case_expression.hpp" #include "duckdb/parser/expression/conjunction_expression.hpp" #include "duckdb/parser/expression/window_expression.hpp" @@ -370,19 +374,16 @@ bool Binder::IsQualifiedCountStar(const ParsedExpression &expr) { return arguments.size() == 1 && IsQualifiedStar(arguments[0].GetExpression()); } -//! CASE WHEN col1 IS NOT NULL OR ... OR coln IS NOT NULL THEN 1 END -static unique_ptr AnyColumnNotNull(vector> columns) { - vector> checks; - for (auto &column : columns) { - checks.push_back(make_uniq(ExpressionType::OPERATOR_IS_NOT_NULL, std::move(column))); - } - auto case_expr = make_uniq(); - CaseCheck case_check; - case_check.when_expr = make_uniq(ExpressionType::CONJUNCTION_OR, std::move(checks)); - case_check.then_expr = ConstantExpression::FromValue(Value::BIGINT(1)); - case_expr->CaseChecksMutable().push_back(std::move(case_check)); - case_expr->ElseMutable() = ConstantExpression::FromValue(Value()); - return std::move(case_expr); +static ColumnBinding BindRowPresence(Binder &binder, LogicalOperator &input) { + // Append to an existing projection without changing its other column bindings. + if (input.type == LogicalOperatorType::LOGICAL_PROJECTION) { + auto &projection = input.Cast(); + auto column = ColumnBinding::PushExpression(projection.expressions, + make_uniq(Value::BOOLEAN(true))); + return ColumnBinding(projection.table_index, column); + } + // Reserve a binding until all references to this input have been bound. + return ColumnBinding(binder.GenerateTableIndex(), ProjectionIndex(0)); } static unique_ptr GetRowIdColumn(Binding &binding) { @@ -402,8 +403,9 @@ static unique_ptr GetRowIdColumn(Binding &binding) { return make_uniq(entry->second.name, binding.GetBindingAlias()); } -//! Returns the argument that COUNT(tbl.*) counts, or nullptr if every row of tbl is counted -static unique_ptr GetCountStarArgument(StarExpression &star, BindContext &bind_context) { +//! Resolve an existing COUNT argument, or identify the join input that needs a row-presence column. +static unique_ptr GetCountStarArgument(const StarExpression &star, BindContext &bind_context, + optional_ptr &presence_input) { if (bind_context.GetBindingsList().empty()) { // nothing to resolve the relation against (e.g. when verifying a macro definition) return nullptr; @@ -411,7 +413,7 @@ static unique_ptr GetCountStarArgument(StarExpression &star, B ErrorData error; auto binding = bind_context.GetBinding(star.RelationName(), error); if (binding) { - if (!binding->IsNullExtended()) { + if (!binding->GetNullExtendedInput()) { return nullptr; } auto row_id = GetRowIdColumn(*binding); @@ -419,25 +421,58 @@ static unique_ptr GetCountStarArgument(StarExpression &star, B // the row id is only NULL for NULL-extended rows return row_id; } - // without a row id, a row in which all columns are NULL is indistinguishable from a NULL-extended row - vector> columns; - bind_context.GenerateAllColumnExpressions(star, columns); - return AnyColumnNotNull(std::move(columns)); + presence_input = binding->GetNullExtendedInput(); + return nullptr; } // struct.* auto struct_binding = bind_context.GetMatchingBinding(star.RelationName(), star); if (!struct_binding) { error.Throw(); } - if (!struct_binding->IsNullExtended()) { + if (!struct_binding->GetNullExtendedInput()) { return nullptr; } return make_uniq(star.RelationName(), struct_binding->GetBindingAlias()); } +static unique_ptr GetGroupedCountStarArgument(BindContext &context, const StarExpression &star) { + auto grouped_star = star.Copy(); + vector> columns; + context.GenerateAllColumnExpressions(grouped_star->Cast(), columns); + for (auto &column : columns) { + column = make_uniq(ExpressionType::OPERATOR_IS_NOT_NULL, std::move(column)); + } + auto result = make_uniq(); + CaseCheck check; + check.when_expr = make_uniq(ExpressionType::CONJUNCTION_OR, std::move(columns)); + check.then_expr = ConstantExpression::FromValue(Value::BIGINT(1)); + result->CaseChecksMutable().push_back(std::move(check)); + result->ElseMutable() = ConstantExpression::FromValue(Value()); + return std::move(result); +} + //! COUNT(tbl.*) counts every row of tbl, except for the rows that an outer join NULL-extended -unique_ptr Binder::TryRewriteQualifiedCountStar(const ParsedExpression &expr) { - if (!IsQualifiedCountStar(expr)) { +unique_ptr BaseSelectBinder::TryRewriteQualifiedCountStar(const ParsedExpression &expr, + unique_ptr &presence) { + if (!Binder::IsQualifiedCountStar(expr)) { + return nullptr; + } + auto &star = GetFunctionArguments(expr)[0].GetExpression().Cast(); + optional_ptr input; + auto count_argument = GetCountStarArgument(star, binder.bind_context, input); + if (input && expr.GetExpressionClass() == ExpressionClass::WINDOW && + (!node.groups.group_expressions.empty() || !node.groups.grouping_sets.empty())) { + // Use the grouping-set output as the window's argument. + count_argument = GetGroupedCountStarArgument(binder.bind_context, star); + input = nullptr; + } + if (input) { + auto entry = node.row_presence.find(*input); + if (entry == node.row_presence.end()) { + auto column = BindRowPresence(binder, *input); + entry = node.row_presence.emplace(*input, column).first; + } + presence = make_uniq(LogicalType::BOOLEAN, entry->second); return nullptr; } auto result = expr.Copy(); @@ -446,8 +481,6 @@ unique_ptr Binder::TryRewriteQualifiedCountStar(const ParsedEx result->SetAlias(Identifier(expr.ToString())); } auto &arguments = GetFunctionArgumentsMutable(*result); - auto &star = arguments[0].GetExpressionMutable()->Cast(); - auto count_argument = GetCountStarArgument(star, bind_context); if (count_argument) { arguments[0] = FunctionArgument(std::move(count_argument)); } else { diff --git a/src/duckdb/src/planner/binder/expression/bind_window_expression.cpp b/src/duckdb/src/planner/binder/expression/bind_window_expression.cpp index 7511c9b90..de02c43b7 100644 --- a/src/duckdb/src/planner/binder/expression/bind_window_expression.cpp +++ b/src/duckdb/src/planner/binder/expression/bind_window_expression.cpp @@ -9,6 +9,7 @@ #include "duckdb/parser/expression/case_expression.hpp" #include "duckdb/parser/expression/constant_expression.hpp" #include "duckdb/parser/expression/function_expression.hpp" +#include "duckdb/parser/expression/star_expression.hpp" #include "duckdb/parser/expression/window_expression.hpp" #include "duckdb/planner/binder.hpp" #include "duckdb/planner/expression/bound_aggregate_expression.hpp" @@ -128,7 +129,8 @@ BindResult BaseSelectBinder::BindWindowExpression(WindowExpression &window, idx_ std::move(window.FilterMutable()), nullptr, window.Distinct()); return BindMacro(*macro, entry->Cast(), depth, macro_expr); } - auto count_star = binder.TryRewriteQualifiedCountStar(window); + unique_ptr presence; + auto count_star = TryRewriteQualifiedCountStar(window, presence); if (count_star) { return BindWindowExpression(count_star->Cast(), depth); } @@ -176,24 +178,24 @@ BindResult BaseSelectBinder::BindWindowExpression(WindowExpression &window, idx_ transport_try_errors = false; ErrorData error; vector> bound_args; - for (auto &child : window.GetArgumentsMutable()) { - // arguments are aliased by their name, if any (see BindFunction for the rationale) - bound_args.push_back(BindChild(child.GetExpressionMutable(), depth, error, child.GetName())); + if (presence) { + D_ASSERT(window.GetArguments().size() == 1); + const auto &star = window.GetArguments()[0].GetExpression().Cast(); + bound_columns.push_back({Identifier(star.ToString()), star.GetQueryLocation()}); + bound_args.push_back(std::move(presence)); + } else { + for (auto &child : window.GetArgumentsMutable()) { + // arguments are aliased by their name, if any (see BindFunction for the rationale) + bound_args.push_back(BindChild(child.GetExpressionMutable(), depth, error, child.GetName())); + } } vector> bound_partitions; for (auto &child : window.PartitionsMutable()) { - auto bound_partition = BindChild(child, depth, error); - if (!error.HasError() && bound_partition->IsVolatile()) { - throw BinderException(error_context, "PARTITION BY window expressions cannot be volatile"); - } - bound_partitions.push_back(std::move(bound_partition)); + bound_partitions.push_back(BindChild(child, depth, error)); } vector> bound_orders; for (auto &order : window.OrderByMutable()) { auto bound_order = BindChild(order.expression, depth, error); - if (!error.HasError() && bound_order->IsVolatile()) { - throw BinderException(error_context, "ORDER BY window expressions cannot be volatile"); - } // If the frame is a RANGE frame and the type is a time, // then we have to convert the time to a timestamp to avoid wrapping. @@ -346,8 +348,7 @@ BindResult BaseSelectBinder::BindWindowExpression(WindowExpression &window, idx_ const bool range_end = window.WindowEnd() == WindowBoundary::EXPR_PRECEDING_RANGE || window.WindowEnd() == WindowBoundary::EXPR_FOLLOWING_RANGE; if ((range_start || range_end) && bound_orders.size() == 1) { - result->RetainSQLRange(range_start ? bound_start.get() : nullptr, range_end ? bound_end.get() : nullptr, - bound_orders[0]->GetReturnType()); + result->RetainSQLRange(bound_orders[0]->GetReturnType()); } // Convert RANGE boundary expressions to ORDER +/- expressions. diff --git a/src/duckdb/src/planner/binder/query_node/plan_select_node.cpp b/src/duckdb/src/planner/binder/query_node/plan_select_node.cpp index 3f6bceeef..3734dad0d 100644 --- a/src/duckdb/src/planner/binder/query_node/plan_select_node.cpp +++ b/src/duckdb/src/planner/binder/query_node/plan_select_node.cpp @@ -1,5 +1,7 @@ +#include "duckdb/optimizer/column_binding_replacer.hpp" #include "duckdb/planner/binder.hpp" #include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/planner/expression/bound_reference_expression.hpp" #include "duckdb/planner/operator/list.hpp" #include "duckdb/planner/operator/logical_dummy_scan.hpp" @@ -135,6 +137,36 @@ bool Binder::DebugAggregateStateExportVerify(BoundSelectNode &statement, unique_ return true; } +static idx_t PlanRowPresence(Binder &binder, LogicalOperator &root, unique_ptr &input, + const reference_map_t &row_presence) { + idx_t found = 0; + for (auto &child : input->children) { + found += PlanRowPresence(binder, root, child, row_presence); + } + auto marker = row_presence.find(*input); + if (marker == row_presence.end()) { + return found; + } + if (input->type == LogicalOperatorType::LOGICAL_PROJECTION) { + return found + 1; + } + + auto index = binder.GenerateTableIndex(); + auto projection = LogicalProjection::CreateIdentity(index, std::move(input)); + auto input_bindings = projection->children[0]->GetColumnBindings(); + auto marker_column = ColumnBinding::PushExpression(projection->expressions, + make_uniq(Value::BOOLEAN(true))); + + CorrelatedColumnBindingReplacer replacer; + replacer.AddReplacements(input_bindings, LogicalOperator::GenerateColumnBindings(index, input_bindings.size())); + replacer.replacement_bindings.emplace_back(marker->second, ColumnBinding(index, marker_column)); + replacer.BuildIndex(); + replacer.stop_operator = *projection; + input = std::move(projection); + replacer.VisitOperator(root); + return found + 1; +} + unique_ptr Binder::CreatePlan(BoundSelectNode &statement) { D_ASSERT(statement.from_table.plan); if (IsBindingTrySubquery()) { @@ -179,7 +211,8 @@ unique_ptr Binder::CreatePlan(BoundSelectNode &statement) { // GROUP BY expressions containing UNNEST must expand rows before aggregation. plan_unnests(statement.unnests.GroupBy()); - if (!statement.aggregates.empty() || !statement.groups.group_expressions.empty() || statement.having) { + if (!statement.aggregates.empty() || !statement.groups.group_expressions.empty() || + statement.groups.grouping_sets.size() > 1 || statement.having) { if (!statement.groups.group_expressions.empty()) { // visit the groups for (auto &group : statement.groups.group_expressions) { @@ -203,9 +236,7 @@ unique_ptr Binder::CreatePlan(BoundSelectNode &statement) { root = std::move(aggregate); } } else if (!statement.groups.grouping_sets.empty()) { - // edge case: we have grouping sets but no groups or aggregates - // this can only happen if we have e.g. select 1 from tbl group by (); - // just output a dummy scan + // A single empty grouping set without aggregates produces one row, e.g. SELECT 1 FROM tbl GROUP BY (). root = make_uniq_base(statement.group_index); } @@ -264,6 +295,15 @@ unique_ptr Binder::CreatePlan(BoundSelectNode &statement) { prune->AddChild(std::move(root)); root = std::move(prune); } + if (!statement.row_presence.empty()) { + idx_t found = 0; + for (auto &child : root->children) { + found += PlanRowPresence(*this, *root, child, statement.row_presence); + } + if (found != statement.row_presence.size()) { + throw InternalException("Could not locate all inputs for qualified COUNT in the completed plan"); + } + } return root; } diff --git a/src/duckdb/src/planner/binder/statement/bind_create.cpp b/src/duckdb/src/planner/binder/statement/bind_create.cpp index 729dbfc3a..3652ba82e 100644 --- a/src/duckdb/src/planner/binder/statement/bind_create.cpp +++ b/src/duckdb/src/planner/binder/statement/bind_create.cpp @@ -590,6 +590,20 @@ SchemaCatalogEntry &Binder::BindCreateFunctionInfo(CreateInfo &info) { } else { storage_manager.CheckQueryDecimalsAreSupported(*function->Cast().query_node); } + for (const auto &type : function->types) { + storage_manager.CheckEmptyMemberNamesAreSupported(type, "macro parameters"); + } + storage_manager.CheckEmptyMemberNamesAreSupported(function->return_type, "macro return types"); + for (auto &default_parameter : function->default_parameters) { + storage_manager.CheckExpressionEmptyMemberNamesAreSupported(*default_parameter.second); + } + if (info.type == CatalogType::MACRO_ENTRY) { + storage_manager.CheckExpressionEmptyMemberNamesAreSupported( + *function->Cast().expression); + } else { + storage_manager.CheckQueryEmptyMemberNamesAreSupported( + *function->Cast().query_node); + } } vector dummy_types; @@ -759,6 +773,10 @@ SchemaCatalogEntry &Binder::BindCreateTriggerInfo(CreateTriggerInfo &create_trig msg += "Use an in-memory database, ATTACH with (STORAGE_VERSION v2.0.0)"; throw BinderException(msg); } + if (!create_trigger_info.temporary && !attached.IsTemporary() && create_trigger_info.trigger_action) { + // the trigger action is stored + storage_manager.CheckQueryEmptyMemberNamesAreSupported(*create_trigger_info.trigger_action); + } } if (create_trigger_info.timing == TriggerTiming::INSTEAD_OF) { @@ -963,6 +981,7 @@ BoundStatement Binder::Bind(CreateStatement &stmt) { auto &attached = schema.ParentCatalog().GetAttached(); if (!attached.IsTemporary() && attached.HasStorageManager()) { attached.GetStorageManager().CheckQueryDecimalsAreSupported(*base.query->node); + attached.GetStorageManager().CheckQueryEmptyMemberNamesAreSupported(*base.query->node); } } BindCreateViewInfo(base); @@ -1092,6 +1111,7 @@ BoundStatement Binder::Bind(CreateStatement &stmt) { auto &attached = catalog.GetAttached(); if (!create_type_info.temporary && attached.HasStorageManager()) { attached.GetStorageManager().CheckDecimalWidthIsSupported(create_type_info.type); + attached.GetStorageManager().CheckEmptyMemberNamesAreSupported(create_type_info.type, "types"); } } break; diff --git a/src/duckdb/src/planner/binder/statement/bind_create_table.cpp b/src/duckdb/src/planner/binder/statement/bind_create_table.cpp index 004350f35..915e19e34 100644 --- a/src/duckdb/src/planner/binder/statement/bind_create_table.cpp +++ b/src/duckdb/src/planner/binder/statement/bind_create_table.cpp @@ -318,6 +318,13 @@ void Binder::BindGeneratedColumns(BoundCreateTableInfo &info) { D_ASSERT(col.Generated()); auto expression = col.GeneratedExpression().Copy(); + // a positional reference would resolve against the table itself, it cannot name a dependency + ParsedExpressionIterator::VisitExpression( + *expression, [&](const PositionalReferenceExpression &) { + throw BinderException( + "Failed to bind generated column %s because the expression contains a positional reference", + col.Name()); + }); auto bound_expression = expr_binder.Bind(expression); D_ASSERT(bound_expression); diff --git a/src/duckdb/src/planner/binder/statement/bind_export.cpp b/src/duckdb/src/planner/binder/statement/bind_export.cpp index 1ee1414a1..aaf6b46f5 100644 --- a/src/duckdb/src/planner/binder/statement/bind_export.cpp +++ b/src/duckdb/src/planner/binder/statement/bind_export.cpp @@ -12,6 +12,7 @@ #include "duckdb/parser/parsed_data/exported_table_data.hpp" #include "duckdb/parser/constraints/foreign_key_constraint.hpp" #include "duckdb/parser/expression/cast_expression.hpp" +#include "duckdb/parser/expression/type_expression.hpp" #include "duckdb/parser/tableref/basetableref.hpp" #include "duckdb/parser/query_node/select_node.hpp" #include "duckdb/common/numeric_utils.hpp" @@ -192,6 +193,14 @@ BoundStatement Binder::Bind(ExportStatement &stmt) { // is supported, and we can export additional ALTER TABLEs for the self-references. for (auto &t : tables) { auto &table = t.get().Cast(); + for (auto &column : table.GetColumns().Logical()) { + // the exported CREATE TABLE has to spell the type, and an empty member name has no spelling ("") + if (TypeExpression::HasEmptyStructMemberName(column.Type())) { + throw BinderException("Failed to export database: column %s of table %s has the type %s, which " + "cannot be written in SQL because of its empty STRUCT member name", + column.Name(), table.name, column.Type().ToString()); + } + } for (auto &constraint : table.GetConstraints()) { if (constraint->type != ConstraintType::FOREIGN_KEY) { continue; diff --git a/src/duckdb/src/planner/binder/tableref/bind_joinref.cpp b/src/duckdb/src/planner/binder/tableref/bind_joinref.cpp index 47809656a..8ade6d1e9 100644 --- a/src/duckdb/src/planner/binder/tableref/bind_joinref.cpp +++ b/src/duckdb/src/planner/binder/tableref/bind_joinref.cpp @@ -179,7 +179,9 @@ BoundStatement Binder::BindNearestJoin(JoinRef &ref) { auto lateral_join = make_uniq(JoinRefType::REGULAR); lateral_join->type = ref.type; lateral_join->left = std::move(ref.left); - lateral_join->right = make_uniq(std::move(select_statement), std::move(target_alias)); + auto target = make_uniq(std::move(select_statement), std::move(target_alias)); + target->lateral = SubqueryLateralType::FROM_CLAUSE_WRAPPER; + lateral_join->right = std::move(target); lateral_join->condition = ConstantExpression::Boolean(true); lateral_join->query_location = ref.query_location; return Bind(*lateral_join); @@ -194,6 +196,9 @@ BoundStatement Binder::Bind(JoinRef &ref) { result->right_binder = Binder::CreateBinder(context, this); auto &left_binder = *result->left_binder; auto &right_binder = *result->right_binder; + // the right side can see the left side, and every FROM item the left side of an enclosing join can see + left_binder.from_clause_lateral_scopes = from_clause_lateral_scopes; + right_binder.from_clause_lateral_scopes = from_clause_lateral_scopes + 1; result->type = ref.type; result->left = left_binder.BindJoin(*this, *ref.left); @@ -369,12 +374,12 @@ BoundStatement Binder::Bind(JoinRef &ref) { const bool full_outer = result->type == JoinType::OUTER || ref.ref_type == JoinRefType::POSITIONAL; if (result->type == JoinType::LEFT || full_outer) { for (auto &binding : right_binder.bind_context.GetBindingsList()) { - binding->SetNullExtended(); + binding->SetNullExtended(*result->right.plan); } } if (result->type == JoinType::RIGHT || full_outer) { for (auto &binding : left_binder.bind_context.GetBindingsList()) { - binding->SetNullExtended(); + binding->SetNullExtended(*result->left.plan); } } auto right_bindings = right_binder.bind_context.GetBindingAliases(); diff --git a/src/duckdb/src/planner/binder/tableref/bind_match_recognize_ref.cpp b/src/duckdb/src/planner/binder/tableref/bind_match_recognize_ref.cpp index 685162a4b..5e6711494 100644 --- a/src/duckdb/src/planner/binder/tableref/bind_match_recognize_ref.cpp +++ b/src/duckdb/src/planner/binder/tableref/bind_match_recognize_ref.cpp @@ -929,6 +929,8 @@ BoundStatement Binder::Bind(MatchRecognizeRef &ref) { // the input is bound once, here, while its tables and qualified columns are still what the query // wrote, and before this clause generates any name of its own auto input_binder = Binder::CreateBinder(context, this); + // the input is part of the FROM clause that contains the MATCH_RECOGNIZE + input_binder->from_clause_lateral_scopes = from_clause_lateral_scopes; auto bound_input = input_binder->Bind(*ref.input); // what the columns are called is what the bind context says, not what the table ref bind reports case_insensitive_set_t input_names; diff --git a/src/duckdb/src/planner/binder/tableref/bind_pivot.cpp b/src/duckdb/src/planner/binder/tableref/bind_pivot.cpp index ee7427b6f..7e795b7e9 100644 --- a/src/duckdb/src/planner/binder/tableref/bind_pivot.cpp +++ b/src/duckdb/src/planner/binder/tableref/bind_pivot.cpp @@ -1089,6 +1089,8 @@ BoundStatement Binder::Bind(PivotRef &ref) { } auto copied_source = ref.source->Copy(); auto star_binder = Binder::CreateBinder(context, this); + // the source is part of the FROM clause that contains the pivot + star_binder->from_clause_lateral_scopes = from_clause_lateral_scopes; star_binder->Bind(*copied_source); // figure out the set of column names that are in the source of the pivot diff --git a/src/duckdb/src/planner/binder/tableref/bind_subqueryref.cpp b/src/duckdb/src/planner/binder/tableref/bind_subqueryref.cpp index 6b23f77ae..32ee6cc3f 100644 --- a/src/duckdb/src/planner/binder/tableref/bind_subqueryref.cpp +++ b/src/duckdb/src/planner/binder/tableref/bind_subqueryref.cpp @@ -1,13 +1,59 @@ +#include "duckdb/common/enums/implicit_lateral_subqueries.hpp" +#include "duckdb/logging/logger.hpp" +#include "duckdb/main/settings.hpp" #include "duckdb/parser/tableref/subqueryref.hpp" #include "duckdb/planner/binder.hpp" namespace duckdb { +static ImplicitLateralSubqueries ResolveImplicitLateralSubqueries(ClientContext &context) { + auto setting = Settings::Get(context); + if (setting == ImplicitLateralSubqueries::DEFAULT) { + // implicit lateral subqueries are deprecated: this becomes ERROR in a future release + return ImplicitLateralSubqueries::WARN; + } + return setting; +} + +void Binder::CheckImplicitLateralSubquery(const SubqueryRef &ref, const Binder &subquery_binder) { + // correlations up to this depth reference FROM items of the same FROM clause, deeper ones an enclosing query + bool references_from_item = false; + for (auto &col : subquery_binder.correlated_columns) { + if (col.depth <= from_clause_lateral_scopes) { + references_from_item = true; + break; + } + } + if (!references_from_item) { + return; + } + auto behavior = ResolveImplicitLateralSubqueries(context); + if (behavior == ImplicitLateralSubqueries::ALLOW) { + return; + } + const string msg = "Subquery in FROM references a column of an earlier FROM item without the LATERAL keyword. " + "Implicit lateral subqueries are deprecated and will be an error in a future release - add " + "LATERAL before the subquery (e.g. \"FROM t, LATERAL (SELECT t.x)\"), or use SET " + "implicit_lateral_subqueries='allow' to keep the old behavior."; + if (behavior == ImplicitLateralSubqueries::ERROR) { + throw BinderException(ref, msg); + } + DUCKDB_LOG_WARNING(context, msg); +} + BoundStatement Binder::Bind(SubqueryRef &ref) { auto binder = Binder::CreateBinder(context, this); binder->SetCanContainNulls(true); binder->SetInsideSubquery(); + if (ref.lateral == SubqueryLateralType::FROM_CLAUSE_WRAPPER) { + // the FROM clause of a generated wrapper belongs to the FROM clause that contains the wrapper + binder->from_clause_lateral_scopes = from_clause_lateral_scopes; + } auto subquery = binder->BindNode(*ref.subquery->node); + // only subqueries the user wrote without LATERAL are checked, table functions (e.g. unnest) are exempt + if (ref.lateral == SubqueryLateralType::IMPLICIT) { + CheckImplicitLateralSubquery(ref, *binder); + } binder->alias = ref.alias.empty() ? "unnamed_subquery" : ref.alias; auto bind_index = subquery.plan->GetRootIndex(); Identifier subquery_alias; diff --git a/src/duckdb/src/planner/collation_binding.cpp b/src/duckdb/src/planner/collation_binding.cpp index 08b5f8bff..8f239c561 100644 --- a/src/duckdb/src/planner/collation_binding.cpp +++ b/src/duckdb/src/planner/collation_binding.cpp @@ -222,7 +222,8 @@ static bool PushStructCollation(ClientContext &context, unique_ptr & std::move(arguments)); // Wrap the extracted field in its collation functions, recursing into nested fields. requires_collation |= binding.PushCollation(context, field, child_types[i].second, type); - field->SetAlias(Identifier(child_types[i].first)); + // a STRUCT member is passed by name to struct_pack, also when that name is empty + field->SetAlias(is_tuple ? Identifier() : child_types[i].first.AsSet()); fields.push_back(std::move(field)); } diff --git a/src/duckdb/src/planner/column_qualifier.cpp b/src/duckdb/src/planner/column_qualifier.cpp index ebe8b644a..04f0796b0 100644 --- a/src/duckdb/src/planner/column_qualifier.cpp +++ b/src/duckdb/src/planner/column_qualifier.cpp @@ -1,5 +1,6 @@ #include "duckdb/planner/column_qualifier.hpp" +#include "duckdb/catalog/catalog_entry.hpp" #include "duckdb/parser/parsed_expression_iterator.hpp" #include "duckdb/parser/expression/columnref_expression.hpp" #include "duckdb/parser/expression/constant_expression.hpp" @@ -237,10 +238,13 @@ void ColumnQualifier::QualifyColumnNames(unique_ptr &expr, vec case ExpressionType::FUNCTION: { // Special-handling for lambdas, which are inside function expressions. auto &function = expr->Cast(); + optional_ptr function_entry; if (!ExpressionBinder::IsUnnestFunction(function.FunctionName())) { - QualifyFunction(function); + function_entry = QualifyFunction(function); } - if (function.IsLambdaFunction()) { + // Aggregate arguments use JSON arrows, never lambda parameters. + if (function.IsLambdaFunction() && + (!function_entry || function_entry->type != CatalogType::AGGREGATE_FUNCTION_ENTRY)) { return QualifyColumnNamesInLambda(function, lambda_params); } diff --git a/src/duckdb/src/planner/expression/bound_function_expression.cpp b/src/duckdb/src/planner/expression/bound_function_expression.cpp index a36d25feb..46da675a0 100644 --- a/src/duckdb/src/planner/expression/bound_function_expression.cpp +++ b/src/duckdb/src/planner/expression/bound_function_expression.cpp @@ -45,11 +45,8 @@ bool BoundFunctionExpression::RequiresOrderedExecution() const { } bool has_value = false; ExpressionIterator::EnumerateChildren(*this, [&](const Expression &child) { - if (child.GetExpressionType() != ExpressionType::BOUND_FUNCTION) { - return; - } - auto &child_function = child.Cast().Function(); - has_value |= child_function.RequiresOrderedExecution(); + ExpressionIterator::VisitExpression( + child, [&](const auto &child_function) { has_value |= child_function.RequiresOrderedExecution(); }); }); return has_value; } diff --git a/src/duckdb/src/planner/expression/bound_window_expression.cpp b/src/duckdb/src/planner/expression/bound_window_expression.cpp index 21466321a..03ce799cf 100644 --- a/src/duckdb/src/planner/expression/bound_window_expression.cpp +++ b/src/duckdb/src/planner/expression/bound_window_expression.cpp @@ -1,8 +1,6 @@ #include "duckdb/planner/expression/bound_window_expression.hpp" #include "duckdb/catalog/catalog_entry/window_function_catalog_entry.hpp" #include "duckdb/parser/expression/window_expression.hpp" -#include "duckdb/parser/expression/constant_expression.hpp" -#include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/parser/expression_map.hpp" #include "duckdb/function/aggregate_function.hpp" @@ -158,14 +156,7 @@ bool BoundWindowExpression::KeysAreCompatible(const BoundWindowExpression &other return true; } -void BoundWindowExpression::RetainSQLRange(optional_ptr start, optional_ptr end, - const LogicalType &order_type) { - sql_range_start = start && start->GetExpressionClass() == ExpressionClass::BOUND_CONSTANT - ? ConstantExpression::FromValue(start->Cast().GetValue()) - : nullptr; - sql_range_end = end && end->GetExpressionClass() == ExpressionClass::BOUND_CONSTANT - ? ConstantExpression::FromValue(end->Cast().GetValue()) - : nullptr; +void BoundWindowExpression::RetainSQLRange(const LogicalType &order_type) { sql_range_order_type = order_type; } @@ -213,8 +204,6 @@ unique_ptr BoundWindowExpression::Copy() const { new_window->exclude_clause = exclude_clause; new_window->start_expr = start_expr ? start_expr->Copy() : nullptr; new_window->end_expr = end_expr ? end_expr->Copy() : nullptr; - new_window->sql_range_start = sql_range_start ? sql_range_start->Copy() : nullptr; - new_window->sql_range_end = sql_range_end ? sql_range_end->Copy() : nullptr; new_window->sql_range_order_type = sql_range_order_type; new_window->sql_range_start_boundary = sql_range_start_boundary ? make_uniq(*sql_range_start_boundary) : nullptr; @@ -299,8 +288,6 @@ void BoundWindowExpression::Serialize(Serializer &serializer) const { serializer.WriteProperty(212, "exclude_clause", exclude_clause); serializer.WriteProperty(213, "distinct", distinct); serializer.WriteProperty(214, "arg_orders", arg_orders); - serializer.WritePropertyWithDefault(215, "sql_range_start", sql_range_start, unique_ptr()); - serializer.WritePropertyWithDefault(216, "sql_range_end", sql_range_end, unique_ptr()); serializer.WritePropertyWithDefault(217, "sql_range_order_type", sql_range_order_type, LogicalType::INVALID); serializer.WritePropertyWithDefault(218, "sql_range_start_boundary", sql_range_start_boundary, @@ -353,10 +340,8 @@ unique_ptr BoundWindowExpression::Deserialize(Deserializer &deserial deserializer.ReadProperty(212, "exclude_clause", result->exclude_clause); deserializer.ReadProperty(213, "distinct", result->distinct); deserializer.ReadPropertyWithExplicitDefault(214, "arg_orders", result->arg_orders, vector()); - deserializer.ReadPropertyWithExplicitDefault(215, "sql_range_start", result->sql_range_start, - unique_ptr()); - deserializer.ReadPropertyWithExplicitDefault(216, "sql_range_end", result->sql_range_end, - unique_ptr()); + deserializer.ReadDeletedProperty>(215, "sql_range_start"); + deserializer.ReadDeletedProperty>(216, "sql_range_end"); deserializer.ReadPropertyWithExplicitDefault(217, "sql_range_order_type", result->sql_range_order_type, LogicalType::INVALID); deserializer.ReadPropertyWithExplicitDefault(218, "sql_range_start_boundary", result->sql_range_start_boundary, diff --git a/src/duckdb/src/planner/expression/window_range_info.cpp b/src/duckdb/src/planner/expression/window_range_info.cpp index a126bb366..6d28b20f6 100644 --- a/src/duckdb/src/planner/expression/window_range_info.cpp +++ b/src/duckdb/src/planner/expression/window_range_info.cpp @@ -109,6 +109,11 @@ optional_ptr WindowRangeBoundary::Match(const Expression &expr return call.GetChildren()[1].get(); } +const LogicalType &WindowRangeBoundary::LogicalOffsetType() const { + // the binder records the logical arguments of a call of two operands + return arguments.size() == 2 && arguments[1].IsComplete() ? arguments[1] : offset_type; +} + void WindowRangeCast::Serialize(Serializer &serializer) const { serializer.WriteProperty(100, "source_type", source_type); serializer.WriteProperty(101, "target_type", target_type); diff --git a/src/duckdb/src/planner/expression_binder/check_binder.cpp b/src/duckdb/src/planner/expression_binder/check_binder.cpp index 0796abc02..2c6f26681 100644 --- a/src/duckdb/src/planner/expression_binder/check_binder.cpp +++ b/src/duckdb/src/planner/expression_binder/check_binder.cpp @@ -19,6 +19,8 @@ BindResult CheckBinder::BindExpression(unique_ptr &expr_ptr, i return BindResult("window functions are not allowed in check constraints"); case ExpressionClass::SUBQUERY: return BindResult("cannot use subquery in check constraint"); + case ExpressionClass::POSITIONAL_REFERENCE: + return BindResult("positional references are not allowed in check constraints"); case ExpressionClass::COLUMN_REF: return BindCheckColumn(expr.Cast()); default: diff --git a/src/duckdb/src/planner/expression_binder/constant_binder.cpp b/src/duckdb/src/planner/expression_binder/constant_binder.cpp index 01f4ab11d..4f8c7affc 100644 --- a/src/duckdb/src/planner/expression_binder/constant_binder.cpp +++ b/src/duckdb/src/planner/expression_binder/constant_binder.cpp @@ -21,6 +21,8 @@ BindResult ConstantBinder::BindExpression(unique_ptr &expr_ptr } throw BinderException::Unsupported(expr, clause + " cannot contain column names"); } + case ExpressionClass::POSITIONAL_REFERENCE: + throw BinderException::Unsupported(expr, clause + " cannot contain positional references"); case ExpressionClass::SUBQUERY: throw BinderException(clause + " cannot contain subqueries"); case ExpressionClass::DEFAULT: diff --git a/src/duckdb/src/planner/expression_binder/index_binder.cpp b/src/duckdb/src/planner/expression_binder/index_binder.cpp index 0ad5b04da..0cbecf06a 100644 --- a/src/duckdb/src/planner/expression_binder/index_binder.cpp +++ b/src/duckdb/src/planner/expression_binder/index_binder.cpp @@ -542,6 +542,12 @@ unique_ptr IndexBinder::BindCreateIndex(ClientContext &context, IndexKeyBinding binding {key_version, false, string()}; auto &properties = binder.GetStatementProperties(); const auto statement_requires_rebind = properties.always_require_rebind; + if (db.HasStorageManager()) { + // the key expressions are stored with the index + for (auto &expr : create_index_info->expressions) { + db.GetStorageManager().CheckExpressionEmptyMemberNamesAreSupported(*expr); + } + } vector> expressions; { IndexKeyBindingScope scope(keys, binding); diff --git a/src/duckdb/src/planner/filter/expression_filter.cpp b/src/duckdb/src/planner/filter/expression_filter.cpp index 0dd25d71e..431316e2c 100644 --- a/src/duckdb/src/planner/filter/expression_filter.cpp +++ b/src/duckdb/src/planner/filter/expression_filter.cpp @@ -123,6 +123,55 @@ unique_ptr ExpressionFilter::CreateComparisonFilter(Expression return make_uniq(std::move(comparison)); } +static void ExtractOptionalFilterInputs(unique_ptr &expression, vector> &arguments, + vector &argument_indexes) { + if (expression->GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { + throw InternalException("Mapped optional filters require bound scan references"); + } + if (expression->GetExpressionClass() == ExpressionClass::BOUND_REF) { + const auto &ref = expression->Cast(); + if (ref.Index() >= argument_indexes.size()) { + throw InternalException("Mapped optional filter reference is out of range"); + } + // Keep whole scan inputs visible; the predicate retains any field extraction applied to them. + auto &argument_index = argument_indexes[ref.Index()]; + if (argument_index == DConstants::INVALID_INDEX) { + argument_index = arguments.size(); + arguments.push_back(ref.Copy()); + } else if (arguments[argument_index]->GetReturnType() != ref.GetReturnType()) { + throw InternalException("Mapped optional filter references have conflicting types"); + } + if (ref.Index() != argument_index) { + expression = ref.WithIndex(argument_index); + } + return; + } + ExpressionIterator::EnumerateChildren(*expression, [&](unique_ptr &child) { + ExtractOptionalFilterInputs(child, arguments, argument_indexes); + }); +} + +unique_ptr ExpressionFilter::CreateOptionalFilter(unique_ptr predicate, + vector column_indexes) { + if (column_indexes.size() < 2) { + throw InternalException("Mapped optional filters require at least two scan columns"); + } + vector> arguments; + if (predicate) { + vector argument_indexes(column_indexes.size(), DConstants::INVALID_INDEX); + ExtractOptionalFilterInputs(predicate, arguments, argument_indexes); + } + vector types; + for (auto &argument : arguments) { + types.push_back(argument->GetReturnType()); + } + auto function = OptionalFilterScalarFun::GetFunction(std::move(types)); + auto bind_data = make_uniq(std::move(predicate)); + auto expression = + make_uniq(BoundScalarFunction(function), std::move(arguments), std::move(bind_data)); + return make_uniq(std::move(expression), std::move(column_indexes)); +} + unique_ptr ExpressionFilter::CreateSelectivityOptionalFilter(unique_ptr child_expr, const LogicalType &column_type, SelectivityOptionalFilterType type) { @@ -245,8 +294,9 @@ FilterPropagateResult ExpressionFilter::CheckStatistics(ClientContext &context, return CheckExpressionStatistics(&context, *expr, stats); } -static FilterPropagateResult CheckZonemapAgainstConstants(const BaseStatistics &stats, ExpressionType comparison_type, - array_ptr values) { +FilterPropagateResult ExpressionFilter::CheckZonemapAgainstConstants(const BaseStatistics &stats, + ExpressionType comparison_type, + array_ptr values) { D_ASSERT(values.size() > 0); switch (values[0].type().InternalType()) { case PhysicalType::BOOL: @@ -277,17 +327,43 @@ static FilterPropagateResult CheckZonemapAgainstConstants(const BaseStatistics & } } +namespace { +// Borrow either a scan's contiguous statistics or a function's already-derived argument statistics. +class FilterStatisticsView { +public: + explicit FilterStatisticsView(array_ptr stats) + : contiguous(stats.data()), references(nullptr), count(stats.size()) { + } + explicit FilterStatisticsView(const vector> &stats) + : contiguous(nullptr), references(stats.data()), count(stats.size()) { + } + optional_ptr Get(idx_t index) const { + if (index >= count) { + return nullptr; + } + return contiguous ? optional_ptr(&contiguous[index]) : references[index]; + } + +private: + const BaseStatistics *contiguous; + //! An empty argument vector may have null data; individual null entries mean unknown statistics. + const optional_ptr *references; + idx_t count; +}; +} // namespace + +static FilterPropagateResult CheckExpressionStatisticsInternal(optional_ptr context, + const Expression &expression, + const FilterStatisticsView &input_stats); + static optional_ptr TryGetExpressionStats(optional_ptr context_p, const Expression &expr, - array_ptr input_stats, + const FilterStatisticsView &input_stats, vector> &owned_stats) { switch (expr.GetExpressionClass()) { case ExpressionClass::BOUND_REF: { auto index = expr.Cast().Index(); - if (index >= input_stats.size()) { - return nullptr; - } - return &input_stats[index]; + return input_stats.Get(index); } case ExpressionClass::BOUND_CONSTANT: { auto &constant = expr.Cast().GetValue(); @@ -520,7 +596,7 @@ bool ExpressionFilter::CanPropagateExpressionStatistics(const Expression &expr) static optional_ptr TryGetFilterStats(optional_ptr context_p, const Expression &expr, - array_ptr input_stats, + const FilterStatisticsView &input_stats, vector> &owned_stats) { return TryGetExpressionStats(context_p, expr, input_stats, owned_stats); } @@ -528,7 +604,7 @@ static optional_ptr TryGetFilterStats(optional_ptr ExpressionFilter::TryGetExpressionStatistics(ClientContext &context, const Expression &expr, array_ptr input_stats) { vector> owned_stats; - auto result = TryGetExpressionStats(&context, expr, input_stats, owned_stats); + auto result = TryGetExpressionStats(&context, expr, FilterStatisticsView(input_stats), owned_stats); return result ? result->ToUnique() : nullptr; } @@ -596,7 +672,7 @@ TryPrepareVariantComparisonStats(const BaseStatistics &stats, Value &constant, static FilterPropagateResult CheckComparisonStatistics(optional_ptr context_p, const BoundFunctionExpression &comp_expr, - array_ptr input_stats) { + const FilterStatisticsView &input_stats) { vector> owned_stats; optional_ptr filter_stats; optional_ptr constant_expr; @@ -641,8 +717,8 @@ static FilterPropagateResult CheckComparisonStatistics(optional_ptr(&comparison_constant, 1)); + auto result = ExpressionFilter::CheckZonemapAgainstConstants(*filter_stats, comparison_type, + array_ptr(&comparison_constant, 1)); if (filter_stats->CanHaveNull()) { if (result == FilterPropagateResult::FILTER_ALWAYS_FALSE && comparison_type != ExpressionType::COMPARE_DISTINCT_FROM) { @@ -658,7 +734,7 @@ static FilterPropagateResult CheckComparisonStatistics(optional_ptr context_p, const BoundFunctionExpression &between, - array_ptr input_stats) { + const FilterStatisticsView &input_stats) { auto &lower = BoundBetweenExpression::LowerBound(between); auto &upper = BoundBetweenExpression::UpperBound(between); if (lower.GetExpressionType() != ExpressionType::VALUE_CONSTANT || @@ -678,10 +754,10 @@ static FilterPropagateResult CheckBetweenStatistics(optional_ptr if (!between_stats->CanHaveNoNull()) { return FilterPropagateResult::FILTER_ALWAYS_FALSE; } - auto lower_res = CheckZonemapAgainstConstants(*between_stats, BoundBetweenExpression::LowerComparisonType(between), - array_ptr(&lower_val, 1)); - auto upper_res = CheckZonemapAgainstConstants(*between_stats, BoundBetweenExpression::UpperComparisonType(between), - array_ptr(&upper_val, 1)); + auto lower_res = ExpressionFilter::CheckZonemapAgainstConstants( + *between_stats, BoundBetweenExpression::LowerComparisonType(between), array_ptr(&lower_val, 1)); + auto upper_res = ExpressionFilter::CheckZonemapAgainstConstants( + *between_stats, BoundBetweenExpression::UpperComparisonType(between), array_ptr(&upper_val, 1)); if (between_stats->CanHaveNull()) { if (lower_res == FilterPropagateResult::FILTER_ALWAYS_FALSE || upper_res == FilterPropagateResult::FILTER_ALWAYS_FALSE) { @@ -725,10 +801,10 @@ static FilterPropagateResult CheckBoolStatistics(const BaseStatistics &stats, bo static FilterPropagateResult CheckFunctionStatistics(optional_ptr context_p, const BoundFunctionExpression &func_expr, - array_ptr input_stats) { + const FilterStatisticsView &input_stats) { if (ExpressionBarrier::IsBarrier(func_expr)) { // pruning never evaluates the expression, and only ever removes rows - the barrier can be seen through - return ExpressionFilter::CheckExpressionStatistics(context_p, *func_expr.GetChildren()[0], input_stats); + return CheckExpressionStatisticsInternal(context_p, *func_expr.GetChildren()[0], input_stats); } if (func_expr.GetExpressionType() == ExpressionType::COMPARE_BETWEEN) { return CheckBetweenStatistics(context_p, func_expr, input_stats); @@ -756,13 +832,13 @@ static FilterPropagateResult CheckFunctionStatistics(optional_ptr for (auto &child : func_expr.GetChildren()) { child_stats.push_back(TryGetFilterStats(context_p, *child, input_stats, owned_stats)); } - FunctionStatisticsPruneInput input(func_expr, func_expr.BindInfo().get(), child_stats); + FunctionStatisticsPruneInput input(func_expr, func_expr.BindInfo().get(), child_stats, context_p); return func_expr.Function().GetFilterPruneCallback()(input); } static FilterPropagateResult CheckNullOperatorStatistics(optional_ptr context_p, const BoundOperatorExpression &op_expr, - array_ptr input_stats, + const FilterStatisticsView &input_stats, ExpressionType operator_type) { if (op_expr.GetChildren().empty()) { return FilterPropagateResult::NO_PRUNING_POSSIBLE; @@ -792,7 +868,7 @@ static FilterPropagateResult CheckNullOperatorStatistics(optional_ptr context_p, const BoundOperatorExpression &op_expr, - array_ptr input_stats) { + const FilterStatisticsView &input_stats) { if (op_expr.GetChildren().size() <= 1) { return FilterPropagateResult::NO_PRUNING_POSSIBLE; } @@ -819,7 +895,8 @@ static FilterPropagateResult CheckInOperatorStatistics(optional_ptr constants(values.data(), values.size()); - auto result = CheckZonemapAgainstConstants(*filter_stats, ExpressionType::COMPARE_EQUAL, constants); + auto result = + ExpressionFilter::CheckZonemapAgainstConstants(*filter_stats, ExpressionType::COMPARE_EQUAL, constants); if (result == FilterPropagateResult::NO_PRUNING_POSSIBLE && NumericStats::ConstantsCoverRange(*filter_stats, constants)) { // an integral column whose whole [min, max] range is listed always matches @@ -831,22 +908,20 @@ static FilterPropagateResult CheckInOperatorStatistics(optional_ptr input_stats, +static FilterPropagateResult CheckBoolRefStatistics(const Expression &expr, const FilterStatisticsView &input_stats, bool negated) { if (expr.GetExpressionClass() != ExpressionClass::BOUND_REF || expr.GetReturnType().id() != LogicalTypeId::BOOLEAN) { return FilterPropagateResult::NO_PRUNING_POSSIBLE; } auto index = expr.Cast().Index(); - if (index >= input_stats.size()) { - return FilterPropagateResult::NO_PRUNING_POSSIBLE; - } - return CheckBoolStatistics(input_stats[index], negated); + auto stats = input_stats.Get(index); + return stats ? CheckBoolStatistics(*stats, negated) : FilterPropagateResult::NO_PRUNING_POSSIBLE; } static FilterPropagateResult CheckNotOperatorStatistics(optional_ptr context_p, const BoundOperatorExpression &op_expr, - array_ptr input_stats) { + const FilterStatisticsView &input_stats) { if (op_expr.GetChildren().size() != 1) { return FilterPropagateResult::NO_PRUNING_POSSIBLE; } @@ -877,7 +952,7 @@ static FilterPropagateResult CheckNotOperatorStatistics(optional_ptr context_p, const BoundOperatorExpression &op_expr, - array_ptr input_stats) { + const FilterStatisticsView &input_stats) { switch (op_expr.GetExpressionType()) { case ExpressionType::OPERATOR_IS_NULL: case ExpressionType::OPERATOR_IS_NOT_NULL: @@ -905,12 +980,12 @@ static FilterPropagateResult CheckOperatorStatistics(optional_ptr static FilterPropagateResult CheckConjunctionStatistics(optional_ptr context_p, const BoundConjunctionExpression &conj, - array_ptr input_stats) { + const FilterStatisticsView &input_stats) { switch (conj.GetExpressionType()) { case ExpressionType::CONJUNCTION_AND: { auto result = FilterPropagateResult::FILTER_ALWAYS_TRUE; for (auto &child : conj.GetChildren()) { - auto prune_result = ExpressionFilter::CheckExpressionStatistics(context_p, *child, input_stats); + auto prune_result = CheckExpressionStatisticsInternal(context_p, *child, input_stats); if (prune_result == FilterPropagateResult::FILTER_ALWAYS_FALSE) { return FilterPropagateResult::FILTER_ALWAYS_FALSE; } @@ -927,7 +1002,7 @@ static FilterPropagateResult CheckConjunctionStatistics(optional_ptr context_p, const Expression &expr, array_ptr input_stats) { + return CheckExpressionStatisticsInternal(context_p, expr, FilterStatisticsView(input_stats)); +} + +FilterPropagateResult +ExpressionFilter::CheckExpressionStatistics(optional_ptr context_p, const Expression &expr, + const vector> &input_stats) { + return CheckExpressionStatisticsInternal(context_p, expr, FilterStatisticsView(input_stats)); +} + +static FilterPropagateResult CheckExpressionStatisticsInternal(optional_ptr context_p, + const Expression &expr, + const FilterStatisticsView &input_stats) { switch (expr.GetExpressionClass()) { case ExpressionClass::BOUND_FUNCTION: return CheckFunctionStatistics(context_p, expr.Cast(), input_stats); diff --git a/src/duckdb/src/planner/filter/table_filter_bloom_function.cpp b/src/duckdb/src/planner/filter/table_filter_bloom_function.cpp index c05a4d913..3a40b5e1b 100644 --- a/src/duckdb/src/planner/filter/table_filter_bloom_function.cpp +++ b/src/duckdb/src/planner/filter/table_filter_bloom_function.cpp @@ -163,16 +163,15 @@ void BloomFilter::Seal(ClientContext &context) { useful = std::pow(density, static_cast(N_BITS)) < static_cast(selectivity_threshold); } -HugeAllocation BloomFilter::CopyBuffer(ClientContext &context) const { +void BloomFilter::CopyBuffer(ClientContext &context, HugeAllocation &buffer) const { D_ASSERT(initialized && sealed && !published); const auto size = GetBitmapSize(); - auto result = BufferAllocator::Get(context).AllocateHuge(size); + D_ASSERT(buffer.IsSet() && buffer.GetSize() == size); constexpr idx_t COPY_CHUNK_SIZE = idx_t(4) * 1024 * 1024; for (idx_t offset = 0; offset < size; offset += COPY_CHUNK_SIZE) { context.InterruptCheck(); - memcpy(result.get() + offset, data_ptr_cast(bf) + offset, MinValue(COPY_CHUNK_SIZE, size - offset)); + memcpy(buffer.get() + offset, data_ptr_cast(bf) + offset, MinValue(COPY_CHUNK_SIZE, size - offset)); } - return result; } void BloomFilter::ReplaceBuffer(HugeAllocation buffer) { diff --git a/src/duckdb/src/planner/filter/table_filter_functions.cpp b/src/duckdb/src/planner/filter/table_filter_functions.cpp index 9816ef10e..bcb7c8f86 100644 --- a/src/duckdb/src/planner/filter/table_filter_functions.cpp +++ b/src/duckdb/src/planner/filter/table_filter_functions.cpp @@ -10,8 +10,10 @@ #include "duckdb/planner/filter/table_filter_function_helpers.hpp" #include "duckdb/common/exception/binder_exception.hpp" +#include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" #include "duckdb/planner/expression/bound_reference_expression.hpp" +#include "duckdb/planner/expression_iterator.hpp" namespace duckdb { @@ -86,6 +88,25 @@ unique_ptr CreateOptionalFilterExpression(unique_ptr chi return CreateSingleArgumentFunctionExpression(function, target_type, std::move(bind_data)); } +unique_ptr ExpandOptionalFilterExpression(const BoundFunctionExpression &expression) { + D_ASSERT(expression.Function().GetName() == OptionalFilterScalarFun::NAME); + if (!expression.BindInfo()) { + return make_uniq(Value::BOOLEAN(true)); + } + auto &data = expression.BindInfo()->Cast(); + auto result = data.child_filter_expr ? data.child_filter_expr->Copy() + : make_uniq(Value::BOOLEAN(true)); + ExpressionIterator::VisitExpressionMutable( + result, [&](BoundReferenceExpression &ref, unique_ptr &slot) { + if (ref.Index() >= expression.GetChildren().size() || + ref.GetReturnType() != expression.GetChildren()[ref.Index()]->GetReturnType()) { + throw InternalException("Optional filter reference does not match its input"); + } + slot = expression.GetChildren()[ref.Index()]->Copy(); + }); + return result; +} + unique_ptr CreateSelectivityOptionalFilterExpression(unique_ptr child_expr, const LogicalType &target_type, float selectivity_threshold, diff --git a/src/duckdb/src/planner/filter/table_filter_optional_function.cpp b/src/duckdb/src/planner/filter/table_filter_optional_function.cpp index 870b38005..a793456af 100644 --- a/src/duckdb/src/planner/filter/table_filter_optional_function.cpp +++ b/src/duckdb/src/planner/filter/table_filter_optional_function.cpp @@ -56,8 +56,15 @@ static idx_t OptionalFilterSelect(DataChunk &args, ExpressionState &state, optio } ScalarFunction OptionalFilterScalarFun::GetFunction(const LogicalType &input_type) { - ScalarFunction func(NAME, {input_type}, LogicalType::BOOLEAN, OptionalFilterFunction, TableFilterFunctions::Bind); - func.GetSignature().GetParameter(0).SetName("col"); + return GetFunction(vector {input_type}); +} + +ScalarFunction OptionalFilterScalarFun::GetFunction(vector input_types) { + ScalarFunction func(NAME, std::move(input_types), LogicalType::BOOLEAN, OptionalFilterFunction, + TableFilterFunctions::Bind); + if (func.GetSignature().GetParameterCount() == 1) { + func.GetSignature().GetParameter(0).SetName("col"); + } func.SetSelectCallback(OptionalFilterSelect); func.SetNullHandling(FunctionNullHandling::SPECIAL_HANDLING); func.SetFilterPruneCallback(OptionalFilterScalarFun::FilterPrune); @@ -74,11 +81,7 @@ FilterPropagateResult OptionalFilterScalarFun::FilterPrune(const FunctionStatist if (!data.child_filter_expr) { return FilterPropagateResult::NO_PRUNING_POSSIBLE; } - auto column_stats = input.ChildStats(0); - if (!column_stats) { - return FilterPropagateResult::NO_PRUNING_POSSIBLE; - } - return ExpressionFilter::CheckExpressionStatistics(*data.child_filter_expr, *column_stats); + return ExpressionFilter::CheckExpressionStatistics(input.context, *data.child_filter_expr, input.child_stats); } string OptionalFilterScalarFun::ToString(const string &child_filter_string) { @@ -86,7 +89,9 @@ string OptionalFilterScalarFun::ToString(const string &child_filter_string) { } ScalarFunction TableFilterOptionalFun::GetFunction() { - return OptionalFilterScalarFun::GetFunction(LogicalType::ANY); + auto function = OptionalFilterScalarFun::GetFunction(vector {}); + function.GetSignature().AddArgs("col", LogicalType::ANY); + return function; } } // namespace duckdb diff --git a/src/duckdb/src/planner/logical_operator.cpp b/src/duckdb/src/planner/logical_operator.cpp index 0d0136fba..e33f6e8df 100644 --- a/src/duckdb/src/planner/logical_operator.cpp +++ b/src/duckdb/src/planner/logical_operator.cpp @@ -182,7 +182,6 @@ void LogicalOperator::ResolveOperatorTypesFromChildren() { types.clear(); // now resolve the types for this operator ResolveTypes(); - D_ASSERT(types.size() == GetColumnBindings().size()); } void LogicalOperator::VerifyOperatorTypes() { @@ -193,6 +192,7 @@ void LogicalOperator::VerifyOperatorTypes() { types.clear(); try { ResolveTypes(); + D_ASSERT(types.size() == GetColumnBindings().size()); bool types_match = types.size() == original_types.size(); for (idx_t i = 0; types_match && i < types.size(); i++) { types_match = types[i].EqualsIncludingCollation(original_types[i]); diff --git a/src/duckdb/src/planner/logical_operator_visitor.cpp b/src/duckdb/src/planner/logical_operator_visitor.cpp index 6d8c7fa2b..5e45de484 100644 --- a/src/duckdb/src/planner/logical_operator_visitor.cpp +++ b/src/duckdb/src/planner/logical_operator_visitor.cpp @@ -233,6 +233,27 @@ void LogicalOperatorVisitor::VisitOperatorExpressions(LogicalOperator &op) { } void LogicalOperatorVisitor::VisitExpression(unique_ptr *expression) { + if (!VisitExpressionReplacement(expression)) { + VisitExpressionChildren(**expression); + } +} + +void LogicalOperatorVisitor::VisitExpressionIteratively(unique_ptr *expression) { + vector>> pending {*expression}; + while (!pending.empty()) { + auto ¤t = pending.back().get(); + pending.pop_back(); + if (VisitExpressionReplacement(¤t)) { + continue; + } + auto child_start = NumericCast>>::difference_type>(pending.size()); + ExpressionIterator::EnumerateChildren(*current, + [&](unique_ptr &child) { pending.push_back(child); }); + std::reverse(pending.begin() + child_start, pending.end()); + } +} + +bool LogicalOperatorVisitor::VisitExpressionReplacement(unique_ptr *expression) { auto &expr = **expression; unique_ptr result; switch (expr.GetExpressionClass()) { @@ -283,10 +304,9 @@ void LogicalOperatorVisitor::VisitExpression(unique_ptr *expression) } if (result) { *expression = std::move(result); - } else { - // visit the children of this node - VisitExpressionChildren(expr); + return true; } + return false; } void LogicalOperatorVisitor::VisitExpressionChildren(Expression &expr) { diff --git a/src/duckdb/src/planner/operator/logical_join.cpp b/src/duckdb/src/planner/operator/logical_join.cpp index ab5ec92f9..cc63cd8c5 100644 --- a/src/duckdb/src/planner/operator/logical_join.cpp +++ b/src/duckdb/src/planner/operator/logical_join.cpp @@ -12,7 +12,21 @@ LogicalJoin::LogicalJoin(JoinType join_type, LogicalOperatorType logical_type) } vector LogicalJoin::GetColumnBindings() { - auto left_bindings = MapBindings(children[0]->GetColumnBindings(), left_projection_map); + if (join_type == JoinType::SEMI || join_type == JoinType::ANTI || join_type == JoinType::MARK) { + return GetColumnBindings(children[0]->GetColumnBindings(), {}); + } + if (join_type == JoinType::RIGHT_SEMI || join_type == JoinType::RIGHT_ANTI) { + return GetColumnBindings({}, children[1]->GetColumnBindings()); + } + return GetColumnBindings(children[0]->GetColumnBindings(), children[1]->GetColumnBindings()); +} + +vector LogicalJoin::GetColumnBindings(const vector &left, + const vector &right) { + if (join_type == JoinType::RIGHT_SEMI || join_type == JoinType::RIGHT_ANTI) { + return MapBindings(right, right_projection_map); + } + auto left_bindings = MapBindings(left, left_projection_map); if (join_type == JoinType::SEMI || join_type == JoinType::ANTI) { // for SEMI and ANTI join we only project the left hand side return left_bindings; @@ -24,10 +38,7 @@ vector LogicalJoin::GetColumnBindings() { return left_bindings; } // for other join types we project both the LHS and the RHS - auto right_bindings = MapBindings(children[1]->GetColumnBindings(), right_projection_map); - if (join_type == JoinType::RIGHT_SEMI || join_type == JoinType::RIGHT_ANTI) { - return right_bindings; - } + auto right_bindings = MapBindings(right, right_projection_map); left_bindings.insert(left_bindings.end(), right_bindings.begin(), right_bindings.end()); return left_bindings; } diff --git a/src/duckdb/src/planner/operator/logical_materialized_cte.cpp b/src/duckdb/src/planner/operator/logical_materialized_cte.cpp index 8c4022903..e1498fa03 100644 --- a/src/duckdb/src/planner/operator/logical_materialized_cte.cpp +++ b/src/duckdb/src/planner/operator/logical_materialized_cte.cpp @@ -3,6 +3,15 @@ namespace duckdb { +void CTEFilterDependency::Clear(LogicalOperator &op) { + if (op.type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) { + op.Cast().filter_dependency.reset(); + } + for (auto &child : op.children) { + Clear(*child); + } +} + bool CTEFilterDependency::MatchesConsumers(const vector> &references) const { if (references.size() != 2) { return false; diff --git a/src/duckdb/src/planner/sql_export/bound_expression_sql_exporter.cpp b/src/duckdb/src/planner/sql_export/bound_expression_sql_exporter.cpp index 6c208c98f..e51b113ff 100644 --- a/src/duckdb/src/planner/sql_export/bound_expression_sql_exporter.cpp +++ b/src/duckdb/src/planner/sql_export/bound_expression_sql_exporter.cpp @@ -300,16 +300,8 @@ BoundExpressionSQLExportState::ExportColumnRef(const BoundColumnRefExpression &e } if (!expression.GetReturnType().EqualsIncludingCollation(resolved->type)) { if (expression.GetReturnType().id() != LogicalTypeId::VARCHAR) { - auto issue = BoundExpressionSQLExportState::UnsupportedFeature( - path, "nested_result_collation", - "Changing nested input collations requires a typed SQL representation"); - issue.facts.emplace_back("logical_type", Value(expression.GetReturnType().ToString())); - issue.facts.emplace_back("input_logical_type", Value(resolved->type.ToString())); - issue.facts.emplace_back("input_varchar_collations", - Value(SQLExportHelpers::TypeCollationSignature(resolved->type))); - issue.facts.emplace_back("varchar_collations", - Value(SQLExportHelpers::TypeCollationSignature(expression.GetReturnType()))); - return BoundExpressionSQLExportResult::Failure({std::move(issue)}); + // cast_to_type keeps the values and takes the collations of its witness, also where that has none + return CastToConstructedType(expression.GetReturnType(), std::move(result.GetValue()), path); } if (StringType::GetCollation(expression.GetReturnType()).empty()) { return BoundExpressionSQLExportResult::Failure({BoundExpressionSQLExportState::UnsupportedFeature( diff --git a/src/duckdb/src/planner/sql_export/sql_export_limit.cpp b/src/duckdb/src/planner/sql_export/sql_export_limit.cpp index 4cc9c8911..f1a5c3251 100644 --- a/src/duckdb/src/planner/sql_export/sql_export_limit.cpp +++ b/src/duckdb/src/planner/sql_export/sql_export_limit.cpp @@ -226,6 +226,16 @@ LogicalPlanVerificationResult LimitSQLExporter::Export(LogicalLi return LogicalPlanVerificationResult::Failure(expression); } target = std::move(expression.GetValue()); + if (!target->HasSubquery()) { + // Keep dynamic LIMIT validation when a projected input has become constant. + auto scalar = make_uniq(); + scalar->select_list.push_back(std::move(target)); + auto subquery = make_uniq(); + subquery->SubqueryMutable() = make_uniq(); + subquery->SubqueryMutable()->node = std::move(scalar); + subquery->GetSubqueryTypeMutable() = SubqueryType::SCALAR; + target = std::move(subquery); + } if (value.Type() == LimitNodeType::EXPRESSION_PERCENTAGE) { modifier->limit_type = LimitValueType::PERCENTAGE; } diff --git a/src/duckdb/src/planner/sql_export/sql_export_window.cpp b/src/duckdb/src/planner/sql_export/sql_export_window.cpp index 07579afb7..99dea4cb9 100644 --- a/src/duckdb/src/planner/sql_export/sql_export_window.cpp +++ b/src/duckdb/src/planner/sql_export/sql_export_window.cpp @@ -1,8 +1,6 @@ #include "duckdb/planner/sql_export/bound_expression_sql_exporter_internal.hpp" #include "duckdb/planner/expression/bound_aggregate_expression.hpp" #include "duckdb/planner/sql_export_helpers.hpp" -#include "duckdb/parser/expression/cast_expression.hpp" -#include "duckdb/parser/expression/constant_expression.hpp" #include "duckdb/planner/expression/bound_cast_expression.hpp" #include "duckdb/planner/expression/bound_constant_expression.hpp" #include "duckdb/planner/expression/bound_function_expression.hpp" @@ -15,35 +13,21 @@ struct WindowSQLFrame { optional_ptr order; optional_ptr start; optional_ptr end; - unique_ptr start_literal; - unique_ptr end_literal; + unique_ptr start_constant; + unique_ptr end_constant; }; -static optional NumericRangeLiteral(const ParsedExpression &literal) { - if (literal.GetExpressionClass() == ExpressionClass::CONSTANT) { - auto value = literal.Cast().GetLiteral().ToValue(); - return value.type().IsNumeric() && !value.IsNull() ? optional(value) : optional(); - } - if (literal.GetExpressionClass() == ExpressionClass::CAST) { - auto &cast = literal.Cast(); - auto type = UnboundType::TryDefaultBind(cast.TargetType()); - auto child = NumericRangeLiteral(cast.Child()); - if (child && type.IsNumeric() && !cast.IsTryCast()) { - return child->DefaultTryCastAs(type); - } - } - return {}; +static bool IsRangeOffset(WindowBoundary boundary) { + return boundary == WindowBoundary::EXPR_PRECEDING_RANGE || boundary == WindowBoundary::EXPR_FOLLOWING_RANGE; } -//! The SQL offset of a RANGE frame endpoint: the retained literal when it still describes the endpoint, -//! otherwise the live input the binder's endpoint arithmetic was derived from +//! The SQL offset of a RANGE frame endpoint: the live input the binder's endpoint arithmetic was derived from, or a +//! zero offset when the optimizer reduced that arithmetic to the ordering key static optional_ptr RangeOffset(const BoundWindowExpression &expression, const WindowSQLFrame &frame, const unique_ptr &endpoint, WindowBoundary boundary, - const unique_ptr &literal, - const unique_ptr &origin) { - const bool is_range_offset = - boundary == WindowBoundary::EXPR_PRECEDING_RANGE || boundary == WindowBoundary::EXPR_FOLLOWING_RANGE; - if (!is_range_offset) { + const unique_ptr &origin, + unique_ptr &constant) { + if (!IsRangeOffset(boundary)) { return endpoint.get(); } if (!origin || !endpoint || !frame.order) { @@ -54,13 +38,15 @@ static optional_ptr RangeOffset(const BoundWindowExpression &e if (!origin_matches_endpoint) { return nullptr; } - const bool has_literal_offset = literal && literal->GetExpressionClass() == ExpressionClass::BOUND_CONSTANT; - const bool endpoint_is_order = has_literal_offset && Expression::Equals(*endpoint, *order.expression); - if (endpoint_is_order) { - auto &value = literal->Cast().GetValue(); - if (!value.IsNull() && value.type().IsNumeric() && value == Value::Numeric(value.type(), 0)) { - return literal.get(); - } + // the type the call was bound with for its offset. The function binder resolves the call from this type and the + // type of the key, so an offset exported in it binds the recorded call again. It is the type of the call's offset + // operand unless the call fitted the operand itself: decimal arithmetic casts it to its result type + auto &offset_type = origin->LogicalOffsetType(); + if (offset_type.IsNumeric() && Expression::Equals(*endpoint, *order.expression)) { + // the endpoint is the ordering key: the optimizer removed the arithmetic of a zero offset, or folded it over a + // constant key. Zero binds the call again and yields the key + constant = make_uniq(Value::Numeric(offset_type, 0)); + return constant.get(); } auto input = origin->Match(*endpoint, *frame.order); if (!input) { @@ -71,15 +57,37 @@ static optional_ptr RangeOffset(const BoundWindowExpression &e if (offset_is_constant && offset.Cast().GetValue().IsNull()) { return nullptr; } - if (has_literal_offset && offset_is_constant) { - auto &original = literal->Cast().GetValue(); - auto ¤t = offset.Cast().GetValue(); - const bool has_numeric_offsets = original.type().IsNumeric() && current.type().IsNumeric(); - if (!original.IsNull() && has_numeric_offsets && original == current) { - return literal.get(); + if (offset_type == origin->offset_type) { + return &offset; + } + // an offset the call fitted: exported in the fitted type it is an operand of another call, which over a decimal + // key binds a result one digit wider than the plan's, or none at all once that passes max_decimal_width + if (!frame.order->GetReturnType().EqualsIncludingCollation(origin->arguments[0])) { + return nullptr; + } + if (!offset_is_constant) { + // the call wrapped the offset in a cast from the type it was bound with + if (!BoundCastExpression::IsCast(offset)) { + return nullptr; } + auto &cast = offset.Cast(); + const bool is_fit = BoundCastExpression::HasValidBindData(cast) && !BoundCastExpression::IsTryCast(cast) && + BoundCastExpression::SourceType(cast).EqualsIncludingCollation(offset_type); + return is_fit ? &BoundCastExpression::Child(cast) : nullptr; + } + // the function binder folded the cast of a constant + auto &fitted = offset.Cast().GetValue(); + auto value = fitted.DefaultTryCastAs(offset_type); + if (!value) { + return nullptr; + } + auto refitted = value->DefaultTryCastAs(origin->offset_type); + if (!refitted || !Value::NotDistinctFrom(*refitted, fitted)) { + // the type the call was bound with does not hold the constant the call has now + return nullptr; } - return &offset; + constant = make_uniq(std::move(*value)); + return constant.get(); } static bool IsOrderDependentBoundary(WindowBoundary boundary) { @@ -104,16 +112,10 @@ static WindowSQLFrame ReconstructWindowFrame(const BoundWindowExpression &expres frame.order = nullptr; } } - auto retained_offset = [&](const unique_ptr &literal) -> unique_ptr { - auto value = literal ? NumericRangeLiteral(*literal) : optional(); - return value ? make_uniq(*value) : nullptr; - }; - frame.start_literal = retained_offset(expression.SQLRangeStart()); - frame.end_literal = retained_offset(expression.SQLRangeEnd()); - frame.start = RangeOffset(expression, frame, expression.StartExpr(), expression.WindowStart(), frame.start_literal, - expression.SQLRangeStartBoundary()); - frame.end = RangeOffset(expression, frame, expression.EndExpr(), expression.WindowEnd(), frame.end_literal, - expression.SQLRangeEndBoundary()); + frame.start = RangeOffset(expression, frame, expression.StartExpr(), expression.WindowStart(), + expression.SQLRangeStartBoundary(), frame.start_constant); + frame.end = RangeOffset(expression, frame, expression.EndExpr(), expression.WindowEnd(), + expression.SQLRangeEndBoundary(), frame.end_constant); return frame; } diff --git a/src/duckdb/src/planner/sql_export/table_function_sql_export.cpp b/src/duckdb/src/planner/sql_export/table_function_sql_export.cpp index 828f813c1..c2f798e3b 100644 --- a/src/duckdb/src/planner/sql_export/table_function_sql_export.cpp +++ b/src/duckdb/src/planner/sql_export/table_function_sql_export.cpp @@ -97,6 +97,25 @@ static bool AppendTableFunctionColumnPath(vector &path, const Logica return AppendTableFunctionColumnPath(path, child_type, index.GetChildIndexes()[0], source_type); } +//! Renders [relation, column, field...]; fields from the first empty name on use subscripts, as `""` does not parse +static unique_ptr TableFunctionColumnPathToSQL(vector path) { + D_ASSERT(path.size() >= 2); + idx_t column_ref_size = 2; + while (column_ref_size < path.size() && !path[column_ref_size].empty()) { + column_ref_size++; + } + vector fields(path.begin() + NumericCast(column_ref_size), path.end()); + path.resize(column_ref_size); + unique_ptr result = make_uniq(std::move(path)); + for (auto &field : fields) { + auto extract = make_uniq(ExpressionType::ARRAY_EXTRACT); + extract->GetChildrenMutable().push_back(std::move(result)); + extract->GetChildrenMutable().push_back(ConstantExpression::FromValue(Value(field.GetIdentifierName()))); + result = std::move(extract); + } + return result; +} + static unique_ptr TableScanColumnToSQL(const ColumnIndex &index, const LogicalType &type, unique_ptr expression) { if (!index.IsPushdownExtract()) { @@ -170,11 +189,11 @@ static unique_ptr TableFunctionColumn(const LogicalGet &get, c source_type)) { return nullptr; } - auto column = make_uniq(std::move(path)); + auto column = TableFunctionColumnPathToSQL(std::move(path)); if (!source_type.EqualsIncludingCollation(index.GetScanType())) { return make_uniq(index.GetScanType(), std::move(column)); } - return std::move(column); + return column; } SQLSourceQueryResult LogicalPlanSQLExportHelpers::ReconstructSQLSource(ClientContext &context, const LogicalGet &get, diff --git a/src/duckdb/src/planner/subquery/has_volatile_expressions.cpp b/src/duckdb/src/planner/subquery/has_volatile_expressions.cpp index a2b515871..c993fbbd6 100644 --- a/src/duckdb/src/planner/subquery/has_volatile_expressions.cpp +++ b/src/duckdb/src/planner/subquery/has_volatile_expressions.cpp @@ -8,7 +8,7 @@ namespace duckdb { -static bool IsVolatileIgnoringError(const Expression &expr) { +bool HasVolatileExpressionsIgnoringError(const Expression &expr) { switch (expr.GetExpressionClass()) { case ExpressionClass::BOUND_FUNCTION: { auto &function = expr.Cast().Function(); @@ -26,15 +26,16 @@ static bool IsVolatileIgnoringError(const Expression &expr) { return expr.IsVolatile(); } bool is_volatile = false; - ExpressionIterator::EnumerateChildren( - expr, [&](const Expression &child) { is_volatile = is_volatile || IsVolatileIgnoringError(child); }); + ExpressionIterator::EnumerateChildren(expr, [&](const Expression &child) { + is_volatile = is_volatile || HasVolatileExpressionsIgnoringError(child); + }); return is_volatile; } bool HasVolatileExpressionsIgnoringError(const LogicalOperator &op) { bool is_volatile = false; LogicalOperatorVisitor::EnumerateExpressions(op, [&](const unique_ptr *expression) { - if (IsVolatileIgnoringError(**expression)) { + if (HasVolatileExpressionsIgnoringError(**expression)) { is_volatile = true; } }); diff --git a/src/duckdb/src/planner/table_binding.cpp b/src/duckdb/src/planner/table_binding.cpp index 4857b98cc..e77004b5d 100644 --- a/src/duckdb/src/planner/table_binding.cpp +++ b/src/duckdb/src/planner/table_binding.cpp @@ -65,12 +65,14 @@ void Binding::SetColumnType(idx_t col_idx, LogicalType type_p) { types[col_idx] = std::move(type_p); } -void Binding::SetNullExtended() { - null_extended = true; +void Binding::SetNullExtended(LogicalOperator &input) { + if (!null_extended_input) { + null_extended_input = input; + } } -bool Binding::IsNullExtended() const { - return null_extended; +optional_ptr Binding::GetNullExtendedInput() const { + return null_extended_input; } const Identifier &Binding::GetAlias() const { diff --git a/src/duckdb/src/planner/table_filter_set.cpp b/src/duckdb/src/planner/table_filter_set.cpp index 068914f32..6d3558c85 100644 --- a/src/duckdb/src/planner/table_filter_set.cpp +++ b/src/duckdb/src/planner/table_filter_set.cpp @@ -268,6 +268,9 @@ unique_ptr TableFilterSet::TableFilterIteratorEntry::TakeFilter() { bool TableFilterSet::HasFilters() const { return !filters.empty(); } +bool TableFilterSet::HasAnyFilters() const { + return HasFilters() || HasMultiColumnFilters(); +} idx_t TableFilterSet::FilterCount() const { return filters.size(); } @@ -318,6 +321,10 @@ void TableFilterSet::RemoveFilterByColumnIndex(ProjectionIndex col_idx) { } void TableFilterSet::SetFilterByColumnIndex(ProjectionIndex col_idx, unique_ptr filter) { + if (filter->filter_type == TableFilterType::EXPRESSION_FILTER && + !filter->Cast().column_indexes.empty()) { + throw InternalException("Cannot set a multi-column filter as a single-column filter"); + } filters[col_idx] = std::move(filter); } @@ -395,16 +402,26 @@ void TableFilterSet::PushFilter(ProjectionIndex col_idx, unique_ptr } void TableFilterSet::PushMultiColumnFilter(unique_ptr filter) { - const auto &expression_filter = - ExpressionFilter::GetExpressionFilter(*filter, "TableFilterSet::PushMultiColumnFilter"); + auto &expression_filter = ExpressionFilter::GetExpressionFilter(*filter, "TableFilterSet::PushMultiColumnFilter"); if (!expression_filter.expr || expression_filter.column_indexes.size() < 2) { throw InternalException("Multi-column filter must reference at least two columns"); } + if (!ExpressionFilter::IsRootNonSelectivityOptionalFilter(expression_filter)) { + throw InternalException("Multi-column pruning filters must be optional filters"); + } for (const auto &column_index : expression_filter.column_indexes) { if (!column_index.IsValid()) { throw InternalException("Cannot push a multi-column filter over an invalid ProjectionIndex"); } } + // Visible references address the declared scan inputs; the optional predicate has its own argument positions. + ExpressionIterator::EnumerateExpression(expression_filter.expr, [&](const Expression &expression) { + if (expression.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF || + (expression.GetExpressionClass() == ExpressionClass::BOUND_REF && + expression.Cast().Index() >= expression_filter.column_indexes.size())) { + throw InternalException("Multi-column filter reference does not match its scan inputs"); + } + }); for (const auto &existing_filter : multi_column_filters) { if (ExpressionFilter::GetExpressionFilter(*existing_filter, "TableFilterSet::PushMultiColumnFilter") .Equals(expression_filter)) { @@ -418,6 +435,59 @@ const vector> &TableFilterSet::GetMultiColumnFilters() c return multi_column_filters; } +void TableFilterSet::VisitFilters( + const std::function)> &callback) const { + for (const auto &entry : filters) { + callback(*entry.second, array_ptr(&entry.first, 1)); + } + for (const auto &filter : multi_column_filters) { + const auto &expression_filter = ExpressionFilter::GetExpressionFilter(*filter, "TableFilterSet::VisitFilters"); + callback(*filter, array_ptr(expression_filter.column_indexes.data(), + expression_filter.column_indexes.size())); + } +} + +void TableFilterSet::VisitColumns(const std::function &callback) const { + VisitFilters([&](const TableFilter &, array_ptr columns) { + for (const auto &column : columns) { + callback(column); + } + }); +} + +void TableFilterSet::LoadSerializedPruningFilters(vector> filters) { + for (auto &filter : filters) { + if (!filter || filter->filter_type != TableFilterType::EXPRESSION_FILTER) { + throw SerializationException("Expected an expression filter in serialized multi-column filters"); + } + auto &expression_filter = ExpressionFilter::GetExpressionFilter(*filter, "Deserialize multi-column filters"); + if (!expression_filter.expr) { + throw SerializationException("Missing expression in serialized multi-column filter"); + } + // Older plans store raw pruning predicates; current plans retain the optional expression and its inputs. + if (!ExpressionFilter::IsRootNonSelectivityOptionalFilter(expression_filter)) { + filter = ExpressionFilter::CreateOptionalFilter(std::move(expression_filter.expr), + std::move(expression_filter.column_indexes)); + } + PushMultiColumnFilter(std::move(filter)); + } +} + +void TableFilterSet::RemapColumns(const std::function &remap) { + TableFilterSet result; + for (auto &entry : filters) { + result.PushFilter(remap(entry.first), std::move(entry.second)); + } + for (auto &filter : multi_column_filters) { + auto &expression_filter = ExpressionFilter::GetExpressionFilter(*filter, "TableFilterSet::RemapColumns"); + for (auto &column : expression_filter.column_indexes) { + column = remap(column); + } + result.PushMultiColumnFilter(std::move(filter)); + } + *this = std::move(result); +} + vector> DynamicTableFilterSet::AddDisjunction(ProjectionIndex column, idx_t alternative_count) { D_ASSERT(alternative_count > 1); @@ -498,16 +568,7 @@ unique_ptr DynamicTableFilterSet::GetFinalTableFilters(const PhysicalTableScan &scan, optional_ptr existing_filters) const { lock_guard l(lock); - auto result = make_uniq(); - if (existing_filters) { - for (auto &filter_entry : *existing_filters) { - result->PushFilter(filter_entry.GetIndex(), filter_entry.Filter().Cast().Copy()); - } - for (const auto &filter : existing_filters->GetMultiColumnFilters()) { - result->PushMultiColumnFilter( - ExpressionFilter::GetExpressionFilter(*filter, "DynamicTableFilterSet::GetFinalTableFilters").Copy()); - } - } + auto result = existing_filters ? existing_filters->Copy() : make_uniq(); for (auto &entry : filters) { for (auto &filter_entry : *entry.second) { result->PushFilter(filter_entry.GetIndex(), filter_entry.Filter().Cast().Copy()); @@ -528,7 +589,7 @@ DynamicTableFilterSet::GetFinalTableFilters(const PhysicalTableScan &scan, result->PushFilter(group.column, make_uniq(std::move(disjunction))); } } - if (!result->HasFilters() && !result->HasMultiColumnFilters()) { + if (!result->HasAnyFilters()) { return nullptr; } // Work only on this execution's copy. Contradictions can safely retain their original scan predicates. diff --git a/src/duckdb/src/storage/block_allocator.cpp b/src/duckdb/src/storage/block_allocator/block_allocator.cpp similarity index 67% rename from src/duckdb/src/storage/block_allocator.cpp rename to src/duckdb/src/storage/block_allocator/block_allocator.cpp index d1417c449..1af3b9f94 100644 --- a/src/duckdb/src/storage/block_allocator.cpp +++ b/src/duckdb/src/storage/block_allocator/block_allocator.cpp @@ -1,5 +1,7 @@ #include "duckdb/storage/block_allocator.hpp" -#include "duckdb/storage/sharded_allocator_queue.hpp" +#include "duckdb/common/no_destructor.hpp" +#include "duckdb/storage/block_allocator/sharded_allocator_queue.hpp" +#include "duckdb/storage/buffer/buffer_pool.hpp" #include "duckdb/common/allocator.hpp" #include "duckdb/common/types/uuid.hpp" @@ -217,6 +219,27 @@ static bool OnDeallocation(const data_ptr_t pointer, const idx_t size) { #endif } +static idx_t BackingGranularity(idx_t block_size, BlockAllocatorPool::BackingPolicy backing_policy) { +#if defined(__linux__) && INTPTR_MAX == INT64_MAX && defined(MADV_NOHUGEPAGE) + if (backing_policy == BlockAllocatorPool::BackingPolicy::SPARSE) { + const auto page_size = sysconf(_SC_PAGESIZE); + if (page_size > 0 && IsPowerOfTwo(idx_t(page_size)) && block_size % idx_t(page_size) == 0) { + return idx_t(page_size); + } + } +#endif + return block_size; +} + +static bool DisableHugePages(data_ptr_t pointer, idx_t size) { +#if defined(__linux__) && defined(MADV_NOHUGEPAGE) + // Huge-page promotion could populate discarded tails beyond the charged prefix. + return madvise(pointer, size, MADV_NOHUGEPAGE) == 0; +#else + return false; +#endif +} + //===--------------------------------------------------------------------===// // BlockAllocatorThreadLocalState //===--------------------------------------------------------------------===// @@ -312,7 +335,8 @@ class BlockAllocatorThreadLocalState { } // We have run out of local blocks - if (TryGetBatch(touched, *block_allocator->touched) || TryGetBatch(untouched, *block_allocator->untouched)) { + if (TryGetBatch(touched, *block_allocator->pool->touched) || + TryGetBatch(untouched, *block_allocator->pool->untouched)) { // We have refilled local blocks pointer = TryAllocateFromLocal(); D_ASSERT(pointer); @@ -320,15 +344,15 @@ class BlockAllocatorThreadLocalState { } // Borrow individual blocks so a remote batch cannot occupy this thread's local cache. - for (auto queue : {block_allocator->touched.get(), block_allocator->untouched.get()}) { + for (auto queue : {block_allocator->pool->touched.get(), block_allocator->pool->untouched.get()}) { for (idx_t offset = 1; offset < queue->queues.Count(); offset++) { uint32_t block; if (!queue->queues.Get((preferred_shard + offset) % queue->queues.Count()).TryDequeueBulk(&block, 1)) { continue; } - pointer = block_allocator->GetPointer(block); - if (queue == block_allocator->touched.get()) { - block_allocator->UpdateCachedBlocks(-1, cache_slot); + pointer = block_allocator->pool->GetPointer(block); + if (queue == block_allocator->pool->touched.get()) { + block_allocator->pool->UpdateCachedBlocks(-1, cache_slot); OnSharedReuse(1); } else { try { @@ -350,8 +374,8 @@ class BlockAllocatorThreadLocalState { } void Free(const data_ptr_t pointer) { - touched.push_back(block_allocator->GetBlockID(pointer)); - block_allocator->UpdateCachedBlocks(1, cache_slot); + touched.push_back(block_allocator->pool->GetBlockID(pointer)); + block_allocator->pool->UpdateCachedBlocks(1, cache_slot); if (touched.size() < BlockAllocatorConfig::FREE_THRESHOLD) { return; } @@ -376,9 +400,9 @@ class BlockAllocatorThreadLocalState { annotated_lock_guard guard(lifetime_state->lock); if (lifetime_state->alive) { // local blocks only come out of a ready pool, whose queues stay published until the allocator dies - D_ASSERT(block_allocator->IsInitialized()); + D_ASSERT(block_allocator->pool->IsInitialized()); TryReturnTouched(touched.size()); - TryReturnBlocks(untouched, *block_allocator->untouched, untouched.size()); + TryReturnBlocks(untouched, *block_allocator->pool->untouched, untouched.size()); return touched.empty() && untouched.empty(); } } @@ -415,13 +439,14 @@ class BlockAllocatorThreadLocalState { if (count == 0) { return true; } - block_allocator->retention.Return(count, block_allocator->GetUsableBlockCount(), RetentionTimeMillis()); - if (count < touched.size() || block_allocator->touched->queues.Count() > 1) { + block_allocator->pool->retention.Return(count, block_allocator->pool->GetUsableBlockCount(), + RetentionTimeMillis()); + if (count < touched.size() || block_allocator->pool->touched->queues.Count() > 1) { std::sort(touched.begin(), touched.end()); } - const auto returned = TryReturnBlocks(touched, *block_allocator->touched, count); + const auto returned = TryReturnBlocks(touched, *block_allocator->pool->touched, count); if (returned < count) { - block_allocator->retention.Reuse(count - returned, RetentionTimeMillis()); + block_allocator->pool->retention.Reuse(count - returned, RetentionTimeMillis()); } return returned == count; } @@ -437,8 +462,8 @@ class BlockAllocatorThreadLocalState { cached_uuid = block_allocator_p.uuid; block_allocator = block_allocator_p; lifetime_state = block_allocator_p.lifetime_state; - cache_slot = block_allocator_p.next_cache_slot.fetch_add(1, std::memory_order_relaxed) % - block_allocator_p.cached_blocks.size(); + cache_slot = block_allocator_p.pool->next_cache_slot.fetch_add(1, std::memory_order_relaxed) % + block_allocator_p.pool->cached_blocks.size(); next_decay_check = 0; preferred_shard = block_allocator_p.GetLocalPoolShard(); untouched.reserve(BlockAllocatorConfig::BATCH_SIZE); @@ -446,23 +471,23 @@ class BlockAllocatorThreadLocalState { } data_ptr_t TryAllocateFromLocal() { - if (!touched.empty() && block_allocator->touched->queues.Count() > 1 && - block_allocator->touched->Home(touched.back()) != preferred_shard) { + if (!touched.empty() && block_allocator->pool->touched->queues.Count() > 1 && + block_allocator->pool->touched->Home(touched.back()) != preferred_shard) { // Prefer returning foreign frees, but keep them reusable if queue metadata allocation fails. TryReturnTouched(touched.size()); // The returned batch may also contain local blocks; prefer those to untouched backing. if (touched.empty()) { - TryGetBatch(touched, *block_allocator->touched); + TryGetBatch(touched, *block_allocator->pool->touched); } } if (!touched.empty()) { - const auto pointer = block_allocator->GetPointer(touched.back()); + const auto pointer = block_allocator->pool->GetPointer(touched.back()); touched.pop_back(); - block_allocator->UpdateCachedBlocks(-1, cache_slot); + block_allocator->pool->UpdateCachedBlocks(-1, cache_slot); return pointer; } if (!untouched.empty()) { - const auto pointer = block_allocator->GetPointer(untouched.back()); + const auto pointer = block_allocator->pool->GetPointer(untouched.back()); OnFirstAllocation(pointer, block_allocator->block_size); untouched.pop_back(); return pointer; @@ -472,15 +497,15 @@ class BlockAllocatorThreadLocalState { void OnSharedReuse(idx_t count) { const auto now = RetentionTimeMillis(); - block_allocator->retention.Reuse(count, now); + block_allocator->pool->retention.Reuse(count, now); if (now >= next_decay_check) { next_decay_check = now + BlockAllocatorConfig::ACTIVE_DECAY_INTERVAL_MS; try { block_allocator->FlushAllocationCache(BlockAllocatorConfig::MAX_FLUSH_BLOCKS * block_allocator->block_size, BlockAllocator::ReclaimMode::OPPORTUNISTIC); - block_allocator->FreeInternal(optional_idx(), BlockAllocatorConfig::MAX_FLUSH_BLOCKS, - BlockAllocator::ReclaimMode::OPPORTUNISTIC); + block_allocator->pool->FreeInternal(optional_idx(), BlockAllocatorConfig::MAX_FLUSH_BLOCKS, + BlockAllocator::ReclaimMode::OPPORTUNISTIC); } catch (...) { // Failed reclamation leaves blocks available for reuse. } @@ -493,7 +518,7 @@ class BlockAllocatorThreadLocalState { const auto size = global.queues.Get(preferred_shard).TryDequeueBulk(local.begin(), BlockAllocatorConfig::BATCH_SIZE); local.resize(size); - if (size > 0 && RefersToSameObject(global, *block_allocator->touched)) { + if (size > 0 && RefersToSameObject(global, *block_allocator->pool->touched)) { OnSharedReuse(size); } std::sort(local.begin(), local.end()); @@ -566,7 +591,10 @@ BlockAllocatorThreadLocalState &GetBlockAllocatorThreadLocalState(const BlockAll worker_local_state->TryInitialize(block_allocator); return *worker_local_state; } + // the destructor gives the thread's blocks back when the thread exits + DUCKDB_ALLOW_STATIC_LIFETIME_BEGIN thread_local BlockAllocatorThreadLocalStateHolder local_state(block_allocator); + DUCKDB_ALLOW_STATIC_LIFETIME_END local_state.state.TryInitialize(block_allocator); return local_state.state; #endif @@ -586,37 +614,95 @@ static bool ThreadHasLocalState() { // BlockAllocator //===--------------------------------------------------------------------===// class AllocationCache { + using ReclaimMode = BlockAllocatorPool::ReclaimMode; static constexpr idx_t MIN_SHIFT = 19; static constexpr idx_t MAX_SHIFT = 32; static constexpr idx_t MAX_LOCAL_SPARES = 16; + // Rounded size classes share one eighth of the fixed pool's reservation budget. + static constexpr idx_t POOL_BUDGET_DIVISOR = 8; + static constexpr idx_t MAX_EXACT_POOL_SHIFT = 28; // Retain at most 1 GiB per size class, or one larger allocation. static constexpr idx_t MAX_CACHED_BYTES_PER_BUCKET = 1024ULL * 1024 * 1024; - struct CachedAllocation { - data_ptr_t pointer = nullptr; - optional_idx home; - }; - struct alignas(64) Bucket { explicit Bucket(idx_t shard_count) : queues(shard_count) { } - ShardedAllocatorQueue queues; + ShardedAllocatorQueue queues; atomic last_return_ms {0}; // Keep queue metadata and the infrequently updated timestamp off the admission counter's cache line. alignas(64) atomic count {0}; }; public: - explicit AllocationCache(Allocator &allocator) : allocator(allocator), shard_count(AllocatorShardCount()) { + AllocationCache(Allocator &allocator, idx_t block_size, idx_t pool_size) + : allocator(allocator), block_size(block_size), first_pool_shift(CountZeros::Trailing(block_size) + 1), + shard_count(AllocatorShardCount()) { for (auto &bucket : buckets) { bucket = make_uniq(shard_count); } + const auto budget = pool_size / POOL_BUDGET_DIVISOR; + idx_t class_count = 0; + for (auto shift = first_pool_shift; shift <= MAX_SHIFT; shift++) { + const auto size = idx_t(1) << shift; + // Each equal share must hold two usable slots plus a guard per shard, even in the largest class. + if (budget / (class_count + 1) / size / shard_count < 3) { + break; + } + class_count++; + } + try { + pools.reserve(class_count); + for (idx_t i = 0; i < class_count; i++) { + const auto size = idx_t(1) << (first_pool_shift + i); + const auto blocks_per_shard = budget / class_count / size / shard_count; + pools.push_back(make_uniq(size, blocks_per_shard * shard_count * size, shard_count, + BlockAllocatorPool::BackingPolicy::SPARSE)); + // Shared size classes spread counter updates by ownership shard instead of by TLS cache. + pools.back()->next_cache_slot.store(MinValue(shard_count, pools.back()->cached_blocks.size()), + std::memory_order_relaxed); + } + } catch (const std::bad_alloc &) { + // Size-class metadata is optional, like the mappings themselves. + pools.clear(); + } + rounded_pool_count = pools.size(); + if (pools.empty()) { + return; + } + // Larger exact-size allocations need only a few addressable slots per shard, without rounding + // partial requests up to these capacities. Keep the rounded classes and their capacities intact. + try { + for (auto shift = first_pool_shift + pools.size(); shift <= MAX_EXACT_POOL_SHIFT; shift++) { + const auto size = idx_t(1) << shift; + pools.push_back(make_uniq(size, 3 * shard_count * size, shard_count, + BlockAllocatorPool::BackingPolicy::FULL_SLOT)); + pools.back()->next_cache_slot.store(MinValue(shard_count, pools.back()->cached_blocks.size()), + std::memory_order_relaxed); + } + } catch (const std::bad_alloc &) { + // A missing optional larger class must not disable the already constructed pools. + } } ~AllocationCache() { + // Mapped pools release their backing by unmapping, without first discarding every cached slot. + pools.clear(); + UpdatePadding(-live_padding.load(std::memory_order_relaxed)); Flush(NumericLimits::Maximum()); } + void SetBufferPool(shared_ptr buffer_pool_p, bool cache_mapped_blocks_p) { + D_ASSERT(!buffer_pool); + buffer_pool = std::move(buffer_pool_p); + cache_mapped_blocks = cache_mapped_blocks_p; + // A caller-supplied allocator can already own slots when it is attached to a database. + buffer_pool->UpdateUsedMemory(MemoryTag::ALLOCATOR, live_padding.load(std::memory_order_relaxed)); + } + + idx_t GetPressureCacheAllowance() const { + // Allow a small reusable cache beyond the live-memory budget during pressure trimming. + return buffer_pool ? MinValue(buffer_pool->GetMaxMemory() / 64, 256ULL * 1024 * 1024) : 0; + } bool SupportsSize(idx_t size) const { return size >= (static_cast(1) << MIN_SHIFT) && size <= (static_cast(1) << MAX_SHIFT) && IsPowerOfTwo(size); @@ -624,25 +710,91 @@ class AllocationCache { idx_t GetShardCount() const { return shard_count; } - data_ptr_t Allocate(idx_t size, optional_idx &home) { + optional_idx GetAllocationShard(const_data_ptr_t pointer, idx_t size) const { + auto pool = GetPool(size); + return pool ? pool->GetAllocationShard(pointer) : optional_idx(); + } + bool IsInPool(const_data_ptr_t pointer, idx_t size) const { + auto pool = GetPool(size); + return pool && pool->IsInPool(pointer); + } + bool HasSparseBacking(const_data_ptr_t pointer, idx_t size) const { + auto pool = GetPool(size); + return pool && pool->backing_granularity < pool->block_size && pool->IsInPool(pointer); + } + bool TryResizeInPlace(const_data_ptr_t pointer, idx_t old_size, idx_t size) { + auto pool = GetPool(old_size); + if (!pool || pool.get() != GetPool(size).get() || !pool->IsInPool(pointer)) { + return false; + } + // Growing a foreign slot could first-touch its unused tail on a different node. + if (size > old_size && pool->GetAllocationShard(pointer).GetIndex() != LocalShard()) { + return false; + } + const auto backing = pool->GetBackingSize(size); + const auto old_backing = pool->GetBackingSize(old_size); + if (backing < old_backing) { + // Discard can partially succeed before failing. Replace on page-releasing shrink so a failed + // reallocation cannot destroy bytes in the still-live original allocation. + return false; + } + const auto padding_delta = int64_t(backing - size) - int64_t(old_backing - old_size); + if (size > old_size && padding_delta > 0) { + // Growth may need another page of optional backing; shrink only transfers an existing charge. + return ReservePadding(idx_t(padding_delta), 0, nullptr); + } + UpdatePadding(padding_delta); + return true; + } + data_ptr_t TryAllocatePool(idx_t size, optional_ptr scheduler) { + auto pool = cache_mapped_blocks ? GetPool(size) : nullptr; + if (!pool) { + return nullptr; + } + const auto padding = pool->GetBackingSize(size) - size; + if (!ReservePadding(padding, pool->backing_granularity < pool->block_size ? 0 : pool->block_size, scheduler)) { + return nullptr; + } + try { + if (auto pointer = pool->TryAllocate(size)) { + return pointer; + } + } catch (...) { + UpdatePadding(-int64_t(padding)); + throw; + } + UpdatePadding(-int64_t(padding)); + return nullptr; + } + data_ptr_t Allocate(idx_t size, bool use_pools, optional_ptr scheduler) { + if (use_pools) { + if (auto pointer = TryAllocatePool(size, scheduler)) { + return pointer; + } + } if (SupportsSize(size)) { - if (auto pointer = TryAllocate(size, home)) { + if (auto pointer = TryAllocate(size)) { return pointer; } } - auto pointer = allocator.AllocateData(size); - home = LocalShard(); - return pointer; + return allocator.AllocateData(size); + } + data_ptr_t Reallocate(data_ptr_t pointer, idx_t old_size, idx_t size) { + D_ASSERT(!IsInPool(pointer, old_size)); + return allocator.ReallocateData(pointer, old_size, size); } - data_ptr_t TryAllocate(idx_t size, optional_idx &home) { + void Free(data_ptr_t pointer, idx_t size) { + D_ASSERT(!IsInPool(pointer, size)); + allocator.FreeData(pointer, size); + } + data_ptr_t TryAllocate(idx_t size) { D_ASSERT(SupportsSize(size)); const auto shard = LocalShard(); auto &bucket = *buckets[CountZeros::Trailing(size) - MIN_SHIFT]; - CachedAllocation allocation; - if (bucket.queues.Get(shard).TryDequeue(allocation)) { + data_ptr_t pointer; + if (bucket.queues.Get(shard).TryDequeue(pointer)) { bucket.count.fetch_sub(1, std::memory_order_relaxed); - home = allocation.home; - return allocation.pointer; + return pointer; } // Share surplus buffers, leaving a few local spares without reserving the entire budget. const auto reserve = MinValue(MAX_LOCAL_SPARES, MAX_CACHED_BYTES_PER_BUCKET / size / (2 * shard_count)); @@ -655,22 +807,54 @@ class AllocationCache { continue; } auto &queue = bucket.queues.Get(peer); - if ((reserve == 0 || queue.SizeApprox() > reserve) && queue.TryDequeue(allocation)) { + if ((reserve == 0 || queue.SizeApprox() > reserve) && queue.TryDequeue(pointer)) { bucket.count.fetch_sub(1, std::memory_order_relaxed); - home = allocation.home; - return allocation.pointer; + return pointer; } } } return nullptr; } - bool TryFree(data_ptr_t pointer, idx_t size, optional_idx home) { - D_ASSERT(SupportsSize(size)); + bool TryFree(data_ptr_t pointer, idx_t size) { if (!pointer) { return false; } - // Raw-pointer callers cannot retain ownership across reuse; leave their home unknown. - const auto shard = home.IsValid() ? home.GetIndex() : LocalShard(); + auto pool = GetPool(size); + if (pool && pool->IsInPool(pointer)) { + const auto shard = pool->GetAllocationShard(pointer).GetIndex(); + bool trim_exact_cache = false; + if (pool->block_size >= (idx_t(1) << (first_pool_shift + rounded_pool_count))) { + // Serialize large returns with the cache-limit observation so concurrent frees cannot + // each miss the other's return. Reclamation takes this lock again after it is released. + annotated_lock_guard guard(pool->flush_lock); + pool->Free(pointer, shard % pool->cached_blocks.size()); + trim_exact_cache = pool->GetCachedPoolMemory() > MAX_CACHED_BYTES_PER_BUCKET; + } else { + pool->Free(pointer, shard % pool->cached_blocks.size()); + } + UpdatePadding(-int64_t(pool->GetBackingSize(size) - size)); + if (!cache_mapped_blocks) { + // A supplied BufferPool may reclaim another allocator. Do not retain our pre-binding slots. + try { + pool->FreeInternal(optional_idx(), optional_idx(), ReclaimMode::FORCE); + } catch (...) { + // Ownership has transferred; failed reclamation must not make free or replacement throw. + } + } else if (trim_exact_cache) { + try { + pool->FreeInternal(optional_idx(), optional_idx(), ReclaimMode::FORCE, + MAX_CACHED_BYTES_PER_BUCKET / pool->block_size); + } catch (...) { + // Free retains ownership on failed discard; ordinary pressure/decay can retry. + } + } + return true; + } + if (!SupportsSize(size)) { + return false; + } + // Fallback reuse remains available, but its physical placement is unknown. + const auto shard = LocalShard(); auto &bucket = *buckets[CountZeros::Trailing(size) - MIN_SHIFT]; const auto capacity = MaxValue(MAX_CACHED_BYTES_PER_BUCKET / size, 1); if (bucket.count.fetch_add(1, std::memory_order_relaxed) < capacity) { @@ -680,7 +864,7 @@ class AllocationCache { while (last_return < now && !bucket.last_return_ms.compare_exchange_weak(last_return, now, std::memory_order_relaxed)) { } - if (bucket.queues.Get(shard).Enqueue(CachedAllocation {pointer, home})) { + if (bucket.queues.Get(shard).Enqueue(pointer)) { return true; } } catch (...) { @@ -693,6 +877,15 @@ class AllocationCache { idx_t GetCachedMemory(optional_idx idle_before = optional_idx()) const { idx_t bytes = 0; + for (auto &pool : pools) { + if (idle_before.IsValid()) { + annotated_lock_guard guard(pool->flush_lock); + bytes += pool->GetReclaimableBlockCount(ReclaimMode::DECAY) * pool->block_size; + } else { + // Charge entire slots, including rounding slack and in-flight discards. + bytes += pool->GetCachedPoolMemory(); + } + } for (idx_t i = 0; i < buckets.size(); i++) { bytes += Reclaimable(*buckets[i], idle_before) * (static_cast(1) << (MIN_SHIFT + i)); } @@ -700,8 +893,21 @@ class AllocationCache { } // Maintenance is serialized by BlockAllocator; allocation and return never take that lock. - idx_t Flush(idx_t byte_limit, optional_idx idle_before = optional_idx()) { + idx_t Flush(idx_t byte_limit, optional_idx idle_before = optional_idx(), idx_t *fallback_freed = nullptr, + ReclaimMode mode = ReclaimMode::FORCE) { idx_t freed = 0; + for (idx_t i = pools.size(); i > 0 && freed < byte_limit; i--) { + auto &pool = *pools[i - 1]; + const auto bytes = byte_limit - freed; + const auto blocks = bytes / pool.block_size + (bytes % pool.block_size != 0); + idx_t discarded = 0; + try { + pool.FreeInternal(blocks, optional_idx(), mode, optional_idx(), &discarded); + } catch (...) { + // Reclamation is best effort; undiscarded slots remain reusable. + } + freed += discarded * pool.block_size; + } for (idx_t i = buckets.size(); i > 0 && freed < byte_limit; i--) { auto &bucket = *buckets[i - 1]; const auto size = (static_cast(1) << (MIN_SHIFT + i - 1)); @@ -709,14 +915,17 @@ class AllocationCache { auto remaining = Reclaimable(bucket, idle_before); for (idx_t shard = 0; shard < bucket.queues.Count(); shard++) { auto &queue = bucket.queues.Get(shard); - CachedAllocation allocation; + data_ptr_t pointer; while (remaining > 0 && freed < byte_limit && Reclaimable(bucket, idle_before) > 0) { - if (!queue.TryDequeue(allocation)) { + if (!queue.TryDequeue(pointer)) { break; } - allocator.FreeData(allocation.pointer, size); + Free(pointer, size); bucket.count.fetch_sub(1, std::memory_order_relaxed); freed += size; + if (fallback_freed) { + *fallback_freed += size; + } remaining--; } } @@ -725,6 +934,36 @@ class AllocationCache { } private: + bool ReservePadding(idx_t size, idx_t capacity, optional_ptr scheduler) { + if (size == 0) { + return true; + } + if (buffer_pool) { + const auto workers = + scheduler ? MaxValue(1, scheduler->NumberOfThreads() + scheduler->NumberOfAsyncThreads()) : 1; + // Like uncached read buffers, optional backing must leave room for two more buffers per worker. + // Check before multiplying so an oversized class cannot overflow the headroom calculation. + if (capacity > buffer_pool->GetMaxMemory() / workers / 2 || + !buffer_pool->TryReserveMemory(MemoryTag::ALLOCATOR, size, capacity * workers * 2)) { + return false; + } + live_padding.fetch_add(int64_t(size), std::memory_order_relaxed); + } else { + UpdatePadding(int64_t(size)); + } + return true; + } + + void UpdatePadding(int64_t size) { + if (size == 0) { + return; + } + live_padding.fetch_add(size, std::memory_order_relaxed); + if (buffer_pool) { + buffer_pool->UpdateUsedMemory(MemoryTag::ALLOCATOR, size); + } + } + static idx_t Reclaimable(const Bucket &bucket, optional_idx idle_before) { if (idle_before.IsValid() && bucket.last_return_ms.load(std::memory_order_relaxed) > idle_before.GetIndex()) { return 0; @@ -733,16 +972,37 @@ class AllocationCache { } private: + optional_ptr GetPool(idx_t size) const { + if (size <= block_size) { + return nullptr; + } + const auto shift = 64 - CountZeros::Leading(size - 1); + const auto index = shift - first_pool_shift; + if (index >= rounded_pool_count && !IsPowerOfTwo(size)) { + return nullptr; + } + return index < pools.size() ? pools[index].get() : nullptr; + } idx_t LocalShard() const { return BlockAllocator::GetLocalShard(shard_count); } Allocator &allocator; + const idx_t block_size; + const idx_t first_pool_shift; const idx_t shard_count; + //! Keep the accounting owner alive until all mappings and their padding charges are released. + shared_ptr buffer_pool; + //! A supplied pool that reclaims a different allocator cannot manage these mappings' free backing. + bool cache_mapped_blocks = true; + //! Also tracks standalone allocations, for adoption at binding and cleanup at destruction. + atomic live_padding {0}; + idx_t rounded_pool_count = 0; + vector> pools; array, MAX_SHIFT - MIN_SHIFT + 1> buckets; }; -idx_t BlockAllocator::GetGuardBlockCount() const { +idx_t BlockAllocatorPool::GetGuardBlockCount() const { // Power-of-two blocks of at least 64 KiB align to all supported OS page sizes. if (touched->blocks_per_shard > 1 && block_size >= 64ULL * 1024) { return touched->queues.Count() - 1; @@ -750,7 +1010,7 @@ idx_t BlockAllocator::GetGuardBlockCount() const { return 0; } -idx_t BlockAllocator::GetUsableBlockCount() const { +idx_t BlockAllocatorPool::GetUsableBlockCount() const { return DivBlockSize(pool_size) - GetGuardBlockCount(); } @@ -760,18 +1020,41 @@ BlockAllocator::BlockAllocator(Allocator &allocator_p, const idx_t block_size_p, BlockAllocator::BlockAllocator(Allocator &allocator_p, const idx_t block_size_p, const idx_t pool_size_p, const idx_t shard_count) - : uuid(UUID::GenerateRandomUUID()), allocator(allocator_p), allocation_cache(make_uniq(allocator)), - block_size(block_size_p), block_size_div_shift(CountZeros::Trailing(block_size)), + : uuid(UUID::GenerateRandomUUID()), allocator(allocator_p), + pool(make_uniq(block_size_p, pool_size_p, shard_count, + BlockAllocatorPool::BackingPolicy::FULL_SLOT)), + block_size(block_size_p), + allocation_cache(make_uniq(allocator, block_size, + pool->pool_state.load(std::memory_order_relaxed) == + BlockAllocatorPool::PoolState::UNAVAILABLE + ? 0 + : pool->pool_size)), + lifetime_state(make_shared_ptr()) { +} + +BlockAllocatorPool::BlockAllocatorPool(const idx_t block_size_p, const idx_t pool_size_p, const idx_t shard_count, + const BackingPolicy backing_policy) + : block_size(block_size_p), block_size_div_shift(CountZeros::Trailing(block_size)), + backing_granularity(BackingGranularity(block_size, backing_policy)), pool_size(sizeof(void *) == 8 ? pool_size_p - pool_size_p % block_size : 0), pool_state(pool_size != 0 && DivBlockSize(pool_size) <= NumericLimits::Maximum() ? PoolState::UNINITIALIZED : PoolState::UNAVAILABLE), - touched(make_unsafe_uniq(DivBlockSize(pool_size), shard_count)), - lifetime_state(make_shared_ptr()) { + touched(make_unsafe_uniq(DivBlockSize(pool_size), shard_count)) { D_ASSERT(IsPowerOfTwo(block_size)); retention.Reset(RetentionTimeMillis()); } +BlockAllocatorPool::~BlockAllocatorPool() { + if (IsInitialized()) { + try { + FreeVirtualMemory(pool_base, pool_size); + } catch (...) { + // Not allowed to throw in destructor! + } + } +} + BlockAllocator::~BlockAllocator() { { annotated_lock_guard guard(lifetime_state->lock); @@ -785,13 +1068,6 @@ BlockAllocator::~BlockAllocator() { // Not allowed to throw in destructor! } } - if (IsInitialized()) { - try { - FreeVirtualMemory(pool_base, pool_size); - } catch (...) { - // Not allowed to throw in destructor! - } - } } BlockAllocator &BlockAllocator::Get(DatabaseInstance &db) { @@ -810,10 +1086,7 @@ bool BlockAllocator::IsEnabled() const { return enabled.load(std::memory_order_relaxed); } -bool BlockAllocator::TryUsePool() const { - if (!IsEnabled()) { - return false; - } +bool BlockAllocatorPool::TryInitialize() const { const auto state = pool_state.load(std::memory_order_acquire); if (state != PoolState::UNINITIALIZED) { return state == PoolState::READY; @@ -821,7 +1094,7 @@ bool BlockAllocator::TryUsePool() const { return InitializePool(); } -bool BlockAllocator::InitializePool() const { +bool BlockAllocatorPool::InitializePool() const { annotated_lock_guard guard(pool_init_lock); const auto state = pool_state.load(std::memory_order_relaxed); if (state != PoolState::UNINITIALIZED) { @@ -862,7 +1135,8 @@ bool BlockAllocator::InitializePool() const { } const auto pointer = AllocateVirtualMemory(pool_size); - if (!pointer || !ProtectPoolGuards(pointer)) { + if (!pointer || (backing_granularity < block_size && !DisableHugePages(pointer, pool_size)) || + !ProtectPoolGuards(pointer)) { touched->ReleaseOverflow(); pool_state.store(PoolState::UNAVAILABLE, std::memory_order_release); if (pointer) { @@ -876,7 +1150,7 @@ bool BlockAllocator::InitializePool() const { return true; } -bool BlockAllocator::ProtectPoolGuards(data_ptr_t pointer) const { +bool BlockAllocatorPool::ProtectPoolGuards(data_ptr_t pointer) const { // Separate writable VMAs reduce contention on Linux's VMA reference counter during page faults. // That contention can bottleneck first-touch faults and skew NUMA placement toward one node. const auto guard_block_count = GetGuardBlockCount(); @@ -889,11 +1163,11 @@ bool BlockAllocator::ProtectPoolGuards(data_ptr_t pointer) const { return true; } -bool BlockAllocator::IsInitialized() const { +bool BlockAllocatorPool::IsInitialized() const { return pool_state.load(std::memory_order_acquire) == PoolState::READY; } -bool BlockAllocator::IsInPool(const data_ptr_t pointer) const { +bool BlockAllocatorPool::IsInPool(const_data_ptr_t pointer) const { if (!IsInitialized()) { return false; } @@ -902,11 +1176,11 @@ bool BlockAllocator::IsInPool(const data_ptr_t pointer) const { return address >= base && address - base < pool_size; } -idx_t BlockAllocator::ModuloBlockSize(const idx_t n) const { +idx_t BlockAllocatorPool::ModuloBlockSize(const idx_t n) const { return n & (block_size - 1); } -idx_t BlockAllocator::DivBlockSize(const idx_t n) const { +idx_t BlockAllocatorPool::DivBlockSize(const idx_t n) const { return n >> block_size_div_shift; } @@ -930,6 +1204,10 @@ idx_t BlockAllocator::GetLocalPoolShard() const { } idx_t BlockAllocator::GetPoolShardCount() const { + return pool->GetShardCount(); +} + +idx_t BlockAllocatorPool::GetShardCount() const { return touched->queues.Count(); } @@ -938,6 +1216,10 @@ idx_t BlockAllocator::GetFallbackShardCount() const { } optional_idx BlockAllocator::GetAllocationShard(const_data_ptr_t pointer) const { + return pool->GetAllocationShard(pointer); +} + +optional_idx BlockAllocatorPool::GetAllocationShard(const_data_ptr_t pointer) const { if (!IsInitialized()) { return optional_idx(); } @@ -953,7 +1235,16 @@ optional_idx BlockAllocator::GetAllocationShard(const_data_ptr_t pointer) const return touched->Home(block_id); } -uint32_t BlockAllocator::GetBlockID(const data_ptr_t pointer) const { +optional_idx BlockAllocator::GetAllocationShard(const_data_ptr_t pointer, idx_t size) const { + const auto pool_shard = GetAllocationShard(pointer); + if (pool_shard.IsValid()) { + // Different modulo domains do not preserve the allocating CPU's shard. + return GetPoolShardCount() == GetFallbackShardCount() ? pool_shard : optional_idx(); + } + return allocation_cache->GetAllocationShard(pointer, size); +} + +uint32_t BlockAllocatorPool::GetBlockID(const data_ptr_t pointer) const { D_ASSERT(IsInPool(pointer)); const auto offset = NumericCast(pointer - pool_base); D_ASSERT(ModuloBlockSize(offset) == 0); @@ -962,38 +1253,87 @@ uint32_t BlockAllocator::GetBlockID(const data_ptr_t pointer) const { return block_id; } -void BlockAllocator::VerifyBlockID(const uint32_t block_id) const { +void BlockAllocatorPool::VerifyBlockID(const uint32_t block_id) const { D_ASSERT(block_id < DivBlockSize(pool_size)); D_ASSERT(!IsGuardBlock(block_id)); } -bool BlockAllocator::IsGuardBlock(const uint32_t block_id) const { +bool BlockAllocatorPool::IsGuardBlock(const uint32_t block_id) const { const auto home = touched->Home(block_id); return home < GetGuardBlockCount() && idx_t(block_id) + 1 == (home + 1) * touched->blocks_per_shard; } -data_ptr_t BlockAllocator::GetPointer(const uint32_t block_id) const { +data_ptr_t BlockAllocatorPool::GetPointer(const uint32_t block_id) const { VerifyBlockID(block_id); return pool_base + NumericCast(block_id) * block_size; } data_ptr_t BlockAllocator::AllocateData(const idx_t size) const { - if (size != block_size || !TryUsePool()) { + if (size != block_size || !IsEnabled() || !pool->TryInitialize()) { return AllocateFallbackData(size); } return GetBlockAllocatorThreadLocalState(*this).Allocate(); } data_ptr_t BlockAllocator::AllocateFallbackData(const idx_t size) const { - optional_idx home; - return RetryAfterReclaiming(*this, [&] { return allocation_cache->Allocate(size, home); }); + return RetryAfterReclaiming(*this, [&] { return allocation_cache->Allocate(size, IsEnabled(), scheduler); }); } idx_t BlockAllocator::GetCachedMemory() const { - return GetCachedPoolMemory() + allocation_cache->GetCachedMemory(); + return pool->GetCachedPoolMemory() + allocation_cache->GetCachedMemory(); +} + +idx_t BlockAllocatorPool::GetBackingSize(idx_t size) const { + D_ASSERT(size > 0 && size <= block_size); + return AlignValue(size, backing_granularity); +} + +bool BlockAllocatorPool::TrimBacking(data_ptr_t pointer, idx_t size) const { + const auto retained = GetBackingSize(size); + return retained == block_size || OnDeallocation(pointer + retained, block_size - retained); +} + +data_ptr_t BlockAllocatorPool::TryAllocate(idx_t size) const { + if (!TryInitialize()) { + return nullptr; + } + const auto shard = BlockAllocator::GetLocalShard(GetShardCount()); + uint32_t block; + if (touched->queues.Get(shard).TryDequeueBulk(&block, 1)) { + auto pointer = GetPointer(block); + if (!TrimBacking(pointer, size)) { + // Still charged as a full cached slot; failed trimming cannot expose undercharged backing. + touched->Enqueue(block); + return nullptr; + } + UpdateCachedBlocks(-1, shard % cached_blocks.size()); + retention.Reuse(1, RetentionTimeMillis()); + return pointer; + } + // A foreign untouched slot would acquire backing on the wrong node. Fall back when this shard is full. + if (!untouched->queues.Get(shard).TryDequeueBulk(&block, 1)) { + return nullptr; + } + auto pointer = GetPointer(block); + try { + OnFirstAllocation(pointer, GetBackingSize(size)); + } catch (...) { + untouched->Enqueue(block); + throw; + } + return pointer; +} + +void BlockAllocatorPool::Free(data_ptr_t pointer, idx_t cache_slot) const { + UpdateCachedBlocks(1, cache_slot); + retention.Return(1, GetUsableBlockCount(), RetentionTimeMillis()); + touched->Enqueue(GetBlockID(pointer)); } -idx_t BlockAllocator::GetCachedPoolMemory() const { +idx_t BlockAllocatorPool::GetCachedPoolMemory() const { + if (!IsInitialized()) { + return 0; + } int64_t count = 0; const auto slots = MaxValue(1, MinValue(next_cache_slot.load(std::memory_order_relaxed), cached_blocks.size())); @@ -1003,7 +1343,7 @@ idx_t BlockAllocator::GetCachedPoolMemory() const { return count > 0 ? idx_t(count) * block_size : 0; } -void BlockAllocator::UpdateCachedBlocks(const int64_t count, const idx_t slot) const { +void BlockAllocatorPool::UpdateCachedBlocks(const int64_t count, const idx_t slot) const { cached_blocks[slot].count.fetch_add(count, std::memory_order_relaxed); } @@ -1011,27 +1351,25 @@ void BlockAllocator::FreeData(const data_ptr_t pointer, const idx_t size) const if (!pointer) { return; } - if (!IsInPool(pointer)) { - FreeFallbackData(pointer, size, optional_idx()); + if (!pool->IsInPool(pointer)) { + FreeFallbackData(pointer, size); return; } D_ASSERT(size == block_size); if (!ThreadHasLocalState()) { // creating the state of a thread that only frees allocates and registers a thread_local destructor, which // glibc aborts on when memory is exhausted: hand the block to the global pool directly - UpdateCachedBlocks(1, 0); - retention.Return(1, GetUsableBlockCount(), RetentionTimeMillis()); - touched->Enqueue(GetBlockID(pointer)); + pool->Free(pointer); return; } GetBlockAllocatorThreadLocalState(*this).Free(pointer); } -void BlockAllocator::FreeFallbackData(data_ptr_t pointer, idx_t size, optional_idx home) const { - if (allocation_cache->SupportsSize(size) && allocation_cache->TryFree(pointer, size, home)) { +void BlockAllocator::FreeFallbackData(data_ptr_t pointer, idx_t size) const { + if (allocation_cache->TryFree(pointer, size)) { return; } - allocator.FreeData(pointer, size); + allocation_cache->Free(pointer, size); estimated_unflushed_memory.fetch_add(size, std::memory_order_relaxed); } @@ -1040,14 +1378,26 @@ data_ptr_t BlockAllocator::ReallocateData(const data_ptr_t pointer, const idx_t return pointer; } - const bool old_in_pool = IsInPool(pointer); - const bool new_can_use_pool = new_size == block_size && TryUsePool(); - if (!old_in_pool && !new_can_use_pool) { - return RetryAfterReclaiming(*this, [&] { return allocator.ReallocateData(pointer, old_size, new_size); }); + const bool old_in_pool = pool->IsInPool(pointer) || allocation_cache->IsInPool(pointer, old_size); + if (allocation_cache->TryResizeInPlace(pointer, old_size, new_size)) { + return pointer; + } + data_ptr_t new_pointer = nullptr; + const bool new_fixed_pool = IsEnabled() && new_size == block_size && pool->TryInitialize(); + if (!old_in_pool && !new_fixed_pool) { + if (IsEnabled()) { + new_pointer = + RetryAfterReclaiming(*this, [&] { return allocation_cache->TryAllocatePool(new_size, scheduler); }); + } + if (!new_pointer) { + return RetryAfterReclaiming(*this, + [&] { return allocation_cache->Reallocate(pointer, old_size, new_size); }); + } + } else { + new_pointer = AllocateData(new_size); } // Pool allocations must retain their matching allocation/release paths. - const auto new_pointer = AllocateData(new_size); memcpy(new_pointer, pointer, MinValue(old_size, new_size)); FreeData(pointer, old_size); return new_pointer; @@ -1072,10 +1422,10 @@ static idx_t GetHugePageSize() { } #endif -static void AdviseHugePages(data_ptr_t pointer, idx_t size) { +static void AdviseHugePages(data_ptr_t pointer, idx_t size, const AllocationCache &allocation_cache) { #if defined(__linux__) && INTPTR_MAX == INT64_MAX && defined(MADV_HUGEPAGE) static constexpr idx_t MIN_ADVISE_SIZE = 8ULL * 1024 * 1024; - if (size >= MIN_ADVISE_SIZE) { + if (size >= MIN_ADVISE_SIZE && !allocation_cache.HasSparseBacking(pointer, size)) { static const idx_t huge_page_size = GetHugePageSize(); if (huge_page_size != 0 && size / huge_page_size >= 4) { const auto base = reinterpret_cast(pointer); @@ -1088,23 +1438,12 @@ static void AdviseHugePages(data_ptr_t pointer, idx_t size) { #endif } -data_ptr_t BlockAllocator::AllocateHugeData(const idx_t size, optional_idx &home) const { - home = optional_idx(); - auto pointer = size == block_size && TryUsePool() - ? AllocateData(size) - : RetryAfterReclaiming(*this, [&] { return allocation_cache->Allocate(size, home); }); - AdviseHugePages(pointer, size); +data_ptr_t BlockAllocator::AllocateHugeData(const idx_t size) const { + auto pointer = AllocateData(size); + AdviseHugePages(pointer, size, *allocation_cache); return pointer; } -void BlockAllocator::FreeHugeData(data_ptr_t pointer, const idx_t size, optional_idx home) const { - if (IsInPool(pointer)) { - FreeData(pointer, size); - } else { - FreeFallbackData(pointer, size, home); - } -} - bool BlockAllocator::SupportsFlush() const { return true; } @@ -1118,7 +1457,7 @@ optional_idx BlockAllocator::DecayDelay() const { } void BlockAllocator::ReturnThreadLocalBlocks() const { - if (IsInitialized() && ThreadHasLocalState()) { + if (pool->IsInitialized() && ThreadHasLocalState()) { GetBlockAllocatorThreadLocalState(*this).Clear(); } } @@ -1213,6 +1552,14 @@ void BlockAllocator::ClearScheduler() { scheduler = nullptr; } +void BlockAllocator::SetBufferPool(shared_ptr buffer_pool) { + const bool owns_reclamation = &buffer_pool->block_allocator == this; + if (!owns_reclamation) { + FlushAll(); + } + allocation_cache->SetBufferPool(std::move(buffer_pool), owns_reclamation); +} + void BlockAllocator::ThreadIdle() const { auto scheduler_ref = scheduler; try { @@ -1238,11 +1585,11 @@ void BlockAllocator::ThreadExit() const { Allocator::ThreadIdle(); } -idx_t BlockAllocator::GetFreeBlockCount() const { +idx_t BlockAllocatorPool::GetFreeBlockCount() const { return touched->SizeApprox(); } -idx_t BlockAllocator::GetReclaimableBlockCount(const ReclaimMode mode, const optional_idx cache_limit) const { +idx_t BlockAllocatorPool::GetReclaimableBlockCount(const ReclaimMode mode, const optional_idx cache_limit) const { auto available = GetFreeBlockCount(); if (cache_limit.IsValid()) { const auto cached = DivBlockSize(GetCachedPoolMemory()); @@ -1259,7 +1606,7 @@ idx_t BlockAllocator::FlushPool(const optional_idx block_limit, const optional_i const optional_idx cache_limit) const noexcept { try { ReturnThreadLocalBlocks(); - return FreeInternal(block_limit, task_limit, mode, cache_limit); + return pool->FreeInternal(block_limit, task_limit, mode, cache_limit); } catch (...) { // Failed reclamation leaves blocks available for reuse. return 0; @@ -1272,7 +1619,8 @@ static idx_t AllocationCacheIdleCutoff() { } bool BlockAllocator::HasReclaimableMemory() const { - return GetReclaimableBlockCount(ReclaimMode::DECAY) > 0 || + annotated_lock_guard guard(pool->flush_lock); + return pool->GetReclaimableBlockCount(ReclaimMode::DECAY) > 0 || allocation_cache->GetCachedMemory(AllocationCacheIdleCutoff()) > 0 || estimated_unflushed_memory.load(std::memory_order_relaxed) > 0; } @@ -1290,17 +1638,21 @@ idx_t BlockAllocator::FlushAllocationCache(idx_t byte_limit, ReclaimMode mode) c } else { guard.lock(); } + idx_t fallback_freed = 0; const auto freed = allocation_cache->Flush( - byte_limit, mode != ReclaimMode::FORCE ? optional_idx(AllocationCacheIdleCutoff()) : optional_idx()); - estimated_unflushed_memory.fetch_add(freed, std::memory_order_relaxed); + byte_limit, mode != ReclaimMode::FORCE ? optional_idx(AllocationCacheIdleCutoff()) : optional_idx(), + &fallback_freed, mode); + estimated_unflushed_memory.fetch_add(fallback_freed, std::memory_order_relaxed); return freed; } void BlockAllocator::TrimCachedMemory(idx_t memory_headroom, optional_idx pool_block_limit) const noexcept { const auto cached = allocation_cache->GetCachedMemory(); + memory_headroom += + MinValue(allocation_cache->GetPressureCacheAllowance(), NumericLimits::Maximum() - memory_headroom); // Avoid reading the fixed pool's per-thread counters when even its capacity fits. - if (cached <= memory_headroom && (GetUsableBlockCount() * block_size <= memory_headroom - cached || - GetCachedPoolMemory() <= memory_headroom - cached)) { + if (cached <= memory_headroom && (pool->GetUsableBlockCount() * block_size <= memory_headroom - cached || + pool->GetCachedPoolMemory() <= memory_headroom - cached)) { return; } idx_t pool_headroom; @@ -1310,12 +1662,13 @@ void BlockAllocator::TrimCachedMemory(idx_t memory_headroom, optional_idx pool_b if (total <= memory_headroom) { return; } - const auto freed = allocation_cache->Flush(total - memory_headroom); - estimated_unflushed_memory.fetch_add(freed, std::memory_order_relaxed); + idx_t fallback_freed = 0; + allocation_cache->Flush(total - memory_headroom, optional_idx(), &fallback_freed); + estimated_unflushed_memory.fetch_add(fallback_freed, std::memory_order_relaxed); const auto remaining = allocation_cache->GetCachedMemory(); pool_headroom = memory_headroom - MinValue(memory_headroom, remaining); } - FlushPool(pool_block_limit, optional_idx(), ReclaimMode::FORCE, DivBlockSize(pool_headroom)); + FlushPool(pool_block_limit, optional_idx(), ReclaimMode::FORCE, pool->DivBlockSize(pool_headroom)); } void BlockAllocator::FlushAll() const noexcept { @@ -1330,12 +1683,12 @@ void BlockAllocator::FlushOnShutdown() const noexcept { } void BlockAllocator::FlushForAllocation(const idx_t extra_memory, const idx_t memory_headroom) const noexcept { - TrimCachedMemory(memory_headroom, DivBlockSize(extra_memory)); + TrimCachedMemory(memory_headroom, pool->DivBlockSize(extra_memory)); FlushFallbackAllocator(estimated_unflushed_memory.exchange(0, std::memory_order_relaxed)); } bool BlockAllocator::TryFlushDeallocated(const idx_t threshold, const idx_t memory_headroom) const noexcept { - // Trimmed allocations join the other fallback frees, and are purged with them. + // Pool pages are discarded directly; only fallback frees wait for the allocator purge. TrimCachedMemory(memory_headroom); auto deallocated = estimated_unflushed_memory.load(std::memory_order_relaxed); do { @@ -1382,8 +1735,9 @@ void BlockAllocator::FlushFallbackAllocator(const idx_t deallocated) const noexc } } -idx_t BlockAllocator::FreeInternal(const optional_idx block_limit, const optional_idx task_limit, - const ReclaimMode mode, const optional_idx cache_limit) const { +idx_t BlockAllocatorPool::FreeInternal(const optional_idx block_limit, const optional_idx task_limit, + const ReclaimMode mode, const optional_idx cache_limit, + idx_t *freed_blocks) const { if (!IsInitialized()) { return 0; } @@ -1460,6 +1814,9 @@ idx_t BlockAllocator::FreeInternal(const optional_idx block_limit, const optiona annotated_lock_guard guard(flush_lock); UpdateCachedBlocks(-NumericCast(end - start), 0); reclaiming_blocks -= end - start; + if (freed_blocks) { + *freed_blocks += end - start; + } } untouched->EnqueueBulk( to_free_buffer.begin() + NumericCast::difference_type>(start), end - start); @@ -1469,7 +1826,8 @@ idx_t BlockAllocator::FreeInternal(const optional_idx block_limit, const optiona return remaining; } -bool BlockAllocator::FreeContiguousBlocks(const uint32_t block_id_start, const uint32_t block_id_end_including) const { +bool BlockAllocatorPool::FreeContiguousBlocks(const uint32_t block_id_start, + const uint32_t block_id_end_including) const { VerifyBlockID(block_id_end_including); D_ASSERT(touched->Home(block_id_start) == touched->Home(block_id_end_including)); const auto pointer = GetPointer(block_id_start); diff --git a/src/duckdb/src/storage/buffer/block_handle.cpp b/src/duckdb/src/storage/buffer/block_handle.cpp index 118f4b363..2626f297c 100644 --- a/src/duckdb/src/storage/buffer/block_handle.cpp +++ b/src/duckdb/src/storage/buffer/block_handle.cpp @@ -220,6 +220,19 @@ BufferHandle BlockHandle::LoadFromBuffer(BlockLock &l, data_ptr_t data, unique_p return BufferHandle(shared_from_this(), memory.GetBuffer()); } +BufferHandle BlockHandle::TryPinResident() { + BufferHandle result; + { + BlockLock lock(memory.lock, std::try_to_lock); + if (!lock.owns_lock() || memory.GetState() != BlockState::BLOCK_LOADED || !memory.GetBuffer(lock)) { + return BufferHandle(); + } + memory.IncrementReaders(lock); + result = BufferHandle(shared_from_this(), memory.GetBuffer(lock)); + } + return result; +} + BufferHandle BlockHandle::Load(BlockLock &l, Context &context, unique_ptr reusable_buffer) { memory.VerifyMutex(l); if (memory.GetState() == BlockState::BLOCK_LOADED) { diff --git a/src/duckdb/src/storage/buffer/buffer_pool.cpp b/src/duckdb/src/storage/buffer/buffer_pool.cpp index 4134bdb97..e8dc6f5d5 100644 --- a/src/duckdb/src/storage/buffer/buffer_pool.cpp +++ b/src/duckdb/src/storage/buffer/buffer_pool.cpp @@ -378,6 +378,31 @@ void BufferPool::UpdateUsedMemory(MemoryTag tag, int64_t size) { memory_usage.UpdateUsedMemory(tag, size); } +bool BufferPool::TryReserveMemory(MemoryTag tag, idx_t size, idx_t headroom) { + const auto limit = GetMaxMemory(); + if (headroom > limit || size > limit - headroom) { + return false; + } + const auto admission_limit = limit - headroom; + auto used = GetUsedMemory(false); + if (used > admission_limit - size && GetUsedMemory() > admission_limit - size) { + return false; + } + TempBufferPoolReservation reservation(tag, *this, size); + used = GetUsedMemory(false); + constexpr auto cache_bound = MemoryUsage::MEMORY_USAGE_CACHE_COUNT * MemoryUsage::MEMORY_USAGE_CACHE_THRESHOLD; + if (used >= admission_limit || admission_limit - used <= cache_bound) { + // Include small charges that are still in per-CPU counter caches near the admission threshold. + used = GetUsedMemory(); + } + if (used > admission_limit) { + return false; + } + FlushForAllocation(size, limit); + reservation.size = 0; + return true; +} + idx_t BufferPool::GetUsedMemory(bool flush) const { return memory_usage.GetUsedMemory(flush ? MemoryUsageCaches::FLUSH : MemoryUsageCaches::NO_FLUSH); } diff --git a/src/duckdb/src/storage/data_table.cpp b/src/duckdb/src/storage/data_table.cpp index ada1f09e9..93b96ddc7 100644 --- a/src/duckdb/src/storage/data_table.cpp +++ b/src/duckdb/src/storage/data_table.cpp @@ -612,6 +612,7 @@ void DataTable::Fetch(DuckTransaction &transaction, DataChunk &result, const vec if (!has_local) { // All committed rows — fast path (common case). row_groups->Fetch(transaction, result, column_ids, row_identifiers, fetch_count, state); + RowGroup::VerifyScannedValues(result); return; } @@ -667,6 +668,7 @@ void DataTable::Fetch(DuckTransaction &transaction, DataChunk &result, const vec for (idx_t col = 0; col < result.ColumnCount(); col++) { result.data[col].Slice(inv_perm, fetch_count); } + RowGroup::VerifyScannedValues(result); } void DataTable::FetchCommitted(DataChunk &result, const vector &column_ids, const Vector &row_identifiers, @@ -1591,9 +1593,6 @@ void DataTable::VerifyUpdateConstraints(ConstraintState &state, ClientContext &c throw NotImplementedException("Constraint type not implemented!"); } } - // Ensure that we never call UPDATE for indexed columns. - // Instead, we must rewrite these updates into DELETE + INSERT. - info->indexes.VerifyUpdate(column_ids); } unique_ptr DataTable::InitializeUpdate(TableCatalogEntry &table, ClientContext &context, @@ -1624,6 +1623,9 @@ void DataTable::Update(TableUpdateState &state, ClientContext &context, DuckTabl // first verify that no constraints are violated VerifyUpdateConstraints(*state.constraint_state, context, updates, column_ids); + // Ensure that we never call UPDATE for indexed columns. + // Instead, we must rewrite these updates into DELETE + INSERT. + info->indexes.VerifyUpdate(column_ids); // now perform the actual update Vector row_ids_slice(LogicalType::BIGINT); diff --git a/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp b/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp index 4977e9c88..28adc96ac 100644 --- a/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp +++ b/src/duckdb/src/storage/external_file_cache/caching_file_system.cpp @@ -71,10 +71,35 @@ void TightenCacheDeadline(optional &cached, const optionalTryPinResident(); +#ifdef DEBUG + if (pin.IsValid()) { + D_ASSERT(Checksum(pin.Ptr(), block.nr_bytes) == block.checksum); + } +#endif + return pin; +} + //===----------------------------------------------------------------------===// // FetchBlockTask //===----------------------------------------------------------------------===// @@ -263,44 +288,29 @@ bool CachingFileHandle::StripForceFullDownloadIfPresent() { } shared_ptr CachingFileHandle::EnsureCachedFileCurrent() { - bool needs_reopen = false; - shared_ptr current_cached_file; - { - annotated_lock_guard guard(file_handle_mutex); - if (cached_file && cached_file->generation == external_file_cache.GetGeneration()) { - return cached_file; - } - needs_reopen = file_handle != nullptr; - if (needs_reopen) { - file_handle.reset(); - } - cached_file = external_file_cache.GetOrCreateCachedFile(path.path); - current_cached_file = cached_file; + annotated_lock_guard guard(file_handle_mutex); + if (cached_file && cached_file->generation == external_file_cache.GetGeneration()) { + return cached_file; } - - if (needs_reopen) { - GetFileHandle(); + auto target = external_file_cache.GetOrCreateCachedFile(path.path); + if (!TryAdoptCachedFile(target) && !TryOpenFileHandle(std::move(target))) { + throw IOException("Cannot open file \"%s\": file does not exist", path.path); } - return current_cached_file; + return cached_file; } bool CachingFileHandle::CanUseCache() { auto current_cached_file = EnsureCachedFileCurrent(); - if (!Validate()) { - annotated_lock_guard guard(current_cached_file->meta_lock); - return !current_cached_file->validation_info.IsExpired(); - } - bool has_validation_metadata; - { - const annotated_lock_guard guard(file_handle_mutex); - has_validation_metadata = ExternalFileCache::HasValidationMetadata(validation_info); - } - + const annotated_lock_guard handle_guard(file_handle_mutex); annotated_lock_guard guard(current_cached_file->meta_lock); - if (!current_cached_file->validation_info.cache_valid_until) { - return has_validation_metadata; + return CanUseCache(current_cached_file->validation_info); +} + +bool CachingFileHandle::CanUseCache(const CacheValidationInfo &cached) const { + if (!Validate() || cached.cache_valid_until) { + return !cached.IsExpired(); } - return !current_cached_file->validation_info.IsExpired(); + return ExternalFileCache::HasValidationMetadata(validation_info); } void CachingFileHandle::ReconcileCacheAfterRead(CachedFile &cached_file) { @@ -312,20 +322,24 @@ void CachingFileHandle::ReconcileCacheAfterRead(CachedFile &cached_file) { const annotated_lock_guard guard(cached_file.meta_lock); auto &cached = cached_file.validation_info; - if (ExternalFileCache::IsValid(Validate(), cached, current)) { + switch (GetCacheReconciliation(Validate(), cached, current)) { + case CacheReconciliation::NONE: + return; + case CacheReconciliation::TIGHTEN_DEADLINE: TightenCacheDeadline(cached.cache_valid_until, current.cache_valid_until); return; + case CacheReconciliation::DROP_BLOCKS: + cached = current; + // Existing readers retain their pinned blocks while future reads fetch replacements. + external_file_cache.DropBlocks(cached_file); + return; } - - cached = current; - // Existing readers retain their pinned blocks while future reads fetch replacements. - external_file_cache.DropBlocks(cached_file); } CachingFileHandle::CachingFileHandle(Context &context, CachingFileSystem &caching_file_system_p, const OpenFileInfo &path_p, FileOpenFlags flags_p) : context(context), file_system(caching_file_system_p.file_system), db(caching_file_system_p.db), - external_file_cache(caching_file_system_p.external_file_cache), path(path_p), flags(std::move(flags_p)), + external_file_cache(caching_file_system_p.external_file_cache), path(path_p), flags(flags_p), validate(ExternalFileCacheUtil::GetCacheValidationMode(path_p, context, caching_file_system_p.db)), cached_file(external_file_cache.GetOrCreateCachedFile(path_p.path)), position(0) { } @@ -335,14 +349,11 @@ bool CachingFileHandle::Initialize() { // If caching is disabled, or if we must validate cache entries, we always have to open the file return TryGetFileHandle() != nullptr; } - // If we don't have any cached blocks, we must also open the file. - bool needs_open = false; { - annotated_lock_guard guard(cached_file->map_lock); - needs_open = cached_file->blocks.empty(); - } - if (needs_open && !TryGetFileHandle()) { - return false; + annotated_lock_guard guard(file_handle_mutex); + if (!TryAdoptCachedFile(cached_file) && !TryOpenFileHandle(cached_file)) { + return false; + } } auto needs_full_download = StripForceFullDownloadIfPresent(); if (needs_full_download) { @@ -368,39 +379,62 @@ shared_ptr CachingFileHandle::TryGetFileHandle() { return file_handle; } + return TryOpenFileHandle(cached_file); +} + +bool CachingFileHandle::TryAdoptCachedFile(shared_ptr target) { + if (file_handle || !external_file_cache.IsEnabled() || Validate()) { + return false; + } + annotated_lock_guard meta_guard(target->meta_lock); + annotated_lock_guard map_guard(target->map_lock); + if (target->validation_info.file_size == 0 || target->blocks.empty() || target->validation_info.IsExpired()) { + return false; + } + // Both initial opens and generation refreshes can reuse populated cache metadata without backend I/O. + // validation_info records backend observations, not cached deadlines that another handle may renew. + cached_file = std::move(target); + return true; +} + +shared_ptr CachingFileHandle::TryOpenFileHandle(shared_ptr target) { // The caching file handle can service parallel block fetch tasks against a single shared FileHandle. // Request parallel access on the underlying filesystem handle to avoid races in implementations that // require explicit opt-in for concurrent pread-style access (e.g., HTTPFS). auto internal_flags = flags | FileFlags::FILE_FLAGS_PARALLEL_ACCESS; - file_handle = file_system.OpenFile(path, internal_flags); - if (!file_handle) { + auto handle = file_system.OpenFile(path, internal_flags); + if (!handle) { return nullptr; } // Snapshot the metadata with a single Stats call, avoiding repeated metadata lookups (e.g., fstat) - validation_info = GetValidationInfo(file_system, *file_handle); + auto current = GetValidationInfo(file_system, *handle); { - annotated_lock_guard meta_guard(cached_file->meta_lock); - const bool first_access = (cached_file->validation_info.file_size == 0); - const bool refresh_expired_cache = !Validate() && cached_file->validation_info.IsExpired(); + annotated_lock_guard meta_guard(target->meta_lock); + const bool first_access = (target->validation_info.file_size == 0); + const bool refresh_expired_cache = !Validate() && target->validation_info.IsExpired(); if (first_access || Validate() || refresh_expired_cache) { + const auto can_seek = handle->CanSeek(); + const auto on_disk_file = handle->OnDiskFile(); const bool cache_is_valid = - !refresh_expired_cache && - ExternalFileCache::IsValid(Validate(), cached_file->validation_info, validation_info); + !refresh_expired_cache && ExternalFileCache::IsValid(Validate(), target->validation_info, current); if (!cache_is_valid) { - external_file_cache.DropBlocks(*cached_file); + external_file_cache.DropBlocks(*target); } // A successful validator check refreshes freshness. Without validators, preserve the original deadline. - const bool revalidated = cache_is_valid && ExternalFileCache::HasValidationMetadata(validation_info); - const auto preserved_valid_until = cached_file->validation_info.cache_valid_until; - cached_file->validation_info = validation_info; + const bool revalidated = cache_is_valid && ExternalFileCache::HasValidationMetadata(current); + const auto preserved_valid_until = target->validation_info.cache_valid_until; + target->validation_info = current; if (cache_is_valid && !revalidated) { - cached_file->validation_info.cache_valid_until = preserved_valid_until; + target->validation_info.cache_valid_until = preserved_valid_until; } - cached_file->can_seek = file_handle->CanSeek(); - cached_file->on_disk_file = file_handle->OnDiskFile(); + target->can_seek = can_seek; + target->on_disk_file = on_disk_file; } } + file_handle = std::move(handle); + validation_info = std::move(current); + cached_file = std::move(target); return file_handle; } @@ -413,73 +447,155 @@ bool CachingFileHandle::ReadsAreCached() { } FileBufferHandleGroup CachingFileHandle::Read(const idx_t nr_bytes, const idx_t location) { - static const vector> no_absorb_ranges; - return Read(nr_bytes, location, no_absorb_ranges); + return Read(nr_bytes, location, vector()); } FileBufferHandleGroup CachingFileHandle::Read(const idx_t nr_bytes, const idx_t location, - const vector> &absorb_ranges) { + const vector &absorb_ranges) { + auto result = ReadInternal(nr_bytes, location, absorb_ranges, ReadMode::ALLOW_IO); + if (!result) { + throw InternalException("CachingFileHandle::Read did not acquire the requested blocks"); + } + return std::move(*result); +} + +optional CachingFileHandle::TryReadResident(const idx_t nr_bytes, const idx_t location) { + return ReadInternal(nr_bytes, location, {}, ReadMode::RESIDENT_ONLY); +} + +optional CachingFileHandle::ReadInternal(const idx_t nr_bytes, const idx_t location, + const vector &absorb_ranges, ReadMode mode) { if (nr_bytes == 0) { return FileBufferHandleGroup(); } - if (!ReadsAreCached()) { + auto acquire_blocks = [&](CachedFile &file, idx_t file_size) { + const idx_t max_block_size = external_file_cache.GetCacheMaxBlockSize(file.path); + const idx_t min_block_size = MinValue(external_file_cache.GetCacheMinBlockSize(file.path), max_block_size); + auto request_sizing = flags.GetRequestSizing(); + switch (Settings::Get(db)) { + case ExternalFileCacheRequestSizing::GRID: + request_sizing = RequestSizing::BY_CACHE; + break; + case ExternalFileCacheRequestSizing::EXACT: + request_sizing = RequestSizing::BY_READER; + break; + case ExternalFileCacheRequestSizing::AUTO: + break; + } + idx_t fetch_location = location; + idx_t fetch_end = location + nr_bytes; + if (file_size <= max_block_size) { + // fetch a file that fits in one block whole, so later reads of it hit the cache + fetch_location = 0; + fetch_end = file_size; + } else if (request_sizing == RequestSizing::BY_CACHE) { + fetch_location = location - location % max_block_size; + fetch_end = AlignValue(fetch_end, max_block_size); + } else { + fetch_location = location - location % min_block_size; + fetch_end = AlignValue(fetch_end, min_block_size); + } + fetch_end = MinValue(fetch_end, file_size); + auto lookup = mode == ReadMode::RESIDENT_ONLY ? ExternalFileCache::BlockLookup::EXISTING_ONLY + : ExternalFileCache::BlockLookup::CREATE_MISSING; + return external_file_cache.AcquireBlocks(file, fetch_location, fetch_end - fetch_location, max_block_size, + absorb_ranges.empty() ? nullptr : &absorb_ranges, lookup); + }; + + shared_ptr current_cached_file; + vector> blocks; + if (mode == ReadMode::RESIDENT_ONLY) { + if (!external_file_cache.IsEnabled() || !external_file_cache.ShouldCacheFile(path.path)) { + return nullopt; + } + annotated_unique_lock handle_guard(file_handle_mutex, std::defer_lock); + if (!handle_guard.try_lock() || !cached_file || + cached_file->generation != external_file_cache.GetGeneration()) { + return nullopt; + } + current_cached_file = cached_file; + // Validate policy and acquire block references in one metadata snapshot. An ordinary read may + // tighten the deadline or drop these blocks after returning data; a resident probe must defer to it. + annotated_unique_lock meta_guard(current_cached_file->meta_lock, std::defer_lock); + if (!meta_guard.try_lock() || !CanUseCache(current_cached_file->validation_info) || + GetCacheReconciliation(Validate(), current_cached_file->validation_info, validation_info) != + CacheReconciliation::NONE) { + return nullopt; + } + const auto file_size = Validate() ? validation_info.file_size : current_cached_file->validation_info.file_size; + if (location >= file_size || nr_bytes > file_size - location) { + return nullopt; + } + blocks = acquire_blocks(*current_cached_file, file_size); + } else if (!ReadsAreCached()) { auto buf = AllocateUncachedReadBuffer(external_file_cache.GetBufferManager(), nr_bytes); ReadUncached(buf.GetDataMutable(), nr_bytes, location); vector mem_handles; mem_handles.push_back({std::move(buf), 0, nr_bytes}); return FileBufferHandleGroup(std::move(mem_handles)); - } - - auto current_cached_file = EnsureCachedFileCurrent(); - const idx_t file_size = GetFileSize(); - if (location >= file_size) { - return FileBufferHandleGroup(); - } - LogCacheEvent(context, *this, ExternalFileCacheLogType::READ_EVENT, MinValue(nr_bytes, file_size - location), - location); - const idx_t max_block_size = external_file_cache.GetCacheMaxBlockSize(current_cached_file->path); - const idx_t min_block_size = - MinValue(external_file_cache.GetCacheMinBlockSize(current_cached_file->path), max_block_size); - auto request_sizing = flags.GetRequestSizing(); - switch (Settings::Get(db)) { - case ExternalFileCacheRequestSizing::GRID: - request_sizing = RequestSizing::BY_CACHE; - break; - case ExternalFileCacheRequestSizing::EXACT: - request_sizing = RequestSizing::BY_READER; - break; - case ExternalFileCacheRequestSizing::AUTO: - break; - } - idx_t fetch_location = location; - idx_t fetch_end = location + nr_bytes; - if (file_size <= max_block_size) { - // fetch a file that fits in one block whole, so later reads of it hit the cache - fetch_location = 0; - fetch_end = file_size; - } else if (request_sizing == RequestSizing::BY_CACHE) { - fetch_location = location - location % max_block_size; - fetch_end = AlignValue(fetch_end, max_block_size); } else { - fetch_location = location - location % min_block_size; - fetch_end = AlignValue(fetch_end, min_block_size); + current_cached_file = EnsureCachedFileCurrent(); + const auto file_size = GetFileSize(); + if (location >= file_size) { + return FileBufferHandleGroup(); + } + LogCacheEvent(context, *this, ExternalFileCacheLogType::READ_EVENT, MinValue(nr_bytes, file_size - location), + location); + blocks = acquire_blocks(*current_cached_file, file_size); } - fetch_end = MinValue(fetch_end, file_size); - auto blocks = external_file_cache.AcquireBlocks(*current_cached_file, fetch_location, fetch_end - fetch_location, - max_block_size, absorb_ranges.empty() ? nullptr : &absorb_ranges); const idx_t num_blocks = blocks.size(); + if (mode == ReadMode::RESIDENT_ONLY && num_blocks == 0) { + return nullopt; + } + + vector pins(num_blocks); + // Complete the resident prefix without dispatching fetch tasks. Stop at the first miss: pinning later + // blocks before an earlier fetch runs would prevent that fetch from evicting them to make room. + idx_t first_pending = 0; + for (; first_pending < num_blocks; first_pending++) { + auto &block = *blocks[first_pending]; + annotated_unique_lock guard(block.mtx, std::defer_lock); + if (!guard.try_lock()) { + break; + } + auto pin = TryPinResidentBlock(block); + if (!pin.IsValid()) { + break; + } + const auto valid_bytes = block.nr_bytes; + if (mode == ReadMode::RESIDENT_ONLY && block.location < location + nr_bytes && + block.location + block.size > location && + valid_bytes < MinValue(block.size, location + nr_bytes - block.location)) { + // A loaded block can be shorter than its nominal range, e.g. after a read at EOF. + // Every requested byte must be backed; later blocks cannot fill a hole in this one. + break; + } + pins[first_pending] = {std::move(pin), 0, valid_bytes}; + guard.unlock(); + if (mode == ReadMode::ALLOW_IO) { + LogCacheEvent(context, *this, ExternalFileCacheLogType::HIT_EVENT, valid_bytes, block.location); + } + } - // Schedule block fetch tasks for all blocks. - vector pins(num_blocks); - auto &scheduler = TaskScheduler::GetScheduler(db); - TaskExecutor executor(scheduler, TaskSchedulerType::ASYNC); - - for (idx_t idx = 0; idx < num_blocks; idx++) { - executor.ScheduleTask(make_uniq( - *this, executor, context, external_file_cache.GetBufferManager(), blocks[idx], pins[idx])); + if (mode == ReadMode::RESIDENT_ONLY && first_pending < num_blocks) { + return nullopt; + } + if (mode == ReadMode::RESIDENT_ONLY) { + LogCacheEvent(context, *this, ExternalFileCacheLogType::READ_EVENT, nr_bytes, location); + for (idx_t idx = 0; idx < num_blocks; idx++) { + LogCacheEvent(context, *this, ExternalFileCacheLogType::HIT_EVENT, pins[idx].length, blocks[idx]->location); + } + } + if (first_pending < num_blocks) { + auto &scheduler = TaskScheduler::GetScheduler(db); + TaskExecutor executor(scheduler, TaskSchedulerType::ASYNC); + for (idx_t idx = first_pending; idx < num_blocks; idx++) { + executor.ScheduleTask(make_uniq( + *this, executor, context, external_file_cache.GetBufferManager(), blocks[idx], pins[idx].handle)); + } + executor.WorkOnTasks(); } - executor.WorkOnTasks(); // Build the handle group. vector mem_handles; @@ -492,19 +608,21 @@ FileBufferHandleGroup CachingFileHandle::Read(const idx_t nr_bytes, const idx_t continue; } const idx_t offset_in_block = location > block.location ? location - block.location : 0; - idx_t block_valid_bytes = 0; - { + idx_t block_valid_bytes = pins[idx].length; + if (mode == ReadMode::ALLOW_IO) { annotated_lock_guard block_guard(block.mtx); block_valid_bytes = block.nr_bytes; } const idx_t available_in_block = (block_valid_bytes > offset_in_block) ? (block_valid_bytes - offset_in_block) : 0; const idx_t length = MinValue(available_in_block, remaining); - mem_handles.push_back({std::move(pins[idx]), offset_in_block, length}); + mem_handles.push_back({std::move(pins[idx].handle), offset_in_block, length}); remaining -= length; } - ReconcileCacheAfterRead(*current_cached_file); + if (mode == ReadMode::ALLOW_IO) { + ReconcileCacheAfterRead(*current_cached_file); + } return FileBufferHandleGroup(std::move(mem_handles)); } diff --git a/src/duckdb/src/storage/external_file_cache/caching_file_system_wrapper.cpp b/src/duckdb/src/storage/external_file_cache/caching_file_system_wrapper.cpp index 6ad661148..3e29ef6af 100644 --- a/src/duckdb/src/storage/external_file_cache/caching_file_system_wrapper.cpp +++ b/src/duckdb/src/storage/external_file_cache/caching_file_system_wrapper.cpp @@ -104,7 +104,7 @@ unique_ptr CachingFileSystemWrapper::OpenFile(Context &context, cons unique_ptr CachingFileSystemWrapper::OpenFile(Context &context, const OpenFileInfo &path, FileOpenFlags flags) { if (SupportsOpenFileExtended()) { - return OpenFileExtended(context, path, std::move(flags)); + return OpenFileExtended(context, path, flags); } throw NotImplementedException("CachingFileSystemWrapper: OpenFile is not implemented!"); } diff --git a/src/duckdb/src/storage/external_file_cache/external_file_cache.cpp b/src/duckdb/src/storage/external_file_cache/external_file_cache.cpp index 7c6f6dc8b..e1baf4c9c 100644 --- a/src/duckdb/src/storage/external_file_cache/external_file_cache.cpp +++ b/src/duckdb/src/storage/external_file_cache/external_file_cache.cpp @@ -162,27 +162,35 @@ bool ExternalFileCache::IsRangeAvailable(CachedFile &cached_file, idx_t location return IsRangeAvailableLocked(cached_file.blocks, location, location + nr_bytes); } -//! Whether [begin, end) lies within one of the ranges -static bool WithinRanges(optional_ptr>> ranges, idx_t begin, idx_t end) { +//! Whether the requested byte range lies within one of the ranges +static bool WithinRanges(optional_ptr> ranges, FileRange requested) { if (!ranges) { return false; } for (auto &range : *ranges) { - if (range.first <= begin && end <= range.second) { + if (range.Contains(requested)) { return true; } } return false; } -vector> -ExternalFileCache::AcquireBlocks(CachedFile &cached_file, idx_t location, idx_t nr_bytes, idx_t max_block_size, - optional_ptr>> absorb_ranges) { +vector> ExternalFileCache::AcquireBlocks(CachedFile &cached_file, idx_t location, idx_t nr_bytes, + idx_t max_block_size, + optional_ptr> absorb_ranges, + BlockLookup lookup) { D_ASSERT(nr_bytes > 0); D_ASSERT(max_block_size > 0); const idx_t end = location + nr_bytes; - const annotated_lock_guard map_guard(cached_file.map_lock); + annotated_unique_lock map_guard(cached_file.map_lock, std::defer_lock); + if (lookup == BlockLookup::EXISTING_ONLY) { + if (!map_guard.try_lock()) { + return {}; + } + } else { + map_guard.lock(); + } auto &blocks = cached_file.blocks; // smaller cached blocks between two gaps are re-fetched with them when that saves a request; within the ranges a // read asks for (a column chunk read whole after point lookups left pages of it in the cache) that holds for @@ -191,7 +199,7 @@ ExternalFileCache::AcquireBlocks(CachedFile &cached_file, idx_t location, idx_t if (block.size < max_block_size / 8) { return true; } - return block.size < max_block_size && WithinRanges(absorb_ranges, block_start, block_start + block.size); + return block.size < max_block_size && WithinRanges(absorb_ranges, {block_start, block.size}); }; // start at the block that covers `location`, if any auto it = blocks.upper_bound(location); @@ -206,7 +214,7 @@ ExternalFileCache::AcquireBlocks(CachedFile &cached_file, idx_t location, idx_t idx_t pos = location; while (pos < end) { if (it != blocks.end() && it->first <= pos) { - if (!IsDroppedBlock(*it->second) || it->second.use_count() > 1) { + if (lookup == BlockLookup::EXISTING_ONLY || !IsDroppedBlock(*it->second) || it->second.use_count() > 1) { result.push_back(it->second); pos = it->first + it->second->size; ++it; @@ -215,6 +223,9 @@ ExternalFileCache::AcquireBlocks(CachedFile &cached_file, idx_t location, idx_t // re-fetch a dropped block only as far as this read needs it it = blocks.erase(it); } + if (lookup == BlockLookup::EXISTING_ONLY) { + return {}; + } // create blocks for the missing bytes up to the next cached block idx_t gap_end = it == blocks.end() ? end : MinValue(end, it->first); while (it != blocks.end() && it->first < end && absorbable(it->first, *it->second) && @@ -242,7 +253,9 @@ ExternalFileCache::AcquireBlocks(CachedFile &cached_file, idx_t location, idx_t pos += size; } } - cached_file.UpdateBlockReservation(); + if (lookup == BlockLookup::CREATE_MISSING) { + cached_file.UpdateBlockReservation(); + } return result; } diff --git a/src/duckdb/src/storage/serialization/serialize_nodes.cpp b/src/duckdb/src/storage/serialization/serialize_nodes.cpp index 6a0414ae3..d23b1befb 100644 --- a/src/duckdb/src/storage/serialization/serialize_nodes.cpp +++ b/src/duckdb/src/storage/serialization/serialize_nodes.cpp @@ -389,12 +389,12 @@ ExtraOperatorInfo ExtraOperatorInfo::Deserialize(Deserializer &deserializer) { } void FunctionArgument::Serialize(Serializer &serializer) const { - serializer.WritePropertyWithDefault(100, "name", name); + serializer.WritePropertyWithDefault(100, "name", GetSerializedName()); serializer.WritePropertyWithDefault>(101, "expression", expression); } FunctionArgument FunctionArgument::Deserialize(Deserializer &deserializer) { - auto name = deserializer.ReadPropertyWithDefault(100, "name"); + auto name = deserializer.ReadPropertyWithDefault(100, "name"); auto expression = deserializer.ReadPropertyWithDefault>(101, "expression"); FunctionArgument result(std::move(name), std::move(expression)); return result; @@ -895,7 +895,8 @@ void TableFilterSet::Serialize(Serializer &serializer) const { TableFilterSet TableFilterSet::Deserialize(Deserializer &deserializer) { TableFilterSet result; deserializer.ReadPropertyWithDefault>>(100, "filters", result.GetTableFiltersForDeserialization(deserializer)); - deserializer.ReadPropertyWithExplicitDefault>>(101, "multi_column_filters", result.multi_column_filters, vector>()); + auto multi_column_filters = deserializer.ReadPropertyWithExplicitDefault>>(101, "multi_column_filters", vector>()); + result.LoadSerializedPruningFilters(std::move(multi_column_filters)); return result; } diff --git a/src/duckdb/src/storage/serialization/serialize_tableref.cpp b/src/duckdb/src/storage/serialization/serialize_tableref.cpp index e5ef1b1a0..9486cad0c 100644 --- a/src/duckdb/src/storage/serialization/serialize_tableref.cpp +++ b/src/duckdb/src/storage/serialization/serialize_tableref.cpp @@ -262,12 +262,16 @@ void SubqueryRef::Serialize(Serializer &serializer) const { TableRef::Serialize(serializer); serializer.WritePropertyWithDefault>(200, "subquery", subquery); serializer.WritePropertyWithDefault>(201, "column_name_alias", column_name_alias); + if (serializer.ShouldSerialize(StorageVersion::V2_1_0)) { + serializer.WritePropertyWithDefault(202, "lateral", lateral, SubqueryLateralType::UNRECORDED); + } } unique_ptr SubqueryRef::Deserialize(Deserializer &deserializer) { auto result = duckdb::unique_ptr(new SubqueryRef()); deserializer.ReadPropertyWithDefault>(200, "subquery", result->subquery); deserializer.ReadPropertyWithDefault>(201, "column_name_alias", result->column_name_alias); + deserializer.ReadPropertyWithExplicitDefault(202, "lateral", result->lateral, SubqueryLateralType::UNRECORDED); return std::move(result); } diff --git a/src/duckdb/src/storage/standard_buffer_manager.cpp b/src/duckdb/src/storage/standard_buffer_manager.cpp index 126c64524..2fc783212 100644 --- a/src/duckdb/src/storage/standard_buffer_manager.cpp +++ b/src/duckdb/src/storage/standard_buffer_manager.cpp @@ -851,12 +851,16 @@ data_ptr_t BufferAllocatorData::Reallocate(data_ptr_t pointer, idx_t old_size, i if (old_size == size) { return pointer; } + // Keep logical growth charged while BlockAllocator decides whether optional rounding fits. This does not + // impose admission on the required bytes, and failure releases only this provisional growth. + TempBufferPoolReservation growth(MemoryTag::ALLOCATOR, manager.GetBufferPool(), + size > old_size ? size - old_size : 0); auto result = BlockAllocator::Get(manager.db).ReallocateData(pointer, old_size, size); - // Reallocation only adjusts accounting, and backing failure must leave the old reservation intact. - BufferPoolReservation reservation(MemoryTag::ALLOCATOR, manager.GetBufferPool()); - reservation.size = old_size; - reservation.Resize(size); - reservation.size = 0; + if (size < old_size) { + // Release logical shrinkage only after the allocator has accounted any newly retained padding. + Release(old_size - size); + } + growth.size = 0; return result; } @@ -875,23 +879,24 @@ HugeAllocation BufferAllocator::AllocateHuge(idx_t size) { D_ASSERT(size > 0); auto &data = GetPrivateData()->Cast(); auto reservation = data.Reserve(size); - optional_idx home; - auto pointer = BlockAllocator::Get(data.manager.GetDatabase()).AllocateHugeData(size, home); + auto pointer = BlockAllocator::Get(data.manager.GetDatabase()).AllocateHugeData(size); reservation.size = 0; - return HugeAllocation(*this, pointer, size, home); + return HugeAllocation(*this, pointer, size); } -void BufferAllocator::FreeHuge(data_ptr_t pointer, idx_t size, optional_idx home) { - auto &data = GetPrivateData()->Cast(); - data.Release(size); - BlockAllocator::Get(data.manager.GetDatabase()).FreeHugeData(pointer, size, home); +optional_idx HugeAllocation::GetAllocationShard() const { + if (!pointer) { + return optional_idx(); + } + const auto &data = allocator.get_mutable()->GetPrivateData()->Cast(); + return BlockAllocator::Get(data.manager.GetDatabase()).GetAllocationShard(pointer, allocated_size); } HugeAllocation::HugeAllocation() : allocator(nullptr), pointer(nullptr), allocated_size(0) { } -HugeAllocation::HugeAllocation(BufferAllocator &allocator, data_ptr_t pointer, idx_t allocated_size, optional_idx home) - : allocator(allocator), pointer(pointer), allocated_size(allocated_size), allocation_shard(home) { +HugeAllocation::HugeAllocation(BufferAllocator &allocator, data_ptr_t pointer, idx_t allocated_size) + : allocator(allocator), pointer(pointer), allocated_size(allocated_size) { D_ASSERT(pointer); } @@ -903,14 +908,12 @@ HugeAllocation::HugeAllocation(HugeAllocation &&other) noexcept : allocator(other.allocator), pointer(nullptr), allocated_size(0) { std::swap(pointer, other.pointer); std::swap(allocated_size, other.allocated_size); - std::swap(allocation_shard, other.allocation_shard); } HugeAllocation &HugeAllocation::operator=(HugeAllocation &&other) noexcept { std::swap(allocator, other.allocator); std::swap(pointer, other.pointer); std::swap(allocated_size, other.allocated_size); - std::swap(allocation_shard, other.allocation_shard); return *this; } @@ -919,10 +922,9 @@ void HugeAllocation::Reset() { return; } D_ASSERT(allocator); - allocator->FreeHuge(pointer, allocated_size, allocation_shard); + allocator->GetPrivateData()->Cast().Free(pointer, allocated_size); pointer = nullptr; allocated_size = 0; - allocation_shard = optional_idx(); } BufferAllocator &BufferAllocator::Get(ClientContext &context) { diff --git a/src/duckdb/src/storage/statistics/distinct_statistics.cpp b/src/duckdb/src/storage/statistics/distinct_statistics.cpp index da67816f0..3ac828a3d 100644 --- a/src/duckdb/src/storage/statistics/distinct_statistics.cpp +++ b/src/duckdb/src/storage/statistics/distinct_statistics.cpp @@ -1,4 +1,5 @@ #include "duckdb/storage/statistics/distinct_statistics.hpp" +#include "duckdb/common/no_destructor.hpp" #include "duckdb/common/random_engine.hpp" #include "duckdb/common/string_util.hpp" @@ -120,11 +121,11 @@ void DistinctStatistics::UpdateSample(const Vector &new_data, idx_t count, Vecto return; } - static auto integral_sample = - CreateSampleSelection(MaxValue(LossyNumericCast(INTEGRAL_SAMPLE_RATE * STANDARD_VECTOR_SIZE), 1)); - static auto other_sample = - CreateSampleSelection(MaxValue(LossyNumericCast(BASE_SAMPLE_RATE * STANDARD_VECTOR_SIZE), 1)); - auto &sample_selection = new_data.GetType().IsIntegral() ? integral_sample : other_sample; + static NoDestructor integral_sample(CreateSampleSelection( + MaxValue(LossyNumericCast(INTEGRAL_SAMPLE_RATE * STANDARD_VECTOR_SIZE), 1))); + static NoDestructor other_sample( + CreateSampleSelection(MaxValue(LossyNumericCast(BASE_SAMPLE_RATE * STANDARD_VECTOR_SIZE), 1))); + auto &sample_selection = new_data.GetType().IsIntegral() ? *integral_sample : *other_sample; if (TryUpdateSampleValues(*log, new_data, sample_selection, count)) { sample_count += count; return; diff --git a/src/duckdb/src/storage/statistics/struct_stats.cpp b/src/duckdb/src/storage/statistics/struct_stats.cpp index a144b9595..1a237861b 100644 --- a/src/duckdb/src/storage/statistics/struct_stats.cpp +++ b/src/duckdb/src/storage/statistics/struct_stats.cpp @@ -128,6 +128,14 @@ child_list_t StructStats::ToStruct(const BaseStatistics &stats, bool exac for (idx_t i = 0; i < child_types.size(); i++) { child_info.emplace_back(child_types[i].first, stats.child_stats[i].ToStruct(exact)); } + if (StructType::IsUnnamed(stats.GetType())) { + vector tuple_children; + for (auto &child : child_info) { + tuple_children.push_back(std::move(child.second)); + } + result.emplace_back("child_stats", Value::TUPLE(std::move(tuple_children))); + return result; + } result.emplace_back("child_stats", Value::STRUCT(std::move(child_info))); return result; } diff --git a/src/duckdb/src/storage/storage_manager.cpp b/src/duckdb/src/storage/storage_manager.cpp index 9290198e7..82ed4603d 100644 --- a/src/duckdb/src/storage/storage_manager.cpp +++ b/src/duckdb/src/storage/storage_manager.cpp @@ -8,6 +8,8 @@ #include "duckdb/common/type_visitor.hpp" #include "duckdb/common/types/decimal.hpp" #include "duckdb/parser/expression/cast_expression.hpp" +#include "duckdb/parser/expression/function_expression.hpp" +#include "duckdb/parser/expression/window_expression.hpp" #include "duckdb/parser/expression/subquery_expression.hpp" #include "duckdb/parser/parsed_expression_iterator.hpp" #include "duckdb/parser/query_node.hpp" @@ -346,6 +348,10 @@ string StorageManager::GetUnsupportedTypeReason(const LogicalType &logical_type) case LogicalTypeId::STRUCT: if (storage_version < StorageVersion::V2_0_0 && StructType::GetChildCount(type) == 0) { reason = unsupported("Empty STRUCT columns", StorageVersion::V2_0_0); + } else if (storage_version < EMPTY_MEMBER_NAMES_VERSION_ADDED && IsLoaded() && + StructType::AllUnnamed(StructType::GetChildTypes(type))) { + // older engines read a STRUCT with only empty member names as a TUPLE + reason = unsupported("STRUCT columns with only empty member names", EMPTY_MEMBER_NAMES_VERSION_ADDED); } break; case LogicalTypeId::TUPLE: @@ -449,6 +455,75 @@ void StorageManager::CheckQueryDecimalsAreSupported(QueryNode &node) const { node, [&](unique_ptr &child) { CheckExpressionDecimalsAreSupported(*child); }); } +bool StorageManager::ContainsAllEmptyNamesStruct(const LogicalType &type) { + return TypeVisitor::Contains(type, [](const LogicalType &child) { + return child.id() == LogicalTypeId::STRUCT && child.HasParameters() && + StructType::AllUnnamed(StructType::GetChildTypes(child)); + }); +} + +void StorageManager::CheckEmptyMemberNamesAreSupported(const LogicalType &type, const string &subject) const { + if (GetStorageVersion() >= EMPTY_MEMBER_NAMES_VERSION_ADDED || !ContainsAllEmptyNamesStruct(type)) { + return; + } + throw InvalidInputException(GetUnsupportedPriorToVersionReason( + StringUtil::Format("STRUCT %s with only empty member names", subject), EMPTY_MEMBER_NAMES_VERSION_ADDED)); +} + +static bool HasEmptyArgumentName(const vector &arguments) { + for (auto &argument : arguments) { + if (argument.HasName() && argument.GetName().empty()) { + return true; + } + } + return false; +} + +void StorageManager::CheckExpressionEmptyMemberNamesAreSupported(const ParsedExpression &expression) const { + if (GetStorageVersion() >= EMPTY_MEMBER_NAMES_VERSION_ADDED) { + return; + } + // a work list instead of recursion, the expression tree is user data + vector> work; + work.emplace_back(expression); + while (!work.empty()) { + auto &expr = work.back().get(); + work.pop_back(); + bool empty_argument_name = false; + switch (expr.GetExpressionClass()) { + case ExpressionClass::FUNCTION: + empty_argument_name = HasEmptyArgumentName(expr.Cast().GetArguments()); + break; + case ExpressionClass::WINDOW: + empty_argument_name = HasEmptyArgumentName(expr.Cast().GetArguments()); + break; + case ExpressionClass::CAST: + CheckEmptyMemberNamesAreSupported(UnboundType::TryDefaultBind(expr.Cast().TargetType()), + "casts"); + break; + case ExpressionClass::SUBQUERY: + CheckQueryEmptyMemberNamesAreSupported(*expr.Cast().Subquery()->node); + break; + default: + break; + } + if (empty_argument_name) { + throw InvalidInputException(GetUnsupportedPriorToVersionReason( + "Empty STRUCT member names in stored expressions", EMPTY_MEMBER_NAMES_VERSION_ADDED)); + } + ParsedExpressionIterator::EnumerateChildren(expr, + [&](const ParsedExpression &child) { work.emplace_back(child); }); + } +} + +void StorageManager::CheckQueryEmptyMemberNamesAreSupported(QueryNode &node) const { + if (GetStorageVersion() >= EMPTY_MEMBER_NAMES_VERSION_ADDED) { + return; + } + ParsedExpressionIterator::EnumerateQueryNodeChildren( + node, [&](unique_ptr &child) { CheckExpressionEmptyMemberNamesAreSupported(*child); }); +} + bool StorageManager::HasWAL() const { if (InMemory() || read_only || !load_complete) { return false; diff --git a/src/duckdb/src/storage/table/chunk_info.cpp b/src/duckdb/src/storage/table/chunk_info.cpp index 0a9b01319..ecd98eca5 100644 --- a/src/duckdb/src/storage/table/chunk_info.cpp +++ b/src/duckdb/src/storage/table/chunk_info.cpp @@ -68,7 +68,8 @@ static bool IsDeleteId(transaction_t id) { return id < UPDATE_MARKER_BIT; } -//! Whether writing new_id into a row conflicts with its id: a write by a transaction that the writer does not see +//! Whether writing new_id into a row conflicts with its id: a write by a transaction that the writer does not see, +//! or a delete that it sees static bool IsConflictingId(TransactionData transaction, transaction_t id, transaction_t new_id) { if (id == NOT_DELETED_ID || id == new_id) { return false; @@ -76,15 +77,9 @@ static bool IsConflictingId(TransactionData transaction, transaction_t id, trans if (!transaction.view.Sees(GetWriter(id))) { return true; } - if (IsDeleteId(id)) { - if (GetWriter(id) == GetWriter(new_id)) { - // a concurrent statement of this transaction deleted the row after this write found it - return true; - } - // a transaction cannot see a row whose delete it sees, so it never writes it - throw InternalException("ChunkVectorInfo: write of a row whose delete the transaction sees"); - } - return false; + // a delete the writer sees: a concurrent statement of this transaction that deleted the row after this write + // found it, a MERGE that matches the row twice, or the replay of a WAL that deletes it twice + return IsDeleteId(id); } ChunkVectorInfo::ChunkVectorInfo(FixedSizeAllocator &allocator_p, idx_t start, transaction_t insert_id_p) @@ -176,10 +171,9 @@ idx_t ChunkVectorInfo::TemplatedGetSelVector(const SnapshotView &view, optional_ } continue; } + // deleted rows are often scattered, so a branch per row mispredicts for (idx_t i = base; i < entry_end; i++) { - if (!ValidityMask::RowIsValid(entry, i - base)) { - sel_vector->set_index(count++, i); - } + sel_vector->AppendIf(count, i, !ValidityMask::RowIsValid(entry, i - base)); } } return count; @@ -213,14 +207,15 @@ idx_t ChunkVectorInfo::TemplatedGetSelVector(const SnapshotView &view, optional_ idx_t count = 0; auto segment = allocator.GetHandle(GetDeletedPointer()); auto deleted = segment.GetPtr(); - for (idx_t i = 0; i < max_count; i++) { - if (DELETE_OP::IsDeleted(view, deleted[i])) { - continue; - } - if (sel_vector) { - sel_vector->set_index(count, i); + if (!sel_vector) { + for (idx_t i = 0; i < max_count; i++) { + count += !DELETE_OP::IsDeleted(view, deleted[i]); } - count++; + return count; + } + // deleted rows are often scattered, so a branch per row mispredicts + for (idx_t i = 0; i < max_count; i++) { + sel_vector->AppendIf(count, i, !DELETE_OP::IsDeleted(view, deleted[i])); } return count; } diff --git a/src/duckdb/src/storage/table/geo_column_data.cpp b/src/duckdb/src/storage/table/geo_column_data.cpp index bd3b990fd..444656725 100644 --- a/src/duckdb/src/storage/table/geo_column_data.cpp +++ b/src/duckdb/src/storage/table/geo_column_data.cpp @@ -58,6 +58,15 @@ void GeoColumnData::InitializeScanWithOffset(ColumnScanState &state, idx_t row_i return base_column->InitializeScanWithOffset(state, row_idx); } +FilterPropagateResult GeoColumnData::CheckZonemap(ColumnScanState &state, const ScanFilter &filter, + optional_idx &checked_end) { + // Only the outer validity of an encoded geometry describes the logical rows. + if (storage_type != GeometryStorageType::WKB && !IsDirectNullCheckFilter(filter.filter)) { + return FilterPropagateResult::NO_PRUNING_POSSIBLE; + } + return base_column->CheckZonemap(state, filter, checked_end); +} + idx_t GeoColumnData::Scan(TransactionData transaction, idx_t vector_index, ColumnScanState &state, Vector &result, idx_t target_count) { // Not a shredded column, so just emit the binary format immediately diff --git a/src/duckdb/src/storage/table/row_group.cpp b/src/duckdb/src/storage/table/row_group.cpp index 6ca2c7c5c..b1558e740 100644 --- a/src/duckdb/src/storage/table/row_group.cpp +++ b/src/duckdb/src/storage/table/row_group.cpp @@ -10,7 +10,10 @@ #include "duckdb/common/serializer/serializer.hpp" #include "duckdb/common/typedefs.hpp" #include "duckdb/common/types/vector.hpp" +#include "duckdb/common/vector/array_vector.hpp" #include "duckdb/common/vector/flat_vector.hpp" +#include "duckdb/common/vector/list_vector.hpp" +#include "duckdb/common/vector/struct_vector.hpp" #include "duckdb/execution/adaptive_filter.hpp" #include "duckdb/execution/expression_executor.hpp" #include "duckdb/planner/filter/expression_filter.hpp" @@ -717,44 +720,34 @@ FilterPropagateResult RowGroup::CheckRowIdFilter(const TableFilter &filter, idx_ } bool RowGroup::CheckZonemap(optional_ptr context, ScanFilterInfo &filters, idx_t row_start) { - const auto table_filters = filters.GetTableFilters(); - const auto column_ids = filters.GetColumnIds(); - if (table_filters && column_ids) { - for (const auto &filter : table_filters->GetMultiColumnFilters()) { - const auto &expression_filter = ExpressionFilter::GetExpressionFilter(*filter, "RowGroup::CheckZonemap"); - vector input_stats; - input_stats.reserve(expression_filter.column_indexes.size()); - bool supported = true; - for (const auto &column_index : expression_filter.column_indexes) { - if (column_index.GetIndex() >= column_ids->size()) { - throw InternalException("Multi-column filter column index out of range"); - } - const auto &storage_index = (*column_ids)[column_index.GetIndex()]; - if (storage_index.IsRowIdColumn()) { - input_stats.push_back(CreateRowIdStats(row_start, row_start + count)); - continue; - } - if (storage_index.IsRowNumberColumn()) { - supported = false; - break; - } - auto column_stats = GetStatistics(storage_index); - if (!column_stats) { - supported = false; - break; - } - input_stats.push_back(column_stats->Copy()); - } - if (!supported) { + for (const auto &filter : filters.GetPruningFilters()) { + vector input_stats; + input_stats.reserve(filter.column_ids.size()); + bool supported = true; + for (const auto &storage_index : filter.column_ids) { + if (storage_index.IsRowIdColumn()) { + input_stats.push_back(CreateRowIdStats(row_start, row_start + count)); continue; } - const auto prune_result = ExpressionFilter::CheckExpressionStatistics( - context, *expression_filter.expr, - array_ptr(input_stats.data(), input_stats.size())); - if (prune_result == FilterPropagateResult::FILTER_ALWAYS_FALSE || - prune_result == FilterPropagateResult::FILTER_FALSE_OR_NULL) { - return false; + if (storage_index.IsRowNumberColumn()) { + supported = false; + break; + } + auto column_stats = GetStatistics(storage_index); + if (!column_stats) { + supported = false; + break; } + input_stats.push_back(std::move(*column_stats)); + } + if (!supported) { + continue; + } + const auto prune_result = ExpressionFilter::CheckExpressionStatistics( + context, *filter.expression, array_ptr(input_stats.data(), input_stats.size())); + if (prune_result == FilterPropagateResult::FILTER_ALWAYS_FALSE || + prune_result == FilterPropagateResult::FILTER_FALSE_OR_NULL) { + return false; } } auto &filter_list = filters.GetFilterList(); @@ -973,6 +966,106 @@ bool RowGroup::PrepareScan(ScanOptions options, CollectionScanState &state) { } } +[[noreturn]] static void ThrowEnumValueOutOfRange(idx_t value, idx_t enum_size) { + throw DataCorruptionException("ENUM value %llu is out of range for an ENUM type with %llu values", value, + enum_size); +} + +//! Whether an entry of the ENUM vector, NULL or not, is not a position in the dictionary +template +static bool HasEnumValueOutOfRange(const Vector &vector, idx_t enum_size) { + if (enum_size > NumericLimits::Maximum()) { + return false; + } + T max_value = 0; + auto values = vector.Values(); + for (idx_t i = 0; i < values.size(); i++) { + max_value = MaxValue(max_value, values.GetValueUnsafe(i)); + } + return max_value >= enum_size; +} + +static bool HasEnumValueOutOfRange(const Vector &vector) { + auto &type = vector.GetType(); + switch (type.id()) { + case LogicalTypeId::ENUM: { + auto enum_size = EnumType::GetSize(type); + switch (type.InternalType()) { + case PhysicalType::UINT8: + return HasEnumValueOutOfRange(vector, enum_size); + case PhysicalType::UINT16: + return HasEnumValueOutOfRange(vector, enum_size); + case PhysicalType::UINT32: + return HasEnumValueOutOfRange(vector, enum_size); + default: + throw InternalException("ENUM can only have unsigned integers (except UINT64) as physical types"); + } + } + case LogicalTypeId::STRUCT: + case LogicalTypeId::UNION: + for (auto &child : StructVector::GetEntries(vector)) { + if (HasEnumValueOutOfRange(child)) { + return true; + } + } + return false; + case LogicalTypeId::LIST: + case LogicalTypeId::MAP: + return HasEnumValueOutOfRange(ListVector::GetChild(vector)); + case LogicalTypeId::ARRAY: + return HasEnumValueOutOfRange(ArrayVector::GetChild(vector)); + default: + return false; + } +} + +static void VerifyEnumValue(const Value &value) { + if (value.IsNull()) { + return; + } + auto &type = value.type(); + switch (type.id()) { + case LogicalTypeId::ENUM: { + auto enum_value = value.GetValue(); + if (enum_value >= EnumType::GetSize(type)) { + ThrowEnumValueOutOfRange(enum_value, EnumType::GetSize(type)); + } + break; + } + case LogicalTypeId::STRUCT: + case LogicalTypeId::UNION: + for (auto &child : StructValue::GetChildren(value)) { + VerifyEnumValue(child); + } + break; + case LogicalTypeId::LIST: + case LogicalTypeId::MAP: + for (auto &child : ListValue::GetChildren(value)) { + VerifyEnumValue(child); + } + break; + case LogicalTypeId::ARRAY: + for (auto &child : ArrayValue::GetChildren(value)) { + VerifyEnumValue(child); + } + break; + default: + break; + } +} + +void RowGroup::VerifyScannedValues(const DataChunk &chunk) { + for (auto &vector : chunk.data) { + // the entry of a NULL can hold anything: only look at the validity if an entry is out of range + if (!HasEnumValueOutOfRange(vector)) { + continue; + } + for (idx_t row = 0; row < chunk.size(); row++) { + VerifyEnumValue(vector.GetValue(row)); + } + } +} + void RowGroup::ProcessPreparedScan(ScanOptions options, CollectionScanState &state, DataChunk &result) { const auto &column_ids = state.GetColumnIds(); auto &filter_info = state.GetFilterInfo(); @@ -1093,6 +1186,7 @@ void RowGroup::ProcessPreparedScan(ScanOptions options, CollectionScanState &sta count = approved_tuple_count; } result.SetChildCardinality(count); + VerifyScannedValues(result); FinishVector(state); } @@ -1142,7 +1236,8 @@ void RowGroup::Scan(CollectionScanState &state, DataChunk &result, TableScanType // RowGroupVersionInfo //===--------------------------------------------------------------------===// RowGroupVersionInfo::RowGroupVersionInfo(vector deletes_pointers_p) - : deletes_pointers(std::move(deletes_pointers_p)), deletes_is_loaded(false), version_info(nullptr) { + : deletes_pointers(std::move(deletes_pointers_p)), deletes_is_loaded(false), has_reverted_appends(false), + version_info(nullptr) { } bool RowGroupVersionInfo::HasUnloadedDeletes() const { @@ -1274,6 +1369,8 @@ void RowGroup::RevertAppend(idx_t new_count) { if (new_count > this->count) { throw InternalException("RowGroup::RevertAppend new_count out of range"); } + // set before reverting: once the reverted rows look visible, readers must already see the flag + version_info->MarkRevertedAppend(); // version info or columns that are not loaded hold no appended rows auto vinfo = GetVersionInfoIfLoaded(); if (vinfo) { @@ -1713,7 +1810,7 @@ RowGroupWriteData RowGroup::WriteToDisk(RowGroupWriter &writer) { auto result_row_group = make_shared_ptr(GetCollection(), this->count); result_row_group->columns.resize(GetColumnCount()); result_row_group->column_pointers.resize(GetColumnCount()); - // the rewritten row group shares the version info: deletes stay visible through both + // the rewritten row group shares the version info: deletes and reverted appends stay visible through both result_row_group->version_info = version_info; if (is_loaded) { result_row_group->is_loaded = unique_ptr[]>(new atomic[GetColumnCount()]); @@ -2114,7 +2211,8 @@ PartitionStatistics RowGroup::GetPartitionStats(SegmentNode &row_group result.count = row_group_ref.count; } result.count_type = has_uncommitted_changes ? CountType::COUNT_APPROXIMATE : CountType::COUNT_EXACT; - const bool is_exact = result.count == row_group_ref.count && (!vinfo || !vinfo->HasDeletes()); + const bool is_exact = result.count == row_group_ref.count && (!vinfo || !vinfo->HasDeletes()) && + !row_group_ref.version_info->HasRevertedAppends(); result.partition_row_group = make_shared_ptr(row_group.ReferenceNode(), is_exact); return result; @@ -2133,6 +2231,9 @@ bool RowGroup::ColumnStatsReflectVisibleRows(const StorageIndex &column_idx, Tra return false; } } + if (version_info->HasRevertedAppends()) { + return false; + } auto primary_idx = column_idx.GetPrimaryIndex(); if (ColumnIsLoaded(primary_idx) && GetColumn(primary_idx).HasAnyUpdates()) { return false; diff --git a/src/duckdb/src/storage/table/scan_state.cpp b/src/duckdb/src/storage/table/scan_state.cpp index acc899edb..e0a016599 100644 --- a/src/duckdb/src/storage/table/scan_state.cpp +++ b/src/duckdb/src/storage/table/scan_state.cpp @@ -3,6 +3,9 @@ #include "duckdb/execution/adaptive_filter.hpp" #include "duckdb/parallel/async_result.hpp" #include "duckdb/logging/logger.hpp" +#include "duckdb/planner/expression/bound_function_expression.hpp" +#include "duckdb/planner/filter/expression_filter.hpp" +#include "duckdb/planner/filter/table_filter_functions.hpp" #include "duckdb/storage/table/column_data.hpp" #include "duckdb/storage/table/column_segment.hpp" #include "duckdb/storage/table/row_group.hpp" @@ -26,10 +29,14 @@ TableScanState::~TableScanState() { void TableScanState::Initialize(vector column_ids_p, optional_ptr context, optional_ptr table_filters, optional_ptr table_sampling, idx_t estimated_table_row_count) { - this->column_ids = std::move(column_ids_p); - if (table_filters) { - filters.Initialize(*context, *table_filters, column_ids); - } + Initialize(TableScanInput(std::move(column_ids_p), table_filters), context, table_sampling, + estimated_table_row_count); +} + +void TableScanState::Initialize(TableScanInput input, optional_ptr context, + optional_ptr table_sampling, idx_t estimated_table_row_count) { + filters.Initialize(context, input); + column_ids = std::move(input.column_ids); if (table_sampling) { sampling_info.do_system_sample = table_sampling->method == SampleMethod::SYSTEM_SAMPLE; if (table_sampling->is_percentage) { @@ -63,7 +70,7 @@ void TableScanState::Initialize(vector column_ids_p, optional_ptr< } const vector &TableScanState::GetColumnIds() { - D_ASSERT(!column_ids.empty()); + // a scan can be initialized without columns - it then only produces the cardinality return column_ids; } @@ -88,22 +95,55 @@ ScanFilter::ScanFilter(ClientContext &context, ProjectionIndex index, const vect filter_state = TableFilterState::Initialize(context, filter); } -void ScanFilterInfo::Initialize(ClientContext &context, TableFilterSet &filters, - const vector &column_ids) { - D_ASSERT(filters.HasFilters() || filters.HasMultiColumnFilters()); - table_filters = &filters; - this->column_ids = &column_ids; - if (filters.HasFilters()) { - adaptive_filter = make_uniq(filters); - adaptive_filter->SetLogger(context.GetContext().GetLoggerPtr()); +ScanFilterPruningState::ScanFilterPruningState(const ExpressionFilter &filter, const vector &scan_columns) + : expression(ExpandOptionalFilterExpression(filter.expr->Cast())) { + column_ids.reserve(filter.column_indexes.size()); + for (const auto &index : filter.column_indexes) { + if (index.GetIndex() >= scan_columns.size()) { + throw InternalException("Multi-column filter column index out of range"); + } + column_ids.push_back(scan_columns[index.GetIndex()]); } - filter_list.reserve(filters.FilterCount()); - for (auto &entry : filters) { - filter_list.emplace_back(context, entry.GetIndex(), column_ids, entry.Filter()); +} + +TableScanInput::TableScanInput(vector column_ids_p, optional_ptr filters_p) + : column_ids(std::move(column_ids_p)), filters(filters_p) { + if (!filters || !filters->HasMultiColumnFilters()) { + return; + } + auto result = make_shared_ptr>(); + result->reserve(filters->GetMultiColumnFilters().size()); + for (const auto &filter : filters->GetMultiColumnFilters()) { + result->emplace_back(ExpressionFilter::GetExpressionFilter(*filter, "TableScanInput"), column_ids); + } + pruning_filters = std::move(result); +} + +void ScanFilterInfo::Initialize(optional_ptr context, TableScanInput &input) { + auto filters = input.filters; + const auto &column_ids = input.column_ids; + pruning_filters = std::move(input.pruning_filters); + adaptive_filter.reset(); + filter_list.clear(); + column_has_filter.clear(); + base_column_has_filter.clear(); + always_true_filters = 0; + if (!filters) { + return; + } + D_ASSERT(filters->HasAnyFilters()); + D_ASSERT(context); + if (filters->HasFilters()) { + adaptive_filter = make_uniq(*filters); + adaptive_filter->SetLogger(context->GetContext().GetLoggerPtr()); + } + filter_list.reserve(filters->FilterCount()); + for (auto &entry : *filters) { + filter_list.emplace_back(*context, entry.GetIndex(), column_ids, entry.Filter()); } column_has_filter.reserve(column_ids.size()); for (auto col_idx : ProjectionIndex::GetIndexes(column_ids.size())) { - bool has_filter = table_filters->HasFilter(col_idx); + bool has_filter = filters->HasFilter(col_idx); column_has_filter.push_back(has_filter); } base_column_has_filter = column_has_filter; @@ -118,10 +158,6 @@ bool ScanFilterInfo::ColumnHasFilters(idx_t column_idx) { } bool ScanFilterInfo::HasFilters() const { - if (!table_filters) { - // no filters - return false; - } // if we have filters - check if we need to check any of them return always_true_filters < filter_list.size(); } @@ -400,7 +436,7 @@ bool CollectionScanState::InitializeRowGroupScan(SegmentNode &node, sh if (max_row_group_row == 0) { return false; } - D_ASSERT(!column_scans.empty()); + D_ASSERT(column_scans.size() == GetColumnIds().size()); return true; } diff --git a/src/duckdb/src/storage/wal_replay.cpp b/src/duckdb/src/storage/wal_replay.cpp index 04f407efc..a72c82d75 100644 --- a/src/duckdb/src/storage/wal_replay.cpp +++ b/src/duckdb/src/storage/wal_replay.cpp @@ -6,6 +6,7 @@ #include "duckdb/common/checksum.hpp" #include "duckdb/common/encryption_functions.hpp" #include "duckdb/common/encryption_key_manager.hpp" +#include "duckdb/common/exception/transaction_exception.hpp" #include "duckdb/common/numeric_utils.hpp" #include "duckdb/common/serializer/binary_deserializer.hpp" #include "duckdb/common/serializer/buffered_file_reader.hpp" @@ -1437,7 +1438,12 @@ void WriteAheadLogDeserializer::ReplayDelete() { } } TableDeleteState delete_state; - storage.Delete(delete_state, context, *state.current_table, row_identifiers, chunk.size()); + try { + storage.Delete(delete_state, context, *state.current_table, row_identifiers, chunk.size()); + } catch (TransactionException &) { + // nothing runs next to the replay, so the conflict is with an earlier entry of the WAL + throw DataCorruptionException("Corrupt WAL: delete of a row that is already deleted"); + } } void WriteAheadLogDeserializer::ReplayUpdate() { diff --git a/src/duckdb/src/transaction/commit_state.cpp b/src/duckdb/src/transaction/commit_state.cpp index dd74a7341..07cd7d3b6 100644 --- a/src/duckdb/src/transaction/commit_state.cpp +++ b/src/duckdb/src/transaction/commit_state.cpp @@ -276,6 +276,7 @@ void CommitState::CommitEntryDrop(CatalogEntry &entry, data_ptr_t dataptr, Commi case CatalogType::PREPARED_STATEMENT: case CatalogType::AGGREGATE_FUNCTION_ENTRY: case CatalogType::SCALAR_FUNCTION_ENTRY: + case CatalogType::WINDOW_FUNCTION_ENTRY: case CatalogType::TABLE_FUNCTION_ENTRY: case CatalogType::COPY_FUNCTION_ENTRY: case CatalogType::PRAGMA_FUNCTION_ENTRY: diff --git a/src/duckdb/src/transaction/wal_write_state.cpp b/src/duckdb/src/transaction/wal_write_state.cpp index e72566629..bbe714199 100644 --- a/src/duckdb/src/transaction/wal_write_state.cpp +++ b/src/duckdb/src/transaction/wal_write_state.cpp @@ -170,6 +170,7 @@ void WALWriteState::WriteCatalogEntry(CatalogEntry &entry, data_ptr_t dataptr) { case CatalogType::PREPARED_STATEMENT: case CatalogType::AGGREGATE_FUNCTION_ENTRY: case CatalogType::SCALAR_FUNCTION_ENTRY: + case CatalogType::WINDOW_FUNCTION_ENTRY: case CatalogType::TABLE_FUNCTION_ENTRY: case CatalogType::COPY_FUNCTION_ENTRY: case CatalogType::PRAGMA_FUNCTION_ENTRY: diff --git a/src/duckdb/third_party/mbedtls/include/mbedtls/mbedtls_config.h b/src/duckdb/third_party/mbedtls/include/mbedtls/mbedtls_config.h index 65943829c..c2bad6b6e 100644 --- a/src/duckdb/third_party/mbedtls/include/mbedtls/mbedtls_config.h +++ b/src/duckdb/third_party/mbedtls/include/mbedtls/mbedtls_config.h @@ -3,6 +3,8 @@ // that break if mbedtls features are changed #define MBEDTLS_AES_C +// static AES tables: the lazily generated ones are not thread-safe +#define MBEDTLS_AES_ROM_TABLES #define MBEDTLS_ASN1_PARSE_C #define MBEDTLS_ASN1_WRITE_C #define MBEDTLS_BASE64_C diff --git a/src/duckdb/ub_src_common.cpp b/src/duckdb/ub_src_common.cpp index f3ed364b0..2dac30ae5 100644 --- a/src/duckdb/ub_src_common.cpp +++ b/src/duckdb/ub_src_common.cpp @@ -74,6 +74,8 @@ #include "src/common/optional_idx.cpp" +#include "src/common/partition_selection.cpp" + #include "src/common/path.cpp" #include "src/common/pipe_file_system.cpp" diff --git a/src/duckdb/ub_src_common_vector.cpp b/src/duckdb/ub_src_common_vector.cpp index d39612ab6..78e24b809 100644 --- a/src/duckdb/ub_src_common_vector.cpp +++ b/src/duckdb/ub_src_common_vector.cpp @@ -14,6 +14,8 @@ #include "src/common/vector/sequence_vector.cpp" +#include "src/common/vector/shared_child_vector.cpp" + #include "src/common/vector/shredded_vector.cpp" #include "src/common/vector/string_vector.cpp" diff --git a/src/duckdb/ub_src_execution_index_art.cpp b/src/duckdb/ub_src_execution_index_art.cpp index 226099a8d..3811922a8 100644 --- a/src/duckdb/ub_src_execution_index_art.cpp +++ b/src/duckdb/ub_src_execution_index_art.cpp @@ -28,7 +28,5 @@ #include "src/execution/index/art/node_handle.cpp" -#include "src/execution/index/art/prefix.cpp" - #include "src/execution/index/art/prefix_handle.cpp" diff --git a/src/duckdb/ub_src_function_table.cpp b/src/duckdb/ub_src_function_table.cpp index 616f221a3..7688ab142 100644 --- a/src/duckdb/ub_src_function_table.cpp +++ b/src/duckdb/ub_src_function_table.cpp @@ -24,6 +24,8 @@ #include "src/function/table/repeat_row.cpp" +#include "src/function/table/simple_table_function.cpp" + #include "src/function/table/sniff_csv.cpp" #include "src/function/table/summary.cpp" diff --git a/src/duckdb/ub_src_function_table_system.cpp b/src/duckdb/ub_src_function_table_system.cpp index 52e918ecb..7d6b5a40c 100644 --- a/src/duckdb/ub_src_function_table_system.cpp +++ b/src/duckdb/ub_src_function_table_system.cpp @@ -28,6 +28,8 @@ #include "src/function/table/system/duckdb_grammar_extensions.cpp" +#include "src/function/table/system/duckdb_index_types.cpp" + #include "src/function/table/system/duckdb_indexes.cpp" #include "src/function/table/system/duckdb_keywords.cpp" @@ -38,6 +40,8 @@ #include "src/function/table/system/duckdb_log_contexts.cpp" +#include "src/function/table/system/duckdb_log_types.cpp" + #include "src/function/table/system/duckdb_memory.cpp" #include "src/function/table/system/duckdb_metrics.cpp" diff --git a/src/duckdb/ub_src_optimizer.cpp b/src/duckdb/ub_src_optimizer.cpp index c22328768..0d84b16bf 100644 --- a/src/duckdb/ub_src_optimizer.cpp +++ b/src/duckdb/ub_src_optimizer.cpp @@ -1,3 +1,5 @@ +#include "src/optimizer/aggregate_filter_extractor.cpp" + #include "src/optimizer/aggregate_function_rewriter.cpp" #include "src/optimizer/aggregate_reuse.cpp" @@ -24,9 +26,11 @@ #include "src/optimizer/constant_or_null_simplification.cpp" +#include "src/optimizer/constant_propagation.cpp" + #include "src/optimizer/cse_optimizer.cpp" -#include "src/optimizer/cte_filter_pusher.cpp" +#include "src/optimizer/cte_filter_helpers.cpp" #include "src/optimizer/cte_inlining.cpp" @@ -36,16 +40,12 @@ #include "src/optimizer/cte_runtime_filter_pushdown.cpp" -#include "src/optimizer/cte_semi_join_filter_transfer.cpp" - #include "src/optimizer/deliminator.cpp" #include "src/optimizer/disjunctive_join_rewriter.cpp" #include "src/optimizer/distinctness.cpp" -#include "src/optimizer/duplicate_eliminated_domain_optimizer.cpp" - #include "src/optimizer/empty_result_pullup.cpp" #include "src/optimizer/expression_heuristics.cpp" @@ -58,6 +58,8 @@ #include "src/optimizer/filter_pushdown.cpp" +#include "src/optimizer/filter_pushdown_guarantees.cpp" + #include "src/optimizer/filter_statistics.cpp" #include "src/optimizer/group_by_top_key.cpp" @@ -114,6 +116,8 @@ #include "src/optimizer/remove_unused_columns.cpp" +#include "src/optimizer/removed_subtree_effects.cpp" + #include "src/optimizer/row_group_pruner.cpp" #include "src/optimizer/row_number_rewriter.cpp" diff --git a/src/duckdb/ub_src_optimizer_duplicate_eliminated_domain.cpp b/src/duckdb/ub_src_optimizer_duplicate_eliminated_domain.cpp new file mode 100644 index 000000000..59901dd05 --- /dev/null +++ b/src/duckdb/ub_src_optimizer_duplicate_eliminated_domain.cpp @@ -0,0 +1,20 @@ +#include "src/optimizer/duplicate_eliminated_domain/aggregate_domain.cpp" + +#include "src/optimizer/duplicate_eliminated_domain/domain_analysis.cpp" + +#include "src/optimizer/duplicate_eliminated_domain/domain_cost_model.cpp" + +#include "src/optimizer/duplicate_eliminated_domain/domain_expression.cpp" + +#include "src/optimizer/duplicate_eliminated_domain/domain_key_lineage.cpp" + +#include "src/optimizer/duplicate_eliminated_domain/domain_optimizer.cpp" + +#include "src/optimizer/duplicate_eliminated_domain/domain_recovery.cpp" + +#include "src/optimizer/duplicate_eliminated_domain/domain_restriction.cpp" + +#include "src/optimizer/duplicate_eliminated_domain/domain_scan_source.cpp" + +#include "src/optimizer/duplicate_eliminated_domain/existence_domain.cpp" + diff --git a/src/duckdb/ub_src_optimizer_pushdown.cpp b/src/duckdb/ub_src_optimizer_pushdown.cpp index bb641e2aa..5d528ffd7 100644 --- a/src/duckdb/ub_src_optimizer_pushdown.cpp +++ b/src/duckdb/ub_src_optimizer_pushdown.cpp @@ -4,6 +4,8 @@ #include "src/optimizer/pushdown/pushdown_filter.cpp" +#include "src/optimizer/pushdown/pushdown_filter_join.cpp" + #include "src/optimizer/pushdown/pushdown_get.cpp" #include "src/optimizer/pushdown/pushdown_inner_join.cpp" @@ -14,14 +16,14 @@ #include "src/optimizer/pushdown/pushdown_mark_join.cpp" +#include "src/optimizer/pushdown/pushdown_materialized_cte.cpp" + #include "src/optimizer/pushdown/pushdown_outer_join.cpp" #include "src/optimizer/pushdown/pushdown_projection.cpp" #include "src/optimizer/pushdown/pushdown_secure_view.cpp" -#include "src/optimizer/pushdown/pushdown_semi_anti_join.cpp" - #include "src/optimizer/pushdown/pushdown_set_operation.cpp" #include "src/optimizer/pushdown/pushdown_single_join.cpp" diff --git a/src/duckdb/ub_src_optimizer_relation_statistics.cpp b/src/duckdb/ub_src_optimizer_relation_statistics.cpp index 45770beb5..47abdb331 100644 --- a/src/duckdb/ub_src_optimizer_relation_statistics.cpp +++ b/src/duckdb/ub_src_optimizer_relation_statistics.cpp @@ -1,5 +1,7 @@ #include "src/optimizer/relation_statistics/relation_statistics.cpp" +#include "src/optimizer/relation_statistics/relation_statistics_aggregate.cpp" + #include "src/optimizer/relation_statistics/relation_statistics_extractor.cpp" #include "src/optimizer/relation_statistics/relation_statistics_helper.cpp" diff --git a/src/duckdb/ub_src_storage.cpp b/src/duckdb/ub_src_storage.cpp index d45f5dcd0..101e45520 100644 --- a/src/duckdb/ub_src_storage.cpp +++ b/src/duckdb/ub_src_storage.cpp @@ -2,8 +2,6 @@ #include "src/storage/block.cpp" -#include "src/storage/block_allocator.cpp" - #include "src/storage/buffer_manager.cpp" #include "src/storage/checkpoint_manager.cpp"