Search code examples
swiftcouchbasecouchbase-litesql++

Can I create Where clause in Couchbase Lite swift on runtime from array of conditions?


I am using Couchbase Lite 2.6, I want to build my query on runtime, I am receiving a list of conditions(["Key":"value"]) via an API using which I need to filter my local database and display the values.

Is there any way I can do that using QueryBuilder?

I found a similar discussion on Couchbase forum but it's quite old so the solution is not valid anymore.

https://forums.couchbase.com/t/filter-on-array-filed-in-couchbase-and-couchbase-lite/3983/4


Solution

  • Let me give you an example for android and you can extrapolate that to swift:

        String name = "foo";
        String surname = "bar";
        Expression ex = Expression.property("type").equalTo(Expression.string("user"));
        if(name != null) {
            ex.and(Expression.property("name").equalTo(Expression.string(name)));
        }
    
        if(surname != null) {
            ex.and(Expression.property("surname").equalTo(Expression.string(surname)));
        }
    
        Query query = QueryBuilder
                .select(SelectResult.all())
                .from(DataSource.database(DatabaseManager.getDatabase()))
                .where(ex)
                .limit(Expression.intValue(10));