summaryrefslogtreecommitdiff
path: root/src/mongo/db/query/optimizer/bool_expression.h
blob: 26328efd6ea36a1a5a20b1fba1337fed21e2a6ed (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
/**
 *    Copyright (C) 2022-present MongoDB, Inc.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the Server Side Public License, version 1,
 *    as published by MongoDB, Inc.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    Server Side Public License for more details.
 *
 *    You should have received a copy of the Server Side Public License
 *    along with this program. If not, see
 *    <http://www.mongodb.com/licensing/server-side-public-license>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the Server Side Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */


#pragma once

#include "boost/optional.hpp"
#include <vector>

#include "mongo/db/query/optimizer/algebra/operator.h"
#include "mongo/db/query/optimizer/algebra/polyvalue.h"
#include "mongo/util/assert_util.h"

namespace mongo::optimizer {

template <class T>
struct NoOpNegator {
    T operator()(const T v) const {
        return v;
    }
};

/**
 * Represents a generic boolean expression with arbitrarily nested conjunctions and disjunction
 * elements.
 */
template <class T>
struct BoolExpr {
    class Atom;
    class Conjunction;
    class Disjunction;

    using Node = algebra::PolyValue<Atom, Conjunction, Disjunction>;
    using NodeVector = std::vector<Node>;


    class Atom final : public algebra::OpFixedArity<Node, 0> {
        using Base = algebra::OpFixedArity<Node, 0>;

    public:
        Atom(T expr) : Base(), _expr(std::move(expr)) {}

        bool operator==(const Atom& other) const {
            return _expr == other._expr;
        }

        const T& getExpr() const {
            return _expr;
        }
        T& getExpr() {
            return _expr;
        }

    private:
        T _expr;
    };

    class Conjunction final : public algebra::OpDynamicArity<Node, 0> {
        using Base = algebra::OpDynamicArity<Node, 0>;

    public:
        Conjunction(NodeVector children) : Base(std::move(children)) {
            uassert(6624351, "Must have at least one child", !Base::nodes().empty());
        }

        bool operator==(const Conjunction& other) const {
            return Base::nodes() == other.nodes();
        }
    };

    class Disjunction final : public algebra::OpDynamicArity<Node, 0> {
        using Base = algebra::OpDynamicArity<Node, 0>;

    public:
        Disjunction(NodeVector children) : Base(std::move(children)) {
            uassert(6624301, "Must have at least one child", !Base::nodes().empty());
        }

        bool operator==(const Disjunction& other) const {
            return Base::nodes() == other.nodes();
        }
    };


    /**
     * Utility functions.
     */
    template <typename T1, typename... Args>
    static auto make(Args&&... args) {
        return Node::template make<T1>(std::forward<Args>(args)...);
    }

    template <typename... Args>
    static auto makeSeq(Args&&... args) {
        NodeVector seq;
        (seq.emplace_back(std::forward<Args>(args)), ...);
        return seq;
    }

    template <typename... Args>
    static Node makeSingularDNF(Args&&... args) {
        return make<Disjunction>(
            makeSeq(make<Conjunction>(makeSeq(make<Atom>(T{std::forward<Args>(args)...})))));
    }

    static boost::optional<const T&> getSingularDNF(const Node& n) {
        if (auto disjunction = n.template cast<Disjunction>();
            disjunction != nullptr && disjunction->nodes().size() == 1) {
            if (auto conjunction = disjunction->nodes().front().template cast<Conjunction>();
                conjunction != nullptr && conjunction->nodes().size() == 1) {
                if (auto atom = conjunction->nodes().front().template cast<Atom>();
                    atom != nullptr) {
                    return {atom->getExpr()};
                }
            }
        }
        return {};
    }

    /**
     * Builder which is used to create BoolExpr trees. It supports negation, which is translated
     * internally to conjunction and disjunction via deMorgan elimination. The following template
     * parameters need to be supplied:
     *   1. Flag to enable empty or singular conjunction/disjunction simplifications. For example
     * or-ing 0 elements results in the default constructed value of T (T{}).
     *   2. Flag to allow removing of duplicate predicates. For example "x and x" is simplified to
     * just "x".
     *   3. Negation function. Used for deMorgan transformation. For example "not (x and y) is
     * simplified to neg(x) or neg(y).
     *
     *  Usage:
     *    1. use .pushConj() or .pushDisj() to begin a new conjunction / disjunction.
     *    2. use .atom() to add elements to the current conjunction / disjunction.
     *    3. use .pop() when done adding elements to the current conjunction / disjunction, and
     * implicitly move to adding elements to the parent.
     *    4. When we are done, call .finish(). Finish returns an empty result if no elements have
     * been added to the root level, and we do not simplify singular conjunction/disjunctions.
     */
    template <bool simplifyEmptyOrSingular = false,
              bool removeDups = false,
              class Negator = NoOpNegator<T>>
    class Builder {
        enum class NodeType { Conj, Disj };

        struct StackEntry {
            NodeType _type;
            bool _negated;
            NodeVector _vector;
        };

    public:
        Builder() : _result(), _stack(), _currentNegated(false) {}

        template <typename... Ts>
        Builder& atom(Ts&&... pack) {
            return atom(T{std::forward<Ts>(pack)...});
        }

        Builder& atom(T value) {
            if (isCurrentlyNegated()) {
                value = Negator{}(std::move(value));
            }
            _result = make<Atom>(std::move(value));
            maybeAddToParent();
            return *this;
        }

        Builder& push(const bool isConjunction) {
            const bool negated = isCurrentlyNegated();
            _stack.push_back({(negated == isConjunction) ? NodeType::Disj : NodeType::Conj,
                              negated,
                              NodeVector{}});
            return *this;
        }

        Builder& pushConj() {
            return push(true /*isConjunction*/);
        }

        Builder& pushDisj() {
            return push(false /*isConjunction*/);
        }

        Builder& negate() {
            _currentNegated = !_currentNegated;
            return *this;
        }

        Builder& pop() {
            auto [type, negated, v] = std::move(_stack.back());
            _stack.pop_back();

            if constexpr (simplifyEmptyOrSingular) {
                if (v.empty()) {
                    // Empty set of children: return either default constructed T{} or its negation.
                    _result = make<Atom>(type == NodeType::Conj ? Negator{}(T{}) : T{});
                } else if (v.size() == 1) {
                    // Eliminate singular conjunctions / disjunctions.
                    _result = std::move(v.front());
                } else {
                    createNode(type, std::move(v));
                }
            } else if (v.empty()) {
                _result = boost::none;
            } else {
                createNode(type, std::move(v));
            }

            maybeAddToParent();
            return *this;
        }

        boost::optional<Node> finish() {
            while (!_stack.empty()) {
                pop();
            }
            return std::move(_result);
        }

    private:
        void maybeAddToParent() {
            if (_stack.empty() || !_result) {
                return;
            }

            auto& parentVector = _stack.back()._vector;
            if (!removeDups ||
                std::find(parentVector.cbegin(), parentVector.cend(), *_result) ==
                    parentVector.cend()) {
                // Eliminate duplicate elements.
                parentVector.push_back(std::move(*_result));
            }
            _result = boost::none;
        }

        void createNode(const NodeType type, NodeVector v) {
            if (type == NodeType::Conj) {
                _result = make<Conjunction>(std::move(v));
            } else {
                _result = make<Disjunction>(std::move(v));
            }
        }

        bool isCurrentlyNegated() {
            const bool negated = (!_stack.empty() && _stack.back()._negated) ^ _currentNegated;
            _currentNegated = false;
            return negated;
        }

        boost::optional<Node> _result;
        std::vector<StackEntry> _stack;
        bool _currentNegated;
    };

    /**
     * Converts a BoolExpr to DNF. Assumes 'n' is in CNF. Returns boost::none if the resulting
     * formula would have more than 'maxClauses' clauses.
     */
    static boost::optional<Node> convertToDNF(const Node& n,
                                              boost::optional<size_t> maxClauses = boost::none) {
        tassert(7115100, "Expected Node to be a Conjunction", n.template is<Conjunction>());
        return convertTo<false /*toCNF*/>(n, maxClauses);
    }

    /**
     * Converts a BoolExpr to CNF. Assumes 'n' is in DNF. Returns boost::none if the resulting
     * formula would have more than 'maxClauses' clauses.
     */
    static boost::optional<Node> convertToCNF(const Node& n,
                                              boost::optional<size_t> maxClauses = boost::none) {
        tassert(7115101, "Expected Node to be a Disjunction", n.template is<Disjunction>());
        return convertTo<true /*toCNF*/>(n, maxClauses);
    }

private:
    template <bool toCNF,
              class TopLevel = std::conditional_t<toCNF, Conjunction, Disjunction>,
              class SecondLevel = std::conditional_t<toCNF, Disjunction, Conjunction>>
    static boost::optional<Node> convertTo(const Node& n, boost::optional<size_t> maxClauses) {
        std::vector<NodeVector> newChildren;
        newChildren.push_back({});

        // Process the children of 'n' in order. Suppose the input (in CNF) was (a+b).(c+d). After
        // the first child, we have [[a], [b]] in 'newChildren'. After the second child, we have
        // [[a, c], [b, c], [a, d], [b, d]].
        for (const auto& child : n.template cast<SecondLevel>()->nodes()) {
            auto childNode = child.template cast<TopLevel>();
            auto numGrandChildren = childNode->nodes().size();
            auto frontierSize = newChildren.size();

            if (maxClauses.has_value() && frontierSize * numGrandChildren > maxClauses) {
                return boost::none;
            }

            // Each child (literal) under 'child' is added to a new copy of the existing vectors...
            for (size_t grandChild = 1; grandChild < numGrandChildren; grandChild++) {
                for (size_t i = 0; i < frontierSize; i++) {
                    NodeVector newNodeVec = newChildren.at(i);
                    newNodeVec.push_back(childNode->nodes().at(grandChild));
                    newChildren.push_back(newNodeVec);
                }
            }

            // Except the first child under 'child', which can modify the vectors in place.
            for (size_t i = 0; i < frontierSize; i++) {
                NodeVector& nv = newChildren.at(i);
                nv.push_back(childNode->nodes().front());
            }
        }

        NodeVector res;
        for (size_t i = 0; i < newChildren.size(); i++) {
            res.push_back(make<SecondLevel>(std::move(newChildren[i])));
        }
        return make<TopLevel>(res);
    }
};

}  // namespace mongo::optimizer