반응형

 

#Firebase 를 대처할만한 편리하고 저렴하게 사용할 수 있는 backend solution인 supabase 소개는 따로.!

 

Supabase에서 Database를 생성하고 나서, database 를 사용하는 방법은 다음과 같습니다.

 

supabase guide 를 보면 쉽게 따라하실수 있습니다.

https://supabase.com/docs/reference/dart/upgrade-guide?queryGroups=version&version=2.0x

 

Flutter: Upgrade guide | Supabase Docs

Initialization does not await for session refresh In v1, Supabase.initialize() would await for the session to be refreshed before returning. This caused delays in the app's launch time, especially when the app is opened in a poor network environment. In v2

supabase.com

 

 

 

지금 하고 싶은 이야기는 이미 supabase를 사용하고 계시는 분들에게 유용한 기능인데요.

 

# database 컬럼으로 json 활용

database를 만들어 사용하다 보면, 데이터중에  json 으로 데이터를 넣어야 하는 경우가 있습니다.

 

 

그런데, json 으로 데이터 컬럼을 추가 할경우, 쿼리 할때 데이터를 가져온다음에 name 이나 type을 비교해야 하는 상당히 불편한 부분이 생깁니다.

다행히도 supabase의 eq() 함수는 json data 내부의 필드값을 접근 할 수 있는 기능을 제공합니다.

https://supabase.com/docs/reference/dart/using-filters

final data = await supabase
  .from('test')
  .select()
  .eq('data->type', 'hello');

 

 

 

# eq 의 -> 가 에러가 발생

그런데 안타깝게도 아래와 같은 에러가 발생 할 수 있습니다.

 

PostgrestException(message: invalid input syntax for type json, code: 22P02, details: The input string ended unexpectedly., hint: null)

 

 

아 !,  -> 기능으로 json 내부 접근해서 쿼리 할수 있을 줄 알았는데 동작을 안하네??? 이러고 좌절 하실수 있는데요.

걱정하지 마세요 !

 

제가 찾아본 자료에서는 json 내부에 접근하는 접근자  몇가지 있는데요.

가이드에 나와있는 접근자로는 오류가 발생하고 다른 접근자를 사용하면 됩니다.

가이드에 적힌 '->' json형태의 값을 넘기는 것이고, '->>'를 사용하면 text 값을 정상적으로 처리할 수 있습니다.

 

final data = await supabase
  .from('test')
  .select()
  .eq('data->>type', 'hello');

 

이렇게 사용하면 정상적으로 eq 가 동작합니다.

 

 

#json, jsonb 의 차이 및 접근자에 대해서 더 알고 싶다면

 

OperatorRight Operand TypeDescriptionExampleExample Result

-> int Get JSON array element (indexed from zero, negative integers count from the end) '[{"a":"foo"},{"b":"bar"},{"c":"baz"}]'::json->2 {"c":"baz"}
-> text Get JSON object field by key '{"a": {"b":"foo"}}'::json->'a' {"b":"foo"}
->> int Get JSON array element as text '[1,2,3]'::json->>2 3
->> text Get JSON object field as text '{"a":1,"b":2}'::json->>'b' 2
#> text[] Get JSON object at specified path '{"a": {"b":{"c": "foo"}}}'::json#>'{a,b}' {"c": "foo"}
#>> text[] Get JSON object at specified path as text '{"a":[1,2,3],"b":[4,5,6]}'::json#>>'{a,2}' 3

https://www.postgresql.org/docs/9.5/functions-json.html

 

 

[참고]

https://yeongunheo.tistory.com/entry/PostgreSQL-json-jsonb-%ED%83%80%EC%9E%85%EA%B3%BC-%EC%97%B0%EC%82%B0%EC%9E%90

 

[PostgreSQL] json, jsonb 타입과 연산자

데이터베이스 테이블 내 하나의 컬럼에 JSON 데이터를 저장하는 경우가 있습니다. 보통 외부에서 제공된 데이터를 별도의 처리 없이 그대로 저장할 때 JSON 타입으로 저장하게 됩니다. PostgreSQL은 J

yeongunheo.tistory.com

 

 

#해피코딩

+ Recent posts