drift icon indicating copy to clipboard operation
drift copied to clipboard

How to query a list inside a json

Open manojbcs98 opened this issue 5 years ago • 3 comments

int varietyId; "data": { "varieties": [ 4, 5 ], }

Here i need to query all the entries where varietyId is present inside the "varieties" list. How can this be done?

manojbcs98 avatar Feb 25 '20 09:02 manojbcs98

The best way to use this would be a query in a moor file. You'll also need to enable the json1 extension in your builder options.

You could do something like

import 'path/to/your/table/classes.dart';

findWithVariety(:variety AS INT): SELECT table.* 
  FROM table, json_each(json_extract(table.json_column, '$.data.varieties')) varieties
WHERE :variety IN varieties

Moor will then generate a Selectable<DataClass> findWithVariety(int variety) method which you can get() or watch().

Note that json1 is only available when using moor_ffi.

simolus3 avatar Feb 25 '20 10:02 simolus3

Instead of querying in Moor file cant be done in DAO file? If it can be done in DAO file how it would be?

manojbcs98 avatar Feb 25 '20 11:02 manojbcs98

At the moment this can't be done in Dart. json_extract essentially returns a new table, which is not supported by the Dart api at the moment. Supporting table-valued functions in Dart would probably be a large and complicated change.

simolus3 avatar Feb 25 '20 11:02 simolus3

Is it possible to have the generated classes return the list for the type?

Since varieties is a List<String> how would the table look with json_extract in a drift file?

rodydavis avatar Jan 11 '24 23:01 rodydavis

I should mention that json_each is now available in the Dart query builder as well, so the issue should be addressed with that. The last example in this section is using JSON joins as a filter.

Is it possible to have the generated classes return the list for the type?

Do you mean when something based on json_each or json_extract is used as a result column in a query? If you can write a type converter for the inner field, you can apply it to the result column with MAPPED BY, like shown here for example.

simolus3 avatar Jan 13 '24 10:01 simolus3

Yep that's what I ended up doing (MAPPED BY) and worked well 👍🏼

rodydavis avatar Jan 13 '24 11:01 rodydavis