summaryrefslogtreecommitdiff
path: root/src/mango/src/mango_idx_nouveau.erl
blob: a6e297e3d4024c6483ef1266168b41b2712d5e7a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
% Licensed under the Apache License, Version 2.0 (the "License"); you may not
% use this file except in compliance with the License. You may obtain a copy of
% the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
% License for the specific language governing permissions and limitations under
% the License.

-module(mango_idx_nouveau).

-export([
    validate_new/2,
    validate_fields/1,
    validate_index_def/1,
    add/2,
    remove/2,
    from_ddoc/1,
    to_json/1,
    columns/1,
    is_usable/3,
    get_default_field_options/1
]).

-include_lib("couch/include/couch_db.hrl").
-include("mango.hrl").
-include("mango_idx.hrl").

validate_new(#idx{} = Idx, Db) ->
    {ok, Def} = do_validate(Idx#idx.def),
    maybe_reject_index_all_req(Def, Db),
    {ok, Idx#idx{def = Def}}.

validate_index_def(IndexInfo) ->
    do_validate(IndexInfo).

add(#doc{body = {Props0}} = DDoc, Idx) ->
    Texts1 =
        case proplists:get_value(<<"nouveau">>, Props0) of
            {Texts0} -> Texts0;
            _ -> []
        end,
    NewText = make_text(Idx),
    Texts2 = lists:keystore(element(1, NewText), 1, Texts1, NewText),
    Props1 = lists:keystore(<<"nouveau">>, 1, Props0, {<<"nouveau">>, {Texts2}}),
    {ok, DDoc#doc{body = {Props1}}}.

remove(#doc{body = {Props0}} = DDoc, Idx) ->
    Texts1 =
        case proplists:get_value(<<"nouveau">>, Props0) of
            {Texts0} ->
                Texts0;
            _ ->
                ?MANGO_ERROR({index_not_found, Idx#idx.name})
        end,
    Texts2 = lists:keydelete(Idx#idx.name, 1, Texts1),
    if
        Texts2 /= Texts1 -> ok;
        true -> ?MANGO_ERROR({index_not_found, Idx#idx.name})
    end,
    Props1 =
        case Texts2 of
            [] ->
                lists:keydelete(<<"nouveau">>, 1, Props0);
            _ ->
                lists:keystore(<<"nouveau">>, 1, Props0, {<<"nouveau">>, {Texts2}})
        end,
    {ok, DDoc#doc{body = {Props1}}}.

from_ddoc({Props}) ->
    case lists:keyfind(<<"nouveau">>, 1, Props) of
        {<<"nouveau">>, {Texts}} when is_list(Texts) ->
            lists:flatmap(
                fun({Name, {VProps}}) ->
                    case validate_ddoc(VProps) of
                        invalid_ddoc ->
                            [];
                        Def ->
                            I = #idx{
                                type = <<"nouveau">>,
                                name = Name,
                                def = Def
                            },
                            [I]
                    end
                end,
                Texts
            );
        _ ->
            []
    end.

to_json(Idx) ->
    {[
        {ddoc, Idx#idx.ddoc},
        {name, Idx#idx.name},
        {type, Idx#idx.type},
        {partitioned, Idx#idx.partitioned},
        {def, {def_to_json(Idx#idx.def)}}
    ]}.

columns(Idx) ->
    {Props} = Idx#idx.def,
    {<<"fields">>, Fields} = lists:keyfind(<<"fields">>, 1, Props),
    case Fields of
        <<"all_fields">> ->
            all_fields;
        _ ->
            {DFProps} = couch_util:get_value(<<"default_field">>, Props, {[]}),
            Enabled = couch_util:get_value(<<"enabled">>, DFProps, true),
            Default =
                case Enabled of
                    true -> [<<"$default">>];
                    false -> []
                end,
            Default ++
                lists:map(
                    fun({FProps}) ->
                        {_, Name} = lists:keyfind(<<"name">>, 1, FProps),
                        {_, Type} = lists:keyfind(<<"type">>, 1, FProps),
                        iolist_to_binary([Name, ":", Type])
                    end,
                    Fields
                )
    end.

is_usable(_, Selector, _) when Selector =:= {[]} ->
    false;
is_usable(Idx, Selector, _) ->
    case columns(Idx) of
        all_fields ->
            true;
        Cols ->
            Fields = indexable_fields(Selector),
            sets:is_subset(sets:from_list(Fields), sets:from_list(Cols))
    end.

do_validate({Props}) ->
    {ok, Opts} = mango_opts:validate(Props, opts()),
    {ok, {Opts}};
do_validate(Else) ->
    ?MANGO_ERROR({invalid_index_text, Else}).

def_to_json({Props}) ->
    def_to_json(Props);
def_to_json([]) ->
    [];
def_to_json([{<<"fields">>, <<"all_fields">>} | Rest]) ->
    [{<<"fields">>, []} | def_to_json(Rest)];
def_to_json([{fields, Fields} | Rest]) ->
    [{<<"fields">>, fields_to_json(Fields)} | def_to_json(Rest)];
def_to_json([{<<"fields">>, Fields} | Rest]) ->
    [{<<"fields">>, fields_to_json(Fields)} | def_to_json(Rest)];
% Don't include partial_filter_selector in the json conversion
% if its the default value
def_to_json([{<<"partial_filter_selector">>, {[]}} | Rest]) ->
    def_to_json(Rest);
def_to_json([{Key, Value} | Rest]) ->
    [{Key, Value} | def_to_json(Rest)].

fields_to_json([]) ->
    [];
fields_to_json([{[{<<"name">>, Name}, {<<"type">>, Type0}]} | Rest]) ->
    ok = validate_field_name(Name),
    Type = validate_field_type(Type0),
    [{[{Name, Type}]} | fields_to_json(Rest)];
fields_to_json([{[{<<"type">>, Type0}, {<<"name">>, Name}]} | Rest]) ->
    ok = validate_field_name(Name),
    Type = validate_field_type(Type0),
    [{[{Name, Type}]} | fields_to_json(Rest)].

%% In the future, we can possibly add more restrictive validation.
%% For now, let's make sure the field name is not blank.
validate_field_name(<<"">>) ->
    throw(invalid_field_name);
validate_field_name(Else) when is_binary(Else) ->
    ok;
validate_field_name(_) ->
    throw(invalid_field_name).

validate_field_type(<<"string">>) ->
    <<"string">>;
validate_field_type(<<"text">>) ->
    <<"text">>;
validate_field_type(<<"number">>) ->
    <<"number">>;
validate_field_type(<<"boolean">>) ->
    <<"boolean">>.

validate_fields(<<"all_fields">>) ->
    {ok, all_fields};
validate_fields(Fields) ->
    try fields_to_json(Fields) of
        _ ->
            mango_fields:new(Fields)
    catch
        error:function_clause ->
            ?MANGO_ERROR({invalid_index_fields_definition, Fields});
        throw:invalid_field_name ->
            ?MANGO_ERROR({invalid_index_fields_definition, Fields})
    end.

validate_ddoc(VProps) ->
    try
        Def = proplists:get_value(<<"index">>, VProps),
        validate_index_def(Def),
        Def
    catch
        Error:Reason ->
            couch_log:error(
                "Invalid Index Def ~p: Error. ~p, Reason: ~p",
                [VProps, Error, Reason]
            ),
            invalid_ddoc
    end.

opts() ->
    [
        {<<"default_analyzer">>, [
            {tag, default_analyzer},
            {optional, true},
            {default, <<"keyword">>}
        ]},
        {<<"default_field">>, [
            {tag, default_field},
            {optional, true},
            {default, {[]}}
        ]},
        {<<"partial_filter_selector">>, [
            {tag, partial_filter_selector},
            {optional, true},
            {default, {[]}},
            {validator, fun mango_opts:validate_selector/1}
        ]},
        {<<"selector">>, [
            {tag, selector},
            {optional, true},
            {default, {[]}},
            {validator, fun mango_opts:validate_selector/1}
        ]},
        {<<"fields">>, [
            {tag, fields},
            {optional, true},
            {default, []},
            {validator, fun ?MODULE:validate_fields/1}
        ]},
        {<<"index_array_lengths">>, [
            {tag, index_array_lengths},
            {optional, true},
            {default, true},
            {validator, fun mango_opts:is_boolean/1}
        ]}
    ].

make_text(Idx) ->
    Text =
        {[
            {<<"index">>, Idx#idx.def},
            {<<"analyzer">>, construct_analyzer(Idx#idx.def)}
        ]},
    {Idx#idx.name, Text}.

get_default_field_options(Props) ->
    Default = couch_util:get_value(default_field, Props, {[]}),
    case Default of
        Bool when is_boolean(Bool) ->
            {Bool, <<"standard">>};
        {[]} ->
            {true, <<"standard">>};
        {Opts} ->
            Enabled = couch_util:get_value(<<"enabled">>, Opts, true),
            Analyzer = couch_util:get_value(
                <<"analyzer">>,
                Opts,
                <<"standard">>
            ),
            {Enabled, Analyzer}
    end.

construct_analyzer({Props}) ->
    DefaultAnalyzer = couch_util:get_value(
        default_analyzer,
        Props,
        <<"keyword">>
    ),
    {DefaultField, DefaultFieldAnalyzer} = get_default_field_options(Props),
    DefaultAnalyzerDef =
        case DefaultField of
            true ->
                [{<<"$default">>, DefaultFieldAnalyzer}];
            _ ->
                []
        end,
    case DefaultAnalyzerDef of
        [] ->
            <<"keyword">>;
        _ ->
            {[
                {<<"name">>, <<"perfield">>},
                {<<"default">>, DefaultAnalyzer},
                {<<"fields">>, {DefaultAnalyzerDef}}
            ]}
    end.

indexable_fields(Selector) ->
    TupleTree = mango_selector_text:convert([], Selector),
    indexable_fields([], TupleTree).

indexable_fields(Fields, {op_and, Args}) when is_list(Args) ->
    lists:foldl(
        fun(Arg, Fields0) -> indexable_fields(Fields0, Arg) end,
        Fields,
        Args
    );
%% For queries that use array element access or $in operations, two
%% fields get generated by mango_selector_text:convert. At index
%% definition time, only one field gets defined. In this situation, we
%% remove the extra generated field so that the index can be used. For
%% all other situations, we include the fields as normal.
indexable_fields(
    Fields,
    {op_or, [
        {op_field, Field0},
        {op_field, {[Name | _], _}} = Field1
    ]}
) ->
    case lists:member(<<"[]">>, Name) of
        true ->
            indexable_fields(Fields, {op_field, Field0});
        false ->
            Fields1 = indexable_fields(Fields, {op_field, Field0}),
            indexable_fields(Fields1, Field1)
    end;
indexable_fields(Fields, {op_or, Args}) when is_list(Args) ->
    lists:foldl(
        fun(Arg, Fields0) -> indexable_fields(Fields0, Arg) end,
        Fields,
        Args
    );
indexable_fields(Fields, {op_not, {ExistsQuery, Arg}}) when is_tuple(Arg) ->
    Fields0 = indexable_fields(Fields, ExistsQuery),
    indexable_fields(Fields0, Arg);
% forces "$exists" : false to use _all_docs
indexable_fields(_, {op_not, {_, false}}) ->
    [];
indexable_fields(Fields, {op_insert, Arg}) when is_binary(Arg) ->
    Fields;
%% fieldname.[]:length is not a user defined field.
indexable_fields(Fields, {op_field, {[_, <<":length">>], _}}) ->
    Fields;
indexable_fields(Fields, {op_field, {Name, _}}) ->
    [iolist_to_binary(Name) | Fields];
%% In this particular case, the lucene index is doing a field_exists query
%% so it is looking at all sorts of combinations of field:* and field.*
%% We don't add the field because we cannot pre-determine what field will exist.
%% Hence we just return Fields and make it less restrictive.
indexable_fields(Fields, {op_fieldname, {_, _}}) ->
    Fields;
%% Similar idea to op_fieldname but with fieldname:null
indexable_fields(Fields, {op_null, {_, _}}) ->
    Fields;
indexable_fields(Fields, {op_default, _}) ->
    [<<"$default">> | Fields].

maybe_reject_index_all_req({Def}, Db) ->
    DbName = couch_db:name(Db),
    #user_ctx{name = User} = couch_db:get_user_ctx(Db),
    Fields = couch_util:get_value(fields, Def),
    case {Fields, forbid_index_all()} of
        {all_fields, "true"} ->
            ?MANGO_ERROR(index_all_disabled);
        {all_fields, "warn"} ->
            couch_log:warning(
                "User ~p is indexing all fields in db ~p",
                [User, DbName]
            );
        _ ->
            ok
    end.

forbid_index_all() ->
    config:get("mango", "index_all_disabled", "false").

-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").

setup_all() ->
    Ctx = test_util:start_couch(),
    meck:expect(
        couch_log,
        warning,
        2,
        fun(_, _) ->
            throw({test_error, logged_warning})
        end
    ),
    Ctx.

teardown_all(Ctx) ->
    meck:unload(),
    test_util:stop_couch(Ctx).

setup() ->
    %default index all def that generates {fields, all_fields}
    Index = #idx{def = {[]}},
    DbName = <<"testdb">>,
    UserCtx = #user_ctx{name = <<"u1">>},
    {ok, Db} = couch_db:clustered_db(DbName, UserCtx),
    {Index, Db}.

teardown(_) ->
    ok.

index_all_test_() ->
    {
        setup,
        fun setup_all/0,
        fun teardown_all/1,
        {
            foreach,
            fun setup/0,
            fun teardown/1,
            [
                fun forbid_index_all/1,
                fun default_and_false_index_all/1,
                fun warn_index_all/1
            ]
        }
    }.

forbid_index_all({Idx, Db}) ->
    ?_test(begin
        ok = config:set("mango", "index_all_disabled", "true", false),
        ?assertThrow(
            {mango_error, ?MODULE, index_all_disabled},
            validate_new(Idx, Db)
        )
    end).

default_and_false_index_all({Idx, Db}) ->
    ?_test(begin
        config:delete("mango", "index_all_disabled", false),
        {ok, #idx{def = {Def}}} = validate_new(Idx, Db),
        Fields = couch_util:get_value(fields, Def),
        ?assertEqual(all_fields, Fields),
        ok = config:set("mango", "index_all_disabled", "false", false),
        {ok, #idx{def = {Def2}}} = validate_new(Idx, Db),
        Fields2 = couch_util:get_value(fields, Def2),
        ?assertEqual(all_fields, Fields2)
    end).

warn_index_all({Idx, Db}) ->
    ?_test(begin
        ok = config:set("mango", "index_all_disabled", "warn", false),
        ?assertThrow({test_error, logged_warning}, validate_new(Idx, Db))
    end).

-endif.