Skip to content

DeepPartial in find() does not find nested relation clauses #1847

Closed

Description

@Slessi

Type

[x] mysql
[x] bug report
[x] 0.1.16, 0.2.0-alpha.13 and 0.2.0-alpha.46

Description

If you specify a clause for a property on a relation, that clause gets ignored and ORM instead adds a where clause on the join column against NULL

Reproducing

Simply edit the connection details in the below code to point to an empty mysql database and run it in an environment with TypeORM available. I used ts-node to run if that makes any difference.

/* tslint:disable */
import { BaseEntity, Connection, createConnection, Entity, PrimaryGeneratedColumn, ManyToOne, OneToMany, Column } from "typeorm";

@Entity("threads")
class Thread extends BaseEntity {
    @PrimaryGeneratedColumn()
    public id: number;

    @Column("varchar")
    public name: string;

    @OneToMany((type) => Post, (comments) => comments.thread)
    public posts: Post[];
}

@Entity("posts")
class Post extends BaseEntity {
    @PrimaryGeneratedColumn()
    public id: number;

    @ManyToOne((type) => Thread, (thread) => thread.posts)
    public thread: Thread;
}

(async () => {
    let dbConn: Connection;

    try {
        dbConn = await createConnection({
            type: "mysql",
            host: "127.0.0.1",
            port: 3306,

            database: "database",
            password: "123",
            username: "root",

            synchronize: true,
            logging: true,
            entities: [Thread, Post],
        });

        const threadName = "Mega Thread";

        const thread = await Thread.create({ name: threadName }).save();
        const comment = await Post.create({ thread }).save();

        const test = await Post.find({
            relations: ["thread"],
            where: {
                thread: {
                    name: threadName,
                },
            },
        });

        console.log(test);
    } catch (error) {
        console.error(error.message);
    } finally {
        if (dbConn) {
            dbConn.close();
        }
    }
})();

The above gives me the following SQL with logging enabled:

SELECT
    `Post`.`id` AS `Post_id`,
    `Post`.`threadId` AS `Post_threadId`,
    `Post_thread`.`id` AS `Post_thread_id`,
    `Post_thread`.`name` AS `Post_thread_name`

FROM `posts` `Post`

LEFT JOIN `threads` `Post_thread` ON `Post_thread`.`id`=`Post`.`threadId`

WHERE `Post`.`threadId` = ? -- PARAMETERS: [null]

I expected to see this however:

SELECT
    `Post`.`id` AS `Post_id`,
    `Post`.`threadId` AS `Post_threadId`,
    `Post_thread`.`id` AS `Post_thread_id`,
    `Post_thread`.`name` AS `Post_thread_name`

FROM `posts` `Post`

LEFT JOIN `threads` `Post_thread` ON `Post_thread`.`id`=`Post`.`threadId`

- WHERE `Post`.`threadId` = ? -- PARAMETERS: [null]
+ WHERE `Post_thread`.`name` = ? -- PARAMETERS: ["Mega Thread"]

