Skip to main content

aegis_common/
types.rs

1//! Aegis Types - Core Data Types
2//!
3//! Fundamental data types used throughout the Aegis database platform.
4//! Provides type-safe identifiers, value representations, and common
5//! structures for storage and query operations.
6//!
7//! Key Features:
8//! - Type-safe identifiers (BlockId, PageId, TransactionId, NodeId)
9//! - Multi-paradigm value types (scalar, temporal, document, array)
10//! - Compression and encryption type enumerations
11//! - Serialization support via serde
12//!
13//! @version 0.1.0
14//! @author AutomataNexus Development Team
15
16use chrono::{DateTime, Utc};
17use serde::{Deserialize, Serialize};
18use std::collections::HashMap;
19
20// =============================================================================
21// Identifier Types
22// =============================================================================
23
24/// Unique identifier for storage blocks.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
26pub struct BlockId(pub u64);
27
28/// Unique identifier for buffer pool pages.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
30pub struct PageId(pub u64);
31
32/// Unique identifier for transactions.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
34pub struct TransactionId(pub u64);
35
36/// Unique identifier for cluster nodes.
37#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
38pub struct NodeId(pub String);
39
40/// Unique identifier for shards.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
42pub struct ShardId(pub u32);
43
44/// Log sequence number for WAL entries.
45#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
46pub struct Lsn(pub u64);
47
48// =============================================================================
49// Block Types
50// =============================================================================
51
52/// Classification of storage block contents.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
54pub enum BlockType {
55    TableData,
56    TimeSeriesData,
57    DocumentData,
58    IndexData,
59    LogEntry,
60    Metadata,
61}
62
63/// Compression algorithm for stored data.
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
65pub enum CompressionType {
66    #[default]
67    None,
68    Lz4,
69    Zstd,
70    Snappy,
71}
72
73/// Encryption algorithm for data at rest.
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
75pub enum EncryptionType {
76    #[default]
77    None,
78    Aes256Gcm,
79}
80
81// =============================================================================
82// Value Types
83// =============================================================================
84
85/// Multi-paradigm value representation supporting all Aegis data models.
86#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
87pub enum Value {
88    Null,
89    Boolean(bool),
90    Integer(i64),
91    Float(f64),
92    String(String),
93    #[serde(with = "serde_bytes")]
94    Bytes(Vec<u8>),
95    Timestamp(DateTime<Utc>),
96    Array(Vec<Value>),
97    Object(HashMap<String, Value>),
98}
99
100impl Value {
101    /// Returns the type name of this value.
102    pub fn type_name(&self) -> &'static str {
103        match self {
104            Value::Null => "null",
105            Value::Boolean(_) => "boolean",
106            Value::Integer(_) => "integer",
107            Value::Float(_) => "float",
108            Value::String(_) => "string",
109            Value::Bytes(_) => "bytes",
110            Value::Timestamp(_) => "timestamp",
111            Value::Array(_) => "array",
112            Value::Object(_) => "object",
113        }
114    }
115
116    /// Returns true if this value is null.
117    pub fn is_null(&self) -> bool {
118        matches!(self, Value::Null)
119    }
120
121    /// Attempts to extract a boolean value.
122    pub fn as_bool(&self) -> Option<bool> {
123        match self {
124            Value::Boolean(b) => Some(*b),
125            _ => None,
126        }
127    }
128
129    /// Attempts to extract an integer value.
130    pub fn as_i64(&self) -> Option<i64> {
131        match self {
132            Value::Integer(i) => Some(*i),
133            _ => None,
134        }
135    }
136
137    /// Attempts to extract a float value.
138    pub fn as_f64(&self) -> Option<f64> {
139        match self {
140            Value::Float(f) => Some(*f),
141            Value::Integer(i) => Some(*i as f64),
142            _ => None,
143        }
144    }
145
146    /// Attempts to extract a string reference.
147    pub fn as_str(&self) -> Option<&str> {
148        match self {
149            Value::String(s) => Some(s),
150            _ => None,
151        }
152    }
153
154    /// Attempts to extract a byte slice.
155    pub fn as_bytes(&self) -> Option<&[u8]> {
156        match self {
157            Value::Bytes(b) => Some(b),
158            _ => None,
159        }
160    }
161
162    /// Attempts to extract a timestamp value.
163    pub fn as_timestamp(&self) -> Option<&DateTime<Utc>> {
164        match self {
165            Value::Timestamp(t) => Some(t),
166            _ => None,
167        }
168    }
169
170    /// Attempts to extract an array reference.
171    pub fn as_array(&self) -> Option<&Vec<Value>> {
172        match self {
173            Value::Array(a) => Some(a),
174            _ => None,
175        }
176    }
177
178    /// Attempts to extract an object reference.
179    pub fn as_object(&self) -> Option<&HashMap<String, Value>> {
180        match self {
181            Value::Object(o) => Some(o),
182            _ => None,
183        }
184    }
185}
186
187// =============================================================================
188// Data Type Definitions
189// =============================================================================
190
191/// SQL data type enumeration.
192#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
193pub enum DataType {
194    Any,
195    Boolean,
196    TinyInt,
197    SmallInt,
198    Integer,
199    BigInt,
200    Float,
201    Double,
202    Decimal { precision: u8, scale: u8 },
203    Char(u16),
204    Varchar(u16),
205    Text,
206    Binary(u32),
207    Varbinary(u32),
208    Blob,
209    Date,
210    Time,
211    Timestamp,
212    TimestampTz,
213    Interval,
214    Json,
215    Jsonb,
216    Uuid,
217    Array(Box<DataType>),
218}
219
220// =============================================================================
221// Row and Column Types
222// =============================================================================
223
224/// A single row of data as a vector of values.
225#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
226pub struct Row {
227    pub values: Vec<Value>,
228}
229
230impl Row {
231    pub fn new(values: Vec<Value>) -> Self {
232        Self { values }
233    }
234
235    pub fn get(&self, index: usize) -> Option<&Value> {
236        self.values.get(index)
237    }
238
239    pub fn len(&self) -> usize {
240        self.values.len()
241    }
242
243    pub fn is_empty(&self) -> bool {
244        self.values.is_empty()
245    }
246}
247
248/// Column metadata.
249#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
250pub struct ColumnDef {
251    pub name: String,
252    pub data_type: DataType,
253    pub nullable: bool,
254    pub default: Option<String>,
255}
256
257// =============================================================================
258// Time Range
259// =============================================================================
260
261/// Time range for time series queries.
262#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
263pub struct TimeRange {
264    pub start: DateTime<Utc>,
265    pub end: DateTime<Utc>,
266}
267
268impl TimeRange {
269    pub fn new(start: DateTime<Utc>, end: DateTime<Utc>) -> Self {
270        Self { start, end }
271    }
272
273    pub fn contains(&self, timestamp: &DateTime<Utc>) -> bool {
274        timestamp >= &self.start && timestamp < &self.end
275    }
276
277    pub fn duration(&self) -> chrono::Duration {
278        self.end - self.start
279    }
280}
281
282// =============================================================================
283// Key Range
284// =============================================================================
285
286/// Key range for shard boundaries.
287#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
288pub struct KeyRange {
289    pub start: Option<Vec<u8>>,
290    pub end: Option<Vec<u8>>,
291}
292
293impl KeyRange {
294    pub fn new(start: Option<Vec<u8>>, end: Option<Vec<u8>>) -> Self {
295        Self { start, end }
296    }
297
298    pub fn unbounded() -> Self {
299        Self {
300            start: None,
301            end: None,
302        }
303    }
304
305    pub fn contains(&self, key: &[u8]) -> bool {
306        let after_start = self.start.as_ref().map_or(true, |s| key >= s.as_slice());
307        let before_end = self.end.as_ref().map_or(true, |e| key < e.as_slice());
308        after_start && before_end
309    }
310}