summaryrefslogtreecommitdiff
path: root/src/mongo/db/pipeline/value.h
blob: 6a99b673a7073a74e5e9e8daf500676ef39b0369 (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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
/**
 * Copyright (c) 2011 10gen Inc.
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * 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
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include "mongo/pch.h"
#include "bson/bsontypes.h"
#include "bson/oid.h"
#include "util/intrusive_counter.h"
#include "util/optime.h"

namespace mongo {
    class BSONElement;
    class Builder;
    class Document;
    class Value;

    class ValueIterator :
        public IntrusiveCounterUnsigned {
    public:
        virtual ~ValueIterator();

        /*
          Ask if there are more fields to return.

          @returns true if there are more fields, false otherwise
        */
        virtual bool more() const = 0;

        /*
          Move the iterator to point to the next field and return it.

          @returns the next field's <name, Value>
        */
        virtual intrusive_ptr<const Value> next() = 0;
    };


    /*
      Values are immutable, so these are passed around as
      intrusive_ptr<const Value>.
     */
    class Value :
        public IntrusiveCounterUnsigned {
    public:
        ~Value();

        /*
          Construct a Value from a BSONElement.

          This ignores the name of the element, and only uses the value,
          whatever type it is.

          @returns a new Value initialized from the bsonElement
        */
        static intrusive_ptr<const Value> createFromBsonElement(
            BSONElement *pBsonElement);

        /*
          Construct an integer-valued Value.

          For commonly used values, consider using one of the singleton
          instances defined below.

          @param value the value
          @returns a Value with the given value
        */
        static intrusive_ptr<const Value> createInt(int value);

        /*
          Construct a long or interger-valued Value.
          Used when preforming arithmetic operations with int where the result may be too large
          and need to be stored as long. The Value will be an int if value fits, otherwise it
          will be a long.

          @param value the value
          @returns a Value with the given value
        */
        static intrusive_ptr<const Value> createIntOrLong(long long value);

        /*
          Construct an long(long)-valued Value.

          For commonly used values, consider using one of the singleton
          instances defined below.

          @param value the value
          @returns a Value with the given value
        */
        static intrusive_ptr<const Value> createLong(long long value);

        /*
          Construct a double-valued Value.

          @param value the value
          @returns a Value with the given value
        */
        static intrusive_ptr<const Value> createDouble(double value);

        /*
          Construct a string-valued Value.

          @param value the value
          @returns a Value with the given value
        */
        static intrusive_ptr<const Value> createString(const string &value);

        /*
          Construct a date-valued Value.

          @param value the value
          @returns a Value with the given value
        */
        static intrusive_ptr<const Value> createDate(const long long &value);

        static intrusive_ptr<const Value> createTimestamp(const OpTime& value);

        /*
          Construct a document-valued Value.

          @param value the value
          @returns a Value with the given value
        */
        static intrusive_ptr<const Value> createDocument(
            const intrusive_ptr<Document> &pDocument);

        /*
          Construct an array-valued Value.

          @param value the value
          @returns a Value with the given value
        */
        static intrusive_ptr<const Value> createArray(
            const vector<intrusive_ptr<const Value> > &vpValue);

        /*
          Get the BSON type of the field.

          If the type is jstNULL, no value getter will work.

          @return the BSON type of the field.
        */
        BSONType getType() const;

        /*
          Getters.

          @returns the Value's value; asserts if the requested value type is
          incorrect.
        */
        double getDouble() const;
        string getString() const;
        intrusive_ptr<Document> getDocument() const;
        intrusive_ptr<ValueIterator> getArray() const;
        OID getOid() const;
        bool getBool() const;
        long long getDate() const;
        OpTime getTimestamp() const;
        string getRegex() const;
        string getSymbol() const;
        int getInt() const;
        long long getLong() const;

        /*
          Get the length of an array value.

          @returns the length of the array, if this is array-valued; otherwise
             throws an error
        */
        size_t getArrayLength() const;

        /*
          Add this value to the BSON object under construction.
        */
        void addToBsonObj(BSONObjBuilder *pBuilder, const std::string& fieldName) const;

        /*
          Add this field to the BSON array under construction.

          As part of an array, the Value's name will be ignored.
        */
        void addToBsonArray(BSONArrayBuilder *pBuilder) const;

        /*
          Get references to singleton instances of commonly used field values.
         */
        static intrusive_ptr<const Value> getUndefined();
        static intrusive_ptr<const Value> getNull();
        static intrusive_ptr<const Value> getTrue();
        static intrusive_ptr<const Value> getFalse();
        static intrusive_ptr<const Value> getMinusOne();
        static intrusive_ptr<const Value> getZero();
        static intrusive_ptr<const Value> getOne();

        /**
         * Coerce (cast) a value to a native bool using BSONElement::trueValue() rules, but with
         * some types unsupported.  SERVER-6120
         * @return the bool value
         */
        bool coerceToBool() const;

        /*
          Coerce (cast) a value to an int, using JSON rules.

          @returns the int value
        */
        int coerceToInt() const;

        /*
          Coerce (cast) a value to a long long, using JSON rules.

          @returns the long value
        */
        long long coerceToLong() const;

        /*
          Coerce (cast) a value to a double, using JSON rules.

          @returns the double value
        */
        double coerceToDouble() const;

        /*
          Coerce (cast) a value to a date, using JSON rules.

          @returns the date value
        */
        long long coerceToDate() const;
        time_t coerceToTimeT() const;
        tm coerceToTm() const; // broken-out time struct (see man gmtime)

        OpTime coerceToTimestamp() const;

        /*
          Coerce (cast) a value to a string, using JSON rules.

          @returns the date value
        */
        string coerceToString() const;

        /*
          Compare two Values.

          @param rL left value
          @param rR right value
          @returns an integer less than zero, zero, or an integer greater than
            zero, depending on whether rL < rR, rL == rR, or rL > rR
         */
        static int compare(const intrusive_ptr<const Value> &rL,
                           const intrusive_ptr<const Value> &rR);


        /*
          Figure out what the widest of two numeric types is.

          Widest can be thought of as "most capable," or "able to hold the
          largest or most precise value."  The progression is Int, Long, Double.

          @param rL left value
          @param rR right value
          @returns a BSONType of NumberInt, NumberLong, or NumberDouble
        */
        static BSONType getWidestNumeric(BSONType lType, BSONType rType);

        /*
          Get the approximate storage size of the value, in bytes.

          @returns approximate storage size of the value.
         */
        size_t getApproximateSize() const;

        /*
          Calculate a hash value.

          Meant to be used to create composite hashes suitable for
          boost classes such as unordered_map<>.

          @param seed value to augment with this' hash
        */
        void hash_combine(size_t &seed) const;

        /*
          struct Hash is defined to enable the use of Values as
          keys in boost::unordered_map<>.

          Values are always referenced as immutables in the form
          intrusive_ptr<const Value>, so these operate on that construction.
        */
        struct Hash :
            unary_function<intrusive_ptr<const Value>, size_t> {
            size_t operator()(const intrusive_ptr<const Value> &rV) const;
        };

    protected:
        Value(); // creates null value
        Value(BSONType type); // creates an empty (unitialized value) of type
                                                // mostly useful for Undefined
        Value(bool boolValue);
        Value(int intValue);

    private:
        Value(BSONElement *pBsonElement);

        Value(long long longValue);
        Value(double doubleValue);
        Value(const OpTime& timestampValue);
        Value(const string &stringValue);
        Value(const intrusive_ptr<Document> &pDocument);
        Value(const vector<intrusive_ptr<const Value> > &vpValue);

        void addToBson(Builder *pBuilder) const;

        BSONType type;

        // store values that don't need a ctor/dtor in one of these
        union {
            double doubleValue;
            bool boolValue;
            int intValue;
            long long longValue;
            ReplTime timestampValue;
            unsigned char oidValue[12];
            // The member below is redundant, but useful for clarity and searchability.
            long long dateValue;
        };

        string stringValue; // String, Regex, Symbol
        intrusive_ptr<Document> pDocumentValue;
        vector<intrusive_ptr<const Value> > vpValue; // for arrays

        /*
        These are often used as the result of boolean or comparison
        expressions.

        These are obtained via public static getters defined above.
        */
        static const intrusive_ptr<const Value> pFieldUndefined;
        static const intrusive_ptr<const Value> pFieldNull;
        static const intrusive_ptr<const Value> pFieldTrue;
        static const intrusive_ptr<const Value> pFieldFalse;
        static const intrusive_ptr<const Value> pFieldMinusOne;
        static const intrusive_ptr<const Value> pFieldZero;
        static const intrusive_ptr<const Value> pFieldOne;

        /* this implementation is used for getArray() */
        class vi :
            public ValueIterator {
        public:
            // virtuals from ValueIterator
            virtual ~vi();
            virtual bool more() const;
            virtual intrusive_ptr<const Value> next();

        private:
            friend class Value;
            vi(const intrusive_ptr<const Value> &pSource,
               const vector<intrusive_ptr<const Value> > *pvpValue);

            size_t size;
            size_t nextIndex;
            const vector<intrusive_ptr<const Value> > *pvpValue;
        }; /* class vi */

    };

    /*
      Equality operator for values.

      Useful for unordered_map<>, etc.
     */
    inline bool operator==(const intrusive_ptr<const Value> &v1,
                    const intrusive_ptr<const Value> &v2) {
        return (Value::compare(v1, v2) == 0);
    }

    /*
      For performance reasons, there are various sharable static values
      defined in class Value, obtainable by methods such as getUndefined(),
      getTrue(), getOne(), etc.  We don't want these to go away as they are
      used by a multitude of threads evaluating pipelines.  In order to avoid
      having to use atomic integers in the intrusive reference counter, this
      class overrides the reference counting methods to do nothing, making it
      safe to use for static Values.

      At this point, only the constructors necessary for the static Values in
      common use have been defined.  The remainder can be defined if necessary.
     */
    class ValueStatic :
        public Value {
    public:
        // virtuals from IntrusiveCounterUnsigned
        virtual void addRef() const;
        virtual void release() const;

        // constructors
        ValueStatic();
        ValueStatic(BSONType type);
        ValueStatic(bool boolValue);
        ValueStatic(int intValue);
    };
}

