Skip to main content

reifydb_core/key/
partition.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 ReifyDB
3
4use reifydb_codec::key::encoded::EncodedKey;
5use reifydb_macro::KeyCodec;
6use reifydb_value::value::partition::Partition;
7
8use super::KeyTag;
9use crate::{
10	interface::catalog::object::ObjectId,
11	key::{
12		any::{Field, KeyFields, Width},
13		bound::{TaggedKeyBound, TaggedKeyBoundRange, object_fields},
14		catalog::{KeyDeserializerCatalogExt, KeySerializerCatalogExt},
15	},
16};
17
18#[derive(Debug, Clone, PartialEq, KeyCodec, Hash)]
19#[key(tag = Partition)]
20pub struct PartitionKey {
21	pub object: ObjectId,
22	pub partition: Partition,
23}
24
25impl PartitionKey {
26	pub fn new(object: impl Into<ObjectId>, partition: Partition) -> Self {
27		Self {
28			object: object.into(),
29			partition,
30		}
31	}
32
33	pub fn encoded(object: impl Into<ObjectId>, partition: Partition) -> EncodedKey {
34		Self::new(object, partition).encode()
35	}
36
37	pub fn full_scan(object: impl Into<ObjectId>) -> TaggedKeyBoundRange {
38		let object = object.into();
39		TaggedKeyBoundRange::start_end(
40			TaggedKeyBound::prefix(Self::TAG, object_fields(object)),
41			TaggedKeyBound::prefix(Self::TAG, object_fields(object.prev())),
42		)
43	}
44}
45
46#[cfg(test)]
47#[allow(clippy::disallowed_methods)]
48mod tests {
49	use std::ops::RangeBounds;
50
51	use reifydb_value::value::{Value, partition::Partition};
52
53	use super::PartitionKey;
54	use crate::interface::catalog::{id::TableId, object::ObjectId};
55
56	#[test]
57	fn test_roundtrip() {
58		let key = PartitionKey {
59			object: ObjectId::Table(TableId(7)),
60			partition: Partition::of(&[Value::Utf8("us".to_string())]),
61		};
62		let decoded = PartitionKey::decode(&key.encode()).unwrap();
63		assert_eq!(decoded, key);
64	}
65
66	#[test]
67	fn test_partitions_of_object_share_prefix() {
68		let object = ObjectId::Table(TableId(3));
69		let range = PartitionKey::full_scan(object).encode();
70		let k = PartitionKey::encoded(object, Partition::of(&[Value::Utf8("us".to_string())]));
71		assert!(range.contains(&k));
72		let other = PartitionKey::encoded(
73			ObjectId::Table(TableId(4)),
74			Partition::of(&[Value::Utf8("us".to_string())]),
75		);
76		assert!(!range.contains(&other));
77	}
78}