use std::path::Path;
use super::{Declared, LoadError, Row, Table, open};
use crate::dim::{Dim, Dimensions, IdentifierNamespace, KnownNamespace, Source};
use crate::note::Note;
use crate::types::{DataKind, Dataset};
pub(super) const DEFAULT_ID_COLUMN: &str = "id";
const NOT_INFERRED: &str = "not declared, and the identifiers do not all match one \
namespace's pattern -- declare identifier_namespace";
const DATES_AMONG_THEM: &str = "not declared, and some identifiers are dates rather than \
names -- see this dataset's notes, and re-export the file \
with the identifier column typed as text";
pub(super) struct Reasons {
pub organism: &'static str,
pub subject: &'static str,
pub release: &'static str,
}
pub(super) fn named_list(
path: &Path,
id_column: Option<&str>,
declared: &Declared,
kind: DataKind,
reasons: &Reasons,
) -> Result<Dataset, LoadError> {
let wanted = id_column.unwrap_or(DEFAULT_ID_COLUMN);
let reader = open(path)?;
let mut table = Table::read(reader).map_err(|detail| LoadError::format(path, detail))?;
let at = table.column(wanted).ok_or_else(|| {
LoadError::format(
path,
format!(
"no column named `{wanted}` to read identifiers from; this file's columns are {}",
table.header().join(", ")
),
)
})?;
let mut identifiers: Vec<String> = Vec::new();
let mut notes: Vec<Note> = Vec::new();
while let Some(row) = table
.next_row()
.map_err(|detail| LoadError::format(path, detail))?
{
let identifier = read_identifier(&row, at);
if let Some(note) = Note::about_identifier(identifier)
&& !notes.contains(¬e)
{
notes.push(note);
}
identifiers.push(identifier.to_owned());
}
let dimensions = Dimensions {
organism: super::organism(declared, reasons.organism),
identifier_namespace: namespace(
path,
declared,
&identifiers,
notes
.iter()
.any(|note| matches!(note, Note::IdentifierIsADate { .. })),
),
subject: super::subject(declared, reasons.subject),
release: super::release(declared, reasons.release),
..Dimensions::default()
};
Ok(Dataset::new(kind, Some(path.to_path_buf()), dimensions).with_notes(notes))
}
fn read_identifier(row: &Row, at: usize) -> &str {
row.field(at).unwrap_or_default()
}
fn namespace(
path: &Path,
declared: &Declared,
identifiers: &[String],
dated: bool,
) -> Dim<IdentifierNamespace> {
if let Some(label) = declared
.identifier_namespace
.as_deref()
.map(IdentifierNamespace::new)
&& !label.is_empty()
{
return Dim::known(label, Source::Declared);
}
KnownNamespace::infer(identifiers.iter().map(String::as_str)).map_or_else(
|| {
Dim::unknown(if dated {
DATES_AMONG_THEM
} else {
NOT_INFERRED
})
},
|found| {
Dim::known(
IdentifierNamespace::new(found.name()),
Source::Inferred {
path: path.to_path_buf(),
detail: "the identifiers' own pattern",
},
)
},
)
}