Repository navigation
Expand file tree
/
Copy pathparams.rs
More file actions
2228 lines (2006 loc) · 78.5 KB
/
Copy pathparams.rs
File metadata and controls
2228 lines (2006 loc) · 78.5 KB
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Setting-parameter types shared across ggsql specifications.
//!
//! These model the `SETTING` clause machinery: parameter values, their
//! constraints, and validation. They are used by the plot AST, the table
//! AST, and the writers that consume both.
use crate::naming;
use crate::reader::SqlDialect;
use chrono::{DateTime, Datelike, NaiveDate, NaiveDateTime, NaiveTime, Timelike};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
// =============================================================================
// Array Element Type (for coercion)
// =============================================================================
/// Type of an ArrayElement value, used for type inference and coercion.
///
/// This enum represents the semantic type of values in a scale's input range,
/// allowing discrete scales to infer the target type from their domain values.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArrayElementType {
String,
Number,
Boolean,
Date,
DateTime,
Time,
}
/// Value for geom parameters (also used for literals)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ParameterValue {
String(String),
Number(f64),
Boolean(bool),
Array(Vec<ArrayElement>),
/// Null value to explicitly opt out of a setting
Null,
}
/// A collection of named parameter values, typically from `SET` clauses.
pub type Parameters = HashMap<String, ParameterValue>;
impl std::fmt::Display for ParameterValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ParameterValue::String(s) => write!(f, "'{}'", s),
ParameterValue::Number(n) => write!(f, "{}", n),
ParameterValue::Boolean(b) => write!(f, "{}", b),
ParameterValue::Array(arr) => {
write!(f, "[")?;
for (i, elem) in arr.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
match elem {
ArrayElement::String(s) => write!(f, "'{}'", s)?,
ArrayElement::Number(n) => write!(f, "{}", n)?,
ArrayElement::Boolean(b) => write!(f, "{}", b)?,
ArrayElement::Null => write!(f, "null")?,
ArrayElement::Date(d) => write!(f, "'{}'", d)?,
ArrayElement::DateTime(dt) => write!(f, "'{}'", dt)?,
ArrayElement::Time(t) => write!(f, "'{}'", t)?,
}
}
write!(f, "]")
}
ParameterValue::Null => write!(f, "null"),
}
}
}
/// Elements in arrays (shared type for property values)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ArrayElement {
String(String),
Number(f64),
Boolean(bool),
/// Null placeholder for partial input range inference (e.g., SCALE x FROM (0, null))
Null,
/// Date value (days since Unix epoch 1970-01-01)
Date(i32),
/// DateTime value (microseconds since Unix epoch)
DateTime(i64),
/// Time value (nanoseconds since midnight)
Time(i64),
}
/// Days from CE to Unix epoch (1970-01-01)
const UNIX_EPOCH_CE_DAYS: i32 = 719163;
/// Convert days-since-epoch to ISO date string
fn date_to_iso_string(days: i32) -> String {
NaiveDate::from_num_days_from_ce_opt(days + UNIX_EPOCH_CE_DAYS)
.map(|d| d.format("%Y-%m-%d").to_string())
.unwrap_or_else(|| days.to_string())
}
/// Convert microseconds-since-epoch to ISO datetime string
fn datetime_to_iso_string(micros: i64) -> String {
DateTime::from_timestamp_micros(micros)
.map(|dt| dt.format("%Y-%m-%dT%H:%M:%S").to_string())
.unwrap_or_else(|| micros.to_string())
}
/// Convert nanoseconds-since-midnight to ISO time string
fn time_to_iso_string(nanos: i64) -> String {
let secs = (nanos / 1_000_000_000) as u32;
let nano_part = (nanos % 1_000_000_000) as u32;
NaiveTime::from_num_seconds_from_midnight_opt(secs, nano_part)
.map(|t| t.format("%H:%M:%S").to_string())
.unwrap_or_else(|| format!("{}ns", nanos))
}
/// Get type name for error messages
fn target_type_name(t: ArrayElementType) -> &'static str {
match t {
ArrayElementType::String => "string",
ArrayElementType::Number => "number",
ArrayElementType::Boolean => "boolean",
ArrayElementType::Date => "date",
ArrayElementType::DateTime => "datetime",
ArrayElementType::Time => "time",
}
}
impl ArrayElement {
/// Get the type of this element.
///
/// Returns None for Null values.
pub fn element_type(&self) -> Option<ArrayElementType> {
match self {
Self::String(_) => Some(ArrayElementType::String),
Self::Number(_) => Some(ArrayElementType::Number),
Self::Boolean(_) => Some(ArrayElementType::Boolean),
Self::Date(_) => Some(ArrayElementType::Date),
Self::DateTime(_) => Some(ArrayElementType::DateTime),
Self::Time(_) => Some(ArrayElementType::Time),
Self::Null => None,
}
}
/// Infer the dominant type from a collection of ArrayElements.
///
/// Used by discrete scales to determine the target type from their input range.
/// Nulls are ignored. Returns None if all values are null or the slice is empty.
///
/// If multiple types are present, uses priority: Boolean > Number > Date > DateTime > Time > String
/// (Boolean is highest because it's most specific; String is lowest as it's the fallback)
pub fn infer_type(values: &[ArrayElement]) -> Option<ArrayElementType> {
let mut found_bool = false;
let mut found_number = false;
let mut found_date = false;
let mut found_datetime = false;
let mut found_time = false;
let mut found_string = false;
for elem in values {
match elem {
Self::Boolean(_) => found_bool = true,
Self::Number(_) => found_number = true,
Self::Date(_) => found_date = true,
Self::DateTime(_) => found_datetime = true,
Self::Time(_) => found_time = true,
Self::String(_) => found_string = true,
Self::Null => {}
}
}
// Priority order: most specific to least specific
if found_bool {
Some(ArrayElementType::Boolean)
} else if found_number {
Some(ArrayElementType::Number)
} else if found_date {
Some(ArrayElementType::Date)
} else if found_datetime {
Some(ArrayElementType::DateTime)
} else if found_time {
Some(ArrayElementType::Time)
} else if found_string {
Some(ArrayElementType::String)
} else {
None
}
}
/// Coerce this element to the target type.
///
/// Returns Ok with the coerced value, or Err with a description if coercion is impossible.
///
/// Coercion paths:
/// - String → Boolean: "true"/"false"/"yes"/"no"/"1"/"0" (case-insensitive)
/// - String → Number: parse as f64
/// - String → Date/DateTime/Time: parse ISO format
/// - Number → Boolean: 0 = false, non-zero = true
/// - Number → String: format as string
/// - Number → Date: interpret as days since Unix epoch
/// - Number → DateTime: interpret as microseconds since Unix epoch
/// - Number → Time: interpret as nanoseconds since midnight
/// - Boolean → Number: false = 0, true = 1
/// - Boolean → String: "true"/"false"
/// - Null → any: stays Null
pub fn coerce_to(&self, target: ArrayElementType) -> Result<ArrayElement, String> {
// Already the right type?
if self.element_type() == Some(target) {
return Ok(self.clone());
}
// Null stays Null
if matches!(self, Self::Null) {
return Ok(Self::Null);
}
match (self, target) {
// String → Boolean
(Self::String(s), ArrayElementType::Boolean) => match s.to_lowercase().as_str() {
"true" | "yes" | "1" => Ok(Self::Boolean(true)),
"false" | "no" | "0" => Ok(Self::Boolean(false)),
_ => Err(format!("Cannot coerce string '{}' to boolean", s)),
},
// String → Number
(Self::String(s), ArrayElementType::Number) => s
.parse::<f64>()
.map(Self::Number)
.map_err(|_| format!("Cannot coerce string '{}' to number", s)),
// String → Date
(Self::String(s), ArrayElementType::Date) => {
Self::from_date_string(s).ok_or_else(|| {
format!("Cannot coerce string '{}' to date (expected YYYY-MM-DD)", s)
})
}
// String → DateTime
(Self::String(s), ArrayElementType::DateTime) => Self::from_datetime_string(s)
.ok_or_else(|| format!("Cannot coerce string '{}' to datetime", s)),
// String → Time
(Self::String(s), ArrayElementType::Time) => Self::from_time_string(s)
.ok_or_else(|| format!("Cannot coerce string '{}' to time (expected HH:MM:SS)", s)),
// String → String (identity, already handled above but for completeness)
(Self::String(s), ArrayElementType::String) => Ok(Self::String(s.clone())),
// Number → Boolean
(Self::Number(n), ArrayElementType::Boolean) => Ok(Self::Boolean(*n != 0.0)),
// Number → String
(Self::Number(n), ArrayElementType::String) => Ok(Self::String(n.to_string())),
// Number → Date (days since epoch)
(Self::Number(n), ArrayElementType::Date) => Ok(Self::Date(*n as i32)),
// Number → DateTime (microseconds since epoch)
(Self::Number(n), ArrayElementType::DateTime) => Ok(Self::DateTime(*n as i64)),
// Number → Time (nanoseconds since midnight)
(Self::Number(n), ArrayElementType::Time) => Ok(Self::Time(*n as i64)),
// Boolean → Number
(Self::Boolean(b), ArrayElementType::Number) => {
Ok(Self::Number(if *b { 1.0 } else { 0.0 }))
}
// Boolean → String
(Self::Boolean(b), ArrayElementType::String) => Ok(Self::String(b.to_string())),
// Boolean → temporal types: not supported
(Self::Boolean(_), ArrayElementType::Date)
| (Self::Boolean(_), ArrayElementType::DateTime)
| (Self::Boolean(_), ArrayElementType::Time) => Err(format!(
"Cannot coerce boolean to {}",
target_type_name(target)
)),
// Date → String
(Self::Date(d), ArrayElementType::String) => Ok(Self::String(date_to_iso_string(*d))),
// Date → Number (days since epoch)
(Self::Date(d), ArrayElementType::Number) => Ok(Self::Number(*d as f64)),
// DateTime → String
(Self::DateTime(dt), ArrayElementType::String) => {
Ok(Self::String(datetime_to_iso_string(*dt)))
}
// DateTime → Number (microseconds since epoch)
(Self::DateTime(dt), ArrayElementType::Number) => Ok(Self::Number(*dt as f64)),
// Time → String
(Self::Time(t), ArrayElementType::String) => Ok(Self::String(time_to_iso_string(*t))),
// Time → Number (nanoseconds since midnight)
(Self::Time(t), ArrayElementType::Number) => Ok(Self::Number(*t as f64)),
// Temporal → Boolean: not supported
(Self::Date(_), ArrayElementType::Boolean)
| (Self::DateTime(_), ArrayElementType::Boolean)
| (Self::Time(_), ArrayElementType::Boolean) => {
Err(format!("Cannot coerce {} to boolean", self.type_name()))
}
// Cross-temporal conversions: not supported (lossy)
(Self::Date(_), ArrayElementType::DateTime)
| (Self::Date(_), ArrayElementType::Time)
| (Self::DateTime(_), ArrayElementType::Date)
| (Self::DateTime(_), ArrayElementType::Time)
| (Self::Time(_), ArrayElementType::Date)
| (Self::Time(_), ArrayElementType::DateTime) => Err(format!(
"Cannot coerce {} to {}",
self.type_name(),
target_type_name(target)
)),
// Identity cases (already handled by early return, but needed for exhaustiveness)
(Self::Number(n), ArrayElementType::Number) => Ok(Self::Number(*n)),
(Self::Boolean(b), ArrayElementType::Boolean) => Ok(Self::Boolean(*b)),
(Self::Date(d), ArrayElementType::Date) => Ok(Self::Date(*d)),
(Self::DateTime(dt), ArrayElementType::DateTime) => Ok(Self::DateTime(*dt)),
(Self::Time(t), ArrayElementType::Time) => Ok(Self::Time(*t)),
// Null cases are handled at the top
(Self::Null, _) => Ok(Self::Null),
}
}
/// Homogenize a slice of array elements to a common type.
///
/// Infers the target type from all elements, then attempts to coerce all elements
/// to that type. If coercion fails (e.g., string + number), falls back to String type.
///
/// Returns a new vector with homogenized elements.
pub fn homogenize(values: &[Self]) -> Vec<Self> {
// Infer target type from all elements
let Some(target_type) = Self::infer_type(values) else {
// All nulls or empty array - return cloned as-is
return values.to_vec();
};
// Try to coerce all elements to the inferred type
let coerced: Result<Vec<_>, _> = values
.iter()
.map(|elem| elem.coerce_to(target_type))
.collect();
match coerced {
Ok(coerced_arr) => coerced_arr,
Err(_) => {
// Coercion failed - fall back to String type
values
.iter()
.map(|elem| {
elem.coerce_to(ArrayElementType::String)
.unwrap_or(Self::Null)
})
.collect()
}
}
}
/// Convert this element to a SQL literal string.
///
/// Used for generating SQL expressions from literal values.
pub fn to_sql(&self, dialect: &dyn SqlDialect) -> String {
match self {
Self::String(s) => naming::quote_literal(s),
Self::Number(n) => n.to_string(),
Self::Boolean(b) => dialect.sql_boolean_literal(*b),
Self::Date(d) => dialect.sql_date_literal(*d),
Self::DateTime(dt) => dialect.sql_datetime_literal(*dt),
Self::Time(t) => dialect.sql_time_literal(*t),
Self::Null => "NULL".to_string(),
}
}
/// Get the type name for error messages.
fn type_name(&self) -> &'static str {
match self {
Self::String(_) => "string",
Self::Number(_) => "number",
Self::Boolean(_) => "boolean",
Self::Date(_) => "date",
Self::DateTime(_) => "datetime",
Self::Time(_) => "time",
Self::Null => "null",
}
}
/// Convert to f64 for numeric calculations
pub fn to_f64(&self) -> Option<f64> {
match self {
Self::Number(n) => Some(*n),
Self::Date(d) => Some(*d as f64),
Self::DateTime(dt) => Some(*dt as f64),
Self::Time(t) => Some(*t as f64),
_ => None,
}
}
/// Parse ISO date string "YYYY-MM-DD" to Date variant
pub fn from_date_string(s: &str) -> Option<Self> {
NaiveDate::parse_from_str(s, "%Y-%m-%d")
.ok()
.map(|d| Self::Date(d.num_days_from_ce() - UNIX_EPOCH_CE_DAYS))
}
/// Parse ISO datetime string to DateTime variant
///
/// Supports timezone-aware formats:
/// - RFC3339: `2024-01-15T10:30:00Z`, `2024-01-15T10:30:00+05:30`
/// - With offset: `2024-01-15T10:30:00+0530`
///
/// And timezone-naive formats (interpreted as UTC):
/// - `2024-01-15T10:30:00`, `2024-01-15T10:30:00.123`
/// - `2024-01-15 10:30:00`
pub fn from_datetime_string(s: &str) -> Option<Self> {
// Try RFC3339/ISO8601 with timezone first (e.g., "2024-01-15T10:30:00Z", "2024-01-15T10:30:00+05:30")
if let Ok(dt) = DateTime::parse_from_rfc3339(s) {
return Some(Self::DateTime(dt.timestamp_micros()));
}
// Try formats with explicit timezone offset (non-RFC3339 variants)
for fmt in &[
"%Y-%m-%dT%H:%M:%S%.f%:z", // 2024-01-15T10:30:00.123+05:30
"%Y-%m-%dT%H:%M:%S%:z", // 2024-01-15T10:30:00+05:30
"%Y-%m-%dT%H:%M:%S%.f%z", // 2024-01-15T10:30:00.123+0530
"%Y-%m-%dT%H:%M:%S%z", // 2024-01-15T10:30:00+0530
"%Y-%m-%d %H:%M:%S%:z", // 2024-01-15 10:30:00+05:30
"%Y-%m-%d %H:%M:%S%z", // 2024-01-15 10:30:00+0530
] {
if let Ok(dt) = DateTime::parse_from_str(s, fmt) {
return Some(Self::DateTime(dt.timestamp_micros()));
}
}
// Fall back to naive (timezone-unaware), assumed UTC
for fmt in &[
"%Y-%m-%dT%H:%M:%S%.f",
"%Y-%m-%dT%H:%M:%S",
"%Y-%m-%d %H:%M:%S",
] {
if let Ok(dt) = NaiveDateTime::parse_from_str(s, fmt) {
return Some(Self::DateTime(dt.and_utc().timestamp_micros()));
}
}
None
}
/// Parse ISO time string "HH:MM:SS[.sss]" to Time variant
pub fn from_time_string(s: &str) -> Option<Self> {
for fmt in &["%H:%M:%S%.f", "%H:%M:%S", "%H:%M"] {
if let Ok(t) = NaiveTime::parse_from_str(s, fmt) {
// Convert to nanoseconds since midnight
let nanos =
t.num_seconds_from_midnight() as i64 * 1_000_000_000 + t.nanosecond() as i64;
return Some(Self::Time(nanos));
}
}
None
}
/// Try to parse string as temporal type (Date/DateTime/Time).
///
/// If this is a String variant, attempts to parse it as a temporal type
/// in order of specificity: DateTime > Date > Time.
/// If parsing succeeds, returns the temporal variant. Otherwise returns self unchanged.
///
/// For non-String variants, returns self unchanged.
///
/// # Example
/// ```ignore
/// let elem = ArrayElement::String("1973-06-01".to_string());
/// let parsed = elem.try_as_temporal();
/// // parsed is now ArrayElement::Date(...)
/// ```
pub fn try_as_temporal(self) -> Self {
if let Self::String(ref s) = self {
// Try DateTime first (most specific)
if let Some(dt) = Self::from_datetime_string(s) {
return dt;
}
// Try Date
if let Some(d) = Self::from_date_string(s) {
return d;
}
// Try Time
if let Some(t) = Self::from_time_string(s) {
return t;
}
}
// Fall back to original value if not a string or parsing failed
self
}
/// Convert to string for HashMap keys and display
pub fn to_key_string(&self) -> String {
match self {
Self::String(s) => s.clone(),
Self::Number(n) => n.to_string(),
Self::Boolean(b) => b.to_string(),
Self::Null => "null".to_string(),
Self::Date(d) => date_to_iso_string(*d),
Self::DateTime(dt) => datetime_to_iso_string(*dt),
Self::Time(t) => time_to_iso_string(*t),
}
}
/// Convert to a serde_json::Value
pub fn to_json(&self) -> serde_json::Value {
match self {
ArrayElement::String(s) => serde_json::Value::String(s.clone()),
ArrayElement::Number(n) => serde_json::json!(n),
ArrayElement::Boolean(b) => serde_json::Value::Bool(*b),
ArrayElement::Null => serde_json::Value::Null,
// Temporal types serialize as ISO strings for JSON
ArrayElement::Date(d) => serde_json::Value::String(date_to_iso_string(*d)),
ArrayElement::DateTime(dt) => serde_json::Value::String(datetime_to_iso_string(*dt)),
ArrayElement::Time(t) => serde_json::Value::String(time_to_iso_string(*t)),
}
}
/// Convert Date (days since epoch) to ISO string "YYYY-MM-DD"
pub fn date_to_iso(days: i32) -> String {
date_to_iso_string(days)
}
/// Convert DateTime (microseconds since epoch) to ISO string
pub fn datetime_to_iso(micros: i64) -> String {
datetime_to_iso_string(micros)
}
/// Convert Time (nanoseconds since midnight) to ISO string "HH:MM:SS"
pub fn time_to_iso(nanos: i64) -> String {
time_to_iso_string(nanos)
}
}
impl ParameterValue {
/// Convert to a serde_json::Value
pub fn to_json(&self) -> serde_json::Value {
match self {
ParameterValue::String(s) => serde_json::Value::String(s.clone()),
ParameterValue::Number(n) => serde_json::json!(n),
ParameterValue::Boolean(b) => serde_json::Value::Bool(*b),
ParameterValue::Array(arr) => {
serde_json::Value::Array(arr.iter().map(|e| e.to_json()).collect())
}
ParameterValue::Null => serde_json::Value::Null,
}
}
/// Check if this is a null value
pub fn is_null(&self) -> bool {
matches!(self, ParameterValue::Null)
}
/// Try to extract as a string value
pub fn as_str(&self) -> Option<&str> {
match self {
ParameterValue::String(s) => Some(s),
_ => None,
}
}
/// Try to extract as a number value
pub fn as_number(&self) -> Option<f64> {
match self {
ParameterValue::Number(n) => Some(*n),
_ => None,
}
}
/// Try to extract as a boolean value
pub fn as_bool(&self) -> Option<bool> {
match self {
ParameterValue::Boolean(b) => Some(*b),
_ => None,
}
}
/// Try to extract as an array value
pub fn as_array(&self) -> Option<&[ArrayElement]> {
match self {
ParameterValue::Array(arr) => Some(arr),
_ => None,
}
}
/// Convert this parameter value to a SQL literal string.
///
/// Only supports scalar values (String, Number, Boolean, Null).
/// Arrays are handled separately in annotation layer VALUES clause generation.
pub fn to_sql(&self, dialect: &dyn SqlDialect) -> String {
match self {
ParameterValue::String(s) => naming::quote_literal(s),
ParameterValue::Number(n) => n.to_string(),
ParameterValue::Boolean(b) => dialect.sql_boolean_literal(*b),
ParameterValue::Array(_) => {
panic!("ParameterValue::to_sql() does not support arrays. Arrays in annotation layers should be handled via VALUES clause generation.")
}
ParameterValue::Null => "NULL".to_string(),
}
}
/// Convert a scalar ParameterValue to an ArrayElement.
///
/// Panics if called on an Array variant.
fn to_array_element(&self) -> ArrayElement {
match self {
ParameterValue::Number(num) => ArrayElement::Number(*num),
ParameterValue::String(s) => ArrayElement::String(s.clone()),
ParameterValue::Boolean(b) => ArrayElement::Boolean(*b),
ParameterValue::Null => ArrayElement::Null,
ParameterValue::Array(_) => panic!("Cannot convert Array to single ArrayElement"),
}
}
/// Recycle this value to a target array length.
///
/// - Scalars (String, Number, Boolean, Null) are converted to arrays with n copies
/// - Arrays of length 1 are recycled to n copies of that element
/// - Arrays of target length are returned as-is (after homogenization)
/// - Arrays of other lengths produce an error
pub fn rep(self, n: usize) -> Result<Self, crate::GgsqlError> {
match self {
// Arrays: homogenize types if mixed, then recycle if needed
ParameterValue::Array(arr) => {
if arr.len() == 1 {
// Recycle the single element
let element = arr[0].clone();
Ok(ParameterValue::Array(vec![element; n]))
} else if arr.len() == n {
// Already correct length - homogenize for type consistency
let arr = ArrayElement::homogenize(&arr);
Ok(ParameterValue::Array(arr))
} else {
// Mismatched length - shouldn't happen if validation passed
Err(crate::GgsqlError::InternalError(format!(
"Attempted to recycle array of length {} to length {} (should have been caught earlier)",
arr.len(),
n
)))
}
}
// Scalars: convert to ArrayElement and replicate n times
scalar => {
let elem = scalar.to_array_element();
Ok(ParameterValue::Array(vec![elem; n]))
}
}
}
}
// =============================================================================
// Default Property Types (Shared by Coord, Scale, and Geom traits)
// =============================================================================
/// Default value for a property parameter
///
/// Used by traits to declare both allowed property names and their default values
/// in a single declaration, avoiding the need to keep two separate implementations
/// in sync.
#[derive(Debug, Clone)]
pub enum DefaultParamValue {
String(&'static str),
Number(f64),
Boolean(bool),
Null,
}
// =============================================================================
// Parameter Constraint Types
// =============================================================================
/// Constraint state for a specific type
#[derive(Debug, Clone, Copy)]
pub enum TypeConstraint<T> {
/// Type not allowed for this parameter
Forbidden,
/// Type allowed, any value accepted
Any,
/// Type allowed with specific constraints
Constrained(T),
}
/// Constraint for Number values
#[derive(Debug, Clone, Copy)]
pub struct NumberConstraint {
pub min: Option<f64>,
pub max: Option<f64>,
pub min_exclusive: bool,
pub max_exclusive: bool,
pub whole: bool,
/// Unit suffixes the value must carry, given as a string (empty = plain
/// number) — for a CSS-style measurement like `width => '20%'`/`'240px'`.
/// The numeric part must be finite.
pub units: &'static [&'static str],
}
impl NumberConstraint {
/// No constraints on value
pub const fn unconstrained() -> Self {
Self {
min: None,
max: None,
min_exclusive: false,
max_exclusive: false,
whole: false,
units: &[],
}
}
/// Minimum value (inclusive)
pub const fn min(min: f64) -> Self {
Self {
min: Some(min),
max: None,
min_exclusive: false,
max_exclusive: false,
whole: false,
units: &[],
}
}
/// Minimum value (exclusive)
pub const fn min_exclusive(min: f64) -> Self {
Self {
min: Some(min),
max: None,
min_exclusive: true,
max_exclusive: false,
whole: false,
units: &[],
}
}
/// Value within range (inclusive on both ends)
pub const fn range(min: f64, max: f64) -> Self {
Self {
min: Some(min),
max: Some(max),
min_exclusive: false,
max_exclusive: false,
whole: false,
units: &[],
}
}
/// Whole number (integer) with minimum value (inclusive)
pub const fn count(min: f64) -> Self {
Self {
min: Some(min),
max: None,
min_exclusive: false,
max_exclusive: false,
whole: true,
units: &[],
}
}
/// Whole number (integer) within range (inclusive on both ends)
pub const fn count_range(min: f64, max: f64) -> Self {
Self {
min: Some(min),
max: Some(max),
min_exclusive: false,
max_exclusive: false,
whole: true,
units: &[],
}
}
}
/// Constraint for String values
#[derive(Debug, Clone, Copy)]
pub struct StringConstraint {
/// String must be one of these values (empty = any string allowed)
pub allowed_values: &'static [&'static str],
}
impl StringConstraint {
/// Any string allowed (empty slices = no restriction)
pub const fn unconstrained() -> Self {
Self {
allowed_values: &[],
}
}
/// String must be one of the specified values
pub const fn one_of(values: &'static [&'static str]) -> Self {
Self {
allowed_values: values,
}
}
}
/// Element constraint - specifies type AND value constraints for array elements
#[derive(Debug, Clone, Copy)]
pub enum ArrayElementConstraint {
/// Any element type allowed, no constraints
Any,
/// Must be numbers, with optional value constraint
Number(NumberConstraint),
/// Must be strings, with optional value constraint
String(StringConstraint),
/// Must be booleans
Boolean,
}
/// Constraint for Array values
#[derive(Debug, Clone, Copy)]
pub struct ArrayConstraint {
pub element: ArrayElementConstraint,
pub min_len: Option<usize>,
pub max_len: Option<usize>,
pub allow_null_elements: bool,
}
impl ArrayConstraint {
/// Array of numbers with value constraint
pub const fn of_numbers(constraint: NumberConstraint) -> Self {
Self {
element: ArrayElementConstraint::Number(constraint),
min_len: None,
max_len: None,
allow_null_elements: false,
}
}
/// Array of numbers with exact length and value constraint
pub const fn of_numbers_len(constraint: NumberConstraint, len: usize) -> Self {
Self {
element: ArrayElementConstraint::Number(constraint),
min_len: Some(len),
max_len: Some(len),
allow_null_elements: false,
}
}
/// Array of strings with value constraint
pub const fn of_strings(constraint: StringConstraint) -> Self {
Self {
element: ArrayElementConstraint::String(constraint),
min_len: None,
max_len: None,
allow_null_elements: false,
}
}
/// Array of strings with exact length and value constraint
#[allow(dead_code)]
pub const fn of_strings_len(constraint: StringConstraint, len: usize) -> Self {
Self {
element: ArrayElementConstraint::String(constraint),
min_len: Some(len),
max_len: Some(len),
allow_null_elements: false,
}
}
/// Any element types allowed (including nulls)
#[allow(dead_code)]
pub const fn any_elements() -> Self {
Self {
element: ArrayElementConstraint::Any,
min_len: None,
max_len: None,
allow_null_elements: true,
}
}
/// Builder method to allow null elements
#[allow(dead_code)]
pub const fn with_null_elements(mut self) -> Self {
self.allow_null_elements = true;
self
}
}
/// Validation constraint for a parameter value.
///
/// Each field specifies whether a type is forbidden, allowed (any value), or constrained.
/// Used by `ParamDefinition` to specify validation rules for parameters.
#[derive(Debug, Clone, Copy)]
pub struct ParamConstraint {
pub number: TypeConstraint<NumberConstraint>,
pub string: TypeConstraint<StringConstraint>,
pub boolean: TypeConstraint<()>,
pub array: TypeConstraint<ArrayConstraint>,
pub allow_null: bool,
}
impl ParamConstraint {
/// All types allowed, no constraints (default)
pub const fn unconstrained() -> Self {
Self {
number: TypeConstraint::Any,
string: TypeConstraint::Any,
boolean: TypeConstraint::Any,
array: TypeConstraint::Any,
allow_null: true,
}
}
/// Number only with constraint
pub const fn number(constraint: NumberConstraint) -> Self {
Self {
number: TypeConstraint::Constrained(constraint),
string: TypeConstraint::Forbidden,
boolean: TypeConstraint::Forbidden,
array: TypeConstraint::Forbidden,
allow_null: true,
}
}
/// Number only, any value
#[allow(dead_code)]
pub const fn number_any() -> Self {
Self {
number: TypeConstraint::Any,
string: TypeConstraint::Forbidden,
boolean: TypeConstraint::Forbidden,
array: TypeConstraint::Forbidden,
allow_null: true,
}
}
/// String only with enum constraint
pub const fn string_option(values: &'static [&'static str]) -> Self {
Self {
number: TypeConstraint::Forbidden,
string: TypeConstraint::Constrained(StringConstraint::one_of(values)),
boolean: TypeConstraint::Forbidden,
array: TypeConstraint::Forbidden,
allow_null: true,
}
}
/// A number with a unit suffix, written as a string — for a CSS-style
/// measurement like `width => '20%'`/`'240px'`. The numeric part is
/// constrained by `number`; a bare number without a unit is rejected.
pub const fn number_with_unit(
number: NumberConstraint,
units: &'static [&'static str],
) -> Self {
let mut number = number;
number.units = units;
Self {
number: TypeConstraint::Constrained(number),
string: TypeConstraint::Forbidden,
boolean: TypeConstraint::Forbidden,
array: TypeConstraint::Forbidden,
allow_null: true,
}
}
/// String only
pub const fn string() -> Self {
Self {
number: TypeConstraint::Forbidden,
string: TypeConstraint::Any,
boolean: TypeConstraint::Forbidden,
array: TypeConstraint::Forbidden,
allow_null: true,
}
}
/// Boolean only
pub const fn boolean() -> Self {
Self {
number: TypeConstraint::Forbidden,
string: TypeConstraint::Forbidden,
boolean: TypeConstraint::Any,
array: TypeConstraint::Forbidden,
allow_null: true,
}
}
/// Number or Array of numbers - for `expand` parameter
pub const fn number_or_numeric_array(num: NumberConstraint, arr: ArrayConstraint) -> Self {
Self {
number: TypeConstraint::Constrained(num),
string: TypeConstraint::Forbidden,
boolean: TypeConstraint::Forbidden,
array: TypeConstraint::Constrained(arr),
allow_null: true,
}
}
/// Number, Array of numbers, or String (any) - for `breaks` parameter
pub const fn number_or_array_or_string(num: NumberConstraint, arr: ArrayConstraint) -> Self {
Self {
number: TypeConstraint::Constrained(num),
string: TypeConstraint::Any, // Any string (temporal interval validated elsewhere)
boolean: TypeConstraint::Forbidden,
array: TypeConstraint::Constrained(arr),
allow_null: true,