Activity

  1. pleerock commented on Mar 28, 2018

    @pleerock
    Member

    can you try it in @next? npm i typeorm@next

  2. Slessi commented on Mar 29, 2018

    @Slessi
    ContributorAuthor

    With 0.2.0-alpha.13

    query: START TRANSACTION
    query: INSERT INTO `threads`(`name`) VALUES (?) -- PARAMETERS: ["Mega Thread"]
    query: COMMIT
    query: START TRANSACTION
    query: INSERT INTO `posts`(`threadId`) VALUES (?) -- PARAMETERS: [5]
    query: COMMIT
    query: SELECT `Post`.`id` AS `Post_id`, `Post`.`threadId` AS `Post_threadId`, `Post_thread`.`id` AS `Post_thread_id`, `Post_thread`.`name` AS `Post_thread_name` FROM `posts` `Post` LEFT JOIN `threads` `Post_thread` ON `Post_thread`.`id`=`Post`.`threadId` WHERE `Post`.`threadId` = ? -- PARAMETERS: [null]
    []

    Still attempts

    WHERE `Post`.`threadId` = ? -- PARAMETERS: [null]
    

    It is easily reproduced if you wish, just need to run the code I attached to OP with a connection to any existing mysql DB

  3. pleerock commented on Apr 17, 2018

    @pleerock
    Member

    alpha.13 is very old, please check it on latest alpha.

  4. Slessi commented on Apr 17, 2018

    @Slessi
    ContributorAuthor

    Used typeorm@next again which gives (at time of posting) 0.2.0-alpha.46 and the problem still persists.

    Problem occurs on 0.1.16, 0.2.0-alpha.13 and 0.2.0-alpha.46.

    I see that alpha.13 is now old but I lasted updated 19 days ago at which time it was the latest.

  5. pleerock commented on Apr 17, 2018

    @pleerock
    Member

    nope, it wasn't latest. alpha 13 is kinda 5 months old.

    I see your issue now, you cannot request by non-primary column your relation via find-options. You need to use query builder instead.

  6. Slessi commented on Apr 17, 2018

    @Slessi
    ContributorAuthor

    Can we call it a feature request then? :p

  7. added this to the 0.3.0 milestone on Apr 17, 2018
  8. pleerock commented on Apr 17, 2018

    @pleerock
    Member

    I'll put it on the milestone and will think how we can implement it

  9. gado704555 commented on May 8, 2018

    @gado704555

    I have some question , Is possible to order by relations column like this ?

    const test = await Post.find({ relations: ["thread"], order: { thread: { name: 'DESC' } } });

  10. owengombas commented on Oct 19, 2018

    @owengombas

    I have the same issue, is it implemented in the branch @next ? @pleerock

  11. owengombas commented on Oct 19, 2018

    @owengombas

    So I've made a parser to make nested relations with where conditions
    the first composeQuery argument is the Model (it extends BaseEntity and it's decorated with @entity()) the second parameter is an object the where rules

    import PageModel from './PageModel'
    import RelationModel from './RelationModel'
    import { composeQuery } from './orm-graphql-helpers'
    
    class PageController {
      static getPages({ Id, Title, RelationObj }) {
        return composeQuery(PageModel, {
          Id,
          Title,
          RelationObj: {
            relation: RelationModel.name,
            value: RelationObj
          }
        }).getMany()
      }
    }
    
    // You get all elements that verified all of these conditions
    PageController.getPages({
      Id: 1,
      Title: 'my title', 
      RelationObj: {
        Id: 10,
        MyProperty: 'Hello'
      }
    }).then(...)
    import { BaseEntity } from 'typeorm'
    
    const queryModelName = 'model'
    
    function getQueryFieldName(fieldName: string, mainField: string = null) {
      return `${mainField || queryModelName}.${fieldName}`
    }
    
    function getConditionString (mainField: string, subField: string) {
      return `${getQueryFieldName(subField, mainField)} = :${subField}`
    }
    
    /**
     * Parse the GraphQL query params and execute it with TypeORM
     * @param model The model on which we execute the requets
     * @param obj The where query conditions
     */
    export function composeQuery(model: typeof BaseEntity, obj: Object) {
      const queryBuilder = model.createQueryBuilder(queryModelName)
      const parseObjToQuery = (obj, mainField = queryModelName) => {
        Object.getOwnPropertyNames(obj).map((prop: string) => {
          const value = obj[prop]
    
          // If the object is a relation
          if (value.relation) {
            queryBuilder.innerJoinAndSelect(getQueryFieldName(value.relation), value.relation)
            parseObjToQuery(value.value, value.relation)
          } else {
            // Add the where condition to the query
            const whereCondition = getConditionString(mainField, prop)
            const whereValueToReplace = { [prop]: value }
    
            if (queryBuilder.expressionMap.wheres.length > 0) {
              queryBuilder.andWhere(whereCondition, whereValueToReplace)
            } else {
              queryBuilder.where(whereCondition, whereValueToReplace)
            }
          }
        })
      }
      parseObjToQuery(obj)
      return queryBuilder
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions