use std::fmt::{Display, Formatter};
use std::str::FromStr;
#[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 {
pub fn query(&self) -> &[(String, String)] {
&self.query.0
}
}
)*};
}
macro_rules! filter_methods {
() => {
pub fn level(mut self, dim: Dimension, level: impl Into<String>) -> Self {
self.query.set(format!("lv{}", dim.param()), level);
self
}
pub fn code(mut self, dim: Dimension, codes: impl Into<String>) -> Self {
self.query.set(format!("cd{}", dim.param()), codes);
self
}
pub fn code_from(mut self, dim: Dimension, code: impl Into<String>) -> Self {
self.query.set(format!("cd{}From", dim.param()), code);
self
}
pub fn code_to(mut self, dim: Dimension, code: impl Into<String>) -> Self {
self.query.set(format!("cd{}To", dim.param()), code);
self
}
};
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CollectArea {
Nationwide,
Prefecture,
Municipality,
}
impl CollectArea {
pub fn code(&self) -> &'static str {
match self {
CollectArea::Nationwide => "1",
CollectArea::Prefecture => "2",
CollectArea::Municipality => "3",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SearchKind {
Statistics,
SmallArea,
}
impl SearchKind {
pub fn code(&self) -> &'static str {
match self {
SearchKind::Statistics => "1",
SearchKind::SmallArea => "2",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DataType {
Xls,
Csv,
Pdf,
Xml,
XlsRep,
Db,
}
impl DataType {
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",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ReplaceSpChar {
Keep,
Zero,
Empty,
Na,
}
impl ReplaceSpChar {
pub fn code(&self) -> &'static str {
match self {
ReplaceSpChar::Keep => "0",
ReplaceSpChar::Zero => "1",
ReplaceSpChar::Empty => "2",
ReplaceSpChar::Na => "3",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Dimension {
Tab,
Time,
Area,
Cat01,
Cat02,
Cat03,
Cat04,
Cat05,
Cat06,
Cat07,
Cat08,
Cat09,
Cat10,
Cat11,
Cat12,
Cat13,
Cat14,
Cat15,
}
impl Dimension {
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,
];
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",
}
}
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")
})
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct StatsListParams {
query: Query,
}
impl StatsListParams {
pub fn new() -> Self {
Self::default()
}
pub fn survey_years(mut self, value: impl Into<String>) -> Self {
self.query.set("surveyYears", value);
self
}
pub fn open_years(mut self, value: impl Into<String>) -> Self {
self.query.set("openYears", value);
self
}
pub fn stats_field(mut self, value: impl Into<String>) -> Self {
self.query.set("statsField", value);
self
}
pub fn stats_code(mut self, value: impl Into<String>) -> Self {
self.query.set("statsCode", value);
self
}
pub fn search_word(mut self, value: impl Into<String>) -> Self {
self.query.set("searchWord", value);
self
}
pub fn search_kind(mut self, kind: SearchKind) -> Self {
self.query.set("searchKind", kind.code());
self
}
pub fn collect_area(mut self, area: CollectArea) -> Self {
self.query.set("collectArea", area.code());
self
}
pub fn explanation(mut self, on: bool) -> Self {
self.query.flag("explanationGetFlg", on);
self
}
pub fn stats_name_list(mut self) -> Self {
self.query.set("statsNameList", "Y");
self
}
pub fn start_position(mut self, position: u64) -> Self {
self.query.set("startPosition", position.to_string());
self
}
pub fn limit(mut self, limit: u64) -> Self {
self.query.set("limit", limit.to_string());
self
}
pub fn updated_date(mut self, value: impl Into<String>) -> Self {
self.query.set("updatedDate", value);
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MetaInfoParams {
query: Query,
}
impl MetaInfoParams {
pub fn new(stats_data_id: impl Into<String>) -> Self {
let mut query = Query::default();
query.set("statsDataId", stats_data_id);
MetaInfoParams { query }
}
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)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StatsDataParams {
query: Query,
}
impl StatsDataParams {
pub fn table(stats_data_id: impl Into<String>) -> Self {
let mut query = Query::default();
query.set("statsDataId", stats_data_id);
StatsDataParams { query }
}
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!();
pub fn start_position(mut self, position: u64) -> Self {
self.query.set("startPosition", position.to_string());
self
}
pub fn limit(mut self, limit: u64) -> Self {
self.query.set("limit", limit.to_string());
self
}
pub fn meta(mut self, on: bool) -> Self {
self.query.flag("metaGetFlg", on);
self
}
pub fn count_only(mut self) -> Self {
self.query.set("cntGetFlg", "Y");
self
}
pub fn explanation(mut self, on: bool) -> Self {
self.query.flag("explanationGetFlg", on);
self
}
pub fn annotation(mut self, on: bool) -> Self {
self.query.flag("annotationGetFlg", on);
self
}
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)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DataCatalogParams {
query: Query,
}
impl DataCatalogParams {
pub fn new() -> Self {
Self::default()
}
pub fn survey_years(mut self, value: impl Into<String>) -> Self {
self.query.set("surveyYears", value);
self
}
pub fn open_years(mut self, value: impl Into<String>) -> Self {
self.query.set("openYears", value);
self
}
pub fn stats_field(mut self, value: impl Into<String>) -> Self {
self.query.set("statsField", value);
self
}
pub fn stats_code(mut self, value: impl Into<String>) -> Self {
self.query.set("statsCode", value);
self
}
pub fn search_word(mut self, value: impl Into<String>) -> Self {
self.query.set("searchWord", value);
self
}
pub fn collect_area(mut self, area: CollectArea) -> Self {
self.query.set("collectArea", area.code());
self
}
pub fn explanation(mut self, on: bool) -> Self {
self.query.flag("explanationGetFlg", on);
self
}
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
}
pub fn catalog_id(mut self, value: impl Into<String>) -> Self {
self.query.set("catalogId", value);
self
}
pub fn resource_id(mut self, value: impl Into<String>) -> Self {
self.query.set("resourceId", value);
self
}
pub fn start_position(mut self, position: u64) -> Self {
self.query.set("startPosition", position.to_string());
self
}
pub fn limit(mut self, limit: u64) -> Self {
self.query.set("limit", limit.to_string());
self
}
pub fn updated_date(mut self, value: impl Into<String>) -> Self {
self.query.set("updatedDate", value);
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StatsDatasRequest {
query: Query,
}
impl StatsDatasRequest {
pub fn table(stats_data_id: impl Into<String>) -> Self {
let mut query = Query::default();
query.set("statsDataId", stats_data_id);
StatsDatasRequest { query }
}
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!();
pub fn start_position(mut self, position: u64) -> Self {
self.query.set("startPosition", position.to_string());
self
}
pub fn limit(mut self, limit: u64) -> Self {
self.query.set("limit", limit.to_string());
self
}
pub fn param(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.query.set(name, value);
self
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct StatsDatasParams {
query: Query,
requests: Vec<StatsDatasRequest>,
}
impl StatsDatasParams {
pub fn new() -> Self {
Self::default()
}
pub fn request(mut self, request: StatsDatasRequest) -> Self {
self.requests.push(request);
self
}
pub fn requests(&self) -> &[StatsDatasRequest] {
&self.requests
}
pub fn meta(mut self, on: bool) -> Self {
self.query.flag("metaGetFlg", on);
self
}
pub fn explanation(mut self, on: bool) -> Self {
self.query.flag("explanationGetFlg", on);
self
}
pub fn annotation(mut self, on: bool) -> Self {
self.query.flag("annotationGetFlg", on);
self
}
pub fn replace_sp_char(mut self, replace: ReplaceSpChar) -> Self {
self.query.set("replaceSpChar", replace.code());
self
}
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(","))
}
pub(crate) fn form(&self) -> Vec<(String, String)> {
let mut form = self.query.0.clone();
form.push(("statsDatasSpec".into(), self.spec()));
form
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DatasetsParams {
query: Query,
}
impl DatasetsParams {
pub fn new() -> Self {
Self::default()
}
pub fn collect_area(mut self, area: CollectArea) -> Self {
self.query.set("collectArea", area.code());
self
}
pub fn explanation(mut self, on: bool) -> Self {
self.query.flag("explanationGetFlg", on);
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DatasetParams {
query: Query,
}
impl DatasetParams {
pub fn new(data_set_id: impl Into<String>) -> Self {
let mut query = Query::default();
query.set("dataSetId", data_set_id);
DatasetParams { query }
}
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)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PostDatasetParams {
query: Query,
}
impl PostDatasetParams {
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 }
}
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 }
}
pub fn dataset_id(mut self, value: impl Into<String>) -> Self {
self.query.set("dataSetId", value);
self
}
pub fn name(mut self, value: impl Into<String>) -> Self {
self.query.set("dataSetName", value);
self
}
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"));
}
}