surrealdb-expr 4.0.0

A scalable, distributed, collaborative, document-graph database, for the realtime web
Documentation
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use std::iter::Sum;
use std::ops::Deref;
use std::str::FromStr;
use std::{fmt, ops, time};

use anyhow::Result;
use common::duration::{
	NANOSECONDS_PER_MICROSECOND, NANOSECONDS_PER_MILLISECOND, SECONDS_PER_DAY, SECONDS_PER_HOUR,
	SECONDS_PER_MINUTE, SECONDS_PER_WEEK, SECONDS_PER_YEAR,
};
use revision::{DeserializeRevisioned, SkipCheckRevisioned, revisioned};
use storekey::{BorrowDecode, Encode};
use surrealdb_collections::bounded;
use surrealdb_types::{SqlFormat, ToSql};

use crate::expr::Error;
use crate::expr::statements::info::InfoStructure;
use crate::syn;
use crate::val::{Datetime, IndexFormat, IndexIdFormat, TryAdd, TrySub, Value};

#[revisioned(revision = 1, deserialize = false, skip = true, walk = true)]
#[derive(
	Clone, Copy, Debug, Default, Eq, PartialEq, PartialOrd, Hash, Ord, Encode, BorrowDecode,
)]
#[storekey(format = "()")]
#[storekey(format = "IndexFormat")]
#[storekey(format = "IndexIdFormat")]
pub struct Duration(pub time::Duration);

/// Reads exactly what the derived serializer writes (revision 1: seconds as a varint `u64`, then
/// the sub-second nanoseconds as a varint `u32`).
///
/// Nanoseconds at or above one second carry into the seconds, as `std::time::Duration::new` does;
/// a carry that overflows the seconds is a [`revision::Error::Deserialize`], never a panic. The VM
/// codec applies the same rule.
impl DeserializeRevisioned for Duration {
	fn deserialize_revisioned<R: std::io::Read>(reader: &mut R) -> Result<Self, revision::Error> {
		bounded::read_revision(reader, "Duration", 1)?;
		read_std_duration(reader).map(Self)
	}
}

/// Reads the two fields `std::time::Duration` is serialized as: seconds as a varint `u64`, then
/// the sub-second nanoseconds as a varint `u32`, with no revision header.
///
/// Nanoseconds at or above one second carry into the seconds, as `Duration::new` does; a carry
/// that overflows the seconds is a [`revision::Error::Deserialize`], never a panic.
pub(crate) fn read_std_duration<R: std::io::Read>(
	reader: &mut R,
) -> Result<time::Duration, revision::Error> {
	let secs = u64::deserialize_revisioned(reader)?;
	let nanos = u32::deserialize_revisioned(reader)?;
	let secs = secs.checked_add(u64::from(nanos / NANOSECONDS_PER_SECOND)).ok_or_else(|| {
		revision::Error::Deserialize("a duration past the representable range".to_owned())
	})?;
	Ok(time::Duration::new(secs, nanos % NANOSECONDS_PER_SECOND))
}

impl SkipCheckRevisioned for Duration {
	fn skip_check_revisioned<R: std::io::Read>(reader: &mut R) -> Result<(), revision::Error> {
		Self::deserialize_revisioned(reader).map(drop)
	}
}

const NANOSECONDS_PER_SECOND: u32 = 1_000_000_000;

impl Duration {
	pub const MAX: Duration = Duration(time::Duration::MAX);
	pub const ZERO: Duration = Duration(time::Duration::ZERO);
}

impl From<time::Duration> for Duration {
	fn from(v: time::Duration) -> Self {
		Self(v)
	}
}

impl From<Duration> for time::Duration {
	fn from(s: Duration) -> Self {
		s.0
	}
}

impl From<time::Duration> for Value {
	fn from(value: time::Duration) -> Self {
		Self::Duration(value.into())
	}
}

impl From<Duration> for crate::types::PublicDuration {
	fn from(value: Duration) -> Self {
		Self::from(value.0)
	}
}

impl From<crate::types::PublicDuration> for Duration {
	fn from(value: crate::types::PublicDuration) -> Self {
		Self(value.into_inner())
	}
}

impl FromStr for Duration {
	type Err = ();
	fn from_str(s: &str) -> Result<Self, Self::Err> {
		match syn::duration(s) {
			Ok(v) => Ok(v.into()),
			_ => Err(()),
		}
	}
}

impl Deref for Duration {
	type Target = time::Duration;
	fn deref(&self) -> &Self::Target {
		&self.0
	}
}

impl Duration {
	/// Create a duration from both seconds and nanoseconds components
	pub fn new(secs: u64, nanos: u32) -> Duration {
		time::Duration::new(secs, nanos).into()
	}

