개발

supabase - select 조건에 and, or 여러개 사용하기

jwonelife 2024. 7. 28. 15:13

 

firebase 의 대안이라고 소개되고 있는 supabase 를 사용해보고 있다.

supabase 에 대해 설치 부터 자세하게 설명을 해주는 좋은 블로그 글들이 많으니 해당 글들을 참고해 가면서 하나씩 써보고 있다.

 

아직은 코어하게 쓰는 단계는 아니고 사이드 프로젝트에 사용이 가능할지 테스트 하는 정도로만 써보고 있는데,

아래 select where 조건을 거는데에도 방법을 찾는데 시간이 꽤 걸려서 포스팅한다.

-- 해결해야 하는 조건은 SQL 로 표현하면 이런식이다.
WHERE ((start is NULL OR start <= 21) AND (end is NULL OR end >= 21))
	OR ((start is NULL OR start <= 28) AND (end is NULL OR end >= 28))

 

 

supabase 문서는 잘 되어있는 편이다. 아래 select 방법에 대해서도 몇가지 예가 많이 나와있는데,

💡 Using filters: https://supabase.com/docs/reference/javascript/using-filters

 

몇가지 코드를 javascript 와 SQL 로 설명하면 아래와 같다.

const { data, error } = await supabase
  .from('countries')
  .select()
  .eq('name', 'Albania'); // eq 는 equals
-- 위 구분의 조건은 SQL 로는 다음과 같다.
WHERE name = 'Albania'

 

 

const { data, error } = await supabase
  .from('countries')
  .select()
  .ilike('name', '%alba%'); // ilike 는 대소문자를 무시(ignore)하는 매칭
-- 위 구분의 조건은 SQL 로는 다음과 같다.
WHERE LOWER(name) LIKE '%alba%'

 

 

const { data, error } = await supabase
  .from('countries')
  .select('name')
  .or('id.eq.2,name.eq.Algeria'); // OR 는 다음과 같이 "," 로 구분한다.
-- 위 구분의 조건은 SQL 로는 다음과 같다.
WHERE id = 2 OR name = 'Algeria'

 

 

이런식이다.

보통의 ORM, QueryDSL 관련 코드를 사용해 보았다면 어색하지는 않은 구문이긴 한데..

내가 해결하고 싶은 SQL 조건은 아래와 같았고,

WHERE ((start is NULL OR start <= 21) AND (end is NULL OR end >= 21))
	OR ((start is NULL OR start <= 28) AND (end is NULL OR end >= 28))

 

이걸 supabase 로는 아래와 같이 작성해야 했다.

const start = 21;
const end = 28;
const { data, error } = await supabase
      .from('test1')
      .select()
      .or(
        [
          `and( or(start.is.null, start.lte.${start}), or(end.is.null, end.gte.${start}) )`,
          `and( or(start.is.null, start.lte.${end}), or(end.is.null, end.gte.${end}) )`,
        ].join(',') // 너무 길어서 배열.join 으로 했다
      );
// 한줄로 쓰면 이렇게..
const q = `and( or(start.is.null, start.lte.${start}), or(end.is.null, end.gte.${start}) ), and( or(start.is.null, start.lte.${end}), or(end.is.null, end.gte.${end}) )`
// 좀 더 풀어보면 이런식이 된다.

// javascript
`and( or( $OR1, $OR2 ), or( $OR3, $OR4 ) )`,
`and( or( $OR5, $OR6 ), or( $OR7, $OR8 ) )`

// SQL
WHERE (( $OR1 OR $OR2 ) AND ( $OR3 OR $OR4 ))
	OR (( $OR5 OR $OR6) AND ( $OR7 OR $OR8 ))

 

원하는 조건으로 해결이 되긴 했는데, 하면서도 OR 야? AND 야? 많이 헷갈렸다.. 😆

 

 

rpc 라는것도 있으니 그걸 참고해보는게 좋겠다.

💡 Call a Postgres function : https://supabase.com/docs/reference/javascript/rpc