Skip to content

Union does not put the first query in parenthesis #879

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

Open
MikeOnTea opened this issue Apr 11, 2025 · 0 comments
Open

Union does not put the first query in parenthesis #879

MikeOnTea opened this issue Apr 11, 2025 · 0 comments

Comments

@MikeOnTea
Copy link

MikeOnTea commented Apr 11, 2025

This leads to a wrong query (with the postgresql backend at least), when the first query of the union contains order by and/or limit statements:

let mut q1 = rentals::Entity::find()
			.filter(rentals::Column::FlatId.eq(flat_id.raw()).and(rentals::Column::From.lt(date)))
			.order_by_desc(rentals::Column::From)
			.limit(1);
		let mut q2 = rentals::Entity::find()
			.filter(rentals::Column::FlatId.eq(flat_id.raw()).and(rentals::Column::From.gte(date)))
			.order_by_asc(rentals::Column::From)
			.limit(1);

		let query = QuerySelect::query(&mut q1).union(UnionType::Distinct, QuerySelect::query(&mut q2).to_owned());
		let statement = self.db.get_database_backend().build(query);
		let mut rentals = to_model(rentals::Entity::find().from_raw_sql(statement).all(&self.db).await

The resulting query is:

SELECT "rentals"."id", "rentals"."flat_id", "rentals"."lodger_id", "rentals"."from", "rentals"."until" FROM "rentals" WHERE "rentals"."flat_id" = 'd7851e76-ef23-441d-8b78-e0059f22a502' AND "rentals"."from" < '2025-04-11'
UNION
(SELECT "rentals"."id", "rentals"."flat_id", "rentals"."lodger_id", "rentals"."from", "rentals"."until" FROM "rentals" WHERE "rentals"."flat_id" = 'd7851e76-ef23-441d-8b78-e0059f22a502' AND "rentals"."from" >= '2025-04-11' ORDER BY "rentals"."from" ASC LIMIT 1)
ORDER BY "rentals"."from" DESC LIMIT 1

So the order and limit gets applyed to the unioned result instead of the first union part.

Expected Behavior

The order and limit should be applied to the relevant union parts

Actual Behavior

The order/limit of the first union part gets applied to the result instead

Versions

│   │   ├── sea-orm v1.1.7
│   │   │   ├── sea-orm-macros v1.1.7 (proc-macro)
│   │   │   │   ├── sea-bae v0.2.1 (proc-macro)
│   │   │   ├── sea-query v0.32.3
│   │   │   ├── sea-query-binder v0.7.0
│   │   │   │   ├── sea-query v0.32.3 (*)
│   │   ├── sea-orm v1.1.7 (*)
├── sea-orm v1.1.7 (*)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant