use std::collections::BTreeMap;
use core_traits::KnownEntid;
use core_traits::attribute::Unique;
use super::{
Attribute, Binding, Entid, HasSchema, IntoResult, Keyword, TypedValue, ValueType,
CORE_SCHEMA_VERSION,
};
use super::errors::{MentatError, Result};
use mentat_transaction::{InProgress, Queryable};
use mentat_transaction::entity_builder::{BuildTerms, TermBuilder, Terms};
pub use mentat_db::AttributeBuilder;
pub type Version = u32;
pub type Datom = (Entid, Entid, TypedValue);
#[derive(Clone)]
pub struct Definition {
pub name: Keyword,
pub version: Version,
pub attributes: Vec<(Keyword, Attribute)>,
pub pre: fn(&mut InProgress<'_, '_>, &Vocabulary) -> Result<()>,
pub post: fn(&mut InProgress<'_, '_>, &Vocabulary) -> Result<()>,
}
impl Definition {
pub fn no_op(_ip: &mut InProgress<'_, '_>, _from: &Vocabulary) -> Result<()> {
Ok(())
}
pub fn new<N, A>(name: N, version: Version, attributes: A) -> Definition
where
N: Into<Keyword>,
A: Into<Vec<(Keyword, Attribute)>>,
{
Definition {
name: name.into(),
version,
attributes: attributes.into(),
pre: Definition::no_op,
post: Definition::no_op,
}
}
fn pre(&self, ip: &mut InProgress<'_, '_>, from: &Vocabulary) -> Result<()> {
(self.pre)(ip, from)
}
fn post(&self, ip: &mut InProgress<'_, '_>, from: &Vocabulary) -> Result<()> {
(self.post)(ip, from)
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Vocabulary {
pub entity: Entid,
pub version: Version,
attributes: Vec<(Entid, Attribute)>,
}
impl Vocabulary {
pub fn attributes(&self) -> &Vec<(Entid, Attribute)> {
&self.attributes
}
}
#[derive(Debug, Default, Clone)]
pub struct Vocabularies(pub BTreeMap<Keyword, Vocabulary>);
impl Vocabularies {
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.len() == 0
}
pub fn get(&self, name: &Keyword) -> Option<&Vocabulary> {
self.0.get(name)
}
pub fn iter(&self) -> ::std::collections::btree_map::Iter<'_, Keyword, Vocabulary> {
self.0.iter()
}
}
lazy_static! {
static ref DB_SCHEMA_CORE: Keyword = kw!(:db.schema/core);
static ref DB_SCHEMA_ATTRIBUTE: Keyword = kw!(:db.schema/attribute);
static ref DB_SCHEMA_VERSION: Keyword = kw!(:db.schema/version);
static ref DB_IDENT: Keyword = kw!(:db/ident);
static ref DB_UNIQUE: Keyword = kw!(:db/unique);
static ref DB_UNIQUE_VALUE: Keyword = kw!(:db.unique/value);
static ref DB_UNIQUE_IDENTITY: Keyword = kw!(:db.unique/identity);
static ref DB_IS_COMPONENT: Keyword = Keyword::namespaced("db", "isComponent");
static ref DB_VALUE_TYPE: Keyword = Keyword::namespaced("db", "valueType");
static ref DB_INDEX: Keyword = kw!(:db/index);
static ref DB_FULLTEXT: Keyword = kw!(:db/fulltext);
static ref DB_CARDINALITY: Keyword = kw!(:db/cardinality);
static ref DB_CARDINALITY_ONE: Keyword = kw!(:db.cardinality/one);
static ref DB_CARDINALITY_MANY: Keyword = kw!(:db.cardinality/many);
static ref DB_NO_HISTORY: Keyword = Keyword::namespaced("db", "noHistory");
}
trait HasCoreSchema {
fn core_type(&self, t: ValueType) -> Result<KnownEntid>;
fn core_entid(&self, ident: &Keyword) -> Result<KnownEntid>;
fn core_attribute(&self, ident: &Keyword) -> Result<KnownEntid>;
}
impl<T> HasCoreSchema for T
where
T: HasSchema,
{
fn core_type(&self, t: ValueType) -> Result<KnownEntid> {
self.entid_for_type(t)
.ok_or_else(|| MentatError::MissingCoreVocabulary(DB_SCHEMA_VERSION.clone()))
}
fn core_entid(&self, ident: &Keyword) -> Result<KnownEntid> {
self.get_entid(ident)
.ok_or_else(|| MentatError::MissingCoreVocabulary(DB_SCHEMA_VERSION.clone()))
}
fn core_attribute(&self, ident: &Keyword) -> Result<KnownEntid> {
self.attribute_for_ident(ident)
.ok_or_else(|| MentatError::MissingCoreVocabulary(DB_SCHEMA_VERSION.clone()))
.map(|(_, e)| e)
}
}
impl Definition {
fn description_for_attributes<T, R>(
&self,
attributes: &[R],
via: &T,
diff: Option<BTreeMap<Keyword, Attribute>>,
) -> Result<Terms>
where
T: HasCoreSchema,
R: ::std::borrow::Borrow<(Keyword, Attribute)>,
{
let a_version = via.core_attribute(&DB_SCHEMA_VERSION)?;
let a_ident = via.core_attribute(&DB_IDENT)?;
let a_attr = via.core_attribute(&DB_SCHEMA_ATTRIBUTE)?;
let a_cardinality = via.core_attribute(&DB_CARDINALITY)?;
let a_fulltext = via.core_attribute(&DB_FULLTEXT)?;
let a_index = via.core_attribute(&DB_INDEX)?;
let a_is_component = via.core_attribute(&DB_IS_COMPONENT)?;
let a_value_type = via.core_attribute(&DB_VALUE_TYPE)?;
let a_unique = via.core_attribute(&DB_UNIQUE)?;
let a_no_history = via.core_attribute(&DB_NO_HISTORY)?;
let v_cardinality_many = via.core_entid(&DB_CARDINALITY_MANY)?;
let v_cardinality_one = via.core_entid(&DB_CARDINALITY_ONE)?;
let v_unique_identity = via.core_entid(&DB_UNIQUE_IDENTITY)?;
let v_unique_value = via.core_entid(&DB_UNIQUE_VALUE)?;
let name: TypedValue = self.name.clone().into();
let version: TypedValue = TypedValue::Long(self.version as i64);
let mut entity = TermBuilder::new().describe_tempid("s");
entity.add(a_version, version)?;
entity.add(a_ident, name)?;
let (mut builder, schema) = entity.finish();
for r in attributes.iter() {
let (kw, attr) = r.borrow();
let tempid = builder.named_tempid(kw.to_string());
let name: TypedValue = kw.clone().into();
builder.add(tempid.clone(), a_ident, name)?;
builder.add(schema.clone(), a_attr, tempid.clone())?;
let value_type = via.core_type(attr.value_type)?;
builder.add(tempid.clone(), a_value_type, value_type)?;
let c = if attr.multival {
v_cardinality_many
} else {
v_cardinality_one
};
builder.add(tempid.clone(), a_cardinality, c)?;
builder.add(tempid.clone(), a_index, TypedValue::Boolean(attr.index))?;
builder.add(
tempid.clone(),
a_fulltext,
TypedValue::Boolean(attr.fulltext),
)?;
builder.add(
tempid.clone(),
a_is_component,
TypedValue::Boolean(attr.component),
)?;
builder.add(
tempid.clone(),
a_no_history,
TypedValue::Boolean(attr.no_history),
)?;
if let Some(u) = attr.unique {
let uu = match u {
Unique::Identity => v_unique_identity,
Unique::Value => v_unique_value,
};
builder.add(tempid.clone(), a_unique, uu)?;
} else {
let existing_unique = if let Some(ref diff) = diff {
diff.get(kw).and_then(|a| a.unique)
} else {
None
};
match existing_unique {
None => {
}
Some(Unique::Identity) => {
builder.retract(tempid.clone(), a_unique, v_unique_identity)?;
}
Some(Unique::Value) => {
builder.retract(tempid.clone(), a_unique, v_unique_value)?;
}
}
}
}
builder.build()
}
fn description_diff<T>(&self, via: &T, from: &Vocabulary) -> Result<Terms>
where
T: HasSchema,
{
let relevant = self
.attributes
.iter()
.filter_map(|(keyword, _)|
via.get_entid(keyword)
.and_then(|e| from.find(e).cloned())
.map(|e| (keyword.clone(), e)))
.collect();
self.description_for_attributes(self.attributes.as_slice(), via, Some(relevant))
}
fn description<T>(&self, via: &T) -> Result<Terms>
where
T: HasSchema,
{
self.description_for_attributes(self.attributes.as_slice(), via, None)
}
}
#[derive(Debug, Eq, PartialEq)]
pub enum VocabularyCheck<'definition> {
NotPresent,
Present,
PresentButNeedsUpdate { older_version: Vocabulary },
PresentButTooNew { newer_version: Vocabulary },
PresentButMissingAttributes {
attributes: Vec<&'definition (Keyword, Attribute)>,
},
}
#[derive(Debug, Eq, PartialEq)]
pub enum VocabularyOutcome {
Installed,
InstalledMissingAttributes,
Existed,
Upgraded,
}
pub trait HasVocabularies {
fn read_vocabularies(&self) -> Result<Vocabularies>;
fn read_vocabulary_named(&self, name: &Keyword) -> Result<Option<Vocabulary>>;
}
pub trait VersionedStore: HasVocabularies + HasSchema {
fn check_vocabulary<'definition>(
&self,
definition: &'definition Definition,
) -> Result<VocabularyCheck<'definition>> {
if let Some(vocabulary) = self.read_vocabulary_named(&definition.name)? {
if vocabulary.version == definition.version {
let mut missing: Vec<&'definition (Keyword, Attribute)> = vec![];
for pair in definition.attributes.iter() {
if let Some(entid) = self.get_entid(&pair.0) {
if let Some(existing) = vocabulary.find(entid) {
if *existing == pair.1 {
continue;
} else {
bail!(MentatError::ConflictingAttributeDefinitions(
definition.name.to_string(),
definition.version,
pair.0.to_string(),
existing.clone(),
pair.1.clone()
));
}
}
}
missing.push(pair);
}
if missing.is_empty() {
Ok(VocabularyCheck::Present)
} else {
Ok(VocabularyCheck::PresentButMissingAttributes {
attributes: missing,
})
}
} else if vocabulary.version < definition.version {
Ok(VocabularyCheck::PresentButNeedsUpdate {
older_version: vocabulary,
})
} else {
Ok(VocabularyCheck::PresentButTooNew {
newer_version: vocabulary,
})
}
} else {
Ok(VocabularyCheck::NotPresent)
}
}
fn ensure_vocabulary(&mut self, definition: &Definition) -> Result<VocabularyOutcome>;
fn ensure_vocabularies(
&mut self,
vocabularies: &mut dyn VocabularySource,
) -> Result<BTreeMap<Keyword, VocabularyOutcome>>;
fn verify_core_schema(&self) -> Result<()> {
if let Some(core) = self.read_vocabulary_named(&DB_SCHEMA_CORE)? {
if core.version != CORE_SCHEMA_VERSION {
bail!(MentatError::UnexpectedCoreSchema(
CORE_SCHEMA_VERSION,
Some(core.version)
));
}
} else {
bail!(MentatError::UnexpectedCoreSchema(CORE_SCHEMA_VERSION, None));
}
Ok(())
}
}
pub trait VocabularyStatus {
fn get(&self, name: &Keyword) -> Option<(&Definition, &VocabularyCheck<'_>)>;
fn version(&self, name: &Keyword) -> Option<Version>;
}
#[derive(Default)]
struct CheckedVocabularies<'a> {
items: BTreeMap<Keyword, (&'a Definition, VocabularyCheck<'a>)>,
}
impl<'a> CheckedVocabularies<'a> {
fn add(&mut self, definition: &'a Definition, check: VocabularyCheck<'a>) {
self.items
.insert(definition.name.clone(), (definition, check));
}
fn is_empty(&self) -> bool {
self.items.is_empty()
}
}
impl VocabularyStatus for CheckedVocabularies<'_> {
fn get(&self, name: &Keyword) -> Option<(&Definition, &VocabularyCheck<'_>)> {
self.items.get(name).map(|&(d, ref c)| (d, c))
}
fn version(&self, name: &Keyword) -> Option<Version> {
self.items.get(name).map(|&(d, _)| d.version)
}
}
trait VocabularyMechanics {
fn install_vocabulary(&mut self, definition: &Definition) -> Result<VocabularyOutcome>;
fn install_attributes_for<'definition>(
&mut self,
definition: &'definition Definition,
attributes: Vec<&'definition (Keyword, Attribute)>,
) -> Result<VocabularyOutcome>;
fn upgrade_vocabulary(
&mut self,
definition: &Definition,
from_version: Vocabulary,
) -> Result<VocabularyOutcome>;
}
impl Vocabulary {
fn find<T>(&self, entid: T) -> Option<&Attribute>
where
T: Into<Entid>,
{
let to_find = entid.into();
self.attributes
.iter()
.find(|&&(e, _)| e == to_find)
.map(|(_, a)| a)
}
}
impl VersionedStore for InProgress<'_, '_> {
fn ensure_vocabulary(&mut self, definition: &Definition) -> Result<VocabularyOutcome> {
match self.check_vocabulary(definition)? {
VocabularyCheck::Present => Ok(VocabularyOutcome::Existed),
VocabularyCheck::NotPresent => self.install_vocabulary(definition),
VocabularyCheck::PresentButNeedsUpdate { older_version } => {
self.upgrade_vocabulary(definition, older_version)
}
VocabularyCheck::PresentButMissingAttributes { attributes } => {
self.install_attributes_for(definition, attributes)
}
VocabularyCheck::PresentButTooNew { newer_version } => {
Err(MentatError::ExistingVocabularyTooNew(
definition.name.to_string(),
newer_version.version,
definition.version,
))
}
}
}
fn ensure_vocabularies(
&mut self,
vocabularies: &mut dyn VocabularySource,
) -> Result<BTreeMap<Keyword, VocabularyOutcome>> {
let definitions = vocabularies.definitions();
let mut update = Vec::new();
let mut missing = Vec::new();
let mut out = BTreeMap::new();
let mut work = CheckedVocabularies::default();
for definition in definitions.iter() {
match self.check_vocabulary(definition)? {
VocabularyCheck::Present => {
out.insert(definition.name.clone(), VocabularyOutcome::Existed);
}
VocabularyCheck::PresentButTooNew { newer_version } => {
bail!(MentatError::ExistingVocabularyTooNew(
definition.name.to_string(),
newer_version.version,
definition.version
));
}
c @ VocabularyCheck::NotPresent
| c @ VocabularyCheck::PresentButNeedsUpdate { .. }
| c @ VocabularyCheck::PresentButMissingAttributes { .. } => {
work.add(definition, c);
}
}
}
if work.is_empty() {
return Ok(out);
}
vocabularies.pre(self, &work)?;
for (name, (definition, check)) in work.items.into_iter() {
match check {
VocabularyCheck::NotPresent => {
out.insert(name, self.install_vocabulary(definition)?);
}
VocabularyCheck::PresentButNeedsUpdate { older_version } => {
update.push((definition, older_version));
}
VocabularyCheck::PresentButMissingAttributes { attributes } => {
missing.push((definition, attributes));
}
VocabularyCheck::Present | VocabularyCheck::PresentButTooNew { .. } => {
unreachable!();
}
}
}
for (d, v) in update {
out.insert(d.name.clone(), self.upgrade_vocabulary(d, v)?);
}
for (d, a) in missing {
out.insert(d.name.clone(), self.install_attributes_for(d, a)?);
}
vocabularies.post(self)?;
Ok(out)
}
}
pub trait VocabularySource {
fn definitions(&mut self) -> Vec<Definition>;
fn pre(
&mut self,
_in_progress: &mut InProgress<'_, '_>,
_checks: &dyn VocabularyStatus,
) -> Result<()> {
Ok(())
}
fn post(&mut self, _in_progress: &mut InProgress<'_, '_>) -> Result<()> {
Ok(())
}
}
pub struct SimpleVocabularySource {
pub definitions: Vec<Definition>,
pub pre: Option<fn(&mut InProgress<'_, '_>) -> Result<()>>,
pub post: Option<fn(&mut InProgress<'_, '_>) -> Result<()>>,
}
impl SimpleVocabularySource {
pub fn new(
definitions: Vec<Definition>,
pre: Option<fn(&mut InProgress<'_, '_>) -> Result<()>>,
post: Option<fn(&mut InProgress<'_, '_>) -> Result<()>>,
) -> SimpleVocabularySource {
SimpleVocabularySource {
pre,
post,
definitions,
}
}
pub fn with_definitions(definitions: Vec<Definition>) -> SimpleVocabularySource {
Self::new(definitions, None, None)
}
}
impl VocabularySource for SimpleVocabularySource {
fn pre(
&mut self,
in_progress: &mut InProgress<'_, '_>,
_checks: &dyn VocabularyStatus,
) -> Result<()> {
self.pre.map(|pre| (pre)(in_progress)).unwrap_or(Ok(()))
}
fn post(&mut self, in_progress: &mut InProgress<'_, '_>) -> Result<()> {
self.post.map(|pre| (pre)(in_progress)).unwrap_or(Ok(()))
}
fn definitions(&mut self) -> Vec<Definition> {
self.definitions.clone()
}
}
impl VocabularyMechanics for InProgress<'_, '_> {
fn install_vocabulary(&mut self, definition: &Definition) -> Result<VocabularyOutcome> {
let (terms, _tempids) = definition.description(self)?;
self.transact_entities(terms)?;
Ok(VocabularyOutcome::Installed)
}
fn install_attributes_for<'definition>(
&mut self,
definition: &'definition Definition,
attributes: Vec<&'definition (Keyword, Attribute)>,
) -> Result<VocabularyOutcome> {
let (terms, _tempids) = definition.description_for_attributes(&attributes, self, None)?;
self.transact_entities(terms)?;
Ok(VocabularyOutcome::InstalledMissingAttributes)
}
fn upgrade_vocabulary(
&mut self,
definition: &Definition,
from_version: Vocabulary,
) -> Result<VocabularyOutcome> {
definition.pre(self, &from_version)?;
let (terms, _tempids) = definition.description_diff(self, &from_version)?;
self.transact_entities(terms)?;
definition.post(self, &from_version)?;
Ok(VocabularyOutcome::Upgraded)
}
}
impl<T> HasVocabularies for T
where
T: HasSchema + Queryable,
{
fn read_vocabulary_named(&self, name: &Keyword) -> Result<Option<Vocabulary>> {
if let Some(entid) = self.get_entid(name) {
match self.lookup_value_for_attribute(entid, &DB_SCHEMA_VERSION)? {
None => Ok(None),
Some(TypedValue::Long(version)) if version > 0 && (version < u32::MAX as i64) => {
let version = version as u32;
let attributes = self
.lookup_values_for_attribute(entid, &DB_SCHEMA_ATTRIBUTE)?
.into_iter()
.filter_map(|a| {
if let TypedValue::Ref(a) = a {
self.attribute_for_entid(a).cloned().map(|attr| (a, attr))
} else {
None
}
})
.collect();
Ok(Some(Vocabulary {
entity: entid.into(),
version,
attributes,
}))
}
Some(_) => bail!(MentatError::InvalidVocabularyVersion),
}
} else {
Ok(None)
}
}
fn read_vocabularies(&self) -> Result<Vocabularies> {
let versions: BTreeMap<Entid, u32> = self
.q_once(
r#"[:find ?vocab ?version
:where [?vocab :db.schema/version ?version]]"#,
None,
)
.into_rel_result()?
.into_iter()
.filter_map(|v| match (&v[0], &v[1]) {
(
&Binding::Scalar(TypedValue::Ref(vocab)),
&Binding::Scalar(TypedValue::Long(version)),
) if version > 0 && (version < u32::MAX as i64) => Some((vocab, version as u32)),
(_, _) => None,
})
.collect();
let mut attributes = BTreeMap::<Entid, Vec<(Entid, Attribute)>>::new();
let pairs = self
.q_once(
"[:find ?vocab ?attr :where [?vocab :db.schema/attribute ?attr]]",
None,
)
.into_rel_result()?
.into_iter()
.filter_map(|v| match (&v[0], &v[1]) {
(
&Binding::Scalar(TypedValue::Ref(vocab)),
&Binding::Scalar(TypedValue::Ref(attr)),
) => Some((vocab, attr)),
(_, _) => None,
});
for (vocab, attr) in pairs {
if let Some(attribute) = self.attribute_for_entid(attr).cloned() {
attributes.entry(vocab).or_default().push((attr, attribute));
}
}
Ok(Vocabularies(
versions
.into_iter()
.filter_map(|(vocab, version)| {
self.get_ident(vocab).cloned().map(|name| {
let attrs = attributes.remove(&vocab).unwrap_or_default();
(
name,
Vocabulary {
entity: vocab,
version,
attributes: attrs,
},
)
})
})
.collect(),
))
}
}
#[cfg(test)]
mod tests {
use crate::Store;
use super::HasVocabularies;
#[test]
fn test_read_vocabularies() {
let mut store = Store::open("").expect("opened");
let vocabularies = store
.begin_read()
.expect("in progress")
.read_vocabularies()
.expect("OK");
assert_eq!(vocabularies.len(), 1);
let core = vocabularies.get(&kw!(:db.schema/core)).expect("exists");
assert_eq!(core.version, 1);
}
#[test]
fn test_core_schema() {
let mut store = Store::open("").expect("opened");
let in_progress = store.begin_transaction().expect("in progress");
let vocab = in_progress.read_vocabularies().expect("vocabulary");
assert_eq!(1, vocab.len());
assert_eq!(
1,
vocab
.get(&kw!(:db.schema/core))
.expect("core vocab")
.version
);
}
}