reifydb_sub_flow/transaction/
dictionary.rs1use postcard::{from_bytes, to_stdvec};
5use reifydb_codec::{encoded::row::EncodedRow, key::encoded::EncodedKey};
6use reifydb_core::{
7 interface::catalog::dictionary::Dictionary,
8 key::{
9 EncodableKey,
10 dictionary::{DictionaryEntryIndexKey, DictionaryEntryKey},
11 },
12};
13use reifydb_transaction::{dictionary::DictionaryReader, multi::RangeScope};
14use reifydb_value::{
15 Result,
16 util::hash::xxh3_128,
17 value::{
18 Value,
19 dictionary::{DictionaryEntryId, DictionaryId},
20 },
21};
22
23use super::FlowTransaction;
24
25impl DictionaryReader for FlowTransaction {
26 fn read(&mut self, key: &EncodedKey) -> Result<Option<EncodedRow>> {
27 self.get(key)
28 }
29
30 fn max_index_id(&mut self, dictionary: DictionaryId) -> Result<Option<u128>> {
31 let range = DictionaryEntryIndexKey::full_scan(dictionary);
32 let mut iter = self.range(range, RangeScope::All, 1);
33 match iter.next() {
34 Some(result) => Ok(DictionaryEntryIndexKey::decode(&result?.key).map(|key| key.id)),
35 None => Ok(None),
36 }
37 }
38}
39
40impl FlowTransaction {
41 pub fn find_dictionary(&self, id: DictionaryId) -> Option<Dictionary> {
42 self.catalog().cache().find_dictionary_at(id, self.version())
43 }
44
45 pub fn find_dictionary_by_name(&self, name: &str) -> Option<Dictionary> {
46 let version = self.version();
47 let (namespace_name, dictionary_name) = name.rsplit_once("::")?;
48 let namespace = self.catalog().cache().find_namespace_by_name_at(namespace_name, version)?;
49 self.catalog().cache().find_dictionary_by_name_at(namespace.id(), dictionary_name, version)
50 }
51
52 pub fn find_in_dictionary(
53 &mut self,
54 dictionary: &Dictionary,
55 value: &Value,
56 ) -> Result<Option<DictionaryEntryId>> {
57 let value_bytes = to_stdvec(value).expect("failed to serialize dictionary value");
58 let hash = xxh3_128(&value_bytes).0.to_be_bytes();
59 let entry_key = DictionaryEntryKey::encoded(dictionary.id, hash);
60 match self.get(&entry_key)? {
61 Some(v) => {
62 let id = u128::from_be_bytes(v.0[..16].try_into().unwrap());
63 Ok(Some(DictionaryEntryId::from_u128(id, dictionary.id_type.clone())?))
64 }
65 None => Ok(None),
66 }
67 }
68
69 pub fn get_from_dictionary(&mut self, dictionary: &Dictionary, id: DictionaryEntryId) -> Result<Option<Value>> {
70 let index_key = DictionaryEntryIndexKey::new(dictionary.id, id.to_u128()).encode();
71 match self.get(&index_key)? {
72 Some(v) => Ok(Some(from_bytes(&v.0).expect("failed to deserialize dictionary value"))),
73 None => Ok(None),
74 }
75 }
76}