OmniSciDB  c1a53651b2
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
WindowContext.h
Go to the documentation of this file.
1 /*
2  * Copyright 2022 HEAVY.AI, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include "Analyzer/Analyzer.h"
20 #include "DataMgr/Chunk/Chunk.h"
23 #include "Shared/sqltypes.h"
24 
25 #include <functional>
26 #include <unordered_map>
27 
28 // Returns true for value window functions, false otherwise.
30  switch (kind) {
36  return true;
37  default:
38  return false;
39  }
40 }
41 
42 // Returns true for aggregate window functions, false otherwise.
44  switch (kind) {
53  return true;
54  default:
55  return false;
56  }
57 }
58 
60  switch (kind) {
63  return true;
64  default:
65  return false;
66  }
67 }
68 
69 class Executor;
70 
72  std::vector<int64_t*> aggregate_tree_for_integer_type_;
73  std::vector<double*> aggregate_tree_for_double_type_;
74  std::vector<SumAndCountPair<int64_t>*> derived_aggregate_tree_for_integer_type_;
75  std::vector<SumAndCountPair<double>*> derived_aggregate_tree_for_double_type_;
77 
78  void resizeStorageForWindowFraming(size_t partition_count) {
79  aggregate_tree_for_integer_type_.resize(partition_count);
80  aggregate_tree_for_double_type_.resize(partition_count);
81  derived_aggregate_tree_for_integer_type_.resize(partition_count);
82  derived_aggregate_tree_for_double_type_.resize(partition_count);
83  }
84 };
85 
89  llvm::Value* current_row_pos_lv;
90  llvm::Value* current_col_value_lv;
92  llvm::Value* int64_t_zero_val_lv;
93  llvm::Value* int64_t_one_val_lv;
95  llvm::Value* order_key_buf_ptr_lv;
96  std::string order_type_col_name;
99  llvm::Value* nulls_first_lv;
100  llvm::Value* null_start_pos_lv;
101  llvm::Value* null_end_pos_lv;
102 };
103 
109 };
110 
111 // Per-window function context which encapsulates the logic for computing the various
112 // window function kinds and keeps ownership of buffers which contain the results. For
113 // rank functions, the code generated for the projection simply reads the values and
114 // writes them to the result set. For value and aggregate functions, only the iteration
115 // order is written to the buffer, the rest is handled by generating code in a similar
116 // way we do for non-window queries.
118  public:
119  // non-partitioned version
121  const size_t elem_count,
122  const ExecutorDeviceType device_type,
123  std::shared_ptr<RowSetMemoryOwner> row_set_mem_owner);
124 
125  // partitioned version
127  const Analyzer::WindowFunction* window_func,
128  QueryPlanHash cache_key,
129  const std::shared_ptr<HashJoin>& partitions,
130  const size_t elem_count,
131  const ExecutorDeviceType device_type,
132  std::shared_ptr<RowSetMemoryOwner> row_set_mem_owner,
133  size_t aggregation_tree_fan_out = g_window_function_aggregation_tree_fanout);
134 
136 
138 
140 
141  // Adds the order column buffer to the context and keeps ownership of it.
142  void addOrderColumn(const int8_t* column,
143  const SQLTypeInfo& ti,
144  const std::vector<std::shared_ptr<Chunk_NS::Chunk>>& chunks_owner);
145 
147 
149  const int8_t* column,
150  const std::vector<std::shared_ptr<Chunk_NS::Chunk>>& chunks_owner);
151 
152  enum class WindowComparatorResult { LT, EQ, GT };
153  using Comparator =
154  std::function<WindowFunctionContext::WindowComparatorResult(const int64_t lhs,
155  const int64_t rhs)>;
156 
157  std::vector<Comparator> createComparator(size_t partition_idx);
158 
159  // Computes the window function result to be used during the actual projection query.
160  void compute(
161  std::unordered_map<QueryPlanHash, size_t>& sorted_partition_key_ref_count_map,
162  std::unordered_map<QueryPlanHash, std::shared_ptr<std::vector<int64_t>>>&
163  sorted_partition_cache,
164  std::unordered_map<QueryPlanHash, AggregateTreeForWindowFraming>&
165  aggregate_tree_map);
166 
167  // Returns a pointer to the window function associated with this context.
169 
170  // Returns a pointer to the output buffer of the window function result.
171  const int8_t* output() const;
172 
173  // Returns a pointer to the sorted row index buffer
174  const int64_t* sortedPartition() const;
175 
176  // Returns a pointer to the value field of the aggregation state.
177  const int64_t* aggregateState() const;
178 
179  // Returns a pointer to the count field of the aggregation state.
180  const int64_t* aggregateStateCount() const;
181 
182  // Returns a handle to the pending outputs for the aggregate window function.
183  int64_t aggregateStatePendingOutputs() const;
184 
185  const int64_t* partitionStartOffset() const;
186 
187  const int64_t* partitionNumCountBuf() const;
188 
189  const std::vector<const int8_t*>& getColumnBufferForWindowFunctionExpressions() const;
190 
191  const std::vector<const int8_t*>& getOrderKeyColumnBuffers() const;
192 
193  const std::vector<SQLTypeInfo>& getOrderKeyColumnBufferTypes() const;
194 
196 
198 
200 
202 
203  size_t* getAggregateTreeDepth() const;
204 
205  size_t getAggregateTreeFanout() const;
206 
207  int64_t* getNullValueStartPos() const;
208 
209  int64_t* getNullValueEndPos() const;
210 
211  // Returns a pointer to the partition start bitmap.
212  const int8_t* partitionStart() const;
213 
214  // Returns a pointer to the partition end bitmap.
215  const int8_t* partitionEnd() const;
216 
217  // Returns the element count in the columns used by the window function.
218  size_t elementCount() const;
219 
220  const int32_t* payload() const;
221 
222  const int32_t* offsets() const;
223 
224  const int32_t* counts() const;
225 
226  size_t partitionCount() const;
227 
228  const bool needsToBuildAggregateTree() const;
229 
230  private:
231  // State for a window aggregate. The count field is only used for average.
232  struct AggregateState {
233  int64_t val;
234  int64_t count;
235  std::vector<void*> outputs;
236  llvm::Value* row_number = nullptr;
237  };
238 
239  static Comparator makeComparator(const Analyzer::ColumnVar* col_var,
240  const int8_t* partition_values,
241  const int32_t* partition_indices,
242  const bool asc_ordering,
243  const bool nulls_first);
244 
245  void computePartitionBuffer(const size_t partition_idx,
246  int64_t* output_for_partition_buff,
247  const Analyzer::WindowFunction* window_func);
248 
249  void sortPartition(const size_t partition_idx,
250  int64_t* output_for_partition_buff,
251  bool should_parallelize);
252 
253  void computeNullRangeOfSortedPartition(const SQLTypeInfo& order_col_ti,
254  size_t partition_idx,
255  const int32_t* original_col_idx_buf,
256  const int64_t* ordered_col_idx_buf);
257 
259  size_t partition_idx,
260  size_t partition_size,
261  const int32_t* original_rowid_buf,
262  const int64_t* ordered_rowid_buf,
263  const SQLTypeInfo& input_col_ti);
264 
265  void fillPartitionStart();
266 
267  void fillPartitionEnd();
268 
269  void resizeStorageForWindowFraming(bool const for_reuse = false);
270 
272 
276  // Keeps ownership of order column.
277  std::vector<std::vector<std::shared_ptr<Chunk_NS::Chunk>>> order_columns_owner_;
278  // Order column buffers.
279  std::vector<const int8_t*> order_columns_;
280  std::vector<SQLTypeInfo> order_columns_ti_;
281  // Hash table which contains the partitions specified by the window.
282  std::shared_ptr<HashJoin> partitions_;
283  // The number of elements in the table.
284  size_t elem_count_;
285  // The output of the window function.
286  int8_t* output_;
287  std::shared_ptr<std::vector<int64_t>> sorted_partition_buf_;
288  // Keeps ownership of column referenced in window function expression.
289  std::vector<std::vector<std::shared_ptr<Chunk_NS::Chunk>>>
291  // Column buffers used for window function expression
292  std::vector<const int8_t*> window_func_expr_columns_;
293  // we need to build a segment tree depending on the input column type
294  std::vector<std::shared_ptr<void>> segment_trees_owned_;
301  // Markers for partition start used to reinitialize state for aggregate window
302  // functions.
304  // Markers for partition end used to reinitialize state for aggregate window
305  // functions.
306  int8_t* partition_end_;
307  // State for aggregate function over a window.
310  std::shared_ptr<RowSetMemoryOwner> row_set_mem_owner_;
311 
312  // For use when we do not have partitions_ hash table
313  const int32_t dummy_count_;
314  const int32_t dummy_offset_;
315  // dummy_payload_ is only initialized if there is no partitions_ hash table
316  // TODO(todd): There is no need for index buffer for non-partitioned
317  // window functions, as the row to index mapping is the identity function,
318  // so refactor makeComparator and ilk to allow for this
319  int32_t* dummy_payload_;
320 };
321 
322 // Keeps track of the multiple window functions in a window query.
324  public:
326  std::unique_ptr<WindowFunctionContext> window_function_context,
327  const size_t target_index);
328 
329  // Marks the window function at the given target index as active. This simplifies the
330  // code generation since it's now context sensitive. Each value window function can
331  // have its own iteration order, therefore fetching a column at a given position
332  // changes depending on which window function is active.
334  Executor* executor,
335  const size_t target_index) const;
336 
337  // Resets the active window function, which restores the regular (non-window) codegen
338  // behavior.
339  static void resetWindowFunctionContext(Executor* executor);
340 
341  // Gets the current active window function.
342  static WindowFunctionContext* getActiveWindowFunctionContext(Executor* executor);
343 
344  // Creates the context for a window function execution unit.
345  static WindowProjectNodeContext* create(Executor* executor);
346 
347  // Retrieves the context for the active window function execution unit.
348  static const WindowProjectNodeContext* get(Executor* executor);
349 
350  // Resets the active context.
351  static void reset(Executor* executor);
352 
353  private:
354  // A map from target index to the context associated with the window function at that
355  // target index.
356  std::unordered_map<size_t, std::unique_ptr<WindowFunctionContext>> window_contexts_;
357 };
358 
360 
size_t getAggregateTreeFanout() const
Defines data structures for the semantic analysis phase of query processing.
std::vector< SumAndCountPair< double > * > derived_aggregate_tree_for_double_type_
Definition: WindowContext.h:75
void addOrderColumn(const int8_t *column, const SQLTypeInfo &ti, const std::vector< std::shared_ptr< Chunk_NS::Chunk >> &chunks_owner)
llvm::Value * num_elem_current_partition_lv
Definition: WindowContext.h:94
std::shared_ptr< RowSetMemoryOwner > row_set_mem_owner_
int64_t * ordered_partition_null_start_pos_
llvm::Value * current_col_value_lv
Definition: WindowContext.h:90
const int32_t dummy_count_
std::vector< double * > aggregate_tree_for_double_type_
Definition: WindowContext.h:73
ExecutorDeviceType
int64_t * getNullValueEndPos() const
bool window_function_conditional_aggregate(const SqlWindowFunctionKind kind)
Definition: WindowContext.h:59
llvm::Value * current_partition_start_offset_lv
const int32_t dummy_offset_
static Comparator makeComparator(const Analyzer::ColumnVar *col_var, const int8_t *partition_values, const int32_t *partition_indices, const bool asc_ordering, const bool nulls_first)
llvm::Value * current_row_pos_lv
Definition: WindowContext.h:89
llvm::Value * target_partition_rowid_ptr_lv
Definition: WindowContext.h:97
const int8_t * partitionStart() const
llvm::Value * frame_end_bound_expr_lv
Definition: WindowContext.h:88
llvm::Value * num_elem_current_partition_lv
llvm::Value * nulls_first_lv
Definition: WindowContext.h:99
const std::vector< SQLTypeInfo > & getOrderKeyColumnBufferTypes() const
void setSortedPartitionCacheKey(QueryPlanHash cache_key)
void computeNullRangeOfSortedPartition(const SQLTypeInfo &order_col_ti, size_t partition_idx, const int32_t *original_col_idx_buf, const int64_t *ordered_col_idx_buf)
static WindowProjectNodeContext * create(Executor *executor)
size_t elementCount() const
const int8_t * output() const
const Analyzer::WindowFunction * window_func_
const int32_t * counts() const
Constants for Builtin SQL Types supported by HEAVY.AI.
const int32_t * offsets() const
llvm::Value * target_partition_sorted_rowid_ptr_lv
llvm::Value * target_partition_rowid_ptr_lv
static WindowFunctionContext * getActiveWindowFunctionContext(Executor *executor)
const bool needsToBuildAggregateTree() const
size_t * getAggregateTreeDepth() const
int64_t ** getAggregationTreesForIntegerTypeWindowExpr() const
const std::vector< const int8_t * > & getColumnBufferForWindowFunctionExpressions() const
int64_t * getNullValueStartPos() const
SumAndCountPair< double > ** getDerivedAggregationTreesForDoubleTypeWindowExpr() const
const int64_t * partitionStartOffset() const
std::vector< std::shared_ptr< void > > segment_trees_owned_
std::shared_ptr< std::vector< int64_t > > sorted_partition_buf_
size_t partitionCount() const
AggregateState aggregate_state_
llvm::Value * null_start_pos_lv
bool window_function_is_value(const SqlWindowFunctionKind kind)
Definition: WindowContext.h:29
size_t g_window_function_aggregation_tree_fanout
const int64_t * aggregateStateCount() const
std::vector< Comparator > createComparator(size_t partition_idx)
QueryPlanHash sorted_partition_cache_key_
const int8_t * partitionEnd() const
std::vector< std::vector< std::shared_ptr< Chunk_NS::Chunk > > > window_func_expr_columns_owner_
void addColumnBufferForWindowFunctionExpression(const int8_t *column, const std::vector< std::shared_ptr< Chunk_NS::Chunk >> &chunks_owner)
static void reset(Executor *executor)
const WindowFunctionContext * activateWindowFunctionContext(Executor *executor, const size_t target_index) const
QueryPlanHash partition_cache_key_
int64_t aggregateStatePendingOutputs() const
void buildAggregationTreeForPartition(SqlWindowFunctionKind agg_type, size_t partition_idx, size_t partition_size, const int32_t *original_rowid_buf, const int64_t *ordered_rowid_buf, const SQLTypeInfo &input_col_ti)
const int64_t * aggregateState() const
std::function< bool(const PermutationIdx, const PermutationIdx)> Comparator
Definition: ResultSet.h:155
WindowFunctionContext & operator=(const WindowFunctionContext &)=delete
SumAndCountPair< int64_t > ** getDerivedAggregationTreesForIntegerTypeWindowExpr() const
Executor(const ExecutorId id, Data_Namespace::DataMgr *data_mgr, const size_t block_size_x, const size_t grid_size_x, const size_t max_gpu_slab_size, const std::string &debug_dir, const std::string &debug_file)
Definition: Execute.cpp:244
llvm::Value * current_partition_start_offset_lv
Definition: WindowContext.h:91
bool window_function_is_aggregate(const SqlWindowFunctionKind kind)
Definition: WindowContext.h:43
void addWindowFunctionContext(std::unique_ptr< WindowFunctionContext > window_function_context, const size_t target_index)
llvm::Value * target_partition_sorted_rowid_ptr_lv
Definition: WindowContext.h:98
std::vector< const int8_t * > window_func_expr_columns_
AggregateTreeForWindowFraming aggregate_trees_
void sortPartition(const size_t partition_idx, int64_t *output_for_partition_buff, bool should_parallelize)
WindowFunctionContext(const Analyzer::WindowFunction *window_func, const size_t elem_count, const ExecutorDeviceType device_type, std::shared_ptr< RowSetMemoryOwner > row_set_mem_owner)
const std::vector< const int8_t * > & getOrderKeyColumnBuffers() const
std::shared_ptr< HashJoin > partitions_
size_t QueryPlanHash
llvm::Value * null_end_pos_lv
void resizeStorageForWindowFraming(size_t partition_count)
Definition: WindowContext.h:78
const int64_t * partitionNumCountBuf() const
bool window_function_requires_peer_handling(const Analyzer::WindowFunction *window_func)
SqlWindowFunctionKind
Definition: sqldefs.h:120
void resizeStorageForWindowFraming(bool const for_reuse=false)
std::unordered_map< size_t, std::unique_ptr< WindowFunctionContext > > window_contexts_
void computePartitionBuffer(const size_t partition_idx, int64_t *output_for_partition_buff, const Analyzer::WindowFunction *window_func)
llvm::Value * order_key_buf_ptr_lv
Definition: WindowContext.h:95
int64_t * partition_start_offset_
llvm::Value * int64_t_zero_val_lv
Definition: WindowContext.h:92
std::vector< const int8_t * > order_columns_
const int64_t * sortedPartition() const
const QueryPlanHash computeAggregateTreeCacheKey() const
static void resetWindowFunctionContext(Executor *executor)
std::vector< SQLTypeInfo > order_columns_ti_
std::vector< SumAndCountPair< int64_t > * > derived_aggregate_tree_for_integer_type_
Definition: WindowContext.h:74
const Analyzer::WindowFunction * getWindowFunction() const
const int32_t * payload() const
std::function< WindowFunctionContext::WindowComparatorResult(const int64_t lhs, const int64_t rhs)> Comparator
size_t * aggregate_trees_depth_
std::vector< std::vector< std::shared_ptr< Chunk_NS::Chunk > > > order_columns_owner_
llvm::Value * int64_t_one_val_lv
Definition: WindowContext.h:93
llvm::Value * frame_start_bound_expr_lv
Definition: WindowContext.h:87
std::vector< int64_t * > aggregate_tree_for_integer_type_
Definition: WindowContext.h:72
const ExecutorDeviceType device_type_
std::string order_type_col_name
Definition: WindowContext.h:96
void compute(std::unordered_map< QueryPlanHash, size_t > &sorted_partition_key_ref_count_map, std::unordered_map< QueryPlanHash, std::shared_ptr< std::vector< int64_t >>> &sorted_partition_cache, std::unordered_map< QueryPlanHash, AggregateTreeForWindowFraming > &aggregate_tree_map)
double ** getAggregationTreesForDoubleTypeWindowExpr() const
int64_t * ordered_partition_null_end_pos_