SeaQL / sea-orm

🐚 An async & dynamic ORM for Rust
https://www.sea-ql.org/SeaORM/
Apache License 2.0
7.3k stars 513 forks source link

Failing find_with_related with column_name attribute #693

Closed bleuse closed 2 years ago

bleuse commented 2 years ago

Description

Defining a has_many relationship when the primary key is a column with a column_name breaks .find_with_related.

Steps to Reproduce

See MWE repository.

Expected Behavior

When I run the query, I expect to retrieve the elements from the database.

Actual Behavior

The query fails with the following message:

Error: Query Error: error returned from database: 1054 (42S22): Unknown column 'container.rust_id' in 'order clause'

Reproduces How Often

It reproduces every-time.

Versions

I am working with MySQL on a debian (not sure if it is relevant for this bug):

$ mysql --version
mysql  Ver 8.0.23-3+b1 for Linux on x86_64 ((Debian))
$ cargo tree | grep sea-                             
sea-orm-column-name-bug v0.1.0 (/home/bleuse/tmpfiles/work/sea-orm-column-name-bug)
├── sea-orm v0.7.1
│   ├── sea-orm-macros v0.7.0 (proc-macro)
│   ├── sea-query v0.23.0
│   │   ├── sea-query-derive v0.2.0 (proc-macro)
│   ├── sea-strum v0.23.0
│   │   └── sea-strum_macros v0.23.0 (proc-macro)

Additional Information

The query generated to handle a .find_with_related call does not respect the column_name attribute set in the Model struct: it uses the name derived from the struct field name.

The generated query is the following:

SELECT
  `container`.`db_id` AS `A_db_id`,
  `content`.`id` AS `B_id`,
  `content`.`container_id` AS `B_container_id`
FROM
  `container`
LEFT JOIN
  `content` ON `container`.`db_id` = `content`.`container_id`
ORDER BY
  `container`.`rust_id` ASC

The ORDER BY clause is wrongly generated as we should not get rust_id but db_id. The rest of the query is correctly generated.

See https://github.com/bleuse/sea-orm-column-name-bug for a MWE.

billy1624 commented 2 years ago

Hey @bleuse, thanks for catching this! I'm working on a patch for this