use crate::{EntityView, FieldView, IndexView, ReferenceView, TypeMemberView, TypeView};
use ic_db::{EntitySchema, FieldType, Schema, TypeBody, TypeSchema};
pub fn entity_view<'a>(
schema: &Schema,
entity: &EntitySchema,
fields: impl Iterator<Item = &'a ic_db::FieldSchema>,
) -> EntityView {
let fields = fields
.map(|field| {
let (kind, mut info) = type_view(field.value);
if entity.auto_increment && entity.primary_key.contains(&field.name) {
info = joined_info(info, "auto-increment");
}
if let Some(default) = field.default {
let value = match default {
ic_db::LiteralDefault::Nat(v) => v.to_string(),
ic_db::LiteralDefault::Int(v) => v.to_string(),
ic_db::LiteralDefault::Bool(v) => v.to_string(),
ic_db::LiteralDefault::Text(v) => format!("{v:?}"),
ic_db::LiteralDefault::Blob(v) => crate::lowercase_hex(v, "0x"),
};
info = joined_info(info, &format!("default {value}"));
}
if let Some(managed) = field.managed {
info = joined_info(
info,
match managed {
ic_db::ManagedTimestamp::CreatedAt => "managed created_at",
ic_db::ManagedTimestamp::UpdatedAt => "managed updated_at",
},
);
}
FieldView {
name: field.name.into(),
kind,
optional: field.optional,
info,
reference: field
.reference
.map(|reference| {
let index = entity
.indexes
.iter()
.find(|index| Some(index.id) == reference.index);
let target = schema
.entities()
.iter()
.find(|target| target.id == reference.entity)
.unwrap();
ReferenceView {
target_entity: target.name.into(),
target_field: target.primary_key[0].into(),
index: Some(if reference.index.is_none() {
format!("Primary key ({})", entity.primary_key.join(", "))
} else {
index.map_or(field.name, |index| index.name).into()
}),
weak_store: None,
member: index
.and_then(|index| index.fields.first()?.split_once('.'))
.filter(|(parent, _)| *parent == field.name)
.map(|(_, member)| member.into()),
}
})
.or_else(|| {
field.weak_reference.map(|weak| ReferenceView {
target_entity: weak.entity.into(),
target_field: weak.key.0.into(),
index: None,
weak_store: Some(weak.store.into()),
member: weak.member.map(str::to_owned),
})
}),
}
})
.collect();
let indexes = entity
.indexes
.iter()
.map(|index| IndexView {
reference: index.reference.map(str::to_owned),
name: index.name.into(),
fields: index.fields.iter().map(|name| (*name).into()).collect(),
unique: index.unique,
present_only: index.present_only,
filter: index.filter.map(|(flag, value)| (flag.into(), value)),
})
.collect();
EntityView {
name: entity.name.into(),
primary: entity
.primary_key
.iter()
.map(|name| (*name).into())
.collect(),
fields,
indexes,
}
}
fn member(name: &str, value: FieldType, optional: bool) -> TypeMemberView {
let (kind, info) = type_view(value);
TypeMemberView {
name: name.into(),
kind,
optional,
info,
}
}
#[must_use]
pub fn named_type_view(definition: &TypeSchema) -> TypeView {
let (kind, members) = match &definition.body {
TypeBody::Checked(rule) => {
let mut value = member("value", rule.primitive(), false);
value.info = format!("{rule:?}");
("Newtype", vec![value])
}
TypeBody::Wrapped(value) => {
let label = if matches!(value, FieldType::List { .. }) {
"List"
} else {
"Newtype"
};
(label, vec![member("value", *value, false)])
}
TypeBody::Map {
key,
value,
max_items,
} => {
let mut key = member("key", *key, false);
key.info = joined_info(format!("map max {max_items} entries"), &key.info);
(
"Map",
vec![key, member("value", value.value, value.optional)],
)
}
TypeBody::Set { item, max_items } => {
let mut item = member("element", *item, false);
item.info = joined_info(format!("max {max_items} items"), &item.info);
("Set", vec![item])
}
TypeBody::Record(fields) => (
"Record",
fields
.iter()
.map(|field| member(field.name, field.value, field.optional))
.collect(),
),
TypeBody::Enum(variants) => (
"Enum",
variants
.iter()
.map(|variant| match variant.payload {
Some(payload) => member(variant.name, payload.value, payload.optional),
None => TypeMemberView {
name: variant.name.into(),
kind: "-".into(),
info: String::new(),
optional: false,
},
})
.collect(),
),
};
TypeView {
name: definition.name.into(),
kind: kind.into(),
members,
}
}
fn type_view(value: FieldType) -> (String, String) {
match value {
FieldType::List { item, max_items } => {
let (kind, info) = type_view(*item);
let item_info = if info.is_empty() {
info
} else {
format!("item {info}")
};
(
format!("List<{kind}>"),
joined_info(format!("max {max_items} items"), &item_info),
)
}
FieldType::Named(link) => (link.name.into(), String::new()),
FieldType::Text { max_bytes } => ("Text".into(), format!("max {max_bytes} bytes")),
FieldType::Blob { max_bytes } => ("Blob".into(), format!("max {max_bytes} bytes")),
FieldType::Principal => ("Principal".into(), "max 29 bytes".into()),
FieldType::Subaccount => ("Subaccount".into(), "1 byte for zero, 33 otherwise".into()),
FieldType::Date => ("Date".into(), "4 bytes; days; 0000–9999".into()),
FieldType::Timestamp => (
"Timestamp".into(),
"Milliseconds since Unix epoch · 8 bytes".into(),
),
FieldType::Decimal { scale } => {
("Decimal".into(), format!("17 bytes; scale {scale}; exact"))
}
FieldType::Duration => (
"Duration".into(),
"Nonnegative elapsed time · 1 ms precision · 8 bytes".into(),
),
FieldType::Ulid => ("Ulid".into(), "16 bytes".into()),
FieldType::Account => (
"Account".into(),
"owner max 29 bytes; subaccount suffix 1 byte for default, 33 otherwise".into(),
),
scalar => (format!("{scalar:?}"), String::new()),
}
}
fn joined_info(bound: String, nested: &str) -> String {
if bound.is_empty() {
nested.to_owned()
} else if nested.is_empty() {
bound
} else {
format!("{bound}; {nested}")
}
}