mongory 2.0.1 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 8c2072dcf73aedcefd0dea480bb582fad714ed573cf7b79e4d5910d1c3569f34
4
- data.tar.gz: 63a82ffa6e27ad051cf2eac736c415744c6d040f13d0bcd4577fa0ff075254c7
3
+ metadata.gz: f41aa0bea7de774e96bbc53a478fd90b5cf12d72fa2684d360424e3ac745677f
4
+ data.tar.gz: 372350cf13aa2735959b627fd60fc20d6e72dd729cb6b2d1cc288620b1e8d59a
5
5
  SHA512:
6
- metadata.gz: d461d1941649106c503740b3041afcb07d85e84f09c335b9bc56d214e426a70bef032db378806b0d206c05f54553ca39bc528f8afcd6a591344c4ae52c0906d3
7
- data.tar.gz: a388c24d319743edaae107a64f9b3d1afa6c598c26bfeb55f7ac00267a62cddb78b1a45b89eba3de7ede9c28beaa5ecfa704e6a497527f19bf96884abf286614
6
+ metadata.gz: d09473d0e1dd40090ca9e65a0598b8f75e117e265415aaba2c4ea74f8c2c013a9710faed1e698e7dfdb70c9d3ece87e1a3e21100628f3c0815b7cc9bafbf339e
7
+ data.tar.gz: c06699ee0bae9d81395e5a684d5261fe95aac83378cf739db4eed0a327391071d92d6bf5a98d58541a9f0bae1b189935cf5f09a0e29cb67ba3370169ea5db273
data/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.1.1] - 2026-11-25
4
+
5
+ ### Performance
6
+ - **O(1) `$in` / `$nin` Hash Lookup (`mongory-core v0.3.1`)**: Bumped `mongory-core` submodule to `v0.3.1`, adding an immutable, arena-allocated, type-bucketed O(1) hash set for `$in` / `$nin` arrays with 16+ items (~15x speedup on 500-item `$in`, ~840x faster than `Mongoid::Matcher` in local benchmarks).
7
+
8
+ ### Docs & Benchmarks
9
+ - Added optional `Mongoid::Matcher` comparison to `script/bench.rb` and updated `docs/performance.md`.
10
+
11
+ ## [2.1.0] - 2026-11-23
12
+
13
+ ### Added
14
+ - **`Mongory.compile` & `Mongory.query`**: Added `Mongory.compile(condition)` (alias `build_matcher`) and `Mongory.query(records)` (alias `build_query`) as primary entry points aligned across the Mongory ecosystem.
15
+
16
+ ### Fixes
17
+ - **C Extension Load Verification & Source-Gem Fallback (`lib/mongory.rb`)**: Fall back to `require 'mongory_ext'` when precompiled `core/<abi>/mongory_ext` is absent (supporting source-gem installs), and verify that `Mongory::Matcher#match?` is defined before reopening `Mongory::Matcher` so stale or incompatible C extensions fail fast with a clear `LoadError`.
18
+
3
19
  ## [2.0.1] - 2026-11-22
4
20
 
5
21
  Aligns with `mongory-core` `v0.3.0` and finishes v2.0.0 cleanup.
data/README.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Mongory (Ruby)
2
2
 