	/// Get the total number of nanoseconds
	pub fn nanos(&self) -> u128 {
		self.0.as_nanos()
	}
	/// Get the total number of microseconds
	pub fn micros(&self) -> u128 {
		self.0.as_micros()
	}
	/// Get the total number of milliseconds
	pub fn millis(&self) -> u128 {
		self.0.as_millis()
	}
	/// Get the total number of seconds
	pub fn secs(&self) -> u64 {
		self.0.as_secs()
	}
	/// Get the total number of minutes
	pub fn mins(&self) -> u64 {
		self.0.as_secs() / SECONDS_PER_MINUTE
	}
	/// Get the total number of hours
	pub fn hours(&self) -> u64 {
		self.0.as_secs() / SECONDS_PER_HOUR
	}
	/// Get the total number of dats
	pub fn days(&self) -> u64 {
		self.0.as_secs() / SECONDS_PER_DAY
	}
	/// Get the total number of months
	pub fn weeks(&self) -> u64 {
		self.0.as_secs() / SECONDS_PER_WEEK
	}
	/// Get the total number of years
	pub fn years(&self) -> u64 {
		self.0.as_secs() / SECONDS_PER_YEAR
	}
	/// Create a duration from nanoseconds
	pub fn from_nanos(nanos: u64) -> Duration {
		time::Duration::from_nanos(nanos).into()
	}
	/// Create a duration from microseconds
	pub fn from_micros(micros: u64) -> Duration {
		time::Duration::from_micros(micros).into()
	}
	/// Create a duration from milliseconds
	pub fn from_millis(millis: u64) -> Duration {
		time::Duration::from_millis(millis).into()
	}
	/// Create a duration from seconds
	pub fn from_secs(secs: u64) -> Duration {
		time::Duration::from_secs(secs).into()
	}
	/// Create a duration from minutes
	pub fn from_mins(mins: u64) -> Option<Duration> {
		mins.checked_mul(SECONDS_PER_MINUTE).map(time::Duration::from_secs).map(|x| x.into())
	}
	/// Create a duration from hours
	pub fn from_hours(hours: u64) -> Option<Duration> {
		hours.checked_mul(SECONDS_PER_HOUR).map(time::Duration::from_secs).map(|x| x.into())
	}
	/// Create a duration from days
	pub fn from_days(days: u64) -> Option<Duration> {
		days.checked_mul(SECONDS_PER_DAY).map(time::Duration::from_secs).map(|x| x.into())
	}
	/// Create a duration from weeks
	pub fn from_weeks(weeks: u64) -> Option<Duration> {
		weeks.checked_mul(SECONDS_PER_WEEK).map(time::Duration::from_secs).map(|x| x.into())
	}
}

impl fmt::Display for Duration {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		// Split up the duration
		let secs = self.0.as_secs();
		let nano = self.0.subsec_nanos();
		// Ensure no empty output
		if secs == 0 && nano == 0 {
			return write!(f, "0ns");
		}
		// Calculate the total years
		let year = secs / SECONDS_PER_YEAR;
		let secs = secs % SECONDS_PER_YEAR;
		// Calculate the total weeks
		let week = secs / SECONDS_PER_WEEK;
		let secs = secs % SECONDS_PER_WEEK;
		// Calculate the total days
		let days = secs / SECONDS_PER_DAY;
		let secs = secs % SECONDS_PER_DAY;
		// Calculate the total hours
		let hour = secs / SECONDS_PER_HOUR;
		let secs = secs % SECONDS_PER_HOUR;
		// Calculate the total minutes
		let mins = secs / SECONDS_PER_MINUTE;
		let secs = secs % SECONDS_PER_MINUTE;
		// Calculate the total milliseconds
		let msec = nano / NANOSECONDS_PER_MILLISECOND;
		let nano = nano % NANOSECONDS_PER_MILLISECOND;
		// Calculate the total microseconds
		let usec = nano / NANOSECONDS_PER_MICROSECOND;
		let nano = nano % NANOSECONDS_PER_MICROSECOND;
		// Write the different parts
		if year > 0 {
			write!(f, "{year}y")?;
		}
		if week > 0 {
			write!(f, "{week}w")?;
		}
		if days > 0 {
			write!(f, "{days}d")?;
		}
		if hour > 0 {
			write!(f, "{hour}h")?;
		}
		if mins > 0 {
			write!(f, "{mins}m")?;
		}
		if secs > 0 {
			write!(f, "{secs}s")?;
		}
		if msec > 0 {
			write!(f, "{msec}ms")?;
		}
		if usec > 0 {
			write!(f, "{usec}µs")?;
		}
		if nano > 0 {
			write!(f, "{nano}ns")?;
		}
		Ok(())
	}
}

impl ToSql for Duration {
	fn fmt_sql(&self, f: &mut String, sql_fmt: SqlFormat) {
		self.to_string().fmt_sql(f, sql_fmt)
	}
}

impl ops::Add for Duration {
	type Output = Self;
	fn add(self, other: Self) -> Self {
		match self.0.checked_add(other.0) {
			Some(v) => Duration::from(v),
			None => Duration::from(time::Duration::MAX),
		}
	}
}

