Skip to main content

estat_api/
dataset.rs

1//! Responses of `refDataset` and `postDataset`.
2
3use crate::EstatError;
4use crate::de;
5use crate::response::{ApiResult, ResultInf, TableInf};
6use serde::{Deserialize, Serialize};
7use serde_json::{Map, Value};
8
9/// Response of [`EstatApi::datasets`](crate::EstatApi::datasets) (`GET_DATASET_LIST`).
10#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
11#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
12#[non_exhaustive]
13pub struct DatasetList {
14    /// Outcome of the request.
15    pub result: ApiResult,
16    /// Parameters as e-Stat received them.
17    #[serde(default)]
18    pub parameter: Map<String, Value>,
19    /// Datasets you can use: your own and those others made public.
20    #[serde(default, deserialize_with = "de::object_or_default")]
21    pub dataset_list_inf: DatasetListInf,
22    /// Fields this crate does not know yet, kept as received.
23    #[serde(flatten)]
24    pub extra: Map<String, Value>,
25}
26
27/// `DATASET_LIST_INF` element.
28#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
29#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
30#[non_exhaustive]
31pub struct DatasetListInf {
32    /// Number of datasets.
33    #[serde(default, deserialize_with = "de::number")]
34    pub number: u64,
35    /// Datasets.
36    #[serde(default, deserialize_with = "de::one_or_many")]
37    pub dataset_inf: Vec<DatasetInf>,
38    /// Fields this crate does not know yet, kept as received.
39    #[serde(flatten)]
40    pub extra: Map<String, Value>,
41}
42
43/// Response of [`EstatApi::dataset`](crate::EstatApi::dataset) (`REF_DATASET`).
44#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
45#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
46#[non_exhaustive]
47pub struct RefDataset {
48    /// Outcome of the request.
49    pub result: ApiResult,
50    /// Parameters as e-Stat received them.
51    #[serde(default)]
52    pub parameter: Map<String, Value>,
53    /// The dataset, with its filters in `narrowing_cond`.
54    pub dataset_inf: DatasetInf,
55    /// Fields this crate does not know yet, kept as received.
56    #[serde(flatten)]
57    pub extra: Map<String, Value>,
58}
59
60/// `DATASET_INF` element: a dataset and the table it refers to.
61#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
62#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
63#[non_exhaustive]
64pub struct DatasetInf {
65    /// Dataset ID (`@id`). Pass it to [`StatsDataParams::dataset`](crate::StatsDataParams::dataset).
66    #[serde(rename = "@id")]
67    pub id: String,
68    /// Name given when it was registered. Not every dataset has one.
69    #[serde(
70        default,
71        deserialize_with = "de::opt_text",
72        skip_serializing_if = "Option::is_none"
73    )]
74    pub dataset_name: Option<String>,
75    /// Filters, such as `CODE_AREA_SELECT` or `LEVEL_AREA_COND`. Only in
76    /// [`RefDataset`].
77    #[serde(
78        default,
79        deserialize_with = "de::object_or_empty",
80        skip_serializing_if = "Option::is_none"
81    )]
82    pub narrowing_cond: Option<Map<String, Value>>,
83    /// `YES` when other users can use it.
84    #[serde(
85        default,
86        deserialize_with = "de::opt_text",
87        skip_serializing_if = "Option::is_none"
88    )]
89    pub public_state: Option<String>,
90    /// Number of values the filters select, in `total_number`.
91    #[serde(default, deserialize_with = "de::object_or_default")]
92    pub result_inf: ResultInf,
93    /// The table.
94    #[serde(
95        default,
96        deserialize_with = "de::object_or_empty",
97        skip_serializing_if = "Option::is_none"
98    )]
99    pub table_inf: Option<TableInf>,
100    /// Fields this crate does not know yet, such as `TABLE_EXPLANATION`.
101    #[serde(flatten)]
102    pub extra: Map<String, Value>,
103}
104
105/// Response of [`EstatApi::post_dataset`](crate::EstatApi::post_dataset) (`POST_DATASET`).
106///
107/// e-Stat answers `postDataset` in XML only; the crate reads the few
108/// elements below from it.
109#[derive(Debug, Clone, PartialEq, Serialize)]
110#[non_exhaustive]
111pub struct PostDataset {
112    /// Outcome of the request.
113    pub result: ApiResult,
114    /// What was registered or deleted.
115    pub regist_inf: RegistInf,
116}
117
118/// `REGIST_INF` element.
119#[derive(Debug, Clone, PartialEq, Serialize)]
120#[non_exhaustive]
121pub struct RegistInf {
122    /// `add`, `update` or `delete` (`@mode`).
123    pub mode: String,
124    /// Dataset ID.
125    pub dataset_id: String,
126    /// Table ID. Not sent when deleting.
127    pub stats_data_id: Option<String>,
128    /// `yes` when other users can use it.
129    pub public_state: Option<String>,
130    /// Number of values the filters select.
131    pub total_number: Option<u64>,
132}
133
134impl PostDataset {
135    /// Reads a `postDataset` response.
136    pub(crate) fn from_xml(http_status: u16, body: &str) -> Result<Self, EstatError> {
137        let Some((_, root)) = element(body, "POST_DATASET") else {
138            if !(200..300).contains(&http_status) {
139                return Err(EstatError::HttpStatus(http_status, body.to_string()));
140            }
141            return Err(unexpected("no POST_DATASET in the body"));
142        };
143        let (_, result) = element(root, "RESULT").ok_or_else(|| unexpected("no RESULT"))?;
144        let status = text(result, "STATUS").unwrap_or_default();
145        let status: u16 = status
146            .trim()
147            .parse()
148            .map_err(|_| unexpected(&format!("STATUS is not a number: {status:?}")))?;
149        let message = text(result, "ERROR_MSG").unwrap_or_default();
150        if status >= 100 {
151            return Err(EstatError::Api { status, message });
152        }
153        let (tag, regist) =
154            element(root, "REGIST_INF").ok_or_else(|| unexpected("no REGIST_INF"))?;
155        Ok(PostDataset {
156            result: ApiResult {
157                status,
158                error_msg: message,
159                date: text(result, "DATE").unwrap_or_default(),
160                extra: Map::new(),
161            },
162            regist_inf: RegistInf {
163                mode: attribute(tag, "mode").unwrap_or_default(),
164                dataset_id: text(regist, "DATASET_ID").unwrap_or_default(),
165                stats_data_id: text(regist, "STATS_DATA_ID"),
166                public_state: text(regist, "PUBLIC_STATE"),
167                total_number: text(regist, "TOTAL_NUMBER").and_then(|n| n.trim().parse().ok()),
168            },
169        })
170    }
171}
172
173fn unexpected(message: &str) -> EstatError {
174    EstatError::UnexpectedResponse(message.to_string())
175}
176
177/// First element with this name: its start tag and its content. An empty
178/// element (`<NAME/>`) has empty content.
179fn element<'a>(xml: &'a str, name: &str) -> Option<(&'a str, &'a str)> {
180    let open = format!("<{name}");
181    let mut from = 0;
182    loop {
183        let start = from + xml[from..].find(&open)?;
184        let after = &xml[start + open.len()..];
185        from = start + open.len();
186        if !after.starts_with(['>', ' ', '/']) {
187            continue;
188        }
189        let end = after.find('>')?;
190        let tag = &after[..end];
191        if tag.ends_with('/') {
192            return Some((tag, ""));
193        }
194        let content = &after[end + 1..];
195        let close = content.find(&format!("</{name}>"))?;
196        return Some((tag, &content[..close]));
197    }
198}
199
200/// Unescaped text of the first element with this name.
201fn text(xml: &str, name: &str) -> Option<String> {
202    element(xml, name).map(|(_, content)| unescape(content))
203}
204
205/// Value of an attribute in a start tag.
206fn attribute(tag: &str, name: &str) -> Option<String> {
207    let key = format!(" {name}=\"");
208    let start = tag.find(&key)? + key.len();
209    let end = tag[start..].find('"')?;
210    Some(unescape(&tag[start..start + end]))
211}
212
213fn unescape(text: &str) -> String {
214    text.replace("&lt;", "<")
215        .replace("&gt;", ">")
216        .replace("&quot;", "\"")
217        .replace("&apos;", "'")
218        .replace("&amp;", "&")
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224
225    const ADDED: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><POST_DATASET><RESULT><STATUS>0</STATUS><ERROR_MSG>正常に終了しました。</ERROR_MSG><DATE>2026-11-12T08:20:00.000+09:00</DATE></RESULT><PARAMETER><LANG>J</LANG><NARROWING_COND><CODE_AREA_SELECT>13000</CODE_AREA_SELECT></NARROWING_COND></PARAMETER><REGIST_INF mode="add"><DATASET_ID>a&amp;b</DATASET_ID><STATS_DATA_ID>0003448237</STATS_DATA_ID><PUBLIC_STATE>no</PUBLIC_STATE><TOTAL_NUMBER>570</TOTAL_NUMBER></REGIST_INF></POST_DATASET>"#;
226
227    #[test]
228    fn reads_registration() {
229        let post = PostDataset::from_xml(200, ADDED).unwrap();
230        assert_eq!(post.result.status, 0);
231        assert_eq!(post.result.error_msg, "正常に終了しました。");
232        assert_eq!(post.result.date, "2026-11-12T08:20:00.000+09:00");
233        let regist = post.regist_inf;
234        assert_eq!(regist.mode, "add");
235        assert_eq!(regist.dataset_id, "a&b");
236        assert_eq!(regist.stats_data_id.as_deref(), Some("0003448237"));
237        assert_eq!(regist.public_state.as_deref(), Some("no"));
238        assert_eq!(regist.total_number, Some(570));
239    }
240
241    #[test]
242    fn reads_errors() {
243        let body = r#"<?xml version="1.0"?><POST_DATASET><RESULT><STATUS>101</STATUS><ERROR_MSG>統計表ID(statsDataId)を指定して下さい。</ERROR_MSG></RESULT><PARAMETER><NARROWING_COND/></PARAMETER></POST_DATASET>"#;
244        let error = PostDataset::from_xml(400, body).unwrap_err();
245        assert!(error.is_invalid_parameter(), "{error}");
246        assert!(error.to_string().contains("statsDataId"));
247
248        let error = PostDataset::from_xml(503, "Service Unavailable").unwrap_err();
249        assert!(matches!(error, EstatError::HttpStatus(503, _)), "{error}");
250        for (body, message) in [
251            ("<html/>", "no POST_DATASET in the body"),
252            ("<POST_DATASET></POST_DATASET>", "no RESULT"),
253            (
254                "<POST_DATASET><RESULT><STATUS>x</STATUS></RESULT></POST_DATASET>",
255                r#"STATUS is not a number: "x""#,
256            ),
257            (
258                "<POST_DATASET><RESULT></RESULT></POST_DATASET>",
259                r#"STATUS is not a number: """#,
260            ),
261            (
262                "<POST_DATASET><RESULT><STATUS>0</STATUS></RESULT></POST_DATASET>",
263                "no REGIST_INF",
264            ),
265        ] {
266            let error = PostDataset::from_xml(200, body).unwrap_err();
267            assert_eq!(error.to_string(), format!("unexpected response: {message}"));
268        }
269    }
270
271    #[test]
272    fn minimal_registration() {
273        let body = "<POST_DATASET><RESULT><STATUS>0</STATUS></RESULT><REGIST_INF><DATASET_ID>d</DATASET_ID><TOTAL_NUMBER>many</TOTAL_NUMBER></REGIST_INF></POST_DATASET>";
274        let post = PostDataset::from_xml(200, body).unwrap();
275        assert_eq!(post.result.error_msg, "");
276        assert_eq!(post.regist_inf.mode, "");
277        assert_eq!(post.regist_inf.stats_data_id, None);
278        assert_eq!(post.regist_inf.total_number, None);
279    }
280
281    #[test]
282    fn elements_and_attributes() {
283        // A longer name with the same prefix is skipped
284        let xml = r#"<A_B>1</A_B><A x="&lt;&quot;&apos;&gt;">2</A>"#;
285        let (tag, content) = element(xml, "A").unwrap();
286        assert_eq!(content, "2");
287        assert_eq!(attribute(tag, "x").as_deref(), Some(r#"<"'>"#));
288        assert_eq!(attribute(tag, "y"), None);
289        assert_eq!(attribute(r#" x="open"#, "x"), None);
290        assert_eq!(element("<A/>", "A"), Some(("/", "")));
291        assert_eq!(element("<A>open", "A"), None);
292        assert_eq!(element("<A", "A"), None);
293        assert_eq!(element("<B>", "A"), None);
294    }
295}