estat-api 0.1.0

Unofficial async Rust client and CLI for the e-Stat API v3.0, the API of Japan's official statistics portal (政府統計の総合窓口): table search, metadata, statistical data with paging, bulk requests, datasets and the data catalog
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
//! Request parameters.
//!
//! Each builder keeps the query as name/value pairs. Setting the same
//! parameter twice keeps the last value.

use std::fmt::{Display, Formatter};
use std::str::FromStr;

/// Query pairs shared by the builders.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
struct Query(Vec<(String, String)>);

impl Query {
    fn set(&mut self, name: impl Into<String>, value: impl Into<String>) {
        let name = name.into();
        let value = value.into();
        match self.0.iter_mut().find(|(n, _)| *n == name) {
            Some(pair) => pair.1 = value,
            None => self.0.push((name, value)),
        }
    }

    fn flag(&mut self, name: &str, on: bool) {
        self.set(name, if on { "Y" } else { "N" });
    }
}

macro_rules! query_accessor {
    ($($ty:ty),*) => {$(
        impl $ty {
            /// Parameters in the order they were set, without `appId` and `lang`.
            pub fn query(&self) -> &[(String, String)] {
                &self.query.0
            }
        }
    )*};
}

/// Filter setters shared by the builders that take narrowing conditions.
macro_rules! filter_methods {
    () => {
        /// Hierarchy level (`lvTab`, `lvArea`, ...): `X`, `X-X`, `-X` or `X-`.
        pub fn level(mut self, dim: Dimension, level: impl Into<String>) -> Self {
            self.query.set(format!("lv{}", dim.param()), level);
            self
        }

        /// Item codes (`cdTab`, `cdArea`, ...), up to 100 separated by commas.
        /// `min` and `max` stand for the smallest and largest code.
        pub fn code(mut self, dim: Dimension, codes: impl Into<String>) -> Self {
            self.query.set(format!("cd{}", dim.param()), codes);
            self
        }

        /// Codes from this one on (`cdTabFrom`, ...).
        pub fn code_from(mut self, dim: Dimension, code: impl Into<String>) -> Self {
            self.query.set(format!("cd{}From", dim.param()), code);
            self
        }

        /// Codes up to this one (`cdTabTo`, ...).
        pub fn code_to(mut self, dim: Dimension, code: impl Into<String>) -> Self {
            self.query.set(format!("cd{}To", dim.param()), code);
            self
        }
    };
}

/// Area level of the tables to search (`collectArea`, 集計地域区分).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CollectArea {
    /// `1`: whole country (全国).
    Nationwide,
    /// `2`: prefectures (都道府県).
    Prefecture,
    /// `3`: municipalities (市区町村).
    Municipality,
}

impl CollectArea {
    /// Parameter value, `1` to `3`.
    pub fn code(&self) -> &'static str {
        match self {
            CollectArea::Nationwide => "1",
            CollectArea::Prefecture => "2",
            CollectArea::Municipality => "3",
        }
    }
}

/// Kind of data to search in [`StatsListParams`] (`searchKind`, 検索データ種別).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SearchKind {
    /// `1`: statistics (統計情報), the default.
    Statistics,
    /// `2`: small areas and grid squares (小地域・地域メッシュ).
    SmallArea,
}

impl SearchKind {
    /// Parameter value, `1` or `2`.
    pub fn code(&self) -> &'static str {
        match self {
            SearchKind::Statistics => "1",
            SearchKind::SmallArea => "2",
        }
    }
}

/// File format to search in [`DataCatalogParams`] (`dataType`, 検索データ形式).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DataType {
    /// `XLS`: Excel file.
    Xls,
    /// `CSV`: CSV file.
    Csv,
    /// `PDF`: PDF file.
    Pdf,
    /// `XML`: XML file.
    Xml,
    /// `XLS_REP`: Excel file laid out for reading (閲覧用).
    XlsRep,
    /// `DB`: table in the statistics database, usable with `getStatsData`.
    Db,
}

impl DataType {
    /// Parameter value, such as `XLS_REP`.
    pub fn code(&self) -> &'static str {
        match self {
            DataType::Xls => "XLS",
            DataType::Csv => "CSV",
            DataType::Pdf => "PDF",
            DataType::Xml => "XML",
            DataType::XlsRep => "XLS_REP",
            DataType::Db => "DB",
        }
    }
}

