surrealdb_core/sql/
range.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
use super::Id;
use crate::cnf::GENERATION_ALLOCATION_LIMIT;
use crate::ctx::Context;
use crate::dbs::Options;
use crate::doc::CursorDoc;
use crate::err::Error;
use crate::sql::{Number, Subquery, Value};
use crate::syn;
use reblessive::tree::Stk;
use revision::revisioned;
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::fmt;
use std::ops::Bound;
use std::str::FromStr;

pub(crate) const TOKEN: &str = "$surrealdb::private::sql::Range";

#[revisioned(revision = 1)]
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash)]
#[serde(rename = "$surrealdb::private::sql::Range")]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[non_exhaustive]
pub struct Range {
	pub beg: Bound<Value>,
	pub end: Bound<Value>,
}

impl FromStr for Range {
	type Err = ();
	fn from_str(s: &str) -> Result<Self, Self::Err> {
		Self::try_from(s)
	}
}

impl TryFrom<&str> for Range {
	type Error = ();
	fn try_from(v: &str) -> Result<Self, Self::Error> {
		match syn::range(v) {
			Ok(v) => Ok(v),
			_ => Err(()),
		}
	}
}

impl From<(Bound<Id>, Bound<Id>)> for Range {
	fn from(v: (Bound<Id>, Bound<Id>)) -> Self {
		fn convert(v: Bound<Id>) -> Bound<Value> {
			match v {
				Bound::Included(v) => Bound::Included(v.into()),
				Bound::Excluded(v) => Bound::Excluded(v.into()),
				Bound::Unbounded => Bound::Unbounded,
			}
		}

		Self {
			beg: convert(v.0),
			end: convert(v.1),
		}
	}
}

impl TryInto<std::ops::Range<i64>> for Range {
	type Error = Error;
	fn try_into(self) -> Result<std::ops::Range<i64>, Self::Error> {
		let beg = match self.beg {
			Bound::Unbounded => i64::MIN,
			Bound::Included(beg) => to_i64(beg)?,
			Bound::Excluded(beg) => to_i64(beg)? + 1,
		};

		let end = match self.end {
			Bound::Unbounded => i64::MAX,
			Bound::Included(end) => to_i64(end)? + 1,
			Bound::Excluded(end) => to_i64(end)?,
		};

		if (beg + *GENERATION_ALLOCATION_LIMIT as i64) < end {
			Err(Error::RangeTooBig {
				max: *GENERATION_ALLOCATION_LIMIT,
			})
		} else {
			Ok(beg..end)
		}
	}
}

impl Range {
	/// Construct a new range
	pub fn new(beg: Bound<Value>, end: Bound<Value>) -> Self {
		Self {
			beg,
			end,
		}
	}

	/// Process this type returning a computed simple Value
	pub(crate) async fn compute(
		&self,
		stk: &mut Stk,
		ctx: &Context,
		opt: &Options,
		doc: Option<&CursorDoc>,
	) -> Result<Value, Error> {
		Ok(Value::Range(Box::new(Range {
			beg: match &self.beg {
				Bound::Included(v) => Bound::Included(v.compute(stk, ctx, opt, doc).await?),
				Bound::Excluded(v) => Bound::Excluded(v.compute(stk, ctx, opt, doc).await?),
				Bound::Unbounded => Bound::Unbounded,
			},
			end: match &self.end {
				Bound::Included(v) => Bound::Included(v.compute(stk, ctx, opt, doc).await?),
				Bound::Excluded(v) => Bound::Excluded(v.compute(stk, ctx, opt, doc).await?),
				Bound::Unbounded => Bound::Unbounded,
			},
		})))
	}

	/// Validate that a Range contains only computed Values
	pub fn validate_computed(&self) -> Result<(), Error> {
		match &self.beg {
			Bound::Included(ref v) | Bound::Excluded(ref v) => v.validate_computed()?,
			Bound::Unbounded => {}
		}
		match &self.end {
			Bound::Included(ref v) | Bound::Excluded(ref v) => v.validate_computed()?,
			Bound::Unbounded => {}
		}

		Ok(())
	}
}

impl PartialOrd for Range {
	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
		Some(self.cmp(other))
	}
}

impl Ord for Range {
	fn cmp(&self, other: &Self) -> Ordering {
		match &self.beg {
			Bound::Unbounded => match &other.beg {
				Bound::Unbounded => Ordering::Equal,
				_ => Ordering::Less,
			},
			Bound::Included(v) => match &other.beg {
				Bound::Unbounded => Ordering::Greater,
				Bound::Included(w) => match v.cmp(w) {
					Ordering::Equal => match &self.end {
						Bound::Unbounded => match &other.end {
							Bound::Unbounded => Ordering::Equal,
							_ => Ordering::Greater,
						},
						Bound::Included(v) => match &other.end {
							Bound::Unbounded => Ordering::Less,
							Bound::Included(w) => v.cmp(w),
							_ => Ordering::Greater,
						},
						Bound::Excluded(v) => match &other.end {
							Bound::Excluded(w) => v.cmp(w),
							_ => Ordering::Less,
						},
					},
					ordering => ordering,
				},
				_ => Ordering::Less,
			},
			Bound::Excluded(v) => match &other.beg {
				Bound::Excluded(w) => match v.cmp(w) {
					Ordering::Equal => match &self.end {
						Bound::Unbounded => match &other.end {
							Bound::Unbounded => Ordering::Equal,
							_ => Ordering::Greater,
						},
						Bound::Included(v) => match &other.end {
							Bound::Unbounded => Ordering::Less,
							Bound::Included(w) => v.cmp(w),
							_ => Ordering::Greater,
						},
						Bound::Excluded(v) => match &other.end {
							Bound::Excluded(w) => v.cmp(w),
							_ => Ordering::Less,
						},
					},
					ordering => ordering,
				},
				_ => Ordering::Greater,
			},
		}
	}
}

impl fmt::Display for Range {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		fn bound_value(v: &Value) -> Value {
			if v.can_be_range_bound() {
				v.to_owned()
			} else {
				Value::Subquery(Box::new(Subquery::Value(v.to_owned())))
			}
		}

		match &self.beg {
			Bound::Unbounded => write!(f, ""),
			Bound::Included(v) => write!(f, "{}", bound_value(v)),
			Bound::Excluded(v) => write!(f, "{}>", bound_value(v)),
		}?;
		match &self.end {
			Bound::Unbounded => write!(f, ".."),
			Bound::Excluded(v) => write!(f, "..{}", bound_value(v)),
			Bound::Included(v) => write!(f, "..={}", bound_value(v)),
		}?;
		Ok(())
	}
}

fn to_i64(v: Value) -> Result<i64, Error> {
	match v {
		Value::Number(Number::Int(v)) => Ok(v),
		v => Err(Error::InvalidRangeValue {
			expected: "int".to_string(),
			found: v.kindof().to_string(),
		}),
	}
}

// Structs needed for revision convertion from old ranges

#[revisioned(revision = 1)]
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash)]
#[serde(rename = "$surrealdb::private::sql::Range")]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[non_exhaustive]
pub struct OldRange {
	pub tb: String,
	pub beg: Bound<Id>,
	pub end: Bound<Id>,
}