Skip to content

Deprecate Query::get_many (etc) and make many return a Result #18120

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions benches/benches/bevy_ecs/world/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ criterion_group!(
world_despawn,
world_despawn_recursive,
query_get,
query_get_many::<2>,
query_get_many::<5>,
query_get_many::<10>,
query_many::<2>,
query_many::<5>,
query_many::<10>,
entity_set_build_and_lookup,
);
14 changes: 4 additions & 10 deletions benches/benches/bevy_ecs/world/world_get.rs
Original file line number Diff line number Diff line change
Expand Up @@ -307,8 +307,8 @@ pub fn query_get(criterion: &mut Criterion) {
group.finish();
}

pub fn query_get_many<const N: usize>(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group(format!("query_get_many_{N}"));
pub fn query_many<const N: usize>(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group(format!("query_many_{N}"));
group.warm_up_time(core::time::Duration::from_millis(500));
group.measurement_time(core::time::Duration::from_secs(2 * N as u64));

Expand All @@ -325,10 +325,7 @@ pub fn query_get_many<const N: usize>(criterion: &mut Criterion) {

bencher.iter(|| {
let mut count = 0;
for comp in entity_groups
.iter()
.filter_map(|&ids| query.get_many(ids).ok())
{
for comp in entity_groups.iter().filter_map(|&ids| query.many(ids).ok()) {
black_box(comp);
count += 1;
black_box(count);
Expand All @@ -348,10 +345,7 @@ pub fn query_get_many<const N: usize>(criterion: &mut Criterion) {

bencher.iter(|| {
let mut count = 0;
for comp in entity_groups
.iter()
.filter_map(|&ids| query.get_many(ids).ok())
{
for comp in entity_groups.iter().filter_map(|&ids| query.many(ids).ok()) {
black_box(comp);
count += 1;
black_box(count);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use bevy_ecs::prelude::*;
struct A(usize);

fn system(mut query: Query<&mut A>, e: Entity) {
let a1 = query.get_many([e, e]).unwrap();
let a1 = query.many([e, e]).unwrap();
let a2 = query.get_mut(e).unwrap();
//~^ E0502
println!("{} {}", a1[0].0, a2.0);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
error[E0502]: cannot borrow `query` as mutable because it is also borrowed as immutable
--> tests/ui/system_query_get_many_lifetime_safety.rs:8:14
--> tests/ui/system_query_many_lifetime_safety.rs:8:14
|
7 | let a1 = query.get_many([e, e]).unwrap();
7 | let a1 = query.many([e, e]).unwrap();
| ----- immutable borrow occurs here
8 | let a2 = query.get_mut(e).unwrap();
| ^^^^^^^^^^^^^^^^ mutable borrow occurs here
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use bevy_ecs::prelude::*;
struct A(usize);

fn system(mut query: Query<&mut A>, e: Entity) {
let a1 = query.get_many_mut([e, e]).unwrap();
let a1 = query.many_mut([e, e]).unwrap();
let a2 = query.get_mut(e).unwrap();
//~^ E0499
println!("{} {}", a1[0].0, a2.0);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
error[E0499]: cannot borrow `query` as mutable more than once at a time
--> tests/ui/system_query_get_many_mut_lifetime_safety.rs:8:14
--> tests/ui/system_query_many_mut_lifetime_safety.rs:8:14
|
7 | let a1 = query.get_many_mut([e, e]).unwrap();
7 | let a1 = query.many_mut([e, e]).unwrap();
| ----- first mutable borrow occurs here
8 | let a2 = query.get_mut(e).unwrap();
| ^^^^^ second mutable borrow occurs here
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_ecs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1820,7 +1820,7 @@ mod tests {

world.insert_batch(values);
let mut query = world.query::<(Option<&A>, &B, &C)>();
let component_values = query.get_many(&world, [e0, e1, e2]).unwrap();
let component_values = query.many(&world, [e0, e1, e2]).unwrap();

assert_eq!(
component_values,
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_ecs/src/query/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub enum QueryEntityError<'w> {
EntityDoesNotExist(EntityDoesNotExistError),
/// The [`Entity`] was requested mutably more than once.
///
/// See [`Query::get_many_mut`](crate::system::Query::get_many_mut) for an example.
/// See [`Query::many_mut`](crate::system::Query::many_mut) for an example.
AliasedMutability(Entity),
}

Expand Down
13 changes: 5 additions & 8 deletions crates/bevy_ecs/src/query/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -438,14 +438,14 @@ mod tests {
}

#[test]
fn get_many_only_mut_checks_duplicates() {
fn many_only_mut_checks_duplicates() {
let mut world = World::new();
let id = world.spawn(A(10)).id();
let mut query_state = world.query::<&mut A>();
let mut query = query_state.query_mut(&mut world);
let result = query.get_many([id, id]);
let result = query.many([id, id]);
assert_eq!(result, Ok([&A(10), &A(10)]));
let mut_result = query.get_many_mut([id, id]);
let mut_result = query.many_mut([id, id]);
assert!(mut_result.is_err());
}

Expand Down Expand Up @@ -762,9 +762,8 @@ mod tests {

let _: Option<&Foo> = q.get(&world, e).ok();
let _: Option<&Foo> = q.get_manual(&world, e).ok();
let _: Option<[&Foo; 1]> = q.get_many(&world, [e]).ok();
let _: Option<[&Foo; 1]> = q.many(&world, [e]).ok();
let _: Option<&Foo> = q.single(&world).ok();
let _: &Foo = q.single(&world).unwrap();

// system param
let mut q = SystemState::<Query<&mut Foo>>::new(&mut world);
Expand All @@ -775,10 +774,8 @@ mod tests {
q.iter().for_each(|_: &Foo| ());

let _: Option<&Foo> = q.get(e).ok();
let _: Option<[&Foo; 1]> = q.get_many([e]).ok();
let _: Option<[&Foo; 1]> = q.many([e]).ok();
let _: Option<&Foo> = q.single().ok();
let _: [&Foo; 1] = q.many([e]);
let _: &Foo = q.single().unwrap();
}

// regression test for https://github.com/bevyengine/bevy/pull/8029
Expand Down
66 changes: 46 additions & 20 deletions crates/bevy_ecs/src/query/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -919,12 +919,25 @@ impl<D: QueryData, F: QueryFilter> QueryState<D, F> {
self.query(world).get_inner(entity)
}

/// Returns the read-only query results for the given array of [`Entity`].
///
/// Deprecated alias for [`Self::many`].
#[inline]
#[deprecated(note = "Use `many` instead, which now returns a Result.")]
pub fn get_many<'w, const N: usize>(
&mut self,
world: &'w World,
entities: [Entity; N],
) -> Result<[ROQueryItem<'w, D>; N], QueryEntityError<'w>> {
self.query(world).many_inner(entities)
}

/// Returns the read-only query results for the given array of [`Entity`].
///
/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is
/// returned instead.
///
/// Note that the unlike [`QueryState::get_many_mut`], the entities passed in do not need to be unique.
/// Note that the unlike [`QueryState::many_mut`], the entities passed in do not need to be unique.
///
/// # Examples
///
Expand All @@ -943,21 +956,21 @@ impl<D: QueryData, F: QueryFilter> QueryState<D, F> {
///
/// let mut query_state = world.query::<&A>();
///
/// let component_values = query_state.get_many(&world, entities).unwrap();
/// let component_values = query_state.many(&world, entities).unwrap();
///
/// assert_eq!(component_values, [&A(0), &A(1), &A(2)]);
///
/// let wrong_entity = Entity::from_raw(365);
///
/// assert_eq!(match query_state.get_many(&mut world, [wrong_entity]).unwrap_err() {QueryEntityError::EntityDoesNotExist(error) => error.entity, _ => panic!()}, wrong_entity);
/// assert_eq!(match query_state.many(&mut world, [wrong_entity]).unwrap_err() {QueryEntityError::EntityDoesNotExist(error) => error.entity, _ => panic!()}, wrong_entity);
/// ```
#[inline]
pub fn get_many<'w, const N: usize>(
pub fn many<'w, const N: usize>(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For what it's worth, I'm hoping to deprecate all the querying methods on QueryState in favor of the methods on Query. If we think that's likely to be approved, then we might want to deprecate these two and recommend query(world).many_inner(entities) now so that users don't have to first change get_many() to many() and then change a second time to use query().

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's unlikely that that change makes it into 0.16.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, I know! I wasn't even going to attempt it for 0.16 :).

But if we expect to do it in 0.17, then it might be nice to advise users of QueryState::get_many to switch to query directly instead of switching to QueryState::many in 0.16 and then having to update that code again in the next release.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that the set of users calling QueryState::get_many is small enough that I'm not concerned about that :)

&mut self,
world: &'w World,
entities: [Entity; N],
) -> Result<[ROQueryItem<'w, D>; N], QueryEntityError<'w>> {
self.query(world).get_many_inner(entities)
self.query(world).many_inner(entities)
}

/// Gets the query result for the given [`World`] and [`Entity`].
Expand All @@ -972,6 +985,19 @@ impl<D: QueryData, F: QueryFilter> QueryState<D, F> {
self.query_mut(world).get_inner(entity)
}

/// Returns the query results for the given array of [`Entity`].
///
/// Deprecated alias for [`Self::many_mut`].
#[inline]
#[deprecated(note = "Use `many_mut` instead, which now returns a Result.")]
pub fn get_many_mut<'w, const N: usize>(
&mut self,
world: &'w mut World,
entities: [Entity; N],
) -> Result<[D::Item<'w>; N], QueryEntityError<'w>> {
self.query_mut(world).many_inner(entities)
}

/// Returns the query results for the given array of [`Entity`].
///
/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is
Expand All @@ -993,30 +1019,30 @@ impl<D: QueryData, F: QueryFilter> QueryState<D, F> {
///
/// let mut query_state = world.query::<&mut A>();
///
/// let mut mutable_component_values = query_state.get_many_mut(&mut world, entities).unwrap();
/// let mut mutable_component_values = query_state.many_mut(&mut world, entities).unwrap();
///
/// for mut a in &mut mutable_component_values {
/// a.0 += 5;
/// }
///
/// let component_values = query_state.get_many(&world, entities).unwrap();
/// let component_values = query_state.many(&world, entities).unwrap();
///
/// assert_eq!(component_values, [&A(5), &A(6), &A(7)]);
///
/// let wrong_entity = Entity::from_raw(57);
/// let invalid_entity = world.spawn_empty().id();
///
/// assert_eq!(match query_state.get_many(&mut world, [wrong_entity]).unwrap_err() {QueryEntityError::EntityDoesNotExist(error) => error.entity, _ => panic!()}, wrong_entity);
/// assert_eq!(match query_state.get_many_mut(&mut world, [invalid_entity]).unwrap_err() {QueryEntityError::QueryDoesNotMatch(entity, _) => entity, _ => panic!()}, invalid_entity);
/// assert_eq!(query_state.get_many_mut(&mut world, [entities[0], entities[0]]).unwrap_err(), QueryEntityError::AliasedMutability(entities[0]));
/// assert_eq!(match query_state.many(&mut world, [wrong_entity]).unwrap_err() {QueryEntityError::EntityDoesNotExist(error) => error.entity, _ => panic!()}, wrong_entity);
/// assert_eq!(match query_state.many_mut(&mut world, [invalid_entity]).unwrap_err() {QueryEntityError::QueryDoesNotMatch(entity, _) => entity, _ => panic!()}, invalid_entity);
/// assert_eq!(query_state.many_mut(&mut world, [entities[0], entities[0]]).unwrap_err(), QueryEntityError::AliasedMutability(entities[0]));
/// ```
#[inline]
pub fn get_many_mut<'w, const N: usize>(
pub fn many_mut<'w, const N: usize>(
&mut self,
world: &'w mut World,
entities: [Entity; N],
) -> Result<[D::Item<'w>; N], QueryEntityError<'w>> {
self.query_mut(world).get_many_inner(entities)
self.query_mut(world).many_inner(entities)
}

/// Gets the query result for the given [`World`] and [`Entity`].
Expand Down Expand Up @@ -1328,16 +1354,16 @@ impl<D: QueryData, F: QueryFilter> QueryState<D, F> {
/// a.0 += 5;
/// });
///
/// # let component_values = query_state.get_many(&world, entities).unwrap();
/// # let component_values = query_state.many(&world, entities).unwrap();
///
/// # assert_eq!(component_values, [&A(5), &A(6), &A(7)]);
///
/// # let wrong_entity = Entity::from_raw(57);
/// # let invalid_entity = world.spawn_empty().id();
///
/// # assert_eq!(match query_state.get_many(&mut world, [wrong_entity]).unwrap_err() {QueryEntityError::EntityDoesNotExist(error) => error.entity, _ => panic!()}, wrong_entity);
/// assert_eq!(match query_state.get_many_mut(&mut world, [invalid_entity]).unwrap_err() {QueryEntityError::QueryDoesNotMatch(entity, _) => entity, _ => panic!()}, invalid_entity);
/// # assert_eq!(query_state.get_many_mut(&mut world, [entities[0], entities[0]]).unwrap_err(), QueryEntityError::AliasedMutability(entities[0]));
/// # assert_eq!(match query_state.many(&mut world, [wrong_entity]).unwrap_err() {QueryEntityError::EntityDoesNotExist(error) => error.entity, _ => panic!()}, wrong_entity);
/// assert_eq!(match query_state.many_mut(&mut world, [invalid_entity]).unwrap_err() {QueryEntityError::QueryDoesNotMatch(entity, _) => entity, _ => panic!()}, invalid_entity);
/// # assert_eq!(query_state.many_mut(&mut world, [entities[0], entities[0]]).unwrap_err(), QueryEntityError::AliasedMutability(entities[0]));
/// ```
///
/// # Panics
Expand Down Expand Up @@ -1776,22 +1802,22 @@ mod tests {

#[test]
#[should_panic]
fn right_world_get_many() {
fn right_world_many() {
let mut world_1 = World::new();
let world_2 = World::new();

let mut query_state = world_1.query::<Entity>();
let _panics = query_state.get_many(&world_2, []);
let _panics = query_state.many(&world_2, []);
}

#[test]
#[should_panic]
fn right_world_get_many_mut() {
fn right_world_many_mut() {
let mut world_1 = World::new();
let mut world_2 = World::new();

let mut query_state = world_1.query::<Entity>();
let _panics = query_state.get_many_mut(&mut world_2, []);
let _panics = query_state.many_mut(&mut world_2, []);
}

#[derive(Component, PartialEq, Debug)]
Expand Down
6 changes: 3 additions & 3 deletions crates/bevy_ecs/src/system/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,7 @@ mod tests {
}

#[test]
fn get_many_is_ordered() {
fn many_is_ordered() {
use crate::resource::Resource;
const ENTITIES_COUNT: usize = 1000;

Expand All @@ -411,7 +411,7 @@ mod tests {
let entities_array: [Entity; ENTITIES_COUNT] =
entities_array.0.clone().try_into().unwrap();

for (i, w) in (0..ENTITIES_COUNT).zip(q.get_many(entities_array).unwrap()) {
for (i, w) in (0..ENTITIES_COUNT).zip(q.many(entities_array).unwrap()) {
assert_eq!(i, w.0);
}

Expand All @@ -426,7 +426,7 @@ mod tests {
let entities_array: [Entity; ENTITIES_COUNT] =
entities_array.0.clone().try_into().unwrap();

for (i, w) in (0..ENTITIES_COUNT).zip(q.get_many_mut(entities_array).unwrap()) {
for (i, w) in (0..ENTITIES_COUNT).zip(q.many_mut(entities_array).unwrap()) {
assert_eq!(i, w.0);
}

Expand Down
Loading
Loading