pgmock2에서 "where ... in ..." 조건에 대한 mock 데이터 생성

2022. 6. 20. 16:57서버 프로그래밍

pgmock2를 이용하여 테스트를 작성하려면 다음과 같이 mock 데이터를 등록할 수 있다.

client.add('SELECT * FROM employees where id=$1', ['number'], {
    rowCount: 1,
    rows: [
        { id: 1, name: 'John Smith', position: 'application developer' }
    ]
});

그런데, SELECT * FROM employees where id in (1,2,3) 과 같은 쿼리의 mock 데이터를 등록할 때가 애매해서 찾아보니, 이런 경우에는 SELECT * FROM employees where id = any('{1,2,3}') 이라는 쿼리를 사용하면 쉽게 해결이 된다.

In short: in() needs a list of scalars, while any() needs an array expression.

Per the documentation:

expression IN (value [, ...])

The right-hand side is a parenthesized list of scalar expressions.

Example:

where integerid in (1, 2, 5)

expression operator ANY (array expression)

The right-hand side is a parenthesized expression, which must yield an array value.

Example:

where integerid = any ('{1, 2, 5}');

Because

skill_id_array in Postgres looks like this: {1,2,5}

https://stackoverflow.com/questions/50802927/postgresql-in-error-operator-does-not-exist-integer-integer

 

Postgresql IN error: operator does not exist integer = integer[]

This WHERE ANY query in Nestjs / Express works fine: const sql = 'SELECT * FROM members WHERE '+ integerId + ' = ANY(skill_id_array)'; const membersBySkill = await this.entityManager.query(sql );...

stackoverflow.com

 

따라서 다음과 같이 mock 데이터를 추가하면 된다

client.add('SELECT * FROM employees where id=any($1)', ['string'], {
    rowCount: 1,
    rows: [
        { id: 1, name: 'John Smith', position: 'application developer' }
    ]
});