surrealdb_core/fnc/
time.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
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
use crate::err::Error;
use crate::sql::datetime::Datetime;
use crate::sql::duration::Duration;
use crate::sql::value::Value;
use chrono::offset::TimeZone;
use chrono::{DateTime, Datelike, DurationRound, Local, Timelike, Utc};

pub fn ceil((val, duration): (Datetime, Duration)) -> Result<Value, Error> {
	match chrono::Duration::from_std(*duration) {
		Ok(d) => {
			let floor_to_ceil = |floor: DateTime<Utc>| -> Option<DateTime<Utc>> {
				if floor == *val {
					Some(floor)
				} else {
					floor.checked_add_signed(d)
				}
			};
			// Check for zero duration.
			if d.is_zero() {
				return Ok(Value::Datetime(val));
			}
			let result = val
				.duration_trunc(d)
				.ok()
				.and_then(floor_to_ceil);

			match result {
				Some(v) => Ok(v.into()),
				_ => Err(Error::InvalidArguments {
					name: String::from("time::ceil"),
					message: String::from("The second argument must be a duration, and must be able to be represented as nanoseconds."),
				}),
			}
		},
		_ => Err(Error::InvalidArguments {
			name: String::from("time::ceil"),
			message: String::from("The second argument must be a duration, and must be able to be represented as nanoseconds."),
		}),
	}
}

pub fn day((val,): (Option<Datetime>,)) -> Result<Value, Error> {
	Ok(match val {
		Some(v) => v.day().into(),
		None => Datetime::default().day().into(),
	})
}

pub fn floor((val, duration): (Datetime, Duration)) -> Result<Value, Error> {
	match chrono::Duration::from_std(*duration) {
		Ok(d) => {
			// Check for zero duration
			if d.is_zero() {
				return Ok(Value::Datetime(val));
			}
			match val.duration_trunc(d){
				Ok(v) => Ok(v.into()),
				_ => Err(Error::InvalidArguments {
					name: String::from("time::floor"),
					message: String::from("The second argument must be a duration, and must be able to be represented as nanoseconds."),
				}),
			}
		},
		_ => Err(Error::InvalidArguments {
			name: String::from("time::floor"),
			message: String::from("The second argument must be a duration, and must be able to be represented as nanoseconds."),
		}),
	}
}

pub fn format((val, format): (Datetime, String)) -> Result<Value, Error> {
	Ok(val.format(&format).to_string().into())
}

pub fn group((val, group): (Datetime, String)) -> Result<Value, Error> {
	match group.as_str() {
		"year" => Ok(Utc
			.with_ymd_and_hms(val.year(), 1, 1, 0,0,0)
			.earliest()
			.unwrap()
			.into()),
		"month" => Ok(Utc
			.with_ymd_and_hms(val.year(), val.month(), 1, 0,0,0)
			.earliest()
			.unwrap()
			.into()),
		"day" => Ok(Utc
			.with_ymd_and_hms(val.year(), val.month(), val.day(), 0,0,0)
			.earliest()
			.unwrap()
			.into()),
		"hour" => Ok(Utc
			.with_ymd_and_hms(val.year(), val.month(), val.day(), val.hour(),0,0)
			.earliest()
			.unwrap()
			.into()),
		"minute" => Ok(Utc
			.with_ymd_and_hms(val.year(), val.month(), val.day(), val.hour(), val.minute(),0)
			.earliest()
			.unwrap()
			.into()),
		"second" => Ok(Utc
			.with_ymd_and_hms(val.year(), val.month(), val.day(), val.hour(), val.minute(), val.second())
			.earliest()
			.unwrap()
			.into()),
		_ => Err(Error::InvalidArguments {
			name: String::from("time::group"),
			message: String::from("The second argument must be a string, and can be one of 'year', 'month', 'day', 'hour', 'minute', or 'second'."),
		}),
	}
}