/// Replacement for special characters such as `-` or `X` in data values
/// (`replaceSpChar`, 特殊文字の置換).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ReplaceSpChar {
    /// `0`: keep them, the default.
    Keep,
    /// `1`: replace with `0`.
    Zero,
    /// `2`: replace with an empty string.
    Empty,
    /// `3`: replace with `NA`.
    Na,
}

impl ReplaceSpChar {
    /// Parameter value, `0` to `3`.
    pub fn code(&self) -> &'static str {
        match self {
            ReplaceSpChar::Keep => "0",
            ReplaceSpChar::Zero => "1",
            ReplaceSpChar::Empty => "2",
            ReplaceSpChar::Na => "3",
        }
    }
}

/// One axis of a statistical table: the tabulation item (表章事項), time
/// (時間軸事項), area (地域事項) or a classification (分類事項 01 to 15).
///
/// The id matches `@id` of [`ClassObj`](crate::ClassObj) and the attribute
/// names of [`DataValue`](crate::DataValue).
///
/// ```
/// use estat_api::Dimension;
///
/// let dim: Dimension = "cat01".parse().unwrap();
/// assert_eq!(dim, Dimension::Cat01);
/// assert_eq!(dim.id(), "cat01");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Dimension {
    /// `tab`: tabulation item (表章事項).
    Tab,
    /// `time`: time (時間軸事項).
    Time,
    /// `area`: area (地域事項).
    Area,
    /// `cat01`: classification 01 (分類事項01).
    Cat01,
    /// `cat02`: classification 02 (分類事項02).
    Cat02,
    /// `cat03`: classification 03 (分類事項03).
    Cat03,
    /// `cat04`: classification 04 (分類事項04).
    Cat04,
    /// `cat05`: classification 05 (分類事項05).
    Cat05,
    /// `cat06`: classification 06 (分類事項06).
    Cat06,
    /// `cat07`: classification 07 (分類事項07).
    Cat07,
    /// `cat08`: classification 08 (分類事項08).
    Cat08,
    /// `cat09`: classification 09 (分類事項09).
    Cat09,
    /// `cat10`: classification 10 (分類事項10).
    Cat10,
    /// `cat11`: classification 11 (分類事項11).
    Cat11,
    /// `cat12`: classification 12 (分類事項12).
    Cat12,
    /// `cat13`: classification 13 (分類事項13).
    Cat13,
    /// `cat14`: classification 14 (分類事項14).
    Cat14,
    /// `cat15`: classification 15 (分類事項15).
    Cat15,
}

impl Dimension {
    /// Every dimension, in the order above.
    pub const ALL: [Dimension; 18] = [
        Dimension::Tab,
        Dimension::Time,
        Dimension::Area,
        Dimension::Cat01,
        Dimension::Cat02,
        Dimension::Cat03,
        Dimension::Cat04,
        Dimension::Cat05,
        Dimension::Cat06,
        Dimension::Cat07,
        Dimension::Cat08,
        Dimension::Cat09,
        Dimension::Cat10,
        Dimension::Cat11,
        Dimension::Cat12,
        Dimension::Cat13,
        Dimension::Cat14,
        Dimension::Cat15,
    ];

    /// Id used by e-Stat: `tab`, `time`, `area` or `cat01` to `cat15`.
    pub fn id(&self) -> &'static str {
        match self {
            Dimension::Tab => "tab",
            Dimension::Time => "time",
            Dimension::Area => "area",
            Dimension::Cat01 => "cat01",
            Dimension::Cat02 => "cat02",
            Dimension::Cat03 => "cat03",
            Dimension::Cat04 => "cat04",
            Dimension::Cat05 => "cat05",
            Dimension::Cat06 => "cat06",
            Dimension::Cat07 => "cat07",
            Dimension::Cat08 => "cat08",
            Dimension::Cat09 => "cat09",
            Dimension::Cat10 => "cat10",
            Dimension::Cat11 => "cat11",
            Dimension::Cat12 => "cat12",
            Dimension::Cat13 => "cat13",
            Dimension::Cat14 => "cat14",
            Dimension::Cat15 => "cat15",
        }
    }

    /// Part of the filter parameter names: `Tab`, `Time`, `Area`, `Cat01`, ...
    fn param(&self) -> String {
        let id = self.id();
        id[..1].to_ascii_uppercase() + &id[1..]
    }
}

impl Display for Dimension {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.id())
    }
}