/* ======================= INLINED IMPLEMENTATIONS ========================== */

namespace mongo {

    inline BSONType Value::getType() const {
        return type;
    }

    inline size_t Value::getArrayLength() const {
        verify(getType() == Array);
        return vpValue.size();
    }

    inline intrusive_ptr<const Value> Value::getUndefined() {
        return pFieldUndefined;
    }

    inline intrusive_ptr<const Value> Value::getNull() {
        return pFieldNull;
    }

    inline intrusive_ptr<const Value> Value::getTrue() {
        return pFieldTrue;
    }

    inline intrusive_ptr<const Value> Value::getFalse() {
        return pFieldFalse;
    }

    inline intrusive_ptr<const Value> Value::getMinusOne() {
        return pFieldMinusOne;
    }

    inline intrusive_ptr<const Value> Value::getZero() {
        return pFieldZero;
    }

    inline intrusive_ptr<const Value> Value::getOne() {
        return pFieldOne;
    }

    inline size_t Value::Hash::operator()(
        const intrusive_ptr<const Value> &rV) const {
        size_t seed = 0xf0afbeef;
        rV->hash_combine(seed);
        return seed;
    }

    inline ValueStatic::ValueStatic():
        Value() {
    }

    inline ValueStatic::ValueStatic(BSONType type):
        Value(type) {
    }

    inline ValueStatic::ValueStatic(bool boolValue):
        Value(boolValue) {
    }

    inline ValueStatic::ValueStatic(int intValue):
        Value(intValue) {
    }

};