pub fn hour((val,): (Option<Datetime>,)) -> Result<Value, Error> {
	Ok(match val {
		Some(v) => v.hour().into(),
		None => Datetime::default().hour().into(),
	})
}

pub fn max((array,): (Vec<Datetime>,)) -> Result<Value, Error> {
	Ok(match array.into_iter().max() {
		Some(v) => v.into(),
		None => Value::None,
	})
}

pub fn min((array,): (Vec<Datetime>,)) -> Result<Value, Error> {
	Ok(match array.into_iter().min() {
		Some(v) => v.into(),
		None => Value::None,
	})
}

pub fn minute((val,): (Option<Datetime>,)) -> Result<Value, Error> {
	Ok(match val {
		Some(v) => v.minute().into(),
		None => Datetime::default().minute().into(),
	})
}

pub fn month((val,): (Option<Datetime>,)) -> Result<Value, Error> {
	Ok(match val {
		Some(v) => v.month().into(),
		None => Datetime::default().month().into(),
	})
}

pub fn nano((val,): (Option<Datetime>,)) -> Result<Value, Error> {
	Ok(match val {
		Some(v) => v.timestamp_nanos_opt().unwrap_or_default().into(),
		None => Datetime::default().timestamp_nanos_opt().unwrap_or_default().into(),
	})
}

pub fn millis((val,): (Option<Datetime>,)) -> Result<Value, Error> {
	Ok(match val {
		Some(v) => v.timestamp_millis().into(),
		None => Datetime::default().timestamp_millis().into(),
	})
}

pub fn micros((val,): (Option<Datetime>,)) -> Result<Value, Error> {
	Ok(match val {
		Some(v) => v.timestamp_micros().into(),
		None => Datetime::default().timestamp_micros().into(),
	})
}

pub fn now(_: ()) -> Result<Value, Error> {
	Ok(Datetime::default().into())
}

pub fn round((val, duration): (Datetime, Duration)) -> Result<Value, Error> {
	match chrono::Duration::from_std(*duration) {
		Ok(d) => {
			// Check for zero duration
			if d.is_zero() {
				return Ok(Value::Datetime(val));
			}
			match val.duration_round(d) {
				Ok(v) => Ok(v.into()),
				_ => Err(Error::InvalidArguments {
					name: String::from("time::round"),
					message: String::from("The second argument must be a duration, and must be able to be represented as nanoseconds."),
				}),
			}
		},
		_ => Err(Error::InvalidArguments {
			name: String::from("time::round"),
			message: String::from("The second argument must be a duration, and must be able to be represented as nanoseconds."),
		}),
	}
}

pub fn second((val,): (Option<Datetime>,)) -> Result<Value, Error> {
	Ok(match val {
		Some(v) => v.second().into(),
		None => Datetime::default().second().into(),
	})
}

pub fn timezone(_: ()) -> Result<Value, Error> {
	Ok(Local::now().offset().to_string().into())
}

pub fn unix((val,): (Option<Datetime>,)) -> Result<Value, Error> {
	Ok(match val {
		Some(v) => v.timestamp().into(),
		None => Datetime::default().timestamp().into(),
	})
}

pub fn wday((val,): (Option<Datetime>,)) -> Result<Value, Error> {
	Ok(match val {
		Some(v) => v.weekday().number_from_monday().into(),
		None => Datetime::default().weekday().number_from_monday().into(),
	})
}

pub fn week((val,): (Option<Datetime>,)) -> Result<Value, Error> {
	Ok(match val {
		Some(v) => v.iso_week().week().into(),
		None => Datetime::default().iso_week().week().into(),
	})
}

pub fn yday((val,): (Option<Datetime>,)) -> Result<Value, Error> {
	Ok(match val {
		Some(v) => v.ordinal().into(),
		None => Datetime::default().ordinal().into(),
	})
}

pub fn year((val,): (Option<Datetime>,)) -> Result<Value, Error> {
	Ok(match val {
		Some(v) => v.year().into(),
		None => Datetime::default().year().into(),
	})
}