impl FromStr for Dimension {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Dimension::ALL
            .into_iter()
            .find(|d| d.id() == s)
            .ok_or_else(|| {
                format!("unknown dimension {s:?}: use tab, time, area or cat01 to cat15")
            })
    }
}

/// Parameters of [`EstatApi::stats_list`](crate::EstatApi::stats_list)
/// (`getStatsList`, 統計表情報取得).
///
/// Without any parameter the call lists every table, so narrow it down.
///
/// ```
/// use estat_api::StatsListParams;
///
/// let params = StatsListParams::new()
///     .search_word("人口 AND 東京")
///     .stats_code("00200521")
///     .limit(100);
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct StatsListParams {
    query: Query,
}

impl StatsListParams {
    /// No conditions.
    pub fn new() -> Self {
        Self::default()
    }

    /// Survey period (`surveyYears`): `yyyy`, `yyyymm` or `yyyymm-yyyymm`.
    pub fn survey_years(mut self, value: impl Into<String>) -> Self {
        self.query.set("surveyYears", value);
        self
    }

    /// Release period (`openYears`), in the same format as `survey_years`.
    pub fn open_years(mut self, value: impl Into<String>) -> Self {
        self.query.set("openYears", value);
        self
    }

    /// Statistics field (`statsField`): 2 digits for a major field, 4 for a minor one.
    pub fn stats_field(mut self, value: impl Into<String>) -> Self {
        self.query.set("statsField", value);
        self
    }

    /// Government statistics code (`statsCode`): 5 digits for an agency, 8 for a survey.
    pub fn stats_code(mut self, value: impl Into<String>) -> Self {
        self.query.set("statsCode", value);
        self
    }

    /// Keywords (`searchWord`). `AND`, `OR` and `NOT` combine words, as in `東京 AND 人口`.
    pub fn search_word(mut self, value: impl Into<String>) -> Self {
        self.query.set("searchWord", value);
        self
    }

    /// Kind of data (`searchKind`).
    pub fn search_kind(mut self, kind: SearchKind) -> Self {
        self.query.set("searchKind", kind.code());
        self
    }

    /// Area level (`collectArea`). Ignored for [`SearchKind::SmallArea`].
    pub fn collect_area(mut self, area: CollectArea) -> Self {
        self.query.set("collectArea", area.code());
        self
    }

    /// Include explanations (`explanationGetFlg`, default `true`).
    pub fn explanation(mut self, on: bool) -> Self {
        self.query.flag("explanationGetFlg", on);
        self
    }

    /// List survey names instead of tables (`statsNameList=Y`). The result is
    /// then in [`DataListInf::list_inf`](crate::DataListInf::list_inf).
    pub fn stats_name_list(mut self) -> Self {
        self.query.set("statsNameList", "Y");
        self
    }

    /// First row to return, from 1 (`startPosition`). Pass the previous `NEXT_KEY`.
    pub fn start_position(mut self, position: u64) -> Self {
        self.query.set("startPosition", position.to_string());
        self
    }

    /// Maximum number of rows (`limit`, default 100,000).
    pub fn limit(mut self, limit: u64) -> Self {
        self.query.set("limit", limit.to_string());
        self
    }

    /// Update date (`updatedDate`): `yyyy`, `yyyymm`, `yyyymmdd` or `yyyymmdd-yyyymmdd`.
    pub fn updated_date(mut self, value: impl Into<String>) -> Self {
        self.query.set("updatedDate", value);
        self
    }
}

/// Parameters of [`EstatApi::meta_info`](crate::EstatApi::meta_info)
/// (`getMetaInfo`, メタ情報取得).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MetaInfoParams {
    query: Query,
}

impl MetaInfoParams {
    /// Metadata of the table with this ID (`statsDataId`), such as `0003410379`.
    pub fn new(stats_data_id: impl Into<String>) -> Self {
        let mut query = Query::default();
        query.set("statsDataId", stats_data_id);
        MetaInfoParams { query }
    }

    /// Include explanations (`explanationGetFlg`, default `true`).
    pub fn explanation(mut self, on: bool) -> Self {
        self.query.flag("explanationGetFlg", on);
        self
    }
}

impl<T: Into<String>> From<T> for MetaInfoParams {
    fn from(stats_data_id: T) -> Self {
        MetaInfoParams::new(stats_data_id)
    }
}

