1use std::{
4 hash::{Hash, Hasher},
5 sync::{
6 atomic::{AtomicU64, Ordering},
7 Arc,
8 },
9};
10
11use super::{
12 binding::VectorSource, DataSourceInfo, Date, Duration, ExactInteger, LocalTimestamp, Timestamp,
13};
14mod encoding;
15use crate::{
16 errors::{Diagnostic, DiagnosticKind, ErrorContext, OperationPhase},
17 CategoryValues, Error, Result,
18};
19pub(crate) use encoding::key_bytes;
20
21#[derive(Debug, Clone)]
23#[non_exhaustive]
24pub enum RawKey {
25 String(String),
27 Integer(ExactInteger),
29 Boolean(bool),
31 Float(f64),
33 Tuple(Vec<RawKey>),
35 Date(Date),
37 Instant(Timestamp),
39 Duration(Duration),
41 LocalTimestamp(LocalTimestamp),
43 Interval(IntervalKey),
45 Unavailable(UnavailableKey),
47}
48
49impl From<String> for RawKey {
50 fn from(value: String) -> Self {
51 Self::String(value)
52 }
53}
54impl From<&str> for RawKey {
55 fn from(value: &str) -> Self {
56 Self::String(value.to_owned())
57 }
58}
59
60impl From<&String> for RawKey {
61 fn from(value: &String) -> Self {
62 Self::String(value.clone())
63 }
64}
65
66impl From<ExactInteger> for RawKey {
67 fn from(value: ExactInteger) -> Self {
68 Self::Integer(value)
69 }
70}
71macro_rules! integer_keys {
72 ($($type:ty),+) => {$(
73 impl From<$type> for RawKey {
74 fn from(value:$type)->Self {Self::Integer(value.into())}
75 }
76 )+};
77}
78integer_keys!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize);
79impl From<bool> for RawKey {
80 fn from(value: bool) -> Self {
81 Self::Boolean(value)
82 }
83}
84impl From<f64> for RawKey {
85 fn from(value: f64) -> Self {
86 Self::Float(value)
87 }
88}
89impl<A: Into<RawKey>, B: Into<RawKey>> From<(A, B)> for RawKey {
90 fn from((first, second): (A, B)) -> Self {
91 Self::Tuple(vec![first.into(), second.into()])
92 }
93}
94
95impl PartialEq for RawKey {
96 fn eq(&self, other: &Self) -> bool {
97 match (self, other) {
98 (Self::String(a), Self::String(b)) => a == b,
99 (Self::Integer(a), Self::Integer(b)) => a == b,
100 (Self::Boolean(a), Self::Boolean(b)) => a == b,
101 (Self::Float(a), Self::Float(b)) => a.to_bits() == b.to_bits(),
102 (Self::Tuple(a), Self::Tuple(b)) => a == b,
103 (Self::Date(a), Self::Date(b)) => a == b,
104 (Self::Instant(a), Self::Instant(b)) => a == b,
105 (Self::Duration(a), Self::Duration(b)) => a == b,
106 (Self::LocalTimestamp(a), Self::LocalTimestamp(b)) => a == b,
107 (Self::Interval(a), Self::Interval(b)) => a == b,
108 (Self::Unavailable(a), Self::Unavailable(b)) => a == b,
109 _ => false,
110 }
111 }
112}
113
114impl Eq for RawKey {}
115
116impl Hash for RawKey {
117 fn hash<H: Hasher>(&self, state: &mut H) {
118 std::mem::discriminant(self).hash(state);
119 match self {
120 Self::String(value) => value.hash(state),
121 Self::Integer(value) => value.hash(state),
122 Self::Boolean(value) => value.hash(state),
123 Self::Float(value) => value.to_bits().hash(state),
124 Self::Tuple(value) => value.hash(state),
125 Self::Date(value) => value.hash(state),
126 Self::Instant(value) => value.hash(state),
127 Self::Duration(value) => value.hash(state),
128 Self::LocalTimestamp(value) => value.hash(state),
129 Self::Interval(value) => value.hash(state),
130 Self::Unavailable(value) => value.hash(state),
131 }
132 }
133}
134
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
137pub enum IntervalClosed {
138 Left,
140 Right,
142 Both,
144 Neither,
146}
147
148#[derive(Debug, Clone, PartialEq, Eq, Hash)]
150pub struct IntervalKey {
151 left: Box<RawKey>,
152 right: Box<RawKey>,
153 closed: IntervalClosed,
154}
155
156impl IntervalKey {
157 pub fn new(left: RawKey, right: RawKey, closed: IntervalClosed) -> Result<Self> {
159 let ordered = match (&left, &right) {
160 (RawKey::Integer(a), RawKey::Integer(b)) => a <= b,
161 (RawKey::Float(a), RawKey::Float(b)) => a <= b,
162 (RawKey::Date(a), RawKey::Date(b)) => a <= b,
163 (RawKey::Duration(a), RawKey::Duration(b)) => a <= b,
164 (RawKey::LocalTimestamp(a), RawKey::LocalTimestamp(b)) => a <= b,
165 (RawKey::Instant(a), RawKey::Instant(b)) => a.unix_ns() <= b.unix_ns(),
166 _ => false,
167 };
168 if !ordered {
169 return Err(Error::Data(
170 "interval key requires compatible ordered endpoints".into(),
171 ));
172 }
173 Ok(Self {
174 left: Box::new(left),
175 right: Box::new(right),
176 closed,
177 })
178 }
179 pub fn left(&self) -> &RawKey {
181 &self.left
182 }
183 pub fn right(&self) -> &RawKey {
185 &self.right
186 }
187 pub const fn closed(&self) -> IntervalClosed {
189 self.closed
190 }
191}
192
193static NEXT_UNAVAILABLE_KEY: AtomicU64 = AtomicU64::new(0);
194
195#[derive(Debug, Clone, PartialEq, Eq, Hash)]
197pub struct UnavailableKey {
198 identity: u64,
199 reason: Arc<str>,
200}
201
202impl UnavailableKey {
203 #[doc(hidden)]
205 pub fn new(reason: impl Into<String>) -> Result<Self> {
206 let identity = NEXT_UNAVAILABLE_KEY
207 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
208 value.checked_add(1)
209 })
210 .map_err(|_| Error::Data("raw key identity space exhausted".into()))?;
211 Ok(Self {
212 identity,
213 reason: Arc::from(reason.into()),
214 })
215 }
216 pub(crate) fn identity(&self) -> u64 {
217 self.identity
218 }
219
220 pub fn reason(&self) -> &str {
222 &self.reason
223 }
224}
225
226#[derive(Debug, Clone)]
228pub struct RawKeyValues {
229 name: Arc<str>,
230 codes: Arc<[Option<u32>]>,
231 levels: Arc<[RawKey]>,
232 source: VectorSource,
233}
234
235impl RawKeyValues {
236 pub fn new(name: impl Into<String>, values: impl IntoIterator<Item = RawKey>) -> Result<Self> {
238 Self::nullable(name, values.into_iter().map(Some))
239 }
240
241 pub fn nullable(
243 name: impl Into<String>,
244 values: impl IntoIterator<Item = Option<RawKey>>,
245 ) -> Result<Self> {
246 let name = name.into();
247 let mut levels = Vec::new();
248 let mut indices = std::collections::HashMap::new();
249 let codes = super::source::collect_source(values.into_iter().map(|value| {
250 let Some(value) = value else { return Ok(None) };
251 if let Some(&index) = indices.get(&value) {
252 return Ok(Some(index));
253 }
254 let index = u32::try_from(levels.len()).map_err(|_| {
255 Error::Data(
256 format!("raw key column {name:?} exceeds the distinct-key limit").into(),
257 )
258 })?;
259 super::source::reserve_source(&mut levels, 1)?;
260 crate::operation::check()?;
261 indices.try_reserve(1).map_err(|error| {
262 Error::Data(format!("raw key dictionary storage: {error}").into())
263 })?;
264 indices.insert(value.clone(), index);
265 levels.push(value);
266 Ok(Some(index))
267 }))?;
268 crate::operation::check()?;
269 Ok(Self {
270 name: Arc::from(name),
271 source: VectorSource::direct_nullable(codes.len(), codes.iter().any(Option::is_none)),
272 codes: codes.into(),
273 levels: levels.into(),
274 })
275 }
276 pub fn name(&self) -> &str {
278 &self.name
279 }
280 pub(crate) fn with_name(mut self, name: &str) -> Self {
281 self.name = Arc::from(name);
282 self
283 }
284 pub fn len(&self) -> usize {
286 self.codes.len()
287 }
288 pub fn is_empty(&self) -> bool {
290 self.codes.is_empty()
291 }
292 pub fn get(&self, index: usize) -> Option<Option<&RawKey>> {
294 self.codes
295 .get(index)
296 .map(|code| code.and_then(|code| self.levels.get(code as usize)))
297 }
298 pub fn iter(&self) -> impl ExactSizeIterator<Item = Option<&RawKey>> + '_ {
300 (0..self.len()).map(|index| self.get(index).expect("in-bounds raw key slot"))
301 }
302 pub fn is_valid(&self, index: usize) -> Option<bool> {
304 self.codes.get(index).map(Option::is_some)
305 }
306 #[doc(hidden)]
308 pub fn with_source(mut self, source: DataSourceInfo) -> Result<Self> {
309 self.source = VectorSource::repeated(source, 1, self.len())?.with_original_validity(
310 self.len(),
311 self.has_nulls(),
312 |slot| self.codes[slot].is_some(),
313 )?;
314 Ok(self)
315 }
316
317 pub(crate) fn with_vector_source(mut self, source: VectorSource) -> Self {
318 self.source = source;
319 self
320 }
321
322 #[doc(hidden)]
324 pub fn get_source(&self) -> &DataSourceInfo {
325 self.source.info()
326 }
327
328 pub(crate) fn vector_source(&self) -> &VectorSource {
329 &self.source
330 }
331
332 pub(crate) fn has_nulls(&self) -> bool {
333 self.codes.iter().any(Option::is_none)
334 }
335
336 #[doc(hidden)]
338 pub fn source_slot(&self, index: usize) -> Option<usize> {
339 (index < self.len()).then(|| self.source.slot(index))
340 }
341
342 pub(crate) fn select(&self, indices: &[usize]) -> Result<Self> {
343 let mut selected = Self::nullable(
344 self.name(),
345 indices.iter().map(|&index| {
346 self.get(index)
347 .expect("validated raw key selection")
348 .cloned()
349 }),
350 )?;
351 selected.source = self.source.select(indices)?;
352 Ok(selected)
353 }
354
355 pub fn levels(&self) -> &[RawKey] {
357 &self.levels
358 }
359}
360
361impl PartialEq for RawKeyValues {
362 fn eq(&self, other: &Self) -> bool {
363 self.name == other.name && self.codes == other.codes && self.levels == other.levels
364 }
365}
366impl Eq for RawKeyValues {}
367
368#[derive(Debug, Clone, PartialEq, Eq)]
370#[non_exhaustive]
371pub enum KeyValues {
372 Strings(CategoryValues),
374 Raw(RawKeyValues),
376}
377impl KeyValues {
378 pub(crate) fn key_at(&self, slot: usize) -> Option<RawKey> {
379 match self {
380 Self::Strings(values) => values.get(slot).flatten().map(RawKey::from),
381 Self::Raw(values) => values.get(slot).flatten().cloned(),
382 }
383 }
384
385 pub(crate) fn select(&self, indices: &[usize]) -> crate::Result<Self> {
386 Ok(match self {
387 Self::Strings(values) => Self::Strings(values.select(indices)?),
388 Self::Raw(values) => Self::Raw(values.select(indices)?),
389 })
390 }
391
392 #[doc(hidden)]
395 pub fn repeated_keys(name: &str, keys: &[RawKey], rows: usize) -> Result<Self> {
396 if keys.iter().all(|key| matches!(key, RawKey::String(_))) {
397 Ok(Self::Strings(CategoryValues::new(
398 name,
399 (0..rows).flat_map(|_| {
400 keys.iter().map(|key| match key {
401 RawKey::String(value) => value.as_str(),
402 _ => unreachable!("all keys are strings"),
403 })
404 }),
405 )?))
406 } else {
407 Ok(Self::Raw(RawKeyValues::new(
408 name,
409 (0..rows).flat_map(|_| keys.iter().cloned()),
410 )?))
411 }
412 }
413
414 pub const fn get_strings(&self) -> Option<&CategoryValues> {
416 if let Self::Strings(values) = self {
417 Some(values)
418 } else {
419 None
420 }
421 }
422 pub const fn get_raw(&self) -> Option<&RawKeyValues> {
424 if let Self::Raw(values) = self {
425 Some(values)
426 } else {
427 None
428 }
429 }
430 pub fn len(&self) -> usize {
432 match self {
433 Self::Strings(values) => values.len(),
434 Self::Raw(values) => values.len(),
435 }
436 }
437 pub fn is_empty(&self) -> bool {
439 self.len() == 0
440 }
441 pub fn is_valid(&self, index: usize) -> Option<bool> {
443 match self {
444 Self::Strings(values) => values.is_valid(index),
445 Self::Raw(values) => values.is_valid(index),
446 }
447 }
448}
449
450#[derive(Debug, Clone, PartialEq, Eq)]
452pub struct NamedKeyValues {
453 pub key: RawKey,
455 pub values: KeyValues,
457}
458
459#[derive(Debug, Clone, PartialEq, Eq)]
461pub struct KeyColumns(Arc<[NamedKeyValues]>);
462
463impl KeyColumns {
464 pub fn new(columns: Vec<NamedKeyValues>) -> Result<Self> {
466 let length = columns.first().map_or(0, |column| column.values.len());
467 let mut fields = std::collections::HashSet::new();
468 for column in &columns {
469 if column.values.len() != length {
470 return Err(Error::Data(
471 Diagnostic::new(
472 DiagnosticKind::ShapeMismatch {
473 expected: vec![length],
474 actual: vec![column.values.len()],
475 },
476 "key columns must have the same length",
477 )
478 .with_context(
479 ErrorContext::new()
480 .with_operation(OperationPhase::Bind)
481 .with_binding(column.key.clone()),
482 ),
483 ));
484 }
485 if !fields.insert(&column.key) {
486 return Err(Error::Data("duplicate key column identity".into()));
487 }
488 }
489 Ok(Self(columns.into()))
490 }
491 pub fn columns(&self) -> &[NamedKeyValues] {
493 &self.0
494 }
495 pub fn len(&self) -> usize {
497 self.0.len()
498 }
499 pub fn is_empty(&self) -> bool {
501 self.0.is_empty()
502 }
503 pub(crate) fn row_keys(&self, index: usize) -> Option<Vec<RawKey>> {
504 self.0
505 .iter()
506 .map(|column| match &column.values {
507 KeyValues::Strings(values) => values.get(index)?.map(RawKey::from),
508 KeyValues::Raw(values) => values.get(index)?.cloned(),
509 })
510 .collect()
511 }
512
513 pub fn get(&self, key: &RawKey) -> Result<&KeyValues> {
515 self.0
516 .iter()
517 .find(|column| &column.key == key)
518 .map(|column| &column.values)
519 .ok_or_else(|| {
520 Error::Data(
521 Diagnostic::new(
522 DiagnosticKind::UnknownKey {
523 key: Some(key.clone()),
524 },
525 format!("no key column {key:?}"),
526 )
527 .with_context(ErrorContext::new().with_operation(OperationPhase::Check)),
528 )
529 })
530 }
531}