diff --git a/rslib/src/filtered.rs b/rslib/src/filtered.rs index fca4422e9..bb528a8dc 100644 --- a/rslib/src/filtered.rs +++ b/rslib/src/filtered.rs @@ -230,7 +230,7 @@ impl Collection { let order = order_and_limit_for_search(term, ctx.today); self.search_cards_into_table(&search, SortMode::Custom(order))?; - for mut card in self.storage.all_searched_cards()? { + for mut card in self.storage.all_searched_cards_in_search_order()? { let original = card.clone(); card.move_into_filtered_deck(ctx, position); self.update_card(&mut card, &original, ctx.usn)?; diff --git a/rslib/src/search/cards.rs b/rslib/src/search/cards.rs index e4eb7ce7c..b7289abe9 100644 --- a/rslib/src/search/cards.rs +++ b/rslib/src/search/cards.rs @@ -94,11 +94,17 @@ impl Collection { pub(crate) fn search_cards_into_table(&mut self, search: &str, mode: SortMode) -> Result<()> { let top_node = Node::Group(parse(search)?); let writer = SqlWriter::new(self); + let want_order = mode != SortMode::NoOrder; let (mut sql, args) = writer.build_cards_query(&top_node, mode.required_table())?; self.add_order(&mut sql, mode)?; - self.storage.setup_searched_cards_table()?; + if want_order { + self.storage + .setup_searched_cards_table_to_preserve_order()?; + } else { + self.storage.setup_searched_cards_table()?; + } let sql = format!("insert into search_cids {}", sql); self.storage.db.prepare(&sql)?.execute(&args)?; diff --git a/rslib/src/storage/card/mod.rs b/rslib/src/storage/card/mod.rs index f8dee7328..99bb48c17 100644 --- a/rslib/src/storage/card/mod.rs +++ b/rslib/src/storage/card/mod.rs @@ -273,6 +273,16 @@ impl super::SqliteStorage { .collect() } + pub(crate) fn all_searched_cards_in_search_order(&self) -> Result> { + self.db + .prepare_cached(concat!( + include_str!("get_card.sql"), + ", search_cids where cards.id = search_cids.cid order by search_cids.rowid" + ))? + .query_and_then(NO_PARAMS, |r| row_to_card(r).map_err(Into::into))? + .collect() + } + pub(crate) fn for_each_card_in_search(&self, mut func: F) -> Result<()> where F: FnMut(Card) -> Result<()>, @@ -333,6 +343,12 @@ impl super::SqliteStorage { Ok(()) } + pub(crate) fn setup_searched_cards_table_to_preserve_order(&self) -> Result<()> { + self.db + .execute_batch(include_str!("search_cids_setup_ordered.sql"))?; + Ok(()) + } + pub(crate) fn clear_searched_cards_table(&self) -> Result<()> { self.db .execute("drop table if exists search_cids", NO_PARAMS)?; diff --git a/rslib/src/storage/card/search_cids_setup_ordered.sql b/rslib/src/storage/card/search_cids_setup_ordered.sql new file mode 100644 index 000000000..34cb16647 --- /dev/null +++ b/rslib/src/storage/card/search_cids_setup_ordered.sql @@ -0,0 +1,2 @@ +drop table if exists search_cids; +create temporary table search_cids (cid integer not null); \ No newline at end of file