NoteTypeID

This commit is contained in:
Damien Elmes 2020-03-26 15:00:24 +10:00
parent 4ec30e412a
commit f52e775354
8 changed files with 37 additions and 27 deletions

View file

@ -608,7 +608,9 @@ impl Backend {
self.with_col(|col| { self.with_col(|col| {
col.with_ctx(|ctx| { col.with_ctx(|ctx| {
let nids = search_notes(ctx, &input.search)?; let nids = search_notes(ctx, &input.search)?;
Ok(pb::SearchNotesOut { note_ids: nids }) Ok(pb::SearchNotesOut {
note_ids: nids.into_iter().map(|v| v.0).collect(),
})
}) })
}) })
} }

View file

@ -390,7 +390,7 @@ where
self.maybe_fire_progress_cb()?; self.maybe_fire_progress_cb()?;
} }
let nt = note_types let nt = note_types
.get(&note.mid) .get(&note.ntid)
.ok_or_else(|| AnkiError::DBError { .ok_or_else(|| AnkiError::DBError {
info: "missing note type".to_string(), info: "missing note type".to_string(),
kind: DBErrorKind::MissingEntity, kind: DBErrorKind::MissingEntity,

View file

@ -4,13 +4,10 @@
/// At the moment, this is just basic note reading/updating functionality for /// At the moment, this is just basic note reading/updating functionality for
/// the media DB check. /// the media DB check.
use crate::err::{AnkiError, DBErrorKind, Result}; use crate::err::{AnkiError, DBErrorKind, Result};
use crate::notetypes::NoteTypeID;
use crate::text::strip_html_preserving_image_filenames; use crate::text::strip_html_preserving_image_filenames;
use crate::timestamp::TimestampSecs; use crate::timestamp::TimestampSecs;
use crate::{ use crate::{define_newtype, notetypes::NoteType, types::Usn};
define_newtype,
notetypes::NoteType,
types::{ObjID, Usn},
};
use rusqlite::{params, Connection, Row, NO_PARAMS}; use rusqlite::{params, Connection, Row, NO_PARAMS};
use std::convert::TryInto; use std::convert::TryInto;
@ -19,7 +16,7 @@ define_newtype!(NoteID, i64);
#[derive(Debug)] #[derive(Debug)]
pub(super) struct Note { pub(super) struct Note {
pub id: NoteID, pub id: NoteID,
pub mid: ObjID, pub ntid: NoteTypeID,
pub mtime: TimestampSecs, pub mtime: TimestampSecs,
pub usn: Usn, pub usn: Usn,
fields: Vec<String>, fields: Vec<String>,
@ -51,7 +48,7 @@ pub(crate) fn field_checksum(text: &str) -> u32 {
} }
#[allow(dead_code)] #[allow(dead_code)]
fn get_note(db: &Connection, nid: ObjID) -> Result<Option<Note>> { fn get_note(db: &Connection, nid: NoteID) -> Result<Option<Note>> {
let mut stmt = db.prepare_cached("select id, mid, mod, usn, flds from notes where id=?")?; let mut stmt = db.prepare_cached("select id, mid, mod, usn, flds from notes where id=?")?;
let note = stmt.query_and_then(params![nid], row_to_note)?.next(); let note = stmt.query_and_then(params![nid], row_to_note)?.next();
@ -75,7 +72,7 @@ pub(super) fn for_every_note<F: FnMut(&mut Note) -> Result<()>>(
fn row_to_note(row: &Row) -> Result<Note> { fn row_to_note(row: &Row) -> Result<Note> {
Ok(Note { Ok(Note {
id: row.get(0)?, id: row.get(0)?,
mid: row.get(1)?, ntid: row.get(1)?,
mtime: row.get(2)?, mtime: row.get(2)?,
usn: row.get(3)?, usn: row.get(3)?,
fields: row fields: row

View file

@ -4,13 +4,13 @@
use super::{parser::Node, sqlwriter::node_to_sql}; use super::{parser::Node, sqlwriter::node_to_sql};
use crate::collection::RequestContext; use crate::collection::RequestContext;
use crate::err::Result; use crate::err::Result;
use crate::notes::NoteID;
use crate::search::parser::parse; use crate::search::parser::parse;
use crate::types::ObjID;
pub(crate) fn search_notes<'a, 'b>( pub(crate) fn search_notes<'a, 'b>(
req: &'a mut RequestContext<'b>, req: &'a mut RequestContext<'b>,
search: &'a str, search: &'a str,
) -> Result<Vec<ObjID>> { ) -> Result<Vec<NoteID>> {
let top_node = Node::Group(parse(search)?); let top_node = Node::Group(parse(search)?);
let (sql, args) = node_to_sql(req, &top_node)?; let (sql, args) = node_to_sql(req, &top_node)?;
@ -20,7 +20,7 @@ pub(crate) fn search_notes<'a, 'b>(
); );
let mut stmt = req.storage.db.prepare(&sql)?; let mut stmt = req.storage.db.prepare(&sql)?;
let ids: Vec<i64> = stmt let ids: Vec<_> = stmt
.query_map(&args, |row| row.get(0))? .query_map(&args, |row| row.get(0))?
.collect::<std::result::Result<_, _>>()?; .collect::<std::result::Result<_, _>>()?;

View file

@ -2,7 +2,7 @@
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
use crate::err::{AnkiError, Result}; use crate::err::{AnkiError, Result};
use crate::types::ObjID; use crate::notetypes::NoteTypeID;
use nom::branch::alt; use nom::branch::alt;
use nom::bytes::complete::{escaped, is_not, tag, take_while1}; use nom::bytes::complete::{escaped, is_not, tag, take_while1};
use nom::character::complete::{anychar, char, one_of}; use nom::character::complete::{anychar, char, one_of};
@ -58,7 +58,7 @@ pub(super) enum SearchNode<'a> {
AddedInDays(u32), AddedInDays(u32),
CardTemplate(TemplateKind), CardTemplate(TemplateKind),
Deck(Cow<'a, str>), Deck(Cow<'a, str>),
NoteTypeID(ObjID), NoteTypeID(NoteTypeID),
NoteType(Cow<'a, str>), NoteType(Cow<'a, str>),
Rated { Rated {
days: u32, days: u32,
@ -66,7 +66,7 @@ pub(super) enum SearchNode<'a> {
}, },
Tag(Cow<'a, str>), Tag(Cow<'a, str>),
Duplicates { Duplicates {
note_type_id: ObjID, note_type_id: NoteTypeID,
text: String, text: String,
}, },
State(StateKind), State(StateKind),
@ -339,7 +339,7 @@ fn parse_rated(val: &str) -> ParseResult<SearchNode<'static>> {
/// eg dupes:1231,hello /// eg dupes:1231,hello
fn parse_dupes(val: &str) -> ParseResult<SearchNode<'static>> { fn parse_dupes(val: &str) -> ParseResult<SearchNode<'static>> {
let mut it = val.splitn(2, ','); let mut it = val.splitn(2, ',');
let mid: ObjID = it.next().unwrap().parse()?; let mid: NoteTypeID = it.next().unwrap().parse()?;
let text = it.next().ok_or(ParseError {})?; let text = it.next().ok_or(ParseError {})?;
Ok(SearchNode::Duplicates { Ok(SearchNode::Duplicates {
note_type_id: mid, note_type_id: mid,

View file

@ -7,11 +7,10 @@ use crate::decks::child_ids;
use crate::decks::get_deck; use crate::decks::get_deck;
use crate::err::{AnkiError, Result}; use crate::err::{AnkiError, Result};
use crate::notes::field_checksum; use crate::notes::field_checksum;
use crate::notetypes::NoteTypeID;
use crate::text::matches_wildcard; use crate::text::matches_wildcard;
use crate::text::without_combining; use crate::text::without_combining;
use crate::{ use crate::{collection::RequestContext, text::strip_html_preserving_image_filenames};
collection::RequestContext, text::strip_html_preserving_image_filenames, types::ObjID,
};
use std::fmt::Write; use std::fmt::Write;
struct SqlWriter<'a, 'b> { struct SqlWriter<'a, 'b> {
@ -342,7 +341,7 @@ impl SqlWriter<'_, '_> {
Ok(()) Ok(())
} }
fn write_dupes(&mut self, ntid: ObjID, text: &str) { fn write_dupes(&mut self, ntid: NoteTypeID, text: &str) {
let text_nohtml = strip_html_preserving_image_filenames(text); let text_nohtml = strip_html_preserving_image_filenames(text);
let csum = field_checksum(text_nohtml.as_ref()); let csum = field_checksum(text_nohtml.as_ref());
write!( write!(

View file

@ -5,6 +5,7 @@ use crate::collection::CollectionOp;
use crate::config::Config; use crate::config::Config;
use crate::err::Result; use crate::err::Result;
use crate::err::{AnkiError, DBErrorKind}; use crate::err::{AnkiError, DBErrorKind};
use crate::notetypes::NoteTypeID;
use crate::timestamp::{TimestampMillis, TimestampSecs}; use crate::timestamp::{TimestampMillis, TimestampSecs};
use crate::{ use crate::{
decks::Deck, decks::Deck,
@ -315,11 +316,12 @@ impl StorageContext<'_> {
}) })
} }
pub(crate) fn all_note_types(&self) -> Result<HashMap<ObjID, NoteType>> { pub(crate) fn all_note_types(&self) -> Result<HashMap<NoteTypeID, NoteType>> {
let mut stmt = self.db.prepare("select models from col")?; let mut stmt = self.db.prepare("select models from col")?;
let note_types = stmt let note_types = stmt
.query_and_then(NO_PARAMS, |row| -> Result<HashMap<ObjID, NoteType>> { .query_and_then(NO_PARAMS, |row| -> Result<HashMap<NoteTypeID, NoteType>> {
let v: HashMap<ObjID, NoteType> = serde_json::from_str(row.get_raw(0).as_str()?)?; let v: HashMap<NoteTypeID, NoteType> =
serde_json::from_str(row.get_raw(0).as_str()?)?;
Ok(v) Ok(v)
})? })?
.next() .next()

View file

@ -7,8 +7,18 @@ pub type ObjID = i64;
macro_rules! define_newtype { macro_rules! define_newtype {
( $name:ident, $type:ident ) => { ( $name:ident, $type:ident ) => {
#[repr(transparent)] #[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, #[derive(
serde::Serialize, serde::Deserialize)] Debug,
Clone,
Copy,
PartialEq,
Eq,
PartialOrd,
Ord,
Hash,
serde::Serialize,
serde::Deserialize,
)]
pub struct $name(pub $type); pub struct $name(pub $type);
impl std::fmt::Display for $name { impl std::fmt::Display for $name {
@ -20,7 +30,7 @@ macro_rules! define_newtype {
impl std::str::FromStr for $name { impl std::str::FromStr for $name {
type Err = std::num::ParseIntError; type Err = std::num::ParseIntError;
fn from_str(s: &std::primitive::str) -> std::result::Result<Self, Self::Err> { fn from_str(s: &std::primitive::str) -> std::result::Result<Self, Self::Err> {
$type::from_str(s).map(|n| $name(n)) $type::from_str(s).map($name)
} }
} }