stmo-cli 0.11.0

Turn Claude Code into a data analyst on sql.telemetry.mozilla.org
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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
#![allow(clippy::missing_errors_doc)]

use serde::{Deserialize, Deserializer, Serialize};

fn deserialize_null_as_empty_vec<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
where
    T: Deserialize<'de>,
    D: Deserializer<'de>,
{
    Ok(Option::deserialize(deserializer)?.unwrap_or_default())
}

fn deserialize_viz_id<'de, D>(deserializer: D) -> Result<Option<u64>, D::Error>
where
    D: Deserializer<'de>,
{
    let value: Option<u64> = Option::deserialize(deserializer)?;
    Ok(value.filter(|&id| id != 0))
}

fn default_width() -> u32 {
    1
}

fn deserialize_interval<'de, D>(deserializer: D) -> Result<Option<u64>, D::Error>
where
    D: Deserializer<'de>,
{
    use serde::de::Error;
    match Option::<serde_json::Value>::deserialize(deserializer)? {
        None | Some(serde_json::Value::Null) => Ok(None),
        Some(serde_json::Value::Number(n)) => n
            .as_u64()
            .ok_or_else(|| D::Error::custom("interval is not a valid u64"))
            .map(Some),
        Some(serde_json::Value::String(s)) => s.parse::<u64>().map_err(D::Error::custom).map(Some),
        Some(other) => Err(D::Error::custom(format!(
            "unexpected interval value: {other}"
        ))),
    }
}

fn deserialize_null_as_empty_string<'de, D>(deserializer: D) -> Result<String, D::Error>
where
    D: Deserializer<'de>,
{
    Ok(Option::deserialize(deserializer)?.unwrap_or_default())
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Query {
    pub id: u64,
    pub name: String,
    pub description: Option<String>,
    #[serde(rename = "query")]
    pub sql: String,
    pub data_source_id: u64,
    #[serde(default)]
    pub user: Option<QueryUser>,
    pub schedule: Option<Schedule>,
    pub options: QueryOptions,
    #[serde(default)]
    pub visualizations: Vec<Visualization>,
    pub tags: Option<Vec<String>>,
    pub is_archived: bool,
    pub is_draft: bool,
    pub updated_at: String,
    pub created_at: String,
}

#[derive(Debug, Serialize, Clone)]
pub struct CreateQuery {
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(rename = "query")]
    pub sql: String,
    pub data_source_id: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub schedule: Option<Schedule>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub options: Option<QueryOptions>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<String>>,
    pub is_archived: bool,
    pub is_draft: bool,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct QueryUser {
    pub id: u64,
    pub name: String,
    pub email: String,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct QueryOptions {
    #[serde(default)]
    pub parameters: Vec<Parameter>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Parameter {
    pub name: String,
    pub title: String,
    #[serde(rename = "type")]
    pub param_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub value: Option<serde_json::Value>,
    #[serde(rename = "enumOptions", skip_serializing_if = "Option::is_none")]
    pub enum_options: Option<String>,
    #[serde(rename = "queryId", skip_serializing_if = "Option::is_none")]
    pub query_id: Option<u64>,
    #[serde(rename = "multiValuesOptions", skip_serializing_if = "Option::is_none")]
    pub multi_values_options: Option<MultiValuesOptions>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct MultiValuesOptions {
    #[serde(rename = "prefix", skip_serializing_if = "Option::is_none")]
    pub prefix: Option<String>,
    #[serde(rename = "suffix", skip_serializing_if = "Option::is_none")]
    pub suffix: Option<String>,
    #[serde(rename = "separator", skip_serializing_if = "Option::is_none")]
    pub separator: Option<String>,
    #[serde(rename = "quoteCharacter", skip_serializing_if = "Option::is_none")]
    pub quote_character: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct Schedule {
    #[serde(default, deserialize_with = "deserialize_interval")]
    pub interval: Option<u64>,
    pub time: Option<String>,
    pub day_of_week: Option<String>,
    pub until: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Visualization {
    pub id: u64,
    pub name: String,
    #[serde(rename = "type")]
    pub viz_type: String,
    pub options: serde_json::Value,
    pub description: Option<String>,
}

#[derive(Debug, Serialize, Clone)]
pub struct CreateVisualization {
    pub query_id: u64,
    pub name: String,
    #[serde(rename = "type")]
    pub viz_type: String,
    pub options: serde_json::Value,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct QueriesResponse {
    pub results: Vec<Query>,
    pub count: u64,
    pub page: u64,
    pub page_size: u64,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct VisualizationMetadata {
    #[serde(
        default,
        deserialize_with = "deserialize_viz_id",
        skip_serializing_if = "Option::is_none"
    )]
    pub id: Option<u64>,
    pub name: String,
    #[serde(rename = "type")]
    pub viz_type: String,
    pub options: serde_json::Value,
    pub description: Option<String>,
}

impl From<&Visualization> for VisualizationMetadata {
    fn from(v: &Visualization) -> Self {
        Self {
            id: Some(v.id),
            name: v.name.clone(),
            viz_type: v.viz_type.clone(),
            options: v.options.clone(),
            description: v.description.clone(),
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct QueryMetadata {
    pub id: u64,
    pub name: String,
    pub description: Option<String>,
    pub data_source_id: u64,
    #[serde(default)]
    pub user_id: Option<u64>,
    pub schedule: Option<Schedule>,
    pub options: QueryOptions,
    pub visualizations: Vec<VisualizationMetadata>,
    pub tags: Option<Vec<String>>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct QuerySnippet {
    pub id: u64,
    pub trigger: String,
    pub description: Option<String>,
    pub snippet: String,
    #[serde(default)]
    pub user: Option<QueryUser>,
    pub updated_at: String,
    pub created_at: String,
}

#[derive(Debug, Serialize, Clone)]
pub struct CreateQuerySnippet {
    pub trigger: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    pub snippet: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SnippetMetadata {
    pub id: u64,
    pub trigger: String,
    pub description: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
#[allow(dead_code)]
pub struct User {
    pub id: u64,
    pub name: String,
    pub email: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_image_url: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct DataSource {
    pub id: u64,
    pub name: String,
    #[serde(rename = "type")]
    pub ds_type: String,
    pub syntax: Option<String>,
    pub description: Option<String>,
    pub paused: u8,
    pub pause_reason: Option<String>,
    pub view_only: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub queue_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scheduled_queue_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub groups: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub options: Option<serde_json::Value>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct DataSourceSchema {
    pub schema: Vec<SchemaTable>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SchemaTable {
    pub name: String,
    pub columns: Vec<SchemaColumn>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SchemaColumn {
    pub name: String,
    #[serde(rename = "type")]
    pub column_type: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct RefreshRequest {
    pub max_age: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parameters: Option<std::collections::HashMap<String, serde_json::Value>>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct AdhocRefreshRequest {
    #[serde(rename = "query")]
    pub sql: String,
    pub data_source_id: u64,
    pub max_age: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parameters: Option<std::collections::HashMap<String, serde_json::Value>>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct JobResponse {
    pub job: Job,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Job {
    pub id: String,
    pub status: u8,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub query_result_id: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct QueryResultResponse {
    pub query_result: QueryResult,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct QueryResult {
    pub id: u64,
    pub data: QueryResultData,
    pub runtime: f64,
    pub retrieved_at: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct QueryResultData {
    pub columns: Vec<Column>,
    pub rows: Vec<serde_json::Value>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Column {
    pub name: String,
    #[serde(rename = "type")]
    pub type_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub friendly_name: Option<String>,
}

#[derive(Debug, Clone, Copy)]
pub enum JobStatus {
    Pending = 1,
    Started = 2,
    Success = 3,
    Failure = 4,
    Cancelled = 5,
}

impl JobStatus {
    pub fn from_u8(status: u8) -> anyhow::Result<Self> {
        match status {
            1 => Ok(Self::Pending),
            2 => Ok(Self::Started),
            3 => Ok(Self::Success),
            4 => Ok(Self::Failure),
            5 => Ok(Self::Cancelled),
            _ => Err(anyhow::anyhow!("Invalid job status: {status}")),
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Dashboard {
    pub id: u64,
    pub name: String,
    pub slug: String,
    pub user_id: u64,
    pub is_archived: bool,
    pub is_draft: bool,
    #[serde(rename = "dashboard_filters_enabled")]
    pub filters_enabled: bool,
    pub tags: Vec<String>,
    #[serde(default, deserialize_with = "deserialize_null_as_empty_vec")]
    pub widgets: Vec<Widget>,
}

#[derive(Debug, Serialize)]
pub struct CreateDashboard {
    pub name: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Widget {
    pub id: u64,
    pub dashboard_id: u64,
    pub width: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub visualization_id: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub visualization: Option<WidgetVisualization>,
    #[serde(default, deserialize_with = "deserialize_null_as_empty_string")]
    pub text: String,
    pub options: WidgetOptions,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct WidgetVisualization {
    pub id: u64,
    pub name: String,
    pub query: VisualizationQuery,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct VisualizationQuery {
    pub id: u64,
    pub name: String,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct WidgetOptions {
    pub position: WidgetPosition,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "parameterMappings"
    )]
    pub parameter_mappings: Option<serde_json::Value>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct WidgetPosition {
    pub col: u32,
    pub row: u32,
    #[serde(rename = "sizeX")]
    pub size_x: u32,
    #[serde(rename = "sizeY")]
    pub size_y: u32,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct DashboardMetadata {
    pub id: u64,
    pub name: String,
    pub slug: String,
    pub user_id: u64,
    pub is_draft: bool,
    pub is_archived: bool,
    #[serde(rename = "dashboard_filters_enabled")]
    pub filters_enabled: bool,
    pub tags: Vec<String>,
    pub widgets: Vec<WidgetMetadata>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct WidgetMetadata {
    pub id: u64,
    #[serde(default = "default_width")]
    pub width: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub visualization_id: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub query_id: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub visualization_name: Option<String>,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub text: String,
    pub options: WidgetOptions,
}

#[derive(Debug, Deserialize)]
pub struct DashboardsResponse {
    pub results: Vec<DashboardSummary>,
    pub count: u64,
}

#[derive(Debug, Deserialize)]
pub struct DashboardSummary {
    #[allow(dead_code)]
    pub id: u64,
    pub name: String,
    #[allow(dead_code)]
    pub slug: String,
    pub is_draft: bool,
    pub is_archived: bool,
}

#[derive(Debug, Serialize)]
pub struct CreateWidget {
    pub dashboard_id: u64,
    pub visualization_id: Option<u64>,
    pub text: String,
    pub width: u32,
    pub options: WidgetOptions,
}

#[must_use]
pub fn build_dashboard_level_parameter_mappings(parameters: &[Parameter]) -> serde_json::Value {
    let mut mappings = serde_json::Map::new();
    for param in parameters {
        mappings.insert(
            param.name.clone(),
            serde_json::json!({
                "mapTo": param.name,
                "name": param.name,
                "title": "",
                "type": "dashboard-level",
                "value": null,
            }),
        );
    }
    serde_json::Value::Object(mappings)
}

#[cfg(test)]
#[allow(clippy::missing_errors_doc)]
#[allow(clippy::unnecessary_literal_unwrap)]
mod tests {
    use super::*;

    #[test]
    fn test_job_status_from_u8_valid() {
        assert!(matches!(JobStatus::from_u8(1).unwrap(), JobStatus::Pending));
        assert!(matches!(JobStatus::from_u8(2).unwrap(), JobStatus::Started));
        assert!(matches!(JobStatus::from_u8(3).unwrap(), JobStatus::Success));
        assert!(matches!(JobStatus::from_u8(4).unwrap(), JobStatus::Failure));
        assert!(matches!(
            JobStatus::from_u8(5).unwrap(),
            JobStatus::Cancelled
        ));
    }

    #[test]
    fn test_job_status_from_u8_invalid() {
        assert!(JobStatus::from_u8(0).is_err());
        assert!(JobStatus::from_u8(6).is_err());
        assert!(JobStatus::from_u8(255).is_err());

        let err = JobStatus::from_u8(10).unwrap_err();
        assert!(err.to_string().contains("Invalid job status"));
    }

    #[test]
    fn test_query_serialization() {
        let query = Query {
            id: 1,
            name: "Test Query".to_string(),
            description: None,
            sql: "SELECT * FROM table".to_string(),
            data_source_id: 63,
            user: None,
            schedule: None,
            options: QueryOptions { parameters: vec![] },
            visualizations: vec![],
            tags: None,
            is_archived: false,
            is_draft: false,
            updated_at: "2026-01-21".to_string(),
            created_at: "2026-01-21".to_string(),
        };

        let json = serde_json::to_string(&query).unwrap();
        assert!(json.contains("\"query\":"));
        assert!(json.contains("SELECT * FROM table"));
    }

    #[test]
    fn test_query_metadata_deserialization() {
        let yaml = r"
id: 100064
name: Test Query
description: null
data_source_id: 63
user_id: 530
schedule: null
options:
  parameters:
    - name: project
      title: project
      type: enum
      value:
        - try
      enumOptions: |
        try
        autoland
visualizations: []
tags:
  - bug 1840828
";

        let metadata: QueryMetadata = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(metadata.id, 100_064);
        assert_eq!(metadata.name, "Test Query");
        assert_eq!(metadata.data_source_id, 63);
        assert_eq!(metadata.options.parameters.len(), 1);
        assert_eq!(metadata.options.parameters[0].name, "project");
    }

    #[test]
    fn test_query_snippet_deserialization() {
        let json = r#"{
            "id": 31,
            "trigger": "reviewbot_e2e_action_ctcs",
            "description": "Action-task gap compression CTEs",
            "snippet": "action_tasks AS (\n    SELECT 1\n)",
            "user": {
                "id": 530,
                "name": "jlorenzo@mozilla.com",
                "email": "jlorenzo@mozilla.com"
            },
            "updated_at": "2026-06-24T09:13:26.873Z",
            "created_at": "2026-06-24T09:13:26.873Z"
        }"#;

        let snippet: QuerySnippet = serde_json::from_str(json).unwrap();
        assert_eq!(snippet.id, 31);
        assert_eq!(snippet.trigger, "reviewbot_e2e_action_ctcs");
        assert_eq!(
            snippet.description,
            Some("Action-task gap compression CTEs".to_string())
        );
        assert!(snippet.snippet.contains("action_tasks AS"));
        assert_eq!(snippet.user.unwrap().email, "jlorenzo@mozilla.com");
    }

    #[test]
    fn test_query_snippet_missing_user_deserialization() {
        let json = r#"{
            "id": 12,
            "trigger": "days_ago",
            "description": "",
            "snippet": "(CURRENT_DATE - INTERVAL '$1' DAY)",
            "updated_at": "2018-04-05T19:36:28.831Z",
            "created_at": "2018-04-05T19:09:55.265Z"
        }"#;

        let snippet: QuerySnippet = serde_json::from_str(json).unwrap();
        assert_eq!(snippet.id, 12);
        assert!(snippet.user.is_none());
    }

    #[test]
    fn test_create_query_snippet_serialization() {
        let create = CreateQuerySnippet {
            trigger: "reviewbot_push_duration".to_string(),
            description: Some("Corrected push duration formula".to_string()),
            snippet: "TIMESTAMP_DIFF(a, b, SECOND)".to_string(),
        };

        let json = serde_json::to_string(&create).unwrap();
        assert!(json.contains("\"trigger\":\"reviewbot_push_duration\""));
        assert!(json.contains("\"snippet\":\"TIMESTAMP_DIFF(a, b, SECOND)\""));
        assert!(!json.contains("\"id\""));
    }

    #[test]
    fn test_create_query_snippet_omits_none_description() {
        let create = CreateQuerySnippet {
            trigger: "trig".to_string(),
            description: None,
            snippet: "SELECT 1".to_string(),
        };

        let json = serde_json::to_string(&create).unwrap();
        assert!(!json.contains("description"));
    }

    #[test]
    fn test_snippet_metadata_yaml_roundtrip() {
        let yaml = r"
id: 31
trigger: reviewbot_e2e_action_ctcs
description: Action-task gap compression CTEs
";

        let metadata: SnippetMetadata = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(metadata.id, 31);
        assert_eq!(metadata.trigger, "reviewbot_e2e_action_ctcs");
        assert_eq!(
            metadata.description,
            Some("Action-task gap compression CTEs".to_string())
        );

        let reserialized = serde_yaml::to_string(&metadata).unwrap();
        let roundtripped: SnippetMetadata = serde_yaml::from_str(&reserialized).unwrap();
        assert_eq!(roundtripped.id, metadata.id);
        assert_eq!(roundtripped.trigger, metadata.trigger);
    }

    #[test]
    fn test_datasource_deserialization() {
        let json = r#"{
            "id": 63,
            "name": "Test DB",
            "type": "bigquery",
            "description": null,
            "syntax": "sql",
            "paused": 0,
            "pause_reason": null,
            "view_only": false,
            "queue_name": "queries",
            "scheduled_queue_name": "scheduled_queries",
            "groups": {},
            "options": {}
        }"#;

        let ds: DataSource = serde_json::from_str(json).unwrap();
        assert_eq!(ds.id, 63);
        assert_eq!(ds.name, "Test DB");
        assert_eq!(ds.ds_type, "bigquery");
        assert_eq!(ds.syntax, Some("sql".to_string()));
        assert_eq!(ds.description, None);
        assert_eq!(ds.paused, 0);
        assert!(!ds.view_only);
        assert_eq!(ds.queue_name, Some("queries".to_string()));
    }

    #[test]
    fn test_datasource_with_nulls() {
        let json = r#"{
            "id": 10,
            "name": "Minimal DB",
            "type": "pg",
            "description": "Test description",
            "syntax": null,
            "paused": 1,
            "pause_reason": "Maintenance",
            "view_only": true,
            "queue_name": null,
            "scheduled_queue_name": null,
            "groups": null,
            "options": null
        }"#;

        let ds: DataSource = serde_json::from_str(json).unwrap();
        assert_eq!(ds.id, 10);
        assert_eq!(ds.name, "Minimal DB");
        assert_eq!(ds.ds_type, "pg");
        assert_eq!(ds.description, Some("Test description".to_string()));
        assert_eq!(ds.syntax, None);
        assert_eq!(ds.paused, 1);
        assert_eq!(ds.pause_reason, Some("Maintenance".to_string()));
        assert!(ds.view_only);
        assert_eq!(ds.queue_name, None);
    }

    #[test]
    fn test_datasource_schema_deserialization() {
        let json = r#"{
            "schema": [
                {
                    "name": "table1",
                    "columns": [
                        {"name": "col1", "type": "STRING"},
                        {"name": "col2", "type": "INTEGER"}
                    ]
                },
                {
                    "name": "table2",
                    "columns": [{"name": "id", "type": "INTEGER"}]
                }
            ]
        }"#;

        let schema: DataSourceSchema = serde_json::from_str(json).unwrap();
        assert_eq!(schema.schema.len(), 2);
        assert_eq!(schema.schema[0].name, "table1");
        assert_eq!(schema.schema[0].columns.len(), 2);
        assert_eq!(schema.schema[0].columns[0].name, "col1");
        assert_eq!(schema.schema[0].columns[0].column_type, "STRING");
        assert_eq!(schema.schema[1].name, "table2");
        assert_eq!(schema.schema[1].columns.len(), 1);
    }

    #[test]
    fn test_schema_table_structure() {
        let json = r#"{
            "name": "users",
            "columns": [
                {"name": "id", "type": "INTEGER"},
                {"name": "name", "type": "STRING"},
                {"name": "email", "type": "STRING"}
            ]
        }"#;

        let table: SchemaTable = serde_json::from_str(json).unwrap();
        assert_eq!(table.name, "users");
        assert_eq!(table.columns.len(), 3);
        assert_eq!(table.columns[0].name, "id");
        assert_eq!(table.columns[0].column_type, "INTEGER");
        assert_eq!(table.columns[1].name, "name");
        assert_eq!(table.columns[1].column_type, "STRING");
        assert_eq!(table.columns[2].name, "email");
        assert_eq!(table.columns[2].column_type, "STRING");
    }

    #[test]
    fn test_datasource_serialization() {
        let ds = DataSource {
            id: 123,
            name: "My DB".to_string(),
            ds_type: "mysql".to_string(),
            syntax: Some("sql".to_string()),
            description: Some("Test".to_string()),
            paused: 0,
            pause_reason: None,
            view_only: false,
            queue_name: Some("queries".to_string()),
            scheduled_queue_name: None,
            groups: None,
            options: None,
        };

        let json = serde_json::to_string(&ds).unwrap();
        assert!(json.contains("\"id\":123"));
        assert!(json.contains("\"name\":\"My DB\""));
        assert!(json.contains("\"type\":\"mysql\""));
        assert!(json.contains("\"syntax\":\"sql\""));
    }

    #[test]
    fn test_dashboard_deserialization() {
        let json = r#"{
            "id": 2570,
            "name": "Test Dashboard",
            "slug": "test-dashboard",
            "user_id": 530,
            "is_archived": false,
            "is_draft": false,
            "dashboard_filters_enabled": true,
            "tags": ["tag1", "tag2"],
            "widgets": []
        }"#;

        let dashboard: Dashboard = serde_json::from_str(json).unwrap();
        assert_eq!(dashboard.id, 2570);
        assert_eq!(dashboard.name, "Test Dashboard");
        assert_eq!(dashboard.slug, "test-dashboard");
        assert_eq!(dashboard.user_id, 530);
        assert!(!dashboard.is_archived);
        assert!(!dashboard.is_draft);
        assert!(dashboard.filters_enabled);
        assert_eq!(dashboard.tags, vec!["tag1", "tag2"]);
        assert_eq!(dashboard.widgets.len(), 0);
    }

    #[test]
    fn test_dashboard_with_widgets() {
        let json = r##"{
            "id": 2570,
            "name": "Test Dashboard",
            "slug": "test-dashboard",
            "user_id": 530,
            "is_archived": false,
            "is_draft": false,
            "dashboard_filters_enabled": false,
            "tags": [],
            "widgets": [
                {
                    "id": 75035,
                    "dashboard_id": 2570,
                    "width": 1,
                    "text": "# Test Widget",
                    "options": {
                        "position": {
                            "col": 0,
                            "row": 0,
                            "sizeX": 6,
                            "sizeY": 2
                        }
                    }
                },
                {
                    "id": 75029,
                    "dashboard_id": 2570,
                    "width": 1,
                    "visualization_id": 279588,
                    "visualization": {
                        "id": 279588,
                        "name": "Total MAU",
                        "query": {
                            "id": 114049,
                            "name": "MAU Query"
                        }
                    },
                    "text": "",
                    "options": {
                        "position": {
                            "col": 3,
                            "row": 2,
                            "sizeX": 3,
                            "sizeY": 8
                        },
                        "parameterMappings": {
                            "channel": {
                                "name": "channel",
                                "type": "dashboard-level"
                            }
                        }
                    }
                }
            ]
        }"##;

        let dashboard: Dashboard = serde_json::from_str(json).unwrap();
        assert_eq!(dashboard.widgets.len(), 2);
        assert_eq!(dashboard.widgets[0].id, 75035);
        assert_eq!(dashboard.widgets[0].text, "# Test Widget");
        assert!(dashboard.widgets[0].visualization_id.is_none());
        assert_eq!(dashboard.widgets[1].id, 75029);
        assert_eq!(dashboard.widgets[1].visualization_id, Some(279_588));
        let viz = dashboard.widgets[1].visualization.as_ref().unwrap();
        assert_eq!(viz.id, 279_588);
        assert_eq!(viz.query.id, 114_049);
    }

    #[test]
    fn test_widget_position_serde() {
        let json = r#"{
            "col": 3,
            "row": 5,
            "sizeX": 6,
            "sizeY": 4
        }"#;

        let position: WidgetPosition = serde_json::from_str(json).unwrap();
        assert_eq!(position.col, 3);
        assert_eq!(position.row, 5);
        assert_eq!(position.size_x, 6);
        assert_eq!(position.size_y, 4);

        let serialized = serde_json::to_string(&position).unwrap();
        assert!(serialized.contains("\"sizeX\":6"));
        assert!(serialized.contains("\"sizeY\":4"));
    }

    #[test]
    fn test_dashboard_metadata_yaml() {
        let yaml = r"
id: 2570
name: Test Dashboard
slug: test-dashboard
user_id: 530
is_draft: false
is_archived: false
dashboard_filters_enabled: true
tags:
  - tag1
  - tag2
widgets:
  - id: 75035
    visualization_id: null
    query_id: null
    visualization_name: null
    text: '# Test Widget'
    options:
      position:
        col: 0
        row: 0
        sizeX: 6
        sizeY: 2
      parameter_mappings: null
";

        let metadata: DashboardMetadata = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(metadata.id, 2570);
        assert_eq!(metadata.name, "Test Dashboard");
        assert_eq!(metadata.slug, "test-dashboard");
        assert_eq!(metadata.user_id, 530);
        assert!(!metadata.is_draft);
        assert!(!metadata.is_archived);
        assert!(metadata.filters_enabled);
        assert_eq!(metadata.tags, vec!["tag1", "tag2"]);
        assert_eq!(metadata.widgets.len(), 1);
        assert_eq!(metadata.widgets[0].id, 75035);
        assert_eq!(metadata.widgets[0].text, "# Test Widget");
    }

    #[test]
    fn test_widget_metadata_text_widget() {
        let yaml = r"
id: 75035
visualization_id: null
query_id: null
visualization_name: null
text: '## Section Header'
options:
  position:
    col: 0
    row: 0
    sizeX: 6
    sizeY: 2
  parameter_mappings: null
";

        let widget: WidgetMetadata = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(widget.id, 75035);
        assert!(widget.visualization_id.is_none());
        assert!(widget.query_id.is_none());
        assert!(widget.visualization_name.is_none());
        assert_eq!(widget.text, "## Section Header");
        assert_eq!(widget.options.position.col, 0);
        assert_eq!(widget.options.position.size_x, 6);
    }

    #[test]
    fn test_widget_metadata_viz_widget() {
        let yaml = r"
id: 75029
visualization_id: 279588
query_id: 114049
visualization_name: Total MAU
text: ''
options:
  position:
    col: 3
    row: 2
    sizeX: 3
    sizeY: 8
  parameterMappings:
    channel:
      name: channel
      type: dashboard-level
";

        let widget: WidgetMetadata = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(widget.id, 75029);
        assert_eq!(widget.visualization_id, Some(279_588));
        assert_eq!(widget.query_id, Some(114_049));
        assert_eq!(widget.visualization_name, Some("Total MAU".to_string()));
        assert_eq!(widget.text, "");
        assert!(widget.options.parameter_mappings.is_some());
    }

    #[test]
    fn test_create_widget_serialization() {
        let widget = CreateWidget {
            dashboard_id: 2570,
            visualization_id: Some(279_588),
            text: String::new(),
            width: 1,
            options: WidgetOptions {
                position: WidgetPosition {
                    col: 0,
                    row: 0,
                    size_x: 3,
                    size_y: 2,
                },
                parameter_mappings: None,
            },
        };

        let json = serde_json::to_string(&widget).unwrap();
        assert!(json.contains("\"dashboard_id\":2570"));
        assert!(json.contains("\"visualization_id\":279588"));
        assert!(json.contains("\"sizeX\":3"));
        assert!(json.contains("\"sizeY\":2"));
    }

    #[test]
    fn test_create_text_widget_serialization() {
        let widget = CreateWidget {
            dashboard_id: 2570,
            visualization_id: None,
            text: "Some text".to_string(),
            width: 1,
            options: WidgetOptions {
                position: WidgetPosition {
                    col: 0,
                    row: 0,
                    size_x: 3,
                    size_y: 2,
                },
                parameter_mappings: None,
            },
        };

        let json = serde_json::to_string(&widget).unwrap();
        assert!(json.contains("\"visualization_id\":null"));
    }

    #[test]
    fn test_dashboards_response() {
        let json = r#"{
            "results": [
                {
                    "id": 2570,
                    "name": "Dashboard 1",
                    "slug": "dashboard-1",
                    "is_draft": false,
                    "is_archived": false
                },
                {
                    "id": 2558,
                    "name": "Dashboard 2",
                    "slug": "dashboard-2",
                    "is_draft": true,
                    "is_archived": false
                }
            ],
            "count": 2
        }"#;

        let response: DashboardsResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.results.len(), 2);
        assert_eq!(response.count, 2);
        assert_eq!(response.results[0].id, 2570);
        assert_eq!(response.results[0].name, "Dashboard 1");
        assert_eq!(response.results[0].slug, "dashboard-1");
        assert!(!response.results[0].is_draft);
        assert!(!response.results[0].is_archived);
        assert_eq!(response.results[1].id, 2558);
        assert_eq!(response.results[1].slug, "dashboard-2");
        assert!(response.results[1].is_draft);
    }

    #[test]
    fn test_build_dashboard_level_parameter_mappings_empty() {
        let result = build_dashboard_level_parameter_mappings(&[]);
        assert_eq!(result, serde_json::json!({}));
    }

    #[test]
    fn test_build_dashboard_level_parameter_mappings_with_params() {
        let params = vec![
            Parameter {
                name: "channel".to_string(),
                title: "Channel".to_string(),
                param_type: "enum".to_string(),
                value: None,
                enum_options: None,
                query_id: None,
                multi_values_options: None,
            },
            Parameter {
                name: "date".to_string(),
                title: "Date".to_string(),
                param_type: "date".to_string(),
                value: None,
                enum_options: None,
                query_id: None,
                multi_values_options: None,
            },
        ];

        let result = build_dashboard_level_parameter_mappings(&params);

        let expected = serde_json::json!({
            "channel": {
                "mapTo": "channel",
                "name": "channel",
                "title": "",
                "type": "dashboard-level",
                "value": null,
            },
            "date": {
                "mapTo": "date",
                "name": "date",
                "title": "",
                "type": "dashboard-level",
                "value": null,
            },
        });

        assert_eq!(result, expected);
    }

    #[test]
    fn test_schedule_interval_as_integer() {
        let s: Schedule = serde_json::from_str(r#"{"interval": 3600}"#).unwrap();
        assert_eq!(s.interval, Some(3600));
    }

    #[test]
    fn test_schedule_interval_as_string() {
        let s: Schedule = serde_json::from_str(r#"{"interval": "3600"}"#).unwrap();
        assert_eq!(s.interval, Some(3600));
    }

    #[test]
    fn test_schedule_interval_null() {
        let s: Schedule = serde_json::from_str(r#"{"interval": null}"#).unwrap();
        assert_eq!(s.interval, None);
    }

    #[test]
    fn test_schedule_interval_absent() {
        let s: Schedule = serde_json::from_str(r"{}").unwrap();
        assert_eq!(s.interval, None);
    }

    #[test]
    fn test_column_type_null() {
        let c: Column = serde_json::from_str(
            r#"{"name": "revision", "friendly_name": "revision", "type": null}"#,
        )
        .unwrap();
        assert_eq!(c.name, "revision");
        assert_eq!(c.type_name, None);
    }

    #[test]
    fn test_column_type_present() {
        let c: Column = serde_json::from_str(
            r#"{"name": "time", "friendly_name": "time", "type": "datetime"}"#,
        )
        .unwrap();
        assert_eq!(c.type_name, Some("datetime".to_string()));
    }
}