Skip to main content

akar_processor/physical/
misc.rs

1//! Miscellaneous physical operators (EmptyResult, MultiplicityReducer, Skip, UnionAllScan).
2
3use crate::physical::types::{OperatorResult, PhysicalOperatorExec};
4use akar_common::vector::{DataChunk, ValueVector};
5
6/// Physical operator that always returns an empty result.
7pub struct PhysicalEmptyResult;
8
9impl PhysicalOperatorExec for PhysicalEmptyResult {
10    fn operator_type(&self) -> &str {
11        "empty_result"
12    }
13
14    fn execute(&self, _input: Vec<DataChunk>) -> OperatorResult {
15        Ok(vec![])
16    }
17}
18
19/// Physical operator that reduces the multiplicity of paths (e.g., DISTINCT).
20pub struct PhysicalMultiplicityReducer {
21    pub key_columns: Vec<usize>,
22}
23
24impl PhysicalOperatorExec for PhysicalMultiplicityReducer {
25    fn operator_type(&self) -> &str {
26        "multiplicity_reducer"
27    }
28
29    fn execute(&self, input: Vec<DataChunk>) -> OperatorResult {
30        if input.is_empty() {
31            return Ok(input);
32        }
33
34        let mut result = Vec::new();
35        let mut seen = std::collections::HashSet::new();
36
37        for chunk in input {
38            let mut filter_mask = vec![false; chunk.size];
39            for i in 0..chunk.size {
40                let mut row_keys = Vec::new();
41                for &col_idx in &self.key_columns {
42                    let val = chunk.get_value(col_idx, i).unwrap_or(akar_common::types::Value::Null);
43                    row_keys.push(val);
44                }
45
46                // Using debug format as a fallback hashable representation for arbitrary Value types
47                if seen.insert(format!("{:?}", row_keys)) {
48                    filter_mask[i] = true;
49                }
50            }
51
52            let filtered_size = filter_mask.iter().filter(|&&b| b).count();
53            if filtered_size > 0 {
54                let mut new_fields = Vec::new();
55                let mut new_field_types = Vec::new();
56                for (col_idx, _field) in chunk.fields.iter().enumerate() {
57                    let phys_type = chunk.field_types[col_idx];
58                    let mut new_field = ValueVector::new(phys_type, filtered_size);
59                    let mut current = 0;
60                    for (i, &keep) in filter_mask.iter().enumerate() {
61                        if keep {
62                            if let Some(val) = chunk.get_value(col_idx, i) {
63                                let _ = new_field.set_value(current, &val);
64                            }
65                            current += 1;
66                        }
67                    }
68                    new_fields.push(akar_common::arrow_vector::ArrowVector::from_legacy(&new_field).array);
69                    new_field_types.push(phys_type);
70                }
71                result.push(DataChunk {
72                    fields: new_fields,
73                    field_types: new_field_types,
74                    size: filtered_size,
75                    field_names: chunk.field_names.clone(),
76                    sel_vector: None,
77                });
78            }
79        }
80        Ok(result)
81    }
82}
83
84/// Physical operator for SKIP (OFFSET) in queries.
85pub struct PhysicalSkip {
86    pub skip_count: usize,
87}
88
89impl PhysicalOperatorExec for PhysicalSkip {
90    fn operator_type(&self) -> &str {
91        "skip"
92    }
93
94    fn execute(&self, input: Vec<DataChunk>) -> OperatorResult {
95        let mut remaining_skip = self.skip_count;
96        let mut output = Vec::new();
97
98        for chunk in input {
99            if remaining_skip == 0 {
100                output.push(chunk);
101                continue;
102            }
103
104            if chunk.size <= remaining_skip {
105                remaining_skip -= chunk.size;
106                continue;
107            }
108
109            // Partially skip this chunk
110            let keep_size = chunk.size - remaining_skip;
111            let mut sliced_fields = Vec::new();
112            let mut sliced_types = Vec::new();
113
114            for (col_idx, _field) in chunk.fields.iter().enumerate() {
115                let phys_type = chunk.field_types[col_idx];
116                let mut new_field = ValueVector::new(phys_type, keep_size);
117                for i in 0..keep_size {
118                    let val = chunk
119                        .get_value(col_idx, remaining_skip + i)
120                        .unwrap_or(akar_common::types::Value::Null);
121                    // set_value returns Err only for strings > 255 bytes (legacy
122                    // inline storage limit); drop to NULL instead of panicking.
123                    if new_field.set_value(i, &val).is_err() {
124                        new_field.set_null(i, true);
125                    }
126                }
127                sliced_fields.push(akar_common::arrow_vector::ArrowVector::from_legacy(&new_field).array);
128                sliced_types.push(phys_type);
129            }
130
131            output.push(DataChunk {
132                fields: sliced_fields,
133                field_types: sliced_types,
134                size: keep_size,
135                field_names: chunk.field_names.clone(),
136                sel_vector: None,
137            });
138            remaining_skip = 0;
139        }
140
141        Ok(output)
142    }
143}
144
145/// Physical operator for scanning from a UNION ALL.
146pub struct PhysicalUnionAllScan;
147
148impl PhysicalOperatorExec for PhysicalUnionAllScan {
149    fn operator_type(&self) -> &str {
150        "union_all_scan"
151    }
152
153    fn execute(&self, input: Vec<DataChunk>) -> OperatorResult {
154        Ok(input)
155    }
156}
157
158/// Insert operator — row-level insertion (unlike BatchInsert).
159pub struct PhysicalInsert {
160    pub table_name: String,
161    pub table_id: u64,
162    pub columns: Vec<String>,
163    pub values: Vec<Vec<akar_common::types::Value>>,
164    pub table_catalog: std::sync::Arc<akar_storage::table::TableCatalog>,
165    /// Active transaction id (P52.18).
166    pub txn_id: Option<u64>,
167    /// Undo sink for rollback records (P52.18).
168    pub undo_sink: Option<std::sync::Arc<std::sync::Mutex<Vec<akar_transaction::UndoRecord>>>>,
169}
170
171impl PhysicalOperatorExec for PhysicalInsert {
172    fn operator_type(&self) -> &str {
173        "insert"
174    }
175
176    fn execute(&self, _input: Vec<DataChunk>) -> OperatorResult {
177        let mut inserted = 0;
178
179        // Cek jika tabel adalah rel table atau node table
180        if let Some(mut rel_tbl) = self.table_catalog.get_rel_table_by_name_mut(&self.table_name) {
181            // Rel Table Insert
182            let mut rels_to_insert = Vec::new();
183            for row_values in &self.values {
184                if row_values.len() >= 2 {
185                    // Extract src and dst
186                    let src = if let akar_common::types::Value::Int64(v) = row_values[0] {
187                        v as u64
188                    } else {
189                        0
190                    };
191                    let dst = if let akar_common::types::Value::Int64(v) = row_values[1] {
192                        v as u64
193                    } else {
194                        0
195                    };
196                    let props = if row_values.len() > 2 {
197                        row_values[2..].to_vec()
198                    } else {
199                        vec![]
200                    };
201                    rels_to_insert.push((src, dst, props));
202                }
203            }
204            if !rels_to_insert.is_empty() {
205                let start = rel_tbl.edges.len();
206                if let Ok(count) = rel_tbl.insert_rels_batch(&rels_to_insert) {
207                    inserted += count;
208                    if let Some(sink) = self.undo_sink.as_ref()
209                        && let Ok(mut u) = sink.lock()
210                    {
211                        for idx in start..start + count as usize {
212                            u.push(akar_transaction::UndoRecord::insert(self.table_id, idx as u64));
213                        }
214                    }
215                }
216            }
217        } else if let Some(mut node_tbl) = self.table_catalog.get_node_table_by_name_mut(&self.table_name) {
218            // Node Table Insert
219            for row_values in &self.values {
220                if let Ok(row_id) = node_tbl.insert_row_with_txn(row_values.clone(), self.txn_id) {
221                    inserted += 1;
222                    if let Some(sink) = self.undo_sink.as_ref()
223                        && let Ok(mut u) = sink.lock()
224                    {
225                        u.push(akar_transaction::UndoRecord::insert(self.table_id, row_id));
226                    }
227                }
228            }
229        } else {
230            return Err(format!("Table '{}' not found for INSERT", self.table_name).into());
231        }
232
233        let mut v = ValueVector::new(akar_common::types::PhysicalTypeID::Int64, 1);
234        v.resize(1);
235        v.set_i64(0, inserted as i64);
236        let arr = akar_common::arrow_vector::ArrowVector::from_legacy(&v).array;
237        Ok(vec![DataChunk::new(
238            vec![arr],
239            vec![akar_common::types::PhysicalTypeID::Int64],
240        )])
241    }
242}
243
244/// ExtensionClause operator — handles EXTENSION commands (INSTALL, LOAD).
245pub struct PhysicalExtensionClause {
246    pub action: akar_parser::ast::ExtensionAction,
247    pub extension_name: String,
248}
249
250impl PhysicalOperatorExec for PhysicalExtensionClause {
251    fn operator_type(&self) -> &str {
252        "extension_clause"
253    }
254
255    fn execute(&self, _input: Vec<DataChunk>) -> OperatorResult {
256        let msg = match self.action {
257            akar_parser::ast::ExtensionAction::Install => {
258                format!("Extension '{}' installed successfully.", self.extension_name)
259            }
260            akar_parser::ast::ExtensionAction::Load => {
261                // Pseudo-registry for static extensions
262                if self.extension_name.to_lowercase() == "httpfs" {
263                    format!(
264                        "Extension '{}' loaded (HTTP/S3 virtual file system).",
265                        self.extension_name
266                    )
267                } else if self.extension_name.to_lowercase() == "fts" {
268                    format!("Extension '{}' loaded (Full Text Search).", self.extension_name)
269                } else {
270                    format!("Extension '{}' loaded.", self.extension_name)
271                }
272            }
273            akar_parser::ast::ExtensionAction::Uninstall => {
274                format!("Extension '{}' uninstalled.", self.extension_name)
275            }
276        };
277
278        tracing::info!("{}", msg);
279
280        let mut field = ValueVector::new(akar_common::types::PhysicalTypeID::String, 1);
281        let _ = field.set_value(0, &akar_common::types::Value::String(msg));
282        let arr = akar_common::arrow_vector::ArrowVector::from_legacy(&field).array;
283
284        Ok(vec![DataChunk {
285            fields: vec![arr],
286            field_types: vec![akar_common::types::PhysicalTypeID::String],
287            size: 1,
288            field_names: vec!["message".into()],
289            sel_vector: None,
290        }])
291    }
292}