/// Parameters of [`EstatApi::stats_data`](crate::EstatApi::stats_data)
/// (`getStatsData`, 統計データ取得).
///
/// Filters on the same dimension are combined with AND.
///
/// ```
/// use estat_api::{Dimension, StatsDataParams};
///
/// let params = StatsDataParams::table("0003410379")
///     .code(Dimension::Area, "13000")
///     .code_from(Dimension::Time, "2020000000")
///     .level(Dimension::Cat01, "1")
///     .limit(10_000);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StatsDataParams {
    query: Query,
}

impl StatsDataParams {
    /// Data of a statistical table (`statsDataId`).
    pub fn table(stats_data_id: impl Into<String>) -> Self {
        let mut query = Query::default();
        query.set("statsDataId", stats_data_id);
        StatsDataParams { query }
    }

    /// Data of a dataset registered on e-Stat (`dataSetId`). Its conditions
    /// apply, and filters added here narrow them further.
    pub fn dataset(data_set_id: impl Into<String>) -> Self {
        let mut query = Query::default();
        query.set("dataSetId", data_set_id);
        StatsDataParams { query }
    }

    filter_methods!();

    /// First row to return, from 1 (`startPosition`). Pass the previous `NEXT_KEY`.
    pub fn start_position(mut self, position: u64) -> Self {
        self.query.set("startPosition", position.to_string());
        self
    }

    /// Maximum number of rows (`limit`, default 100,000).
    pub fn limit(mut self, limit: u64) -> Self {
        self.query.set("limit", limit.to_string());
        self
    }

    /// Include the table's metadata in [`StatisticalData::class_inf`](crate::StatisticalData::class_inf)
    /// (`metaGetFlg`, default `true`).
    pub fn meta(mut self, on: bool) -> Self {
        self.query.flag("metaGetFlg", on);
        self
    }

    /// Return only the number of rows, in `RESULT_INF.TOTAL_NUMBER` (`cntGetFlg=Y`).
    pub fn count_only(mut self) -> Self {
        self.query.set("cntGetFlg", "Y");
        self
    }

    /// Include explanations (`explanationGetFlg`, default `true`).
    pub fn explanation(mut self, on: bool) -> Self {
        self.query.flag("explanationGetFlg", on);
        self
    }

    /// Include annotations of values (`annotationGetFlg`, default `true`).
    pub fn annotation(mut self, on: bool) -> Self {
        self.query.flag("annotationGetFlg", on);
        self
    }

    /// Replace special characters in values (`replaceSpChar`).
    pub fn replace_sp_char(mut self, replace: ReplaceSpChar) -> Self {
        self.query.set("replaceSpChar", replace.code());
        self
    }

    pub(crate) fn with_start(&self, position: u64) -> Self {
        self.clone().start_position(position)
    }
}

/// Parameters of [`EstatApi::data_catalog`](crate::EstatApi::data_catalog)
/// (`getDataCatalog`, データカタログ情報取得).
///
/// ```
/// use estat_api::{DataCatalogParams, DataType};
///
/// let params = DataCatalogParams::new()
///     .stats_code("00400001")
///     .data_types([DataType::Xls, DataType::Csv]);
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DataCatalogParams {
    query: Query,
}

impl DataCatalogParams {
    /// No conditions.
    pub fn new() -> Self {
        Self::default()
    }

    /// Survey period (`surveyYears`): `yyyy`, `yyyymm` or `yyyymm-yyyymm`.
    pub fn survey_years(mut self, value: impl Into<String>) -> Self {
        self.query.set("surveyYears", value);
        self
    }

    /// Release period (`openYears`), in the same format as `survey_years`.
    pub fn open_years(mut self, value: impl Into<String>) -> Self {
        self.query.set("openYears", value);
        self
    }

    /// Statistics field (`statsField`): 2 digits for a major field, 4 for a minor one.
    pub fn stats_field(mut self, value: impl Into<String>) -> Self {
        self.query.set("statsField", value);
        self
    }

    /// Government statistics code (`statsCode`): 5 digits for an agency, 8 for a survey.
    pub fn stats_code(mut self, value: impl Into<String>) -> Self {
        self.query.set("statsCode", value);
        self
    }

    /// Keywords (`searchWord`). `AND`, `OR` and `NOT` combine words.
    pub fn search_word(mut self, value: impl Into<String>) -> Self {
        self.query.set("searchWord", value);
        self
    }

    /// Area level (`collectArea`).
    pub fn collect_area(mut self, area: CollectArea) -> Self {
        self.query.set("collectArea", area.code());
        self
    }