impl TryAdd for Duration {
	type Output = Self;
	fn try_add(self, other: Self) -> Result<Self> {
		self.0
			.checked_add(other.0)
			.ok_or_else(|| Error::ArithmeticOverflow(format!("{self} + {other}")))
			.map_err(anyhow::Error::new)
			.map(Duration::from)
	}
}

impl<'b> ops::Add<&'b Duration> for &Duration {
	type Output = Duration;
	fn add(self, other: &'b Duration) -> Duration {
		match self.0.checked_add(other.0) {
			Some(v) => Duration::from(v),
			None => Duration::from(time::Duration::MAX),
		}
	}
}

impl<'b> TryAdd<&'b Duration> for &Duration {
	type Output = Duration;
	fn try_add(self, other: &'b Duration) -> Result<Duration> {
		self.0
			.checked_add(other.0)
			.ok_or_else(|| Error::ArithmeticOverflow(format!("{self} + {other}")))
			.map_err(anyhow::Error::new)
			.map(Duration::from)
	}
}

impl ops::Sub for Duration {
	type Output = Self;
	fn sub(self, other: Self) -> Self {
		match self.0.checked_sub(other.0) {
			Some(v) => Duration::from(v),
			None => Duration::default(),
		}
	}
}

impl TrySub for Duration {
	type Output = Self;
	fn try_sub(self, other: Self) -> Result<Self> {
		self.0
			.checked_sub(other.0)
			.ok_or_else(|| Error::ArithmeticNegativeOverflow(format!("{self} - {other}")))
			.map_err(anyhow::Error::new)
			.map(Duration::from)
	}
}

impl<'b> ops::Sub<&'b Duration> for &Duration {
	type Output = Duration;
	fn sub(self, other: &'b Duration) -> Duration {
		match self.0.checked_sub(other.0) {
			Some(v) => Duration::from(v),
			None => Duration::default(),
		}
	}
}

impl<'b> TrySub<&'b Duration> for &Duration {
	type Output = Duration;
	fn try_sub(self, other: &'b Duration) -> Result<Duration> {
		self.0
			.checked_sub(other.0)
			.ok_or_else(|| Error::ArithmeticNegativeOverflow(format!("{self} - {other}")))
			.map_err(anyhow::Error::new)
			.map(Duration::from)
	}
}

impl ops::Add<Datetime> for Duration {
	type Output = Datetime;
	fn add(self, other: Datetime) -> Datetime {
		match chrono::Duration::from_std(self.0) {
			Ok(d) => match other.0.checked_add_signed(d) {
				Some(v) => Datetime::from(v),
				None => Datetime::MAX_UTC,
			},
			Err(_) => Datetime::MAX_UTC,
		}
	}
}

impl TryAdd<Datetime> for Duration {
	type Output = Datetime;
	fn try_add(self, other: Datetime) -> Result<Datetime> {
		match chrono::Duration::from_std(self.0) {
			Ok(d) => match other.0.checked_add_signed(d) {
				Some(v) => Ok(Datetime::from(v)),
				None => {
					Err(anyhow::Error::new(Error::ArithmeticOverflow(format!("{self} + {other}"))))
				}
			},
			Err(_) => {
				Err(anyhow::Error::new(Error::ArithmeticOverflow(format!("{self} + {other}"))))
			}
		}
	}
}

impl ops::Sub<Datetime> for Duration {
	type Output = Datetime;
	fn sub(self, other: Datetime) -> Datetime {
		match chrono::Duration::from_std(self.0) {
			Ok(d) => match other.0.checked_sub_signed(d) {
				Some(v) => Datetime::from(v),
				None => Datetime::MIN_UTC,
			},
			Err(_) => Datetime::MIN_UTC,
		}
	}
}

impl TrySub<Datetime> for Duration {
	type Output = Datetime;
	fn try_sub(self, other: Datetime) -> Result<Datetime> {
		match chrono::Duration::from_std(self.0) {
			Ok(d) => match other.0.checked_sub_signed(d) {
				Some(v) => Ok(Datetime::from(v)),
				None => Err(anyhow::Error::new(Error::ArithmeticNegativeOverflow(format!(
					"{self} - {other}"
				)))),
			},
			Err(_) => Err(anyhow::Error::new(Error::ArithmeticNegativeOverflow(format!(
				"{self} - {other}"
			)))),
		}
	}
}

impl Sum<Self> for Duration {
	fn sum<I>(iter: I) -> Duration
	where
		I: Iterator<Item = Self>,
	{
		iter.fold(Duration::default(), |a, b| a + b)
	}
}

impl<'a> Sum<&'a Self> for Duration {
	fn sum<I>(iter: I) -> Duration
	where
		I: Iterator<Item = &'a Self>,
	{
		iter.fold(Duration::default(), |a, b| &a + b)
	}
}

impl InfoStructure for Duration {
	fn structure(self) -> Value {
		self.to_string().into()
	}
}