pub mod is {
	use crate::err::Error;
	use crate::sql::{Datetime, Value};

	pub fn leap_year((val,): (Option<Datetime>,)) -> Result<Value, Error> {
		Ok(match val {
			Some(v) => v.naive_utc().date().leap_year().into(),
			None => Datetime::default().naive_utc().date().leap_year().into(),
		})
	}
}

pub mod from {

	use crate::err::Error;
	use crate::sql::datetime::Datetime;
	use crate::sql::{value::Value, Uuid};
	use chrono::DateTime;
	use ulid::Ulid;

	pub fn nanos((val,): (i64,)) -> Result<Value, Error> {
		const NANOS_PER_SEC: i64 = 1_000_000_000;

		let seconds = val.div_euclid(NANOS_PER_SEC);
		let nanoseconds = val.rem_euclid(NANOS_PER_SEC) as u32;

		match DateTime::from_timestamp(seconds, nanoseconds) {
			Some(v) => Ok(Datetime::from(v).into()),
			None => Err(Error::InvalidArguments {
				name: String::from("time::from::nanos"),
				message: String::from("The first argument must be an in-bounds number of nanoseconds relative to January 1, 1970 0:00:00 UTC."),
			}),
		}
	}

	pub fn micros((val,): (i64,)) -> Result<Value, Error> {
		match DateTime::from_timestamp_micros(val) {
			Some(v) => Ok(Datetime::from(v).into()),
			None => Err(Error::InvalidArguments {
				name: String::from("time::from::micros"),
				message: String::from("The first argument must be an in-bounds number of microseconds relative to January 1, 1970 0:00:00 UTC."),
			}),
		}
	}

	pub fn millis((val,): (i64,)) -> Result<Value, Error> {
		match DateTime::from_timestamp_millis(val) {
			Some(v) => Ok(Datetime::from(v).into()),
			None => Err(Error::InvalidArguments {
				name: String::from("time::from::millis"),
				message: String::from("The first argument must be an in-bounds number of milliseconds relative to January 1, 1970 0:00:00 UTC."),
			}),
		}
	}

	pub fn secs((val,): (i64,)) -> Result<Value, Error> {
		match DateTime::from_timestamp(val, 0) {
			Some(v) => Ok(Datetime::from(v).into()),
			None => Err(Error::InvalidArguments {
				name: String::from("time::from::secs"),
				message: String::from("The first argument must be an in-bounds number of seconds relative to January 1, 1970 0:00:00 UTC."),
			}),
		}
	}

	pub fn unix((val,): (i64,)) -> Result<Value, Error> {
		match DateTime::from_timestamp(val, 0) {
			Some(v) => Ok(Datetime::from(v).into()),
			None => Err(Error::InvalidArguments {
				name: String::from("time::from::unix"),
				message: String::from("The first argument must be an in-bounds number of seconds relative to January 1, 1970 0:00:00 UTC."),
			}),
		}
	}

	pub fn ulid((val,): (String,)) -> Result<Value, Error> {
		match Ulid::from_string(&val) {
			Ok(v) => Ok(Datetime::from(DateTime::from(v.datetime())).into()),
			_ => Err(Error::InvalidArguments {
				name: String::from("time::from::ulid"),
				message: String::from(
					"The first argument must be a string, containing a valid ULID.",
				),
			}),
		}
	}

	pub fn uuid((val,): (Uuid,)) -> Result<Value, Error> {
		match val.0.get_timestamp() {
			Some(v) => {
				let (s, ns) = v.to_unix();
				match Datetime::try_from((s as i64, ns)) {
					Ok(v) => Ok(v.into()),
					_ => Err(fail!("Failed to convert UUID Timestamp to Datetime.")),
				}
			}
			None => Err(Error::InvalidArguments {
				name: String::from("time::from::uuid"),
				message: String::from("The first argument must be a v1, v6 or v7 UUID."),
			}),
		}
	}
}