Skip to main content

estat_api/
params.rs

1//! Request parameters.
2//!
3//! Each builder keeps the query as name/value pairs. Setting the same
4//! parameter twice keeps the last value.
5
6use std::fmt::{Display, Formatter};
7use std::str::FromStr;
8
9/// Query pairs shared by the builders.
10#[derive(Debug, Clone, Default, PartialEq, Eq)]
11struct Query(Vec<(String, String)>);
12
13impl Query {
14    fn set(&mut self, name: impl Into<String>, value: impl Into<String>) {
15        let name = name.into();
16        let value = value.into();
17        match self.0.iter_mut().find(|(n, _)| *n == name) {
18            Some(pair) => pair.1 = value,
19            None => self.0.push((name, value)),
20        }
21    }
22
23    fn flag(&mut self, name: &str, on: bool) {
24        self.set(name, if on { "Y" } else { "N" });
25    }
26}
27
28macro_rules! query_accessor {
29    ($($ty:ty),*) => {$(
30        impl $ty {
31            /// Parameters in the order they were set, without `appId` and `lang`.
32            pub fn query(&self) -> &[(String, String)] {
33                &self.query.0
34            }
35        }
36    )*};
37}
38
39/// Filter setters shared by the builders that take narrowing conditions.
40macro_rules! filter_methods {
41    () => {
42        /// Hierarchy level (`lvTab`, `lvArea`, ...): `X`, `X-X`, `-X` or `X-`.
43        pub fn level(mut self, dim: Dimension, level: impl Into<String>) -> Self {
44            self.query.set(format!("lv{}", dim.param()), level);
45            self
46        }
47
48        /// Item codes (`cdTab`, `cdArea`, ...), up to 100 separated by commas.
49        /// `min` and `max` stand for the smallest and largest code.
50        pub fn code(mut self, dim: Dimension, codes: impl Into<String>) -> Self {
51            self.query.set(format!("cd{}", dim.param()), codes);
52            self
53        }
54
55        /// Codes from this one on (`cdTabFrom`, ...).
56        pub fn code_from(mut self, dim: Dimension, code: impl Into<String>) -> Self {
57            self.query.set(format!("cd{}From", dim.param()), code);
58            self
59        }
60
61        /// Codes up to this one (`cdTabTo`, ...).
62        pub fn code_to(mut self, dim: Dimension, code: impl Into<String>) -> Self {
63            self.query.set(format!("cd{}To", dim.param()), code);
64            self
65        }
66    };
67}
68
69/// Area level of the tables to search (`collectArea`, 集計地域区分).
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
71#[non_exhaustive]
72pub enum CollectArea {
73    /// `1`: whole country (全国).
74    Nationwide,
75    /// `2`: prefectures (都道府県).
76    Prefecture,
77    /// `3`: municipalities (市区町村).
78    Municipality,
79}
80
81impl CollectArea {
82    /// Parameter value, `1` to `3`.
83    pub fn code(&self) -> &'static str {
84        match self {
85            CollectArea::Nationwide => "1",
86            CollectArea::Prefecture => "2",
87            CollectArea::Municipality => "3",
88        }
89    }
90}
91
92/// Kind of data to search in [`StatsListParams`] (`searchKind`, 検索データ種別).
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
94#[non_exhaustive]
95pub enum SearchKind {
96    /// `1`: statistics (統計情報), the default.
97    Statistics,
98    /// `2`: small areas and grid squares (小地域・地域メッシュ).
99    SmallArea,
100}
101
102impl SearchKind {
103    /// Parameter value, `1` or `2`.
104    pub fn code(&self) -> &'static str {
105        match self {
106            SearchKind::Statistics => "1",
107            SearchKind::SmallArea => "2",
108        }
109    }
110}
111
112/// File format to search in [`DataCatalogParams`] (`dataType`, 検索データ形式).
113#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
114#[non_exhaustive]
115pub enum DataType {
116    /// `XLS`: Excel file.
117    Xls,
118    /// `CSV`: CSV file.
119    Csv,
120    /// `PDF`: PDF file.
121    Pdf,
122    /// `XML`: XML file.
123    Xml,
124    /// `XLS_REP`: Excel file laid out for reading (閲覧用).
125    XlsRep,
126    /// `DB`: table in the statistics database, usable with `getStatsData`.
127    Db,
128}
129
130impl DataType {
131    /// Parameter value, such as `XLS_REP`.
132    pub fn code(&self) -> &'static str {
133        match self {
134            DataType::Xls => "XLS",
135            DataType::Csv => "CSV",
136            DataType::Pdf => "PDF",
137            DataType::Xml => "XML",
138            DataType::XlsRep => "XLS_REP",
139            DataType::Db => "DB",
140        }
141    }
142}
143
144/// Replacement for special characters such as `-` or `X` in data values
145/// (`replaceSpChar`, 特殊文字の置換).
146#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
147#[non_exhaustive]
148pub enum ReplaceSpChar {
149    /// `0`: keep them, the default.
150    Keep,
151    /// `1`: replace with `0`.
152    Zero,
153    /// `2`: replace with an empty string.
154    Empty,
155    /// `3`: replace with `NA`.
156    Na,
157}
158
159impl ReplaceSpChar {
160    /// Parameter value, `0` to `3`.
161    pub fn code(&self) -> &'static str {
162        match self {
163            ReplaceSpChar::Keep => "0",
164            ReplaceSpChar::Zero => "1",
165            ReplaceSpChar::Empty => "2",
166            ReplaceSpChar::Na => "3",
167        }
168    }
169}
170
171/// One axis of a statistical table: the tabulation item (表章事項), time
172/// (時間軸事項), area (地域事項) or a classification (分類事項 01 to 15).
173///
174/// The id matches `@id` of [`ClassObj`](crate::ClassObj) and the attribute
175/// names of [`DataValue`](crate::DataValue).
176///
177/// ```
178/// use estat_api::Dimension;
179///
180/// let dim: Dimension = "cat01".parse().unwrap();
181/// assert_eq!(dim, Dimension::Cat01);
182/// assert_eq!(dim.id(), "cat01");
183/// ```
184#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
185pub enum Dimension {
186    /// `tab`: tabulation item (表章事項).
187    Tab,
188    /// `time`: time (時間軸事項).
189    Time,
190    /// `area`: area (地域事項).
191    Area,
192    /// `cat01`: classification 01 (分類事項01).
193    Cat01,
194    /// `cat02`: classification 02 (分類事項02).
195    Cat02,
196    /// `cat03`: classification 03 (分類事項03).
197    Cat03,
198    /// `cat04`: classification 04 (分類事項04).
199    Cat04,
200    /// `cat05`: classification 05 (分類事項05).
201    Cat05,
202    /// `cat06`: classification 06 (分類事項06).
203    Cat06,
204    /// `cat07`: classification 07 (分類事項07).
205    Cat07,
206    /// `cat08`: classification 08 (分類事項08).
207    Cat08,
208    /// `cat09`: classification 09 (分類事項09).
209    Cat09,
210    /// `cat10`: classification 10 (分類事項10).
211    Cat10,
212    /// `cat11`: classification 11 (分類事項11).
213    Cat11,
214    /// `cat12`: classification 12 (分類事項12).
215    Cat12,
216    /// `cat13`: classification 13 (分類事項13).
217    Cat13,
218    /// `cat14`: classification 14 (分類事項14).
219    Cat14,
220    /// `cat15`: classification 15 (分類事項15).
221    Cat15,
222}
223
224impl Dimension {
225    /// Every dimension, in the order above.
226    pub const ALL: [Dimension; 18] = [
227        Dimension::Tab,
228        Dimension::Time,
229        Dimension::Area,
230        Dimension::Cat01,
231        Dimension::Cat02,
232        Dimension::Cat03,
233        Dimension::Cat04,
234        Dimension::Cat05,
235        Dimension::Cat06,
236        Dimension::Cat07,
237        Dimension::Cat08,
238        Dimension::Cat09,
239        Dimension::Cat10,
240        Dimension::Cat11,
241        Dimension::Cat12,
242        Dimension::Cat13,
243        Dimension::Cat14,
244        Dimension::Cat15,
245    ];
246
247    /// Id used by e-Stat: `tab`, `time`, `area` or `cat01` to `cat15`.
248    pub fn id(&self) -> &'static str {
249        match self {
250            Dimension::Tab => "tab",
251            Dimension::Time => "time",
252            Dimension::Area => "area",
253            Dimension::Cat01 => "cat01",
254            Dimension::Cat02 => "cat02",
255            Dimension::Cat03 => "cat03",
256            Dimension::Cat04 => "cat04",
257            Dimension::Cat05 => "cat05",
258            Dimension::Cat06 => "cat06",
259            Dimension::Cat07 => "cat07",
260            Dimension::Cat08 => "cat08",
261            Dimension::Cat09 => "cat09",
262            Dimension::Cat10 => "cat10",
263            Dimension::Cat11 => "cat11",
264            Dimension::Cat12 => "cat12",
265            Dimension::Cat13 => "cat13",
266            Dimension::Cat14 => "cat14",
267            Dimension::Cat15 => "cat15",
268        }
269    }
270
271    /// Part of the filter parameter names: `Tab`, `Time`, `Area`, `Cat01`, ...
272    fn param(&self) -> String {
273        let id = self.id();
274        id[..1].to_ascii_uppercase() + &id[1..]
275    }
276}
277
278impl Display for Dimension {
279    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
280        f.write_str(self.id())
281    }
282}
283
284impl FromStr for Dimension {
285    type Err = String;
286
287    fn from_str(s: &str) -> Result<Self, Self::Err> {
288        Dimension::ALL
289            .into_iter()
290            .find(|d| d.id() == s)
291            .ok_or_else(|| {
292                format!("unknown dimension {s:?}: use tab, time, area or cat01 to cat15")
293            })
294    }
295}
296
297/// Parameters of [`EstatApi::stats_list`](crate::EstatApi::stats_list)
298/// (`getStatsList`, 統計表情報取得).
299///
300/// Without any parameter the call lists every table, so narrow it down.
301///
302/// ```
303/// use estat_api::StatsListParams;
304///
305/// let params = StatsListParams::new()
306///     .search_word("人口 AND 東京")
307///     .stats_code("00200521")
308///     .limit(100);
309/// ```
310#[derive(Debug, Clone, Default, PartialEq, Eq)]
311pub struct StatsListParams {
312    query: Query,
313}
314
315impl StatsListParams {
316    /// No conditions.
317    pub fn new() -> Self {
318        Self::default()
319    }
320
321    /// Survey period (`surveyYears`): `yyyy`, `yyyymm` or `yyyymm-yyyymm`.
322    pub fn survey_years(mut self, value: impl Into<String>) -> Self {
323        self.query.set("surveyYears", value);
324        self
325    }
326
327    /// Release period (`openYears`), in the same format as `survey_years`.
328    pub fn open_years(mut self, value: impl Into<String>) -> Self {
329        self.query.set("openYears", value);
330        self
331    }
332
333    /// Statistics field (`statsField`): 2 digits for a major field, 4 for a minor one.
334    pub fn stats_field(mut self, value: impl Into<String>) -> Self {
335        self.query.set("statsField", value);
336        self
337    }
338
339    /// Government statistics code (`statsCode`): 5 digits for an agency, 8 for a survey.
340    pub fn stats_code(mut self, value: impl Into<String>) -> Self {
341        self.query.set("statsCode", value);
342        self
343    }
344
345    /// Keywords (`searchWord`). `AND`, `OR` and `NOT` combine words, as in `東京 AND 人口`.
346    pub fn search_word(mut self, value: impl Into<String>) -> Self {
347        self.query.set("searchWord", value);
348        self
349    }
350
351    /// Kind of data (`searchKind`).
352    pub fn search_kind(mut self, kind: SearchKind) -> Self {
353        self.query.set("searchKind", kind.code());
354        self
355    }
356
357    /// Area level (`collectArea`). Ignored for [`SearchKind::SmallArea`].
358    pub fn collect_area(mut self, area: CollectArea) -> Self {
359        self.query.set("collectArea", area.code());
360        self
361    }
362
363    /// Include explanations (`explanationGetFlg`, default `true`).
364    pub fn explanation(mut self, on: bool) -> Self {
365        self.query.flag("explanationGetFlg", on);
366        self
367    }
368
369    /// List survey names instead of tables (`statsNameList=Y`). The result is
370    /// then in [`DataListInf::list_inf`](crate::DataListInf::list_inf).
371    pub fn stats_name_list(mut self) -> Self {
372        self.query.set("statsNameList", "Y");
373        self
374    }
375
376    /// First row to return, from 1 (`startPosition`). Pass the previous `NEXT_KEY`.
377    pub fn start_position(mut self, position: u64) -> Self {
378        self.query.set("startPosition", position.to_string());
379        self
380    }
381
382    /// Maximum number of rows (`limit`, default 100,000).
383    pub fn limit(mut self, limit: u64) -> Self {
384        self.query.set("limit", limit.to_string());
385        self
386    }
387
388    /// Update date (`updatedDate`): `yyyy`, `yyyymm`, `yyyymmdd` or `yyyymmdd-yyyymmdd`.
389    pub fn updated_date(mut self, value: impl Into<String>) -> Self {
390        self.query.set("updatedDate", value);
391        self
392    }
393}
394
395/// Parameters of [`EstatApi::meta_info`](crate::EstatApi::meta_info)
396/// (`getMetaInfo`, メタ情報取得).
397#[derive(Debug, Clone, PartialEq, Eq)]
398pub struct MetaInfoParams {
399    query: Query,
400}
401
402impl MetaInfoParams {
403    /// Metadata of the table with this ID (`statsDataId`), such as `0003410379`.
404    pub fn new(stats_data_id: impl Into<String>) -> Self {
405        let mut query = Query::default();
406        query.set("statsDataId", stats_data_id);
407        MetaInfoParams { query }
408    }
409
410    /// Include explanations (`explanationGetFlg`, default `true`).
411    pub fn explanation(mut self, on: bool) -> Self {
412        self.query.flag("explanationGetFlg", on);
413        self
414    }
415}
416
417impl<T: Into<String>> From<T> for MetaInfoParams {
418    fn from(stats_data_id: T) -> Self {
419        MetaInfoParams::new(stats_data_id)
420    }
421}
422
423/// Parameters of [`EstatApi::stats_data`](crate::EstatApi::stats_data)
424/// (`getStatsData`, 統計データ取得).
425///
426/// Filters on the same dimension are combined with AND.
427///
428/// ```
429/// use estat_api::{Dimension, StatsDataParams};
430///
431/// let params = StatsDataParams::table("0003410379")
432///     .code(Dimension::Area, "13000")
433///     .code_from(Dimension::Time, "2020000000")
434///     .level(Dimension::Cat01, "1")
435///     .limit(10_000);
436/// ```
437#[derive(Debug, Clone, PartialEq, Eq)]
438pub struct StatsDataParams {
439    query: Query,
440}
441
442impl StatsDataParams {
443    /// Data of a statistical table (`statsDataId`).
444    pub fn table(stats_data_id: impl Into<String>) -> Self {
445        let mut query = Query::default();
446        query.set("statsDataId", stats_data_id);
447        StatsDataParams { query }
448    }
449
450    /// Data of a dataset registered on e-Stat (`dataSetId`). Its conditions
451    /// apply, and filters added here narrow them further.
452    pub fn dataset(data_set_id: impl Into<String>) -> Self {
453        let mut query = Query::default();
454        query.set("dataSetId", data_set_id);
455        StatsDataParams { query }
456    }
457
458    filter_methods!();
459
460    /// First row to return, from 1 (`startPosition`). Pass the previous `NEXT_KEY`.
461    pub fn start_position(mut self, position: u64) -> Self {
462        self.query.set("startPosition", position.to_string());
463        self
464    }
465
466    /// Maximum number of rows (`limit`, default 100,000).
467    pub fn limit(mut self, limit: u64) -> Self {
468        self.query.set("limit", limit.to_string());
469        self
470    }
471
472    /// Include the table's metadata in [`StatisticalData::class_inf`](crate::StatisticalData::class_inf)
473    /// (`metaGetFlg`, default `true`).
474    pub fn meta(mut self, on: bool) -> Self {
475        self.query.flag("metaGetFlg", on);
476        self
477    }
478
479    /// Return only the number of rows, in `RESULT_INF.TOTAL_NUMBER` (`cntGetFlg=Y`).
480    pub fn count_only(mut self) -> Self {
481        self.query.set("cntGetFlg", "Y");
482        self
483    }
484
485    /// Include explanations (`explanationGetFlg`, default `true`).
486    pub fn explanation(mut self, on: bool) -> Self {
487        self.query.flag("explanationGetFlg", on);
488        self
489    }
490
491    /// Include annotations of values (`annotationGetFlg`, default `true`).
492    pub fn annotation(mut self, on: bool) -> Self {
493        self.query.flag("annotationGetFlg", on);
494        self
495    }
496
497    /// Replace special characters in values (`replaceSpChar`).
498    pub fn replace_sp_char(mut self, replace: ReplaceSpChar) -> Self {
499        self.query.set("replaceSpChar", replace.code());
500        self
501    }
502
503    pub(crate) fn with_start(&self, position: u64) -> Self {
504        self.clone().start_position(position)
505    }
506}
507
508/// Parameters of [`EstatApi::data_catalog`](crate::EstatApi::data_catalog)
509/// (`getDataCatalog`, データカタログ情報取得).
510///
511/// ```
512/// use estat_api::{DataCatalogParams, DataType};
513///
514/// let params = DataCatalogParams::new()
515///     .stats_code("00400001")
516///     .data_types([DataType::Xls, DataType::Csv]);
517/// ```
518#[derive(Debug, Clone, Default, PartialEq, Eq)]
519pub struct DataCatalogParams {
520    query: Query,
521}
522
523impl DataCatalogParams {
524    /// No conditions.
525    pub fn new() -> Self {
526        Self::default()
527    }
528
529    /// Survey period (`surveyYears`): `yyyy`, `yyyymm` or `yyyymm-yyyymm`.
530    pub fn survey_years(mut self, value: impl Into<String>) -> Self {
531        self.query.set("surveyYears", value);
532        self
533    }
534
535    /// Release period (`openYears`), in the same format as `survey_years`.
536    pub fn open_years(mut self, value: impl Into<String>) -> Self {
537        self.query.set("openYears", value);
538        self
539    }
540
541    /// Statistics field (`statsField`): 2 digits for a major field, 4 for a minor one.
542    pub fn stats_field(mut self, value: impl Into<String>) -> Self {
543        self.query.set("statsField", value);
544        self
545    }
546
547    /// Government statistics code (`statsCode`): 5 digits for an agency, 8 for a survey.
548    pub fn stats_code(mut self, value: impl Into<String>) -> Self {
549        self.query.set("statsCode", value);
550        self
551    }
552
553    /// Keywords (`searchWord`). `AND`, `OR` and `NOT` combine words.
554    pub fn search_word(mut self, value: impl Into<String>) -> Self {
555        self.query.set("searchWord", value);
556        self
557    }
558
559    /// Area level (`collectArea`).
560    pub fn collect_area(mut self, area: CollectArea) -> Self {
561        self.query.set("collectArea", area.code());
562        self
563    }
564
565    /// Include explanations (`explanationGetFlg`, default `true`).
566    pub fn explanation(mut self, on: bool) -> Self {
567        self.query.flag("explanationGetFlg", on);
568        self
569    }
570
571    /// File formats (`dataType`). All formats when not set.
572    pub fn data_types(mut self, types: impl IntoIterator<Item = DataType>) -> Self {
573        let codes: Vec<&str> = types.into_iter().map(|t| t.code()).collect();
574        self.query.set("dataType", codes.join(","));
575        self
576    }
577
578    /// Catalog ID (`catalogId`).
579    pub fn catalog_id(mut self, value: impl Into<String>) -> Self {
580        self.query.set("catalogId", value);
581        self
582    }
583
584    /// Catalog resource ID (`resourceId`).
585    pub fn resource_id(mut self, value: impl Into<String>) -> Self {
586        self.query.set("resourceId", value);
587        self
588    }
589
590    /// First dataset to return, from 1 (`startPosition`). Pass the previous `NEXT_KEY`.
591    pub fn start_position(mut self, position: u64) -> Self {
592        self.query.set("startPosition", position.to_string());
593        self
594    }
595
596    /// Maximum number of datasets (`limit`, default 100).
597    pub fn limit(mut self, limit: u64) -> Self {
598        self.query.set("limit", limit.to_string());
599        self
600    }
601
602    /// Update date (`updatedDate`): `yyyy`, `yyyymm`, `yyyymmdd` or `yyyymmdd-yyyymmdd`.
603    pub fn updated_date(mut self, value: impl Into<String>) -> Self {
604        self.query.set("updatedDate", value);
605        self
606    }
607}
608
609/// One request of [`StatsDatasParams`]: a table or dataset with its filters.
610///
611/// ```
612/// use estat_api::{Dimension, StatsDatasRequest};
613///
614/// let tokyo = StatsDatasRequest::table("0003448237").code(Dimension::Area, "13000");
615/// ```
616#[derive(Debug, Clone, PartialEq, Eq)]
617pub struct StatsDatasRequest {
618    query: Query,
619}
620
621impl StatsDatasRequest {
622    /// Values of a statistical table (`statsDataId`).
623    pub fn table(stats_data_id: impl Into<String>) -> Self {
624        let mut query = Query::default();
625        query.set("statsDataId", stats_data_id);
626        StatsDatasRequest { query }
627    }
628
629    /// Values of a registered dataset (`dataSetId`).
630    pub fn dataset(data_set_id: impl Into<String>) -> Self {
631        let mut query = Query::default();
632        query.set("dataSetId", data_set_id);
633        StatsDatasRequest { query }
634    }
635
636    filter_methods!();
637
638    /// First row to return, from 1 (`startPosition`).
639    pub fn start_position(mut self, position: u64) -> Self {
640        self.query.set("startPosition", position.to_string());
641        self
642    }
643
644    /// Maximum number of rows (`limit`).
645    pub fn limit(mut self, limit: u64) -> Self {
646        self.query.set("limit", limit.to_string());
647        self
648    }
649
650    /// Any other parameter of `statsDatasSpec`, as e-Stat names it.
651    pub fn param(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
652        self.query.set(name, value);
653        self
654    }
655}
656
657/// Parameters of [`EstatApi::stats_datas`](crate::EstatApi::stats_datas)
658/// (`getStatsDatas`, 統計データ一括取得).
659///
660/// Requests are numbered from 1 in the order they are added; the response
661/// refers to them by that number. All requests together may return at most
662/// 100,000 values.
663///
664/// ```
665/// use estat_api::{Dimension, StatsDatasParams, StatsDatasRequest};
666///
667/// let params = StatsDatasParams::new()
668///     .request(StatsDatasRequest::table("0003448237").code(Dimension::Area, "13000"))
669///     .request(StatsDatasRequest::table("0003448237").code(Dimension::Area, "27000"))
670///     .meta(false);
671/// assert_eq!(
672///     params.spec(),
673///     r#"[{"statsDataId":"0003448237","cdArea":"13000"},{"statsDataId":"0003448237","cdArea":"27000"}]"#
674/// );
675/// ```
676#[derive(Debug, Clone, Default, PartialEq, Eq)]
677pub struct StatsDatasParams {
678    query: Query,
679    requests: Vec<StatsDatasRequest>,
680}
681
682impl StatsDatasParams {
683    /// No requests yet.
684    pub fn new() -> Self {
685        Self::default()
686    }
687
688    /// Adds a request.
689    pub fn request(mut self, request: StatsDatasRequest) -> Self {
690        self.requests.push(request);
691        self
692    }
693
694    /// The requests, in order.
695    pub fn requests(&self) -> &[StatsDatasRequest] {
696        &self.requests
697    }
698
699    /// Include metadata (`metaGetFlg`, default `true`).
700    pub fn meta(mut self, on: bool) -> Self {
701        self.query.flag("metaGetFlg", on);
702        self
703    }
704
705    /// Include explanations (`explanationGetFlg`, default `true`).
706    pub fn explanation(mut self, on: bool) -> Self {
707        self.query.flag("explanationGetFlg", on);
708        self
709    }
710
711    /// Include annotations of values (`annotationGetFlg`, default `true`).
712    pub fn annotation(mut self, on: bool) -> Self {
713        self.query.flag("annotationGetFlg", on);
714        self
715    }
716
717    /// Replace special characters in values (`replaceSpChar`).
718    pub fn replace_sp_char(mut self, replace: ReplaceSpChar) -> Self {
719        self.query.set("replaceSpChar", replace.code());
720        self
721    }
722
723    /// The `statsDatasSpec` parameter: the requests as a JSON array.
724    pub fn spec(&self) -> String {
725        let quote = |s: &str| serde_json::to_string(s).expect("strings serialize to JSON");
726        let requests: Vec<String> = self
727            .requests
728            .iter()
729            .map(|r| {
730                let fields: Vec<String> = r
731                    .query
732                    .0
733                    .iter()
734                    .map(|(n, v)| format!("{}:{}", quote(n), quote(v)))
735                    .collect();
736                format!("{{{}}}", fields.join(","))
737            })
738            .collect();
739        format!("[{}]", requests.join(","))
740    }
741
742    /// The form sent to e-Stat: the flags and `statsDatasSpec`.
743    pub(crate) fn form(&self) -> Vec<(String, String)> {
744        let mut form = self.query.0.clone();
745        form.push(("statsDatasSpec".into(), self.spec()));
746        form
747    }
748}
749
750/// Parameters of [`EstatApi::datasets`](crate::EstatApi::datasets)
751/// (`refDataset` without an ID, データセット参照).
752#[derive(Debug, Clone, Default, PartialEq, Eq)]
753pub struct DatasetsParams {
754    query: Query,
755}
756
757impl DatasetsParams {
758    /// No conditions.
759    pub fn new() -> Self {
760        Self::default()
761    }
762
763    /// Area level (`collectArea`).
764    pub fn collect_area(mut self, area: CollectArea) -> Self {
765        self.query.set("collectArea", area.code());
766        self
767    }
768
769    /// Include explanations (`explanationGetFlg`, default `true`).
770    pub fn explanation(mut self, on: bool) -> Self {
771        self.query.flag("explanationGetFlg", on);
772        self
773    }
774}
775
776/// Parameters of [`EstatApi::dataset`](crate::EstatApi::dataset)
777/// (`refDataset` with an ID, データセット参照).
778#[derive(Debug, Clone, PartialEq, Eq)]
779pub struct DatasetParams {
780    query: Query,
781}
782
783impl DatasetParams {
784    /// The dataset with this ID (`dataSetId`).
785    pub fn new(data_set_id: impl Into<String>) -> Self {
786        let mut query = Query::default();
787        query.set("dataSetId", data_set_id);
788        DatasetParams { query }
789    }
790
791    /// Include explanations (`explanationGetFlg`, default `true`).
792    pub fn explanation(mut self, on: bool) -> Self {
793        self.query.flag("explanationGetFlg", on);
794        self
795    }
796}
797
798impl<T: Into<String>> From<T> for DatasetParams {
799    fn from(data_set_id: T) -> Self {
800        DatasetParams::new(data_set_id)
801    }
802}
803
804/// Parameters of [`EstatApi::post_dataset`](crate::EstatApi::post_dataset)
805/// (`postDataset`, データセット登録).
806///
807/// A dataset stores a table ID and filters under your application ID, so
808/// that [`StatsDataParams::dataset`] can use them later.
809///
810/// ```
811/// use estat_api::{Dimension, PostDatasetParams};
812///
813/// // Register, or update the dataset with this ID
814/// let register = PostDatasetParams::register("0003448237")
815///     .dataset_id("tokyo-population")
816///     .name("東京都の人口")
817///     .code(Dimension::Area, "13000");
818/// // Delete it
819/// let delete = PostDatasetParams::delete("tokyo-population");
820/// ```
821#[derive(Debug, Clone, PartialEq, Eq)]
822pub struct PostDatasetParams {
823    query: Query,
824}
825
826impl PostDatasetParams {
827    /// Registers a dataset for a table (`processMode=E`). It needs at least
828    /// one filter. With [`dataset_id`](Self::dataset_id) of an existing
829    /// dataset, that dataset is updated.
830    pub fn register(stats_data_id: impl Into<String>) -> Self {
831        let mut query = Query::default();
832        query.set("processMode", "E");
833        query.set("statsDataId", stats_data_id);
834        PostDatasetParams { query }
835    }
836
837    /// Deletes a dataset (`processMode=D`).
838    pub fn delete(data_set_id: impl Into<String>) -> Self {
839        let mut query = Query::default();
840        query.set("processMode", "D");
841        query.set("dataSetId", data_set_id);
842        PostDatasetParams { query }
843    }
844
845    /// Dataset ID (`dataSetId`): up to 30 characters of letters, digits and
846    /// `-_.@`. Without it e-Stat makes one from the survey code and the time.
847    pub fn dataset_id(mut self, value: impl Into<String>) -> Self {
848        self.query.set("dataSetId", value);
849        self
850    }
851
852    /// Name or description (`dataSetName`), up to 256 characters.
853    pub fn name(mut self, value: impl Into<String>) -> Self {
854        self.query.set("dataSetName", value);
855        self
856    }
857
858    /// Let other users see and use the dataset (`openSpecified`, default `false`).
859    pub fn public(mut self, on: bool) -> Self {
860        self.query.set("openSpecified", if on { "1" } else { "0" });
861        self
862    }
863
864    filter_methods!();
865}
866
867query_accessor!(
868    StatsListParams,
869    MetaInfoParams,
870    StatsDataParams,
871    DataCatalogParams,
872    StatsDatasRequest,
873    StatsDatasParams,
874    DatasetsParams,
875    DatasetParams,
876    PostDatasetParams
877);
878
879#[cfg(test)]
880mod tests {
881    use super::*;
882
883    fn pairs(query: &[(String, String)]) -> Vec<(&str, &str)> {
884        query
885            .iter()
886            .map(|(n, v)| (n.as_str(), v.as_str()))
887            .collect()
888    }
889
890    #[test]
891    fn stats_list_params() {
892        let params = StatsListParams::new()
893            .survey_years("201001-201212")
894            .open_years("2013")
895            .stats_field("03")
896            .stats_code("00200")
897            .search_word("就業 AND 東京")
898            .search_kind(SearchKind::Statistics)
899            .collect_area(CollectArea::Nationwide)
900            .explanation(false)
901            .stats_name_list()
902            .start_position(101)
903            .limit(100)
904            .updated_date("20240101-20241231")
905            .limit(50);
906        assert_eq!(
907            pairs(params.query()),
908            [
909                ("surveyYears", "201001-201212"),
910                ("openYears", "2013"),
911                ("statsField", "03"),
912                ("statsCode", "00200"),
913                ("searchWord", "就業 AND 東京"),
914                ("searchKind", "1"),
915                ("collectArea", "1"),
916                ("explanationGetFlg", "N"),
917                ("statsNameList", "Y"),
918                ("startPosition", "101"),
919                ("limit", "50"),
920                ("updatedDate", "20240101-20241231"),
921            ]
922        );
923        let params = StatsListParams::new()
924            .search_kind(SearchKind::SmallArea)
925            .collect_area(CollectArea::Prefecture)
926            .explanation(true);
927        assert_eq!(
928            pairs(params.query()),
929            [
930                ("searchKind", "2"),
931                ("collectArea", "2"),
932                ("explanationGetFlg", "Y")
933            ]
934        );
935    }
936
937    #[test]
938    fn meta_info_params() {
939        let params: MetaInfoParams = "0003410379".into();
940        assert_eq!(pairs(params.query()), [("statsDataId", "0003410379")]);
941        let params = MetaInfoParams::new("1").explanation(false);
942        assert_eq!(params.query().len(), 2);
943    }
944
945    #[test]
946    fn stats_data_params() {
947        let params = StatsDataParams::table("0003410379")
948            .level(Dimension::Tab, "1-2")
949            .code(Dimension::Area, "13000,14000")
950            .code_from(Dimension::Time, "min")
951            .code_to(Dimension::Cat15, "max")
952            .start_position(1)
953            .limit(10)
954            .meta(false)
955            .count_only()
956            .explanation(true)
957            .annotation(false)
958            .replace_sp_char(ReplaceSpChar::Na);
959        assert_eq!(
960            pairs(params.query()),
961            [
962                ("statsDataId", "0003410379"),
963                ("lvTab", "1-2"),
964                ("cdArea", "13000,14000"),
965                ("cdTimeFrom", "min"),
966                ("cdCat15To", "max"),
967                ("startPosition", "1"),
968                ("limit", "10"),
969                ("metaGetFlg", "N"),
970                ("cntGetFlg", "Y"),
971                ("explanationGetFlg", "Y"),
972                ("annotationGetFlg", "N"),
973                ("replaceSpChar", "3"),
974            ]
975        );
976        let next = params.with_start(11);
977        assert_eq!(next.query()[5], ("startPosition".into(), "11".into()));
978        assert_eq!(
979            pairs(StatsDataParams::dataset("ds").query()),
980            [("dataSetId", "ds")]
981        );
982        let codes: Vec<&str> = [
983            ReplaceSpChar::Keep,
984            ReplaceSpChar::Zero,
985            ReplaceSpChar::Empty,
986        ]
987        .iter()
988        .map(ReplaceSpChar::code)
989        .collect();
990        assert_eq!(codes, ["0", "1", "2"]);
991    }
992
993    #[test]
994    fn data_catalog_params() {
995        let params = DataCatalogParams::new()
996            .survey_years("2020")
997            .open_years("2021")
998            .stats_field("02")
999            .stats_code("00200521")
1000            .search_word("人口")
1001            .collect_area(CollectArea::Municipality)
1002            .explanation(false)
1003            .data_types([
1004                DataType::Xls,
1005                DataType::Csv,
1006                DataType::Pdf,
1007                DataType::Xml,
1008                DataType::XlsRep,
1009                DataType::Db,
1010            ])
1011            .catalog_id("000001029859")
1012            .resource_id("000001275539")
1013            .start_position(101)
1014            .limit(100)
1015            .updated_date("2024");
1016        assert_eq!(
1017            pairs(params.query()),
1018            [
1019                ("surveyYears", "2020"),
1020                ("openYears", "2021"),
1021                ("statsField", "02"),
1022                ("statsCode", "00200521"),
1023                ("searchWord", "人口"),
1024                ("collectArea", "3"),
1025                ("explanationGetFlg", "N"),
1026                ("dataType", "XLS,CSV,PDF,XML,XLS_REP,DB"),
1027                ("catalogId", "000001029859"),
1028                ("resourceId", "000001275539"),
1029                ("startPosition", "101"),
1030                ("limit", "100"),
1031                ("updatedDate", "2024"),
1032            ]
1033        );
1034    }
1035
1036    #[test]
1037    fn stats_datas_params() {
1038        let request = StatsDatasRequest::dataset("ds")
1039            .level(Dimension::Tab, "1")
1040            .code(Dimension::Area, "13000")
1041            .code_from(Dimension::Time, "1601")
1042            .code_to(Dimension::Time, "max")
1043            .start_position(2)
1044            .limit(10)
1045            .param("cdCat01", "000");
1046        assert_eq!(request.query().len(), 8);
1047        let params = StatsDatasParams::new()
1048            .request(request)
1049            .request(StatsDatasRequest::table("0003448237"))
1050            .meta(false)
1051            .explanation(true)
1052            .annotation(false)
1053            .replace_sp_char(ReplaceSpChar::Empty);
1054        assert_eq!(params.requests().len(), 2);
1055        assert_eq!(
1056            pairs(params.query()),
1057            [
1058                ("metaGetFlg", "N"),
1059                ("explanationGetFlg", "Y"),
1060                ("annotationGetFlg", "N"),
1061                ("replaceSpChar", "2"),
1062            ]
1063        );
1064        assert_eq!(
1065            params.spec(),
1066            r#"[{"dataSetId":"ds","lvTab":"1","cdArea":"13000","cdTimeFrom":"1601","cdTimeTo":"max","startPosition":"2","limit":"10","cdCat01":"000"},{"statsDataId":"0003448237"}]"#
1067        );
1068        let form = params.form();
1069        assert_eq!(form.len(), 5);
1070        assert_eq!(form[4], ("statsDatasSpec".into(), params.spec()));
1071        assert_eq!(StatsDatasParams::new().spec(), "[]");
1072    }
1073
1074    #[test]
1075    fn dataset_params() {
1076        let params = DatasetsParams::new()
1077            .collect_area(CollectArea::Nationwide)
1078            .explanation(false);
1079        assert_eq!(
1080            pairs(params.query()),
1081            [("collectArea", "1"), ("explanationGetFlg", "N")]
1082        );
1083        let params: DatasetParams = "ds".into();
1084        assert_eq!(
1085            pairs(params.explanation(true).query()),
1086            [("dataSetId", "ds"), ("explanationGetFlg", "Y")]
1087        );
1088
1089        let params = PostDatasetParams::register("0003448237")
1090            .dataset_id("my-set")
1091            .name("名前")
1092            .public(true)
1093            .level(Dimension::Area, "2")
1094            .code(Dimension::Cat01, "000")
1095            .code_from(Dimension::Time, "1601")
1096            .code_to(Dimension::Time, "1901");
1097        assert_eq!(
1098            pairs(params.query()),
1099            [
1100                ("processMode", "E"),
1101                ("statsDataId", "0003448237"),
1102                ("dataSetId", "my-set"),
1103                ("dataSetName", "名前"),
1104                ("openSpecified", "1"),
1105                ("lvArea", "2"),
1106                ("cdCat01", "000"),
1107                ("cdTimeFrom", "1601"),
1108                ("cdTimeTo", "1901"),
1109            ]
1110        );
1111        assert_eq!(
1112            pairs(PostDatasetParams::delete("my-set").public(false).query()),
1113            [
1114                ("processMode", "D"),
1115                ("dataSetId", "my-set"),
1116                ("openSpecified", "0")
1117            ]
1118        );
1119    }
1120
1121    #[test]
1122    fn dimensions() {
1123        let ids: Vec<&str> = Dimension::ALL.iter().map(Dimension::id).collect();
1124        assert_eq!(ids[..4], ["tab", "time", "area", "cat01"]);
1125        assert_eq!(ids[17], "cat15");
1126        for dim in Dimension::ALL {
1127            assert_eq!(dim.to_string().parse::<Dimension>(), Ok(dim));
1128        }
1129        assert_eq!(Dimension::Cat07.param(), "Cat07");
1130        let error = "cat16".parse::<Dimension>().unwrap_err();
1131        assert!(error.contains("cat16"));
1132    }
1133}