From 3cb870ec9c0dbb511bf066a02439d040ca8eb34e Mon Sep 17 00:00:00 2001 From: Damien Elmes Date: Sun, 17 May 2020 19:41:47 +1000 Subject: [PATCH] ensure notetype name unique on add as well --- rslib/src/dbcheck.rs | 2 +- rslib/src/notetype/mod.rs | 36 +++++++++++++++++++++++++++++++----- 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/rslib/src/dbcheck.rs b/rslib/src/dbcheck.rs index 50e6a15d0..2af108af3 100644 --- a/rslib/src/dbcheck.rs +++ b/rslib/src/dbcheck.rs @@ -238,7 +238,7 @@ impl Collection { // one note type exists if self.storage.get_all_notetype_names()?.is_empty() { let mut nt = all_stock_notetypes(&self.i18n).remove(0); - self.add_notetype_inner(&mut nt)?; + self.add_notetype_inner(&mut nt, usn)?; } if out.card_ords_duplicated > 0 || out.field_count_mismatch > 0 || out.templates_missing > 0 diff --git a/rslib/src/notetype/mod.rs b/rslib/src/notetype/mod.rs index f948271c0..bbd41d7e7 100644 --- a/rslib/src/notetype/mod.rs +++ b/rslib/src/notetype/mod.rs @@ -100,6 +100,11 @@ impl NoteType { } } + pub(crate) fn set_modified(&mut self, usn: Usn) { + self.mtime_secs = TimestampSecs::now(); + self.usn = usn; + } + fn updated_requirements( &self, parsed: &[(Option, Option)], @@ -227,7 +232,6 @@ impl NoteType { } self.config.reqs = reqs; - // fixme: deal with duplicate note type names on update Ok(()) } @@ -335,14 +339,35 @@ impl From for NoteTypeProto { impl Collection { /// Add a new notetype, and allocate it an ID. pub fn add_notetype(&mut self, nt: &mut NoteType) -> Result<()> { - self.transact(None, |col| col.add_notetype_inner(nt)) + self.transact(None, |col| { + let usn = col.usn()?; + nt.set_modified(usn); + col.add_notetype_inner(nt, usn) + }) } - pub(crate) fn add_notetype_inner(&mut self, nt: &mut NoteType) -> Result<()> { + pub(crate) fn add_notetype_inner(&mut self, nt: &mut NoteType, usn: Usn) -> Result<()> { nt.prepare_for_adding()?; + self.ensure_notetype_name_unique(nt, usn)?; self.storage.add_new_notetype(nt) } + fn ensure_notetype_name_unique(&self, notetype: &mut NoteType, usn: Usn) -> Result<()> { + loop { + match self.storage.get_notetype_id(¬etype.name)? { + Some(did) if did == notetype.id => { + break; + } + None => break, + _ => (), + } + notetype.name += "+"; + notetype.set_modified(usn); + } + + Ok(()) + } + /// Saves changes to a note type. This will force a full sync if templates /// or fields have been added/removed/reordered. pub fn update_notetype(&mut self, nt: &mut NoteType, preserve_usn: bool) -> Result<()> { @@ -363,10 +388,11 @@ impl Collection { col.update_cards_for_changed_templates(nt, existing_notetype.templates.len())?; } + let usn = col.usn()?; if !preserve_usn { - nt.mtime_secs = TimestampSecs::now(); - nt.usn = col.usn()?; + nt.set_modified(usn); } + col.ensure_notetype_name_unique(nt, usn)?; col.storage.update_notetype_config(&nt)?; col.storage.update_notetype_fields(nt.id, &nt.fields)?;