3
+ [![Gem Version](https://img.shields.io/gem/v/mongory)](https://rubygems.org/gems/mongory)
4
+ [![CI](https://github.com/mongoryhq/mongory-rb/actions/workflows/main.yml/badge.svg)](https://github.com/mongoryhq/mongory-rb/actions/workflows/main.yml)
5
+ [![mongory-spec](https://github.com/mongoryhq/mongory-rb/actions/workflows/spec-conformance.yml/badge.svg)](https://github.com/mongoryhq/mongory-rb/actions/workflows/spec-conformance.yml)
6
+ ![Ruby](https://img.shields.io/badge/Ruby-2.6%2B-CC342D)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
8
+
3
9
  **Cross-language, in-memory Mongo-style rule engine & query matcher with built-in Explain & Trace debugging** — powered by the C99 [`mongory-core`](https://github.com/mongoryhq/mongory-core) native extension with cross-language parity via [`mongory-spec`](https://github.com/mongoryhq/mongory-spec).
4
10
 
5
11
  **[Try the Interactive Playground & Visual Explain/Trace Debugger ↗](https://mongoryhq.github.io/mongory-central/)**
@@ -59,6 +65,11 @@ matched = records.mongory
59
65
  rule = JSON.parse('{"age": {"$gte": 18}, "$or": [{"name": {"$regex": "^J"}}, {"name": "Bob"}]}')
60
66
  records.mongory.where(rule).pluck('name')
61
67
  # => ["Jack", "Bob"]
68
+
69
+ # 3. Compile once as a reusable, thread-safe Matcher (ideal for constants)
70
+ ADULT_RULE = Mongory.compile(:age.gte => 18, :active => true)
71
+ ADULT_RULE.match?(records.first)
72
+ # => true
62
73
  ```
63
74
 
64
75
  ### Query Builder Methods
@@ -175,6 +186,11 @@ Mongory::Matchers.register(:class_in, '$classIn', ClassInMatcher)
175
186
  - [Performance & Benchmarks](docs/performance.md)
176
187
  - [Migration Guide](docs/migration.md)
177
188
 
189
+ ## Security & Untrusted Input
190
+
191
+ - **Engine protections**: Pure in-memory C99 evaluation (no SQL, no `$where`/`eval`), arena memory pool chunk limits, and compile-time depth/node budgets (`MaxDepth = 64`, `MaxNodes = 4096`).
192
+ - **Application responsibility**: When accepting query conditions from untrusted users, validate expected scalar types (to prevent operator injection such as `{"$ne" => nil}`), allowlist queryable fields, and configure `Regexp.timeout` (Ruby 3.2+) or restrict untrusted `$regex` patterns.
193
+
178
194
  ## Contributing & License
179
195
 
180
196
  Bug reports and pull requests are welcome on [GitHub](https://github.com/mongoryhq/mongory-rb). Everyone interacting in the project is expected to follow the [Code of Conduct](CODE_OF_CONDUCT.md).
data/docs/performance.md CHANGED
@@ -8,17 +8,26 @@ Run the included benchmark script in `mongory-rb` to measure `Mongory::Matcher`
8
8
  ruby script/bench.rb
9
9
  ```
10
10
 
11
- ### Measured Results (Apple M3, macOS arm64, Ruby `4.0.5`, 100,000 records)
11
+ To include the `Mongoid::Matcher` comparison (optional, keeps `mongory` zero-dependency), install `mongoid` in a separate `GEM_PATH`:
12
12
 
13
- | Engine / Case | Simple (`age >= 18`) | `$or` (`age >= 18` or `status == "active"`) |
14
- |---|---|---|
15
- | Plain Ruby `Array#count` | `7.26 ms` (`72.6 ns/rec`) | `6.85 ms` (`68.5 ns/rec`) |
16
- | `Mongory::Matcher` (`mongory-core` C99) | `7.67 ms` (`76.7 ns/rec`) | `12.92 ms` (`129.2 ns/rec`) |
13
+ ```bash
14
+ gem install --install-dir /tmp/rb-bench-gems --no-document mongoid
15
+ GEM_PATH=/tmp/rb-bench-gems ruby script/bench.rb
16
+ ```
17
+
18
+ ### Measured Results (Apple M3, macOS arm64, Ruby `4.0.5`, 100,000 records x 5 rounds)
19
+
20
+ | Case | Plain Ruby `Array#count` | `Mongory::Matcher` (`mongory-core` C99) | `Mongoid::Matcher` (`mongoid 9.1.2`) | `Mongory` vs `Mongoid` |
21
+ |---|---:|---:|---:|---:|
22
+ | `simple` (`age >= 18`) | `6.31 ms` (`63.1 ns/rec`) | `7.79 ms` (`77.9 ns/rec`) | `322.45 ms` (`3,224.5 ns/rec`) | **41.4x faster** |
23
+ | `$or` (`age >= 18` or `status == "active"`) | `7.18 ms` (`71.8 ns/rec`) | `12.74 ms` (`127.4 ns/rec`) | `396.79 ms` (`3,967.9 ns/rec`) | **31.1x faster** |
24
+ | `in_array_field` (`tags $in ["ruby", "rust"]`) | `8.53 ms` (`85.3 ns/rec`) | `13.64 ms` (`136.4 ns/rec`) | `430.21 ms` (`4,302.1 ns/rec`) | **31.5x faster** |
25
+ | `large_in_500` (`name $in [500 items]`, O(1) hash) | `6.29 ms` (`62.9 ns/rec`) | `11.58 ms` (`115.8 ns/rec`) | `9,735.19 ms` (`97,351.9 ns/rec`) | **840.7x faster** |
17
26
 
18
- > For cross-language benchmarks (`mongory-js`, `mongory-go`), see [Mongory Central](https://mongoryhq.github.io/mongory-central/#benchmarks).
27
+ > For cross-language benchmarks (`mongory-go`, `mongory-js`, `mongory-py`), see [Mongory Central](https://mongoryhq.github.io/mongory-central/#benchmarks).
19
28
 
20
29
  ## Optimization Tips
21
30
 
22
- - **Reuse `Mongory::Matcher` Instances**: Compile once with `Mongory::Matcher.new(condition)` and call `#match?` across records to avoid recompiling the condition tree.
31
+ - **Reuse `Mongory::Matcher` Instances**: Compile once with `Mongory::Matcher.new(condition)` (or `Mongory.compile(condition)`) and call `#match?` across records to avoid recompiling the condition tree.
23
32
  - **Priority Ordering & Dynamic Re-Sorting**: Mongory automatically orders cheaper equality/existence checks before regex or array scans, and re-sorts siblings if a lazy array matcher is constructed.
24
33
  - **Inspect Plans**: Use `.explain` / `.trace` to verify cheap fields short-circuit early.
@@ -1,7 +1,9 @@
1
1
  /**
2
2
  * @file inclusion_matcher.c
3
3
  * @brief Implements $in and $nin matchers for checking value inclusion in an
4
- * array. This is an internal implementation file for the matcher module.
4
+ * array. Uses an immutable, arena-allocated, type-bucketed O(1) hash set for
5
+ * condition arrays with >= 16 elements while falling back to linear scan for
6
+ * small arrays.
5
7
  */
6
8
  #include "inclusion_matcher.h"
7
9
  #include "base_matcher.h" // For mongory_matcher_base_new
@@ -9,45 +11,379 @@
9
11
  #include "mongory-core/foundations/array.h" // For mongory_array operations
10
12
  #include "mongory-core/foundations/error.h" // For mongory_error
11
13
  #include "mongory-core/foundations/value.h" // For mongory_value
14
+ #include <math.h> // For floor, isnan, isfinite, fabs
12
15
  #include <mongory-core.h> // General include
13
- #include "../foundations/utils.h" // For mongory_string_cpy
16
+ #include <stdint.h> // For uint64_t, int64_t, INT64_C
17
+ #include <string.h> // For strlen, memcmp, memset, memcpy
18
+ #include "../foundations/utils.h" // For mongory_string_cpy, mongory_log
19
+
20
+ #define MONGORY_IN_HASH_THRESHOLD 16
21
+ #define MONGORY_IN_SAFE_INT_MAX (INT64_C(1) << 53)
22
+
23
+ typedef struct mongory_in_str_slot {
24
+ const char *str;
25
+ size_t len;
26
+ uint64_t hash;
27
+ } mongory_in_str_slot;
28
+
29
+ typedef enum mongory_in_num_kind {
30
+ MONGORY_IN_NUM_EMPTY = 0,
31
+ MONGORY_IN_NUM_INT = 1,
32
+ MONGORY_IN_NUM_DOUBLE = 2
33
+ } mongory_in_num_kind;
34
+
35
+ typedef struct mongory_in_num_slot {
36
+ mongory_in_num_kind kind;
37
+ uint64_t key_bits; // int64_t bits (for INT) or IEEE-754 double bits (for DOUBLE)
38
+ uint64_t hash;
39
+ mongory_value *val;
40
+ } mongory_in_num_slot;
41
+
42
+ typedef struct mongory_in_set {
43
+ bool has_null;
44
+ bool has_true;
45
+ bool has_false;
46
+
47
+ mongory_in_str_slot *str_slots;
48
+ size_t str_mask;
49
+
50
+ mongory_in_num_slot *num_slots;
51
+ size_t num_mask;
52
+
53
+ mongory_value **fallback;
54
+ size_t fallback_count;
55
+ } mongory_in_set;
56
+
57
+ typedef struct mongory_inclusion_matcher {
58
+ mongory_matcher base;
59
+ mongory_in_set *set;
60
+ } mongory_inclusion_matcher;
61
+
62
+ static inline uint64_t mongory_fnv1a_64(const char *s, size_t len) {
63
+ uint64_t h = UINT64_C(14695981039346656037);
64
+ for (size_t i = 0; i < len; i++) {
65
+ h ^= (uint64_t)(unsigned char)s[i];
66
+ h *= UINT64_C(1099511628211);
67
+ }
68
+ return h;
69
+ }
70
+
71
+ static inline uint64_t mongory_splitmix64(uint64_t x) {
72
+ x += UINT64_C(0x9e3779b97f4a7c15);
73
+ x = (x ^ (x >> 30)) * UINT64_C(0xbf58476d1ce4e5b9);
74
+ x = (x ^ (x >> 27)) * UINT64_C(0x94d049bb133111eb);
75
+ return x ^ (x >> 31);
76
+ }
77
+
78
+ static inline size_t mongory_next_pow2(size_t n) {
79
+ size_t cap = 32;
80
+ while (cap < n && cap < ((size_t)1 << (sizeof(size_t) * 8 - 1))) {
81
+ cap <<= 1;
82
+ }
83
+ return cap;
84
+ }
85
+
86
+ /**
87
+ * Classifies a numeric mongory_value into a canonical hashable key:
88
+ * - Returns MONGORY_IN_NUM_INT for exact integers within [-2^53, 2^53] (including
89
+ * integral doubles like 1.0 and -0.0), so 1 == 1.0 and -0.0 == 0 share the same key.
90
+ * - Returns MONGORY_IN_NUM_DOUBLE for finite non-integer doubles within [-2^53, 2^53]
91
+ * and +/-Infinity.
92
+ * - Returns MONGORY_IN_NUM_EMPTY if the value is NaN (never matches) or exceeds
93
+ * safe exact-integer range (caller routes large numbers to fallback).
94
+ */
95
+ static inline mongory_in_num_kind mongory_in_classify_num(const mongory_value *v, uint64_t *out_bits, bool *out_is_nan) {
96
+ *out_is_nan = false;
97
+ if (v->type == MONGORY_TYPE_INT) {
98
+ int64_t i = v->data.i;
99
+ if (i >= -MONGORY_IN_SAFE_INT_MAX && i <= MONGORY_IN_SAFE_INT_MAX) {
100
+ *out_bits = (uint64_t)i;
101
+ return MONGORY_IN_NUM_INT;
102
+ }
103
+ return MONGORY_IN_NUM_EMPTY;
104
+ }
105
+ if (v->type == MONGORY_TYPE_DOUBLE) {
106
+ double d = v->data.d;
107
+ if (isnan(d)) {
108
+ *out_is_nan = true;
109
+ return MONGORY_IN_NUM_EMPTY;
110
+ }
111
+ if (d == 0.0) {
112
+ *out_bits = 0;
113
+ return MONGORY_IN_NUM_INT;
114
+ }
115
+ if (isfinite(d)) {
116
+ if (fabs(d) > (double)MONGORY_IN_SAFE_INT_MAX) {
117
+ return MONGORY_IN_NUM_EMPTY;
118
+ }
119
+ if (floor(d) == d) {
120
+ int64_t i = (int64_t)d;
121
+ *out_bits = (uint64_t)i;
122
+ return MONGORY_IN_NUM_INT;
123
+ }
124
+ }
125
+ uint64_t bits = 0;
126
+ memcpy(&bits, &d, sizeof(bits));
127
+ *out_bits = bits;
128
+ return MONGORY_IN_NUM_DOUBLE;
129
+ }
130
+ return MONGORY_IN_NUM_EMPTY;
131
+ }
132
+
133
+ static mongory_in_set *mongory_in_set_build(mongory_memory_pool *pool, mongory_array *arr) {
134
+ size_t count = arr->count;
135
+ size_t str_count = 0;
136
+ size_t num_count = 0;
137
+ size_t fb_count = 0;
138
+
139
+ for (size_t i = 0; i < count; i++) {
140
+ mongory_value *elem = arr->get(arr, i);
141
+ if (!elem) {
142
+ continue;
143
+ }
144
+ switch (elem->type) {
145
+ case MONGORY_TYPE_NULL:
146
+ case MONGORY_TYPE_BOOL:
147
+ break;
148
+ case MONGORY_TYPE_STRING:
149
+ if (elem->data.s != NULL) {
150
+ str_count++;
151
+ }
152
+ break;
153
+ case MONGORY_TYPE_INT:
154
+ case MONGORY_TYPE_DOUBLE: {
155
+ uint64_t bits = 0;
156
+ bool is_nan = false;
157
+ if (mongory_in_classify_num(elem, &bits, &is_nan) != MONGORY_IN_NUM_EMPTY) {
158
+ num_count++;
159
+ } else if (!is_nan) {
160
+ fb_count++;
161
+ }
162
+ break;
163
+ }
164
+ default:
165
+ fb_count++;
166
+ break;
167
+ }
168
+ }
169
+
170
+ mongory_in_set *set = MG_ALLOC_PTR(pool, mongory_in_set);
171
+ if (!set) {
172
+ pool->error = &MONGORY_ALLOC_ERROR;
173
+ return NULL;
174
+ }
175
+ memset(set, 0, sizeof(*set));
176
+
177
+ if (str_count > 0) {
178
+ size_t cap = mongory_next_pow2(str_count * 2);
179
+ set->str_slots = (mongory_in_str_slot *)pool->alloc(pool, cap * sizeof(mongory_in_str_slot));
180
+ if (!set->str_slots) {
181
+ pool->error = &MONGORY_ALLOC_ERROR;
182
+ return NULL;
183
+ }
184
+ memset(set->str_slots, 0, cap * sizeof(mongory_in_str_slot));
185
+ set->str_mask = cap - 1;
186
+ }
187
+
188
+ if (num_count > 0) {
189
+ size_t cap = mongory_next_pow2(num_count * 2);
190
+ set->num_slots = (mongory_in_num_slot *)pool->alloc(pool, cap * sizeof(mongory_in_num_slot));
191
+ if (!set->num_slots) {
192
+ pool->error = &MONGORY_ALLOC_ERROR;
193
+ return NULL;
194
+ }
195
+ memset(set->num_slots, 0, cap * sizeof(mongory_in_num_slot));
196
+ set->num_mask = cap - 1;
197
+ }
198
+
199
+ if (fb_count > 0) {
200
+ set->fallback = (mongory_value **)pool->alloc(pool, fb_count * sizeof(mongory_value *));
201
+ if (!set->fallback) {
202
+ pool->error = &MONGORY_ALLOC_ERROR;
203
+ return NULL;
204
+ }
205
+ }
206
+
207
+ for (size_t i = 0; i < count; i++) {
208
+ mongory_value *elem = arr->get(arr, i);
209
+ if (!elem) {
210
+ continue;
211
+ }
212
+ switch (elem->type) {
213
+ case MONGORY_TYPE_NULL:
214
+ set->has_null = true;
215
+ break;
216
+ case MONGORY_TYPE_BOOL:
217
+ if (elem->data.b) {
218
+ set->has_true = true;
219
+ } else {
220
+ set->has_false = true;
221
+ }
222
+ break;
223
+ case MONGORY_TYPE_STRING: {
224
+ const char *s = elem->data.s;
225
+ if (!s) {
226
+ break;
227
+ }
228
+ size_t len = strlen(s);
229
+ uint64_t h = mongory_fnv1a_64(s, len);
230
+ size_t idx = (size_t)(h & set->str_mask);
231
+ while (set->str_slots[idx].str != NULL) {
232
+ if (set->str_slots[idx].hash == h && set->str_slots[idx].len == len &&
233
+ memcmp(set->str_slots[idx].str, s, len) == 0) {
234
+ break;
235
+ }
236
+ idx = (idx + 1) & set->str_mask;
237
+ }
238
+ if (set->str_slots[idx].str == NULL) {
239
+ set->str_slots[idx].str = s;
240
+ set->str_slots[idx].len = len;
241
+ set->str_slots[idx].hash = h;
242
+ }
243
+ break;
244
+ }
245
+ case MONGORY_TYPE_INT:
246
+ case MONGORY_TYPE_DOUBLE: {
247
+ uint64_t bits = 0;
248
+ bool is_nan = false;
249
+ mongory_in_num_kind kind = mongory_in_classify_num(elem, &bits, &is_nan);
250
+ if (kind != MONGORY_IN_NUM_EMPTY) {
251
+ uint64_t h = mongory_splitmix64(bits ^ ((uint64_t)kind << 60));
252
+ size_t idx = (size_t)(h & set->num_mask);
253
+ while (set->num_slots[idx].kind != MONGORY_IN_NUM_EMPTY) {
254
+ if (set->num_slots[idx].kind == kind && set->num_slots[idx].key_bits == bits) {
255
+ break;
256
+ }
257
+ idx = (idx + 1) & set->num_mask;
258
+ }
259
+ if (set->num_slots[idx].kind == MONGORY_IN_NUM_EMPTY) {
260
+ set->num_slots[idx].kind = kind;
261
+ set->num_slots[idx].key_bits = bits;
262
+ set->num_slots[idx].hash = h;
263
+ set->num_slots[idx].val = elem;
264
+ }
265
+ } else if (!is_nan) {
266
+ set->fallback[set->fallback_count++] = elem;
267
+ }
268
+ break;
269
+ }
270
+ default:
271
+ set->fallback[set->fallback_count++] = elem;
272
+ break;
273
+ }
274
+ }
275
+
276
+ return set;
277
+ }
278
+
279
+ static inline bool mongory_in_set_contains_scalar(const mongory_in_set *set, mongory_value *v) {
280
+ if (!v) {
281
+ return false;
282
+ }
283
+ switch (v->type) {
284
+ case MONGORY_TYPE_NULL:
285
+ return set->has_null;
286
+ case MONGORY_TYPE_BOOL:
287
+ return v->data.b ? set->has_true : set->has_false;
288
+ case MONGORY_TYPE_STRING: {
289
+ if (!set->str_slots || !v->data.s) {
290
+ return false;
291
+ }
292
+ const char *s = v->data.s;
293
+ size_t len = strlen(s);
294
+ uint64_t h = mongory_fnv1a_64(s, len);
295
+ size_t idx = (size_t)(h & set->str_mask);
296
+ while (set->str_slots[idx].str != NULL) {
297
+ if (set->str_slots[idx].hash == h && set->str_slots[idx].len == len &&
298
+ memcmp(set->str_slots[idx].str, s, len) == 0) {
299
+ return true;
300
+ }
301
+ idx = (idx + 1) & set->str_mask;
302
+ }
303
+ return false;
304
+ }
305
+ case MONGORY_TYPE_INT:
306
+ case MONGORY_TYPE_DOUBLE: {
307
+ uint64_t bits = 0;
308
+ bool is_nan = false;
309
+ mongory_in_num_kind kind = mongory_in_classify_num(v, &bits, &is_nan);
310
+ if (is_nan) {
311
+ return false;
312
+ }
313
+ if (kind != MONGORY_IN_NUM_EMPTY) {
314
+ if (!set->num_slots) {
315
+ return false;
316
+ }
317
+ uint64_t h = mongory_splitmix64(bits ^ ((uint64_t)kind << 60));
318
+ size_t idx = (size_t)(h & set->num_mask);
319
+ while (set->num_slots[idx].kind != MONGORY_IN_NUM_EMPTY) {
320
+ if (set->num_slots[idx].kind == kind && set->num_slots[idx].key_bits == bits &&
321
+ set->num_slots[idx].val->comp(set->num_slots[idx].val, v) == 0) {
322
+ return true;
323
+ }
324
+ idx = (idx + 1) & set->num_mask;
325
+ }
326
+ return false;
327
+ }
328
+ // Large integer/double outside exact 2^53 range -> check fallback
329
+ for (size_t i = 0; i < set->fallback_count; i++) {
330
+ mongory_value *cand = set->fallback[i];
331
+ if (cand->comp(cand, v) == 0) {
332
+ return true;
333
+ }
334
+ }
335
+ return false;
336
+ }
337
+ default:
338
+ for (size_t i = 0; i < set->fallback_count; i++) {
339
+ mongory_value *cand = set->fallback[i];
340
+ if (cand->comp(cand, v) == 0) {
341
+ return true;
342
+ }
343
+ }
344
+ return false;
345
+ }
346
+ }
14
347
 
15
348
  /**
16
349
  * @brief Validates that the condition for an inclusion matcher is a valid
17
350
  * array.
18
- * @param condition The `mongory_value` condition to validate.
19
- * @return True if `condition` is not NULL, is of type `MONGORY_TYPE_ARRAY`,
20
- * and its internal array data `condition->data.a` is not NULL. False otherwise.
21
351
  */
22
352
  static inline bool mongory_matcher_validate_array_condition(mongory_value *condition) {
23
353
  if (condition == NULL) {
24
- return false; // Condition must exist.
354
+ return false;
25
355
  }
26
356
  if (condition->type != MONGORY_TYPE_ARRAY) {
27
- return false; // Condition must be an array.
357
+ return false;
28
358
  }
29
359
  if (condition->data.a == NULL) {
30
- return false; // The array data within the condition must be valid.
360
+ return false;
31
361
  }
32
362
  return true;
33
363
  }
34
364
 
35
- /**
36
- * @brief Match function for the $in matcher.
37
- *
38
- * If `value_to_check` is a scalar, it checks if `value_to_check` is present in
39
- * `matcher->condition` (which must be an array).
40
- * If `value_to_check` is an array, it checks if any element of `value_to_check`
41
- * is present in `matcher->condition` (array intersection).
42
- *
43
- * @param matcher The $in matcher instance.
44
- * @param value_to_check The value to check for inclusion.
45
- * @return True if `value_to_check` (or one of its elements) is found in the
46
- * condition array, false otherwise.
47
- */
48
365
  static inline bool mongory_matcher_in_match(mongory_matcher *matcher, mongory_value *value_to_check) {
49
366
  if (!value_to_check || !matcher->condition || !matcher->condition->data.a) {
50
- // Invalid inputs or condition is not a proper array.
367
+ return false;
368
+ }
369
+
370
+ mongory_inclusion_matcher *inc = (mongory_inclusion_matcher *)matcher;
371
+ mongory_in_set *set = inc->set;
372
+
373
+ if (set != NULL) {
374
+ if (value_to_check->type != MONGORY_TYPE_ARRAY) {
375
+ return mongory_in_set_contains_scalar(set, value_to_check);
376
+ }
377
+ mongory_array *input_array = value_to_check->data.a;
378
+ if (!input_array) {
379
+ return false;
380
+ }
381
+ for (size_t i = 0; i < input_array->count; i++) {
382
+ mongory_value *input_item = input_array->get(input_array, i);
383
+ if (mongory_in_set_contains_scalar(set, input_item)) {
384
+ return true;
385
+ }
386
+ }
51
387
  return false;
52
388
  }
53
389
 
@@ -72,35 +408,67 @@ static inline bool mongory_matcher_in_match(mongory_matcher *matcher, mongory_va
72
408
  return false;
73
409
  }
74
410
 
75
- mongory_matcher *mongory_matcher_in_new(mongory_memory_pool *pool, mongory_value *condition, void *extern_ctx) {
76
- if (!mongory_matcher_validate_array_condition(condition)) {
77
- mongory_error_set(pool, MONGORY_ERROR_INVALID_ARGUMENT, "$in condition must be a valid array.");
411
+ static mongory_inclusion_matcher *mongory_inclusion_matcher_alloc(mongory_memory_pool *pool, mongory_value *condition,
412
+ void *extern_ctx, const char *name,
413
+ mongory_matcher_match_func match_fn) {
414
+ if (!pool || !pool->alloc) {
415
+ return NULL;
416
+ }
417
+ if (!mongory_compile_budget_count_node(pool)) {
78
418
  return NULL;
79
419
  }
80
- mongory_matcher *matcher = mongory_matcher_base_new(pool, condition, extern_ctx);
81
- if (!matcher) {
420
+ mongory_inclusion_matcher *inc = MG_ALLOC_PTR(pool, mongory_inclusion_matcher);
421
+ if (!inc) {
422
+ pool->error = &MONGORY_ALLOC_ERROR;
82
423
  return NULL;
83
424
  }
84
- matcher->match = mongory_matcher_in_match;
85
- matcher->original_match = mongory_matcher_in_match;
86
- matcher->name = mongory_string_cpy(pool, "In");
87
- if (!matcher->name) {
425
+
426
+ inc->base.original_match = match_fn;
427
+ inc->base.sub_count = 0;
428
+ inc->base.pool = pool;
429
+ inc->base.condition = condition;
430
+ inc->base.name = mongory_string_cpy(pool, (char *)name);
431
+ if (!inc->base.name) {
432
+ return NULL;
433
+ }
434
+ inc->base.match = match_fn;
435
+ inc->base.explain = mongory_matcher_base_explain;
436
+ inc->base.traverse = mongory_matcher_leaf_traverse;
437
+ inc->base.trace_stack = NULL;
438
+ inc->base.trace_level = 0;
439
+ inc->base.extern_ctx = extern_ctx;
440
+ inc->base.parent = NULL;
441
+ inc->set = NULL;
442
+
443
+ mongory_array *cond_arr = condition->data.a;
444
+ if (cond_arr->count >= MONGORY_IN_HASH_THRESHOLD) {
445
+ inc->set = mongory_in_set_build(pool, cond_arr);
446
+ if (!inc->set) {
447
+ return NULL;
448
+ }
449
+ if (inc->set->fallback_count == 0) {
450
+ inc->base.priority = 2.5;
451
+ } else {
452
+ inc->base.priority = 2.5 + mongory_log((double)inc->set->fallback_count + 1.0, 1.5);
453
+ }
454
+ } else {
455
+ inc->base.priority = 1.0 + mongory_log((double)cond_arr->count + 1.0, 1.5);
456
+ }
457
+
458
+ return inc;
459
+ }
460
+
461
+ mongory_matcher *mongory_matcher_in_new(mongory_memory_pool *pool, mongory_value *condition, void *extern_ctx) {
462
+ if (!mongory_matcher_validate_array_condition(condition)) {
463
+ mongory_error_set(pool, MONGORY_ERROR_INVALID_ARGUMENT, "$in condition must be a valid array.");
88
464
  return NULL;
89
465
  }
90
- matcher->priority = 1.0 + mongory_log((double)condition->data.a->count + 1.0, 1.5);
91
- return matcher;
466
+ mongory_inclusion_matcher *inc =
467
+ mongory_inclusion_matcher_alloc(pool, condition, extern_ctx, "In", mongory_matcher_in_match);
468
+ return inc ? &inc->base : NULL;
92
469
  }
93
470
 
94
- /**
95
- * @brief Match function for the $nin (not in) matcher.
96
- * Simply negates the result of the $in logic.
97
- * @param matcher The $nin matcher instance.
98
- * @param value The value to check.
99
- * @return True if the value is NOT found according to $in logic, false
100
- * otherwise.
101
- */
102
471
  static inline bool mongory_matcher_not_in_match(mongory_matcher *matcher, mongory_value *value) {
103
- // $nin is true if $in is false.
104
472
  return !mongory_matcher_in_match(matcher, value);
105
473
  }
106
474
 
@@ -109,16 +477,7 @@ mongory_matcher *mongory_matcher_not_in_new(mongory_memory_pool *pool, mongory_v
109
477
  mongory_error_set(pool, MONGORY_ERROR_INVALID_ARGUMENT, "$nin condition must be a valid array.");
110
478
  return NULL;
111
479
  }
112
- mongory_matcher *matcher = mongory_matcher_base_new(pool, condition, extern_ctx);
113
- if (!matcher) {
114
- return NULL;
115
- }
116
- matcher->match = mongory_matcher_not_in_match;
117
- matcher->original_match = mongory_matcher_not_in_match;
118
- matcher->name = mongory_string_cpy(pool, "Nin");
119
- if (!matcher->name) {
120
- return NULL;
121
- }
122
- matcher->priority = 1.0 + mongory_log((double)condition->data.a->count + 1.0, 1.5);
123
- return matcher;
480
+ mongory_inclusion_matcher *inc =
481
+ mongory_inclusion_matcher_alloc(pool, condition, extern_ctx, "Nin", mongory_matcher_not_in_match);
482
+ return inc ? &inc->base : NULL;
124
483
  }
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Mongory
4
- VERSION = '2.0.1'
4
+ VERSION = '2.1.1'
5
5
  end
data/lib/mongory.rb CHANGED
@@ -74,22 +74,33 @@ module Mongory
74
74
  @condition_converter ||= Converters::ConditionConverter.instance
75
75
  end
76
76
 
77
- # Builds a new query over the given record set.
77
+ # Builds a new query builder over the given record set.
78
+ #
79
+ # @example
80
+ # Mongory.query(records).where(:age.gte => 18).pluck(:name)
78
81
  #
79
82
  # @param records [Enumerable] any enumerable object (Array, AR::Relation, etc.)
80
83
  # @return [QueryBuilder] a new query builder
81
- def self.build_query(records)
84
+ def self.query(records)
82
85
  QueryBuilder.new(records)
83
86
  end
84
87
 
85
- # Builds a new matcher for the given condition.
88
+ singleton_class.alias_method :build_query, :query
89
+
90
+ # Compiles a reusable matcher for the given condition.
91
+ #
92
+ # @example
93
+ # ADULT = Mongory.compile(:age.gte => 18)
94
+ # ADULT.match?(age: 20) #=> true
86
95
  #
87
96
  # @param condition [Hash] the query condition
88
- # @return [Matcher] a new matcher
89
- def self.build_matcher(condition)
97
+ # @return [Matcher] a new compiled matcher
98
+ def self.compile(condition)
90
99
  Matcher.new(condition)
91
100
  end
92
101
 
102
+ singleton_class.alias_method :build_matcher, :compile
103
+
93
104
  # Registers a class to support `.mongory` query DSL.
94
105
  # This injects a `#mongory` method into the given class.
95
106
  #
@@ -123,6 +134,17 @@ module Mongory
123
134
  end
124
135
 
125
136
  abi = RUBY_VERSION.split('.').first(2).join('.')
126
- require_relative "core/#{abi}/mongory_ext"
137
+ begin
138
+ require_relative "core/#{abi}/mongory_ext"
139
+ rescue LoadError
140
+ require 'mongory_ext'
141
+ end
142
+
143
+ unless defined?(Mongory::Matcher) && Mongory::Matcher.method_defined?(:match?)
144
+ raise LoadError,
145
+ "Incompatible or outdated mongory_ext loaded for Ruby #{abi} (Mongory::Matcher not defined). " \
146
+ 'Please recompile the C extension (e.g. `bundle exec rake compile`).'
147
+ end
148
+
127
149
  require_relative 'mongory/matcher'
128
150
  require_relative 'mongory/query_builder'
data/renovate.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "$schema": "https://docs.renovatebot.com/renovate-schema.json",
3
+ "extends": [
4
+ "github>mongoryhq/.github"
5
+ ]
6
+ }
data/script/bench.rb CHANGED
@@ -1,8 +1,14 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'benchmark'
4
3
  require_relative '../lib/mongory'
5
4
 
5
+ HAS_MONGOID = begin
6
+ require 'mongoid'
7
+ true
8
+ rescue LoadError
9
+ false
10
+ end
11
+
6
12
  Mongory.register(Array)
7
13
  Mongory.enable_symbol_snippets!
8
14
 
@@ -12,11 +18,15 @@ ROUNDS = 5
12
18
  records = Array.new(N) do |i|
13
19
  {
14
20
  'age' => 10 + (i % 50),
15
- 'status' => (i % 3).zero? ? 'active' : 'inactive'
21
+ 'status' => (i % 3).zero? ? 'active' : 'inactive',
22
+ 'name' => (i % 5).zero? ? "user#{'abcdef'[i % 6]}" : "other_#{i}",
23
+ 'tags' => (i % 4).zero? ? %w(ruby go) : %w(js c)
16
24
  }
17
25
  end
18
26
 
19
- puts "Ruby: #{RUBY_VERSION} (#{RUBY_PLATFORM}), records=#{N}, rounds=#{ROUNDS}"
27
+ LARGE_IN_TARGETS = ['usera', 'userb'] + Array.new(498) { |i| "other-#{i + 2}" }
28
+
29
+ puts "Ruby: #{RUBY_VERSION} (#{RUBY_PLATFORM}), records=#{N}, rounds=#{ROUNDS}, mongoid=#{HAS_MONGOID}"
20
30
 
21
31
  def bench(label)
22
32
  # Warmup
@@ -27,7 +37,7 @@ def bench(label)
27
37
  elapsed_ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0) * 1000.0) / ROUNDS
28
38
  ns_per_rec = (elapsed_ms * 1_000_000.0) / N
29
39
  puts format(
30
- '%<label>-34s %<ms>8.2f ms / 100k (%<ns>6.1f ns/rec, matched=%<count>d)',
40
+ '%<label>-38s %<ms>8.2f ms / 100k (%<ns>7.1f ns/rec, matched=%<count>d)',
31
41
  label: label,
32
42
  ms: elapsed_ms,
33
43
  ns: ns_per_rec,
@@ -35,6 +45,19 @@ def bench(label)
35
45
  )
36
46
  end
37
47
 
48
+ if HAS_MONGOID
49
+ class BenchDoc
50
+ include Mongoid::Document
51
+ field :age, type: Integer
52
+ field :status, type: String
53
+ field :name, type: String
54
+ field :tags, type: Array
55
+ end
56
+
57
+ mongoid_docs = records.map { |r| BenchDoc.new(r) }
58
+ end
59
+
60
+ # 1. simple
38
61
  bench('Plain Ruby (simple)') do
39
62
  records.count { |r| r['age'].is_a?(Numeric) && r['age'] >= 18 }
40
63
  end
@@ -44,6 +67,14 @@ bench('Mongory::Matcher (simple)') do
44
67
  records.count { |r| simple_m.match?(r) }
45
68
  end
46
69
 
70
+ if HAS_MONGOID
71
+ simple_expr = { 'age' => { '$gte' => 18 } }
72
+ bench('Mongoid::Matcher (simple)') do
73
+ mongoid_docs.count { |d| d._matches?(simple_expr) }
74
+ end
75
+ end
76
+
77
+ # 2. $or
47
78
  bench('Plain Ruby ($or)') do
48
79
  records.count { |r| (r['age'].is_a?(Numeric) && r['age'] >= 18) || r['status'] == 'active' }
49
80
  end
@@ -52,3 +83,45 @@ or_m = Mongory::Matcher.new({ :$or => [{ age: { :$gte => 18 } }, { status: 'acti
52
83
  bench('Mongory::Matcher ($or)') do
53
84
  records.count { |r| or_m.match?(r) }
54
85
  end
86
+
87
+ if HAS_MONGOID
88
+ or_expr = { '$or' => [{ 'age' => { '$gte' => 18 } }, { 'status' => 'active' }] }
89
+ bench('Mongoid::Matcher ($or)') do
90
+ mongoid_docs.count { |d| d._matches?(or_expr) }
91
+ end
92
+ end
93
+
94
+ # 3. $in on array field
95
+ bench('Plain Ruby (in_array_field)') do
96
+ records.count { |r| r['tags'].include?('ruby') || r['tags'].include?('rust') }
97
+ end
98
+
99
+ in_arr_m = Mongory::Matcher.new({ tags: { :$in => %w(ruby rust) } })
100
+ bench('Mongory::Matcher (in_array_field)') do
101
+ records.count { |r| in_arr_m.match?(r) }
102
+ end
103
+
104
+ if HAS_MONGOID
105
+ in_arr_expr = { 'tags' => { '$in' => %w(ruby rust) } }
106
+ bench('Mongoid::Matcher (in_array_field)') do
107
+ mongoid_docs.count { |d| d._matches?(in_arr_expr) }
108
+ end
109
+ end
110
+
111
+ # 4. large $in (500 items)
112
+ large_in_set = LARGE_IN_TARGETS.each_with_object({}) { |k, h| h[k] = true }
113
+ bench('Plain Ruby (large_in_500)') do
114
+ records.count { |r| large_in_set.key?(r['name']) }
115
+ end
116
+
117
+ large_in_m = Mongory::Matcher.new({ name: { :$in => LARGE_IN_TARGETS } })
118
+ bench('Mongory::Matcher (large_in_500)') do
119
+ records.count { |r| large_in_m.match?(r) }
120
+ end
121
+
122
+ if HAS_MONGOID
123
+ large_in_expr = { 'name' => { '$in' => LARGE_IN_TARGETS } }
124
+ bench('Mongoid::Matcher (large_in_500)') do
125
+ mongoid_docs.count { |d| d._matches?(large_in_expr) }
126
+ end
127
+ end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: mongory
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.0.1
4
+ version: 2.1.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - koten0224
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2026-11-22 00:00:00.000000000 Z
11
+ date: 2026-11-25 00:00:00.000000000 Z
12
12
  dependencies: []
13
13
  description: A Mongo-like in-memory query DSL for Ruby
14
14
  email:
@@ -108,6 +108,7 @@ files:
108
108
  - lib/mongory/utils/singleton_builder.rb
109
109
  - lib/mongory/utils/tree_renderer.rb
110
110
  - lib/mongory/version.rb
111
+ - renovate.json
111
112
  - script/bench.rb
112
113
  - scripts/build_with_core.sh
113
114
  - sig/mongory.rbs