    /// Include explanations (`explanationGetFlg`, default `true`).
    pub fn explanation(mut self, on: bool) -> Self {
        self.query.flag("explanationGetFlg", on);
        self
    }

    /// File formats (`dataType`). All formats when not set.
    pub fn data_types(mut self, types: impl IntoIterator<Item = DataType>) -> Self {
        let codes: Vec<&str> = types.into_iter().map(|t| t.code()).collect();
        self.query.set("dataType", codes.join(","));
        self
    }

    /// Catalog ID (`catalogId`).
    pub fn catalog_id(mut self, value: impl Into<String>) -> Self {
        self.query.set("catalogId", value);
        self
    }

    /// Catalog resource ID (`resourceId`).
    pub fn resource_id(mut self, value: impl Into<String>) -> Self {
        self.query.set("resourceId", value);
        self
    }

    /// First dataset to return, from 1 (`startPosition`). Pass the previous `NEXT_KEY`.
    pub fn start_position(mut self, position: u64) -> Self {
        self.query.set("startPosition", position.to_string());
        self
    }

    /// Maximum number of datasets (`limit`, default 100).
    pub fn limit(mut self, limit: u64) -> Self {
        self.query.set("limit", limit.to_string());
        self
    }

    /// Update date (`updatedDate`): `yyyy`, `yyyymm`, `yyyymmdd` or `yyyymmdd-yyyymmdd`.
    pub fn updated_date(mut self, value: impl Into<String>) -> Self {
        self.query.set("updatedDate", value);
        self
    }
}

/// One request of [`StatsDatasParams`]: a table or dataset with its filters.
///
/// ```
/// use estat_api::{Dimension, StatsDatasRequest};
///
/// let tokyo = StatsDatasRequest::table("0003448237").code(Dimension::Area, "13000");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StatsDatasRequest {
    query: Query,
}

impl StatsDatasRequest {
    /// Values of a statistical table (`statsDataId`).
    pub fn table(stats_data_id: impl Into<String>) -> Self {
        let mut query = Query::default();
        query.set("statsDataId", stats_data_id);
        StatsDatasRequest { query }
    }

    /// Values of a registered dataset (`dataSetId`).
    pub fn dataset(data_set_id: impl Into<String>) -> Self {
        let mut query = Query::default();
        query.set("dataSetId", data_set_id);
        StatsDatasRequest { query }
    }

    filter_methods!();

    /// First row to return, from 1 (`startPosition`).
    pub fn start_position(mut self, position: u64) -> Self {
        self.query.set("startPosition", position.to_string());
        self
    }

    /// Maximum number of rows (`limit`).
    pub fn limit(mut self, limit: u64) -> Self {
        self.query.set("limit", limit.to_string());
        self
    }

    /// Any other parameter of `statsDatasSpec`, as e-Stat names it.
    pub fn param(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.query.set(name, value);
        self
    }
}

/// Parameters of [`EstatApi::stats_datas`](crate::EstatApi::stats_datas)
/// (`getStatsDatas`, 統計データ一括取得).
///
/// Requests are numbered from 1 in the order they are added; the response
/// refers to them by that number. All requests together may return at most
/// 100,000 values.
///
/// ```
/// use estat_api::{Dimension, StatsDatasParams, StatsDatasRequest};
///
/// let params = StatsDatasParams::new()
///     .request(StatsDatasRequest::table("0003448237").code(Dimension::Area, "13000"))
///     .request(StatsDatasRequest::table("0003448237").code(Dimension::Area, "27000"))
///     .meta(false);
/// assert_eq!(
///     params.spec(),
///     r#"[{"statsDataId":"0003448237","cdArea":"13000"},{"statsDataId":"0003448237","cdArea":"27000"}]"#
/// );
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct StatsDatasParams {
    query: Query,
    requests: Vec<StatsDatasRequest>,
}

impl StatsDatasParams {
    /// No requests yet.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a request.
    pub fn request(mut self, request: StatsDatasRequest) -> Self {
        self.requests.push(request);
        self
    }

    /// The requests, in order.
    pub fn requests(&self) -> &[StatsDatasRequest] {
        &self.requests
    }

    /// Include metadata (`metaGetFlg`, default `true`).
    pub fn meta(mut self, on: bool) -> Self {
        self.query.flag("metaGetFlg", on);
        self
    }

    /// Include explanations (`explanationGetFlg`, default `true`).
    pub fn explanation(mut self, on: bool) -> Self {
        self.query.flag("explanationGetFlg", on);
        self
    }

    /// Include annotations of values (`annotationGetFlg`, default `true`).
    pub fn annotation(mut self, on: bool) -> Self {
        self.query.flag("annotationGetFlg", on);
        self
    }

    /// Replace special characters in values (`replaceSpChar`).
    pub fn replace_sp_char(mut self, replace: ReplaceSpChar) -> Self {
        self.query.set("replaceSpChar", replace.code());
        self
    }

    /// The `statsDatasSpec` parameter: the requests as a JSON array.
    pub fn spec(&self) -> String {
        let quote = |s: &str| serde_json::to_string(s).expect("strings serialize to JSON");
        let requests: Vec<String> = self
            .requests
            .iter()
            .map(|r| {
                let fields: Vec<String> = r
                    .query
                    .0
                    .iter()
                    .map(|(n, v)| format!("{}:{}", quote(n), quote(v)))
                    .collect();
                format!("{{{}}}", fields.join(","))
            })
            .collect();
        format!("[{}]", requests.join(","))
    }

    /// The form sent to e-Stat: the flags and `statsDatasSpec`.
    pub(crate) fn form(&self) -> Vec<(String, String)> {
        let mut form = self.query.0.clone();
        form.push(("statsDatasSpec".into(), self.spec()));
        form
    }
}

/// Parameters of [`EstatApi::datasets`](crate::EstatApi::datasets)
/// (`refDataset` without an ID, データセット参照).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DatasetsParams {
    query: Query,
}

impl DatasetsParams {
    /// No conditions.
    pub fn new() -> Self {
        Self::default()
    }

    /// Area level (`collectArea`).
    pub fn collect_area(mut self, area: CollectArea) -> Self {
        self.query.set("collectArea", area.code());
        self
    }

    /// Include explanations (`explanationGetFlg`, default `true`).
    pub fn explanation(mut self, on: bool) -> Self {
        self.query.flag("explanationGetFlg", on);
        self
    }
}

/// Parameters of [`EstatApi::dataset`](crate::EstatApi::dataset)
/// (`refDataset` with an ID, データセット参照).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DatasetParams {
    query: Query,
}

impl DatasetParams {
    /// The dataset with this ID (`dataSetId`).
    pub fn new(data_set_id: impl Into<String>) -> Self {
        let mut query = Query::default();
        query.set("dataSetId", data_set_id);
        DatasetParams { query }
    }

    /// Include explanations (`explanationGetFlg`, default `true`).
    pub fn explanation(mut self, on: bool) -> Self {
        self.query.flag("explanationGetFlg", on);
        self
    }
}

impl<T: Into<String>> From<T> for DatasetParams {
    fn from(data_set_id: T) -> Self {
        DatasetParams::new(data_set_id)
    }
}

/// Parameters of [`EstatApi::post_dataset`](crate::EstatApi::post_dataset)
/// (`postDataset`, データセット登録).
///
/// A dataset stores a table ID and filters under your application ID, so
/// that [`StatsDataParams::dataset`] can use them later.
///
/// ```
/// use estat_api::{Dimension, PostDatasetParams};
///
/// // Register, or update the dataset with this ID
/// let register = PostDatasetParams::register("0003448237")
///     .dataset_id("tokyo-population")
///     .name("東京都の人口")
///     .code(Dimension::Area, "13000");
/// // Delete it
/// let delete = PostDatasetParams::delete("tokyo-population");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PostDatasetParams {
    query: Query,
}

impl PostDatasetParams {
    /// Registers a dataset for a table (`processMode=E`). It needs at least
    /// one filter. With [`dataset_id`](Self::dataset_id) of an existing
    /// dataset, that dataset is updated.
    pub fn register(stats_data_id: impl Into<String>) -> Self {
        let mut query = Query::default();
        query.set("processMode", "E");
        query.set("statsDataId", stats_data_id);
        PostDatasetParams { query }
    }

    /// Deletes a dataset (`processMode=D`).
    pub fn delete(data_set_id: impl Into<String>) -> Self {
        let mut query = Query::default();
        query.set("processMode", "D");
        query.set("dataSetId", data_set_id);
        PostDatasetParams { query }
    }

    /// Dataset ID (`dataSetId`): up to 30 characters of letters, digits and
    /// `-_.@`. Without it e-Stat makes one from the survey code and the time.
    pub fn dataset_id(mut self, value: impl Into<String>) -> Self {
        self.query.set("dataSetId", value);
        self
    }

    /// Name or description (`dataSetName`), up to 256 characters.
    pub fn name(mut self, value: impl Into<String>) -> Self {
        self.query.set("dataSetName", value);
        self
    }

    /// Let other users see and use the dataset (`openSpecified`, default `false`).
    pub fn public(mut self, on: bool) -> Self {
        self.query.set("openSpecified", if on { "1" } else { "0" });
        self
    }

    filter_methods!();
}

query_accessor!(
    StatsListParams,
    MetaInfoParams,
    StatsDataParams,
    DataCatalogParams,
    StatsDatasRequest,
    StatsDatasParams,
    DatasetsParams,
    DatasetParams,
    PostDatasetParams
);

#[cfg(test)]
mod tests {
    use super::*;

    fn pairs(query: &[(String, String)]) -> Vec<(&str, &str)> {
        query
            .iter()
            .map(|(n, v)| (n.as_str(), v.as_str()))
            .collect()
    }

    #[test]
    fn stats_list_params() {
        let params = StatsListParams::new()
            .survey_years("201001-201212")
            .open_years("2013")
            .stats_field("03")
            .stats_code("00200")
            .search_word("就業 AND 東京")
            .search_kind(SearchKind::Statistics)
            .collect_area(CollectArea::Nationwide)
            .explanation(false)
            .stats_name_list()
            .start_position(101)
            .limit(100)
            .updated_date("20240101-20241231")
            .limit(50);
        assert_eq!(
            pairs(params.query()),
            [
                ("surveyYears", "201001-201212"),
                ("openYears", "2013"),
                ("statsField", "03"),
                ("statsCode", "00200"),
                ("searchWord", "就業 AND 東京"),
                ("searchKind", "1"),
                ("collectArea", "1"),
                ("explanationGetFlg", "N"),
                ("statsNameList", "Y"),
                ("startPosition", "101"),
                ("limit", "50"),
                ("updatedDate", "20240101-20241231"),
            ]
        );
        let params = StatsListParams::new()
            .search_kind(SearchKind::SmallArea)
            .collect_area(CollectArea::Prefecture)
            .explanation(true);
        assert_eq!(
            pairs(params.query()),
            [
                ("searchKind", "2"),
                ("collectArea", "2"),
                ("explanationGetFlg", "Y")
            ]
        );
    }

    #[test]
    fn meta_info_params() {
        let params: MetaInfoParams = "0003410379".into();
        assert_eq!(pairs(params.query()), [("statsDataId", "0003410379")]);
        let params = MetaInfoParams::new("1").explanation(false);
        assert_eq!(params.query().len(), 2);
    }

    #[test]
    fn stats_data_params() {
        let params = StatsDataParams::table("0003410379")
            .level(Dimension::Tab, "1-2")
            .code(Dimension::Area, "13000,14000")
            .code_from(Dimension::Time, "min")
            .code_to(Dimension::Cat15, "max")
            .start_position(1)
            .limit(10)
            .meta(false)
            .count_only()
            .explanation(true)
            .annotation(false)
            .replace_sp_char(ReplaceSpChar::Na);
        assert_eq!(
            pairs(params.query()),
            [
                ("statsDataId", "0003410379"),
                ("lvTab", "1-2"),
                ("cdArea", "13000,14000"),
                ("cdTimeFrom", "min"),
                ("cdCat15To", "max"),
                ("startPosition", "1"),
                ("limit", "10"),
                ("metaGetFlg", "N"),
                ("cntGetFlg", "Y"),
                ("explanationGetFlg", "Y"),
                ("annotationGetFlg", "N"),
                ("replaceSpChar", "3"),
            ]
        );
        let next = params.with_start(11);
        assert_eq!(next.query()[5], ("startPosition".into(), "11".into()));
        assert_eq!(
            pairs(StatsDataParams::dataset("ds").query()),
            [("dataSetId", "ds")]
        );
        let codes: Vec<&str> = [
            ReplaceSpChar::Keep,
            ReplaceSpChar::Zero,
            ReplaceSpChar::Empty,
        ]
        .iter()
        .map(ReplaceSpChar::code)
        .collect();
        assert_eq!(codes, ["0", "1", "2"]);
    }

    #[test]
    fn data_catalog_params() {
        let params = DataCatalogParams::new()
            .survey_years("2020")
            .open_years("2021")
            .stats_field("02")
            .stats_code("00200521")
            .search_word("人口")
            .collect_area(CollectArea::Municipality)
            .explanation(false)
            .data_types([
                DataType::Xls,
                DataType::Csv,
                DataType::Pdf,
                DataType::Xml,
                DataType::XlsRep,
                DataType::Db,
            ])
            .catalog_id("000001029859")
            .resource_id("000001275539")
            .start_position(101)
            .limit(100)
            .updated_date("2024");
        assert_eq!(
            pairs(params.query()),
            [
                ("surveyYears", "2020"),
                ("openYears", "2021"),
                ("statsField", "02"),
                ("statsCode", "00200521"),
                ("searchWord", "人口"),
                ("collectArea", "3"),
                ("explanationGetFlg", "N"),
                ("dataType", "XLS,CSV,PDF,XML,XLS_REP,DB"),
                ("catalogId", "000001029859"),
                ("resourceId", "000001275539"),
                ("startPosition", "101"),
                ("limit", "100"),
                ("updatedDate", "2024"),
            ]
        );
    }

    #[test]
    fn stats_datas_params() {
        let request = StatsDatasRequest::dataset("ds")
            .level(Dimension::Tab, "1")
            .code(Dimension::Area, "13000")
            .code_from(Dimension::Time, "1601")
            .code_to(Dimension::Time, "max")
            .start_position(2)
            .limit(10)
            .param("cdCat01", "000");
        assert_eq!(request.query().len(), 8);
        let params = StatsDatasParams::new()
            .request(request)
            .request(StatsDatasRequest::table("0003448237"))
            .meta(false)
            .explanation(true)
            .annotation(false)
            .replace_sp_char(ReplaceSpChar::Empty);
        assert_eq!(params.requests().len(), 2);
        assert_eq!(
            pairs(params.query()),
            [
                ("metaGetFlg", "N"),
                ("explanationGetFlg", "Y"),
                ("annotationGetFlg", "N"),
                ("replaceSpChar", "2"),
            ]
        );
        assert_eq!(
            params.spec(),
            r#"[{"dataSetId":"ds","lvTab":"1","cdArea":"13000","cdTimeFrom":"1601","cdTimeTo":"max","startPosition":"2","limit":"10","cdCat01":"000"},{"statsDataId":"0003448237"}]"#
        );
        let form = params.form();
        assert_eq!(form.len(), 5);
        assert_eq!(form[4], ("statsDatasSpec".into(), params.spec()));
        assert_eq!(StatsDatasParams::new().spec(), "[]");
    }

    #[test]
    fn dataset_params() {
        let params = DatasetsParams::new()
            .collect_area(CollectArea::Nationwide)
            .explanation(false);
        assert_eq!(
            pairs(params.query()),
            [("collectArea", "1"), ("explanationGetFlg", "N")]
        );
        let params: DatasetParams = "ds".into();
        assert_eq!(
            pairs(params.explanation(true).query()),
            [("dataSetId", "ds"), ("explanationGetFlg", "Y")]
        );

        let params = PostDatasetParams::register("0003448237")
            .dataset_id("my-set")
            .name("名前")
            .public(true)
            .level(Dimension::Area, "2")
            .code(Dimension::Cat01, "000")
            .code_from(Dimension::Time, "1601")
            .code_to(Dimension::Time, "1901");
        assert_eq!(
            pairs(params.query()),
            [
                ("processMode", "E"),
                ("statsDataId", "0003448237"),
                ("dataSetId", "my-set"),
                ("dataSetName", "名前"),
                ("openSpecified", "1"),
                ("lvArea", "2"),
                ("cdCat01", "000"),
                ("cdTimeFrom", "1601"),
                ("cdTimeTo", "1901"),
            ]
        );
        assert_eq!(
            pairs(PostDatasetParams::delete("my-set").public(false).query()),
            [
                ("processMode", "D"),
                ("dataSetId", "my-set"),
                ("openSpecified", "0")
            ]
        );
    }

    #[test]
    fn dimensions() {
        let ids: Vec<&str> = Dimension::ALL.iter().map(Dimension::id).collect();
        assert_eq!(ids[..4], ["tab", "time", "area", "cat01"]);
        assert_eq!(ids[17], "cat15");
        for dim in Dimension::ALL {
            assert_eq!(dim.to_string().parse::<Dimension>(), Ok(dim));
        }
        assert_eq!(Dimension::Cat07.param(), "Cat07");
        let error = "cat16".parse::<Dimension>().unwrap_err();
        assert!(error.contains("cat16"));
    }
}