mongory 0.8.2 → 0.9.0

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.
Files changed (41) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +31 -0
  3. data/docs/advanced_usage.md +7 -0
  4. data/docs/clang_bridge.md +6 -0
  5. data/ext/mongory_ext/extconf.rb +6 -1
  6. data/ext/mongory_ext/mongory-core/include/mongory-core/foundations/config.h +25 -0
  7. data/ext/mongory_ext/mongory-core/src/foundations/config.c +64 -27
  8. data/ext/mongory_ext/mongory-core/src/foundations/config_private.h +1 -0
  9. data/ext/mongory_ext/mongory-core/src/foundations/memory_pool.c +49 -0
  10. data/ext/mongory_ext/mongory-core/src/foundations/memory_pool_private.h +45 -0
  11. data/ext/mongory_ext/mongory-core/src/foundations/utils.c +2 -5
  12. data/ext/mongory_ext/mongory-core/src/foundations/value.c +44 -7
  13. data/ext/mongory_ext/mongory-core/src/matchers/array_record_matcher.c +31 -10
  14. data/ext/mongory_ext/mongory-core/src/matchers/base_matcher.c +2 -0
  15. data/ext/mongory_ext/mongory-core/src/matchers/compare_matcher.c +32 -13
  16. data/ext/mongory_ext/mongory-core/src/matchers/composite_matcher.c +34 -13
  17. data/ext/mongory_ext/mongory-core/src/matchers/external_matcher.c +76 -15
  18. data/ext/mongory_ext/mongory-core/src/matchers/external_matcher.h +12 -0
  19. data/ext/mongory_ext/mongory-core/src/matchers/literal_matcher.c +55 -17
  20. data/ext/mongory_ext/mongory_ext.c +35 -724
  21. data/ext/mongory_ext/mongory_ext_internal.h +75 -0
  22. data/ext/mongory_ext/rb_mongory_adapters.c +140 -0
  23. data/ext/mongory_ext/rb_mongory_cmatcher.c +386 -0
  24. data/ext/mongory_ext/rb_mongory_value.c +260 -0
  25. data/lib/generators/mongory/install/templates/initializer.rb.erb +5 -0
  26. data/lib/mongory/converters/abstract_converter.rb +6 -5
  27. data/lib/mongory/converters/condition_converter.rb +2 -2
  28. data/lib/mongory/matchers/abstract_matcher.rb +1 -1
  29. data/lib/mongory/matchers/abstract_multi_matcher.rb +2 -2
  30. data/lib/mongory/matchers/array_record_matcher.rb +23 -11
  31. data/lib/mongory/matchers/elem_match_matcher.rb +2 -0
  32. data/lib/mongory/matchers/eq_matcher.rb +4 -2
  33. data/lib/mongory/matchers/hash_condition_matcher.rb +23 -6
  34. data/lib/mongory/matchers/in_matcher.rb +17 -1
  35. data/lib/mongory/matchers/ne_matcher.rb +7 -6
  36. data/lib/mongory/matchers/nin_matcher.rb +2 -6
  37. data/lib/mongory/matchers/regex_matcher.rb +29 -0
  38. data/lib/mongory/matchers.rb +7 -4
  39. data/lib/mongory/version.rb +1 -1
  40. data/lib/mongory.rb +57 -5
  41. metadata +7 -2
@@ -0,0 +1,260 @@
1
+ /**
2
+ * @file rb_mongory_value.c
3
+ * @brief Ruby <-> mongory_value conversion, lazy wrappers, and key caches.
4
+ */
5
+ #include "mongory_ext_internal.h"
6
+ #include <string.h>
7
+
8
+ typedef struct {
9
+ mongory_table *table;
10
+ mongory_memory_pool *pool;
11
+ } hash_conv_ctx;
12
+
13
+ static char *rb_mongory_value_to_cstr(mongory_value *value, mongory_memory_pool *pool) {
14
+ (void)pool;
15
+ VALUE rb_value = (VALUE)value->origin;
16
+ VALUE rb_str = rb_funcall(rb_value, rb_intern("inspect"), 0);
17
+ return StringValueCStr(rb_str);
18
+ }
19
+
20
+ static mongory_value *rb_to_mongory_value_primitive(mongory_memory_pool *pool, VALUE rb_value) {
21
+ mongory_value *mg_value = NULL;
22
+ switch (TYPE(rb_value)) {
23
+ case T_NIL:
24
+ mg_value = mongory_value_wrap_n(pool, NULL);
25
+ break;
26
+
27
+ case T_TRUE:
28
+ mg_value = mongory_value_wrap_b(pool, true);
29
+ break;
30
+
31
+ case T_FALSE:
32
+ mg_value = mongory_value_wrap_b(pool, false);
33
+ break;
34
+
35
+ case T_FIXNUM:
36
+ mg_value = mongory_value_wrap_i(pool, rb_num2long_inline(rb_value));
37
+ break;
38
+
39
+ case T_BIGNUM:
40
+ mg_value = mongory_value_wrap_i(pool, rb_num2ll_inline(rb_value));
41
+ break;
42
+
43
+ case T_FLOAT:
44
+ mg_value = mongory_value_wrap_d(pool, rb_num2dbl(rb_value));
45
+ break;
46
+
47
+ case T_STRING:
48
+ mg_value = mongory_value_wrap_s(pool, StringValueCStr(rb_value));
49
+ break;
50
+
51
+ case T_SYMBOL:
52
+ mg_value = mongory_value_wrap_s(pool, (char *)rb_id2name(rb_sym2id(rb_value)));
53
+ break;
54
+
55
+ case T_REGEXP:
56
+ mg_value = mongory_value_wrap_regex(pool, (void *)rb_value);
57
+ break;
58
+ }
59
+ return mg_value;
60
+ }
61
+
62
+ static mongory_value *rb_to_mongory_value_shallow_rec(mongory_memory_pool *pool, VALUE rb_value, bool converted) {
63
+ mongory_value *mg_value = rb_to_mongory_value_primitive(pool, rb_value);
64
+ if (mg_value) {
65
+ mg_value->origin = rb_value;
66
+ return mg_value;
67
+ }
68
+
69
+ switch (TYPE(rb_value)) {
70
+ case T_ARRAY:
71
+ mg_value = rb_mongory_array_wrap(pool, rb_value);
72
+ break;
73
+
74
+ case T_HASH:
75
+ mg_value = rb_mongory_table_wrap(pool, rb_value);
76
+ break;
77
+
78
+ default:
79
+ if (converted) {
80
+ mg_value = mongory_value_wrap_u(pool, (void *)rb_value);
81
+ break;
82
+ } else {
83
+ VALUE converted_value = rb_funcall(rb_mongory_data_converter, rb_intern("convert"), 1, rb_value);
84
+ return rb_to_mongory_value_shallow_rec(pool, converted_value, true);
85
+ }
86
+ }
87
+ mg_value->origin = rb_value;
88
+ return mg_value;
89
+ }
90
+
91
+ mongory_value *rb_to_mongory_value_shallow(mongory_memory_pool *pool, VALUE rb_value) {
92
+ return rb_to_mongory_value_shallow_rec(pool, rb_value, false);
93
+ }
94
+
95
+ static int hash_foreach_deep_convert_cb(VALUE key, VALUE val, VALUE ptr) {
96
+ hash_conv_ctx *ctx = (hash_conv_ctx *)ptr;
97
+ rb_mongory_memory_pool_t *rb_pool = (rb_mongory_memory_pool_t *)ctx->pool;
98
+ rb_mongory_matcher_t *owner = rb_pool->owner;
99
+ mongory_table *store_map;
100
+ char *key_str;
101
+ if (SYMBOL_P(key)) {
102
+ key_str = (char *)rb_id2name(SYM2ID(key));
103
+ store_map = owner->symbol_map;
104
+ } else {
105
+ if (!RB_TYPE_P(key, T_STRING)) {
106
+ key = rb_obj_as_string(key);
107
+ }
108
+ key_str = StringValueCStr(key);
109
+ store_map = owner->string_map;
110
+ }
111
+ mongory_value *store = mongory_value_wrap_u(ctx->pool, NULL);
112
+ store->origin = (void *)key;
113
+ store_map->set(store_map, key_str, store);
114
+ owner->mark_list->push(owner->mark_list, store);
115
+ mongory_value *cval = rb_to_mongory_value_deep(ctx->pool, val);
116
+ ctx->table->set(ctx->table, key_str, cval);
117
+ return ST_CONTINUE;
118
+ }
119
+
120
+ static mongory_value *rb_to_mongory_value_deep_rec(mongory_memory_pool *pool, VALUE rb_value, bool converted) {
121
+ mongory_value *mg_value = rb_to_mongory_value_primitive(pool, rb_value);
122
+ if (mg_value) {
123
+ mg_value->origin = rb_value;
124
+ return mg_value;
125
+ }
126
+ switch (TYPE(rb_value)) {
127
+ case T_ARRAY: {
128
+ mongory_array *array = mongory_array_new(pool);
129
+
130
+ for (long i = 0; i < RARRAY_LEN(rb_value); i++) {
131
+ array->push(array, rb_to_mongory_value_deep(pool, RARRAY_AREF(rb_value, i)));
132
+ }
133
+ mg_value = mongory_value_wrap_a(pool, array);
134
+ break;
135
+ }
136
+
137
+ case T_HASH: {
138
+ mongory_table *table = mongory_table_new(pool);
139
+
140
+ hash_conv_ctx ctx = {table, pool};
141
+ rb_hash_foreach(rb_value, hash_foreach_deep_convert_cb, (VALUE)&ctx);
142
+
143
+ mg_value = mongory_value_wrap_t(pool, table);
144
+ break;
145
+ }
146
+
147
+ default:
148
+ if (converted) {
149
+ mg_value = mongory_value_wrap_u(pool, (void *)rb_value);
150
+ break;
151
+ } else {
152
+ VALUE converted_value = rb_funcall(rb_mongory_data_converter, rb_intern("convert"), 1, rb_value);
153
+ mg_value = rb_to_mongory_value_deep_rec(pool, converted_value, true);
154
+ break;
155
+ }
156
+ }
157
+ mg_value->origin = rb_value;
158
+ return mg_value;
159
+ }
160
+
161
+ mongory_value *rb_to_mongory_value_deep(mongory_memory_pool *pool, VALUE rb_value) {
162
+ return rb_to_mongory_value_deep_rec(pool, rb_value, false);
163
+ }
164
+
165
+ static mongory_value *rb_mongory_table_get(mongory_table *self, char *key) {
166
+ rb_mongory_table_t *table = (rb_mongory_table_t *)self;
167
+ VALUE rb_hash = table->rb_hash;
168
+ VALUE rb_value = Qundef;
169
+
170
+ VALUE key_str = rb_mongory_cache_fetch_string(table->owner, key);
171
+ rb_value = rb_hash_lookup2(rb_hash, key_str, Qundef);
172
+
173
+ if (rb_value == Qundef) {
174
+ VALUE key_sym = rb_mongory_cache_fetch_symbol(table->owner, key);
175
+ rb_value = rb_hash_lookup2(rb_hash, key_sym, Qundef);
176
+ }
177
+
178
+ if (rb_value == Qundef) {
179
+ return NULL;
180
+ }
181
+ return rb_to_mongory_value_shallow(table->base.pool, rb_value);
182
+ }
183
+
184
+ mongory_value *rb_mongory_table_wrap(mongory_memory_pool *pool, VALUE rb_hash) {
185
+ rb_mongory_table_t *table = MG_ALLOC_PTR(pool, rb_mongory_table_t);
186
+ rb_mongory_memory_pool_t *rb_pool = (rb_mongory_memory_pool_t *)pool;
187
+ table->base.pool = pool;
188
+ table->base.get = rb_mongory_table_get;
189
+ table->rb_hash = rb_hash;
190
+ table->base.count = RHASH_SIZE(rb_hash);
191
+ table->owner = rb_pool->owner;
192
+ mongory_value *mg_value = mongory_value_wrap_t(pool, &table->base);
193
+ mg_value->origin = (void *)rb_hash;
194
+ mg_value->to_str = rb_mongory_value_to_cstr;
195
+ return mg_value;
196
+ }
197
+
198
+ static mongory_value *rb_mongory_array_get(mongory_array *self, size_t index) {
199
+ rb_mongory_array_t *array = (rb_mongory_array_t *)self;
200
+ VALUE rb_array = array->rb_array;
201
+ if (index >= (size_t)RARRAY_LEN(rb_array)) {
202
+ return NULL;
203
+ }
204
+ VALUE rb_value = rb_ary_entry(rb_array, index);
205
+ return rb_to_mongory_value_shallow(self->pool, rb_value);
206
+ }
207
+
208
+ mongory_value *rb_mongory_array_wrap(mongory_memory_pool *pool, VALUE rb_array) {
209
+ rb_mongory_array_t *array = MG_ALLOC_PTR(pool, rb_mongory_array_t);
210
+ rb_mongory_memory_pool_t *rb_pool = (rb_mongory_memory_pool_t *)pool;
211
+ array->base.pool = pool;
212
+ array->base.get = rb_mongory_array_get;
213
+ array->rb_array = rb_array;
214
+ array->base.count = RARRAY_LEN(rb_array);
215
+ array->owner = rb_pool->owner;
216
+ mongory_value *mg_value = mongory_value_wrap_a(pool, &array->base);
217
+ mg_value->origin = (void *)rb_array;
218
+ mg_value->to_str = rb_mongory_value_to_cstr;
219
+ return mg_value;
220
+ }
221
+
222
+ void *mongory_value_to_ruby(mongory_memory_pool *pool, mongory_value *value) {
223
+ (void)pool;
224
+ if (!value)
225
+ return NULL;
226
+ return value->origin;
227
+ }
228
+
229
+ VALUE rb_mongory_cache_fetch_string(rb_mongory_matcher_t *owner, const char *key) {
230
+ if (!owner || !owner->string_map) return rb_utf8_str_new_cstr(key);
231
+ mongory_value *v = owner->string_map->get(owner->string_map, (char *)key);
232
+ if (v && v->origin) return (VALUE)v->origin;
233
+ VALUE s = rb_utf8_str_new_cstr(key);
234
+ mongory_value *store = mongory_value_wrap_u(owner->pool, NULL);
235
+ store->origin = (void *)s;
236
+ owner->string_map->set(owner->string_map, (char *)key, store);
237
+ owner->mark_list->push(owner->mark_list, store);
238
+ return s;
239
+ }
240
+
241
+ static inline VALUE char_key_to_symbol(const char *key, rb_encoding *enc) {
242
+ ID id = rb_check_id_cstr(key, (long)strlen(key), enc);
243
+ if (!id) id = rb_intern3(key, (long)strlen(key), enc);
244
+ return ID2SYM(id);
245
+ }
246
+
247
+ VALUE rb_mongory_cache_fetch_symbol(rb_mongory_matcher_t *owner, const char *key) {
248
+ rb_encoding *enc = rb_utf8_encoding();
249
+ if (!owner || !owner->symbol_map) {
250
+ return char_key_to_symbol(key, enc);
251
+ }
252
+ mongory_value *v = owner->symbol_map->get(owner->symbol_map, (char *)key);
253
+ if (v && v->origin) return (VALUE)v->origin;
254
+ VALUE sym = char_key_to_symbol(key, enc);
255
+ mongory_value *store = mongory_value_wrap_u(owner->pool, NULL);
256
+ store->origin = (void *)sym;
257
+ owner->symbol_map->set(owner->symbol_map, (char *)key, store);
258
+ owner->mark_list->push(owner->mark_list, store);
259
+ return sym;
260
+ }
@@ -31,6 +31,11 @@ Mongory.configure do |mc|
31
31
  # It only defines missing ones, and is safe to use with Mongoid or other libraries.
32
32
  mc.enable_symbol_snippets!
33
33
 
34
+ # Here to use the C extension (`Mongory::CQueryBuilder`) by default for `.mongory` and `Mongory.build_query`.
35
+ # If the C extension is not available on the current platform, it automatically falls back to pure Ruby.
36
+ # Comment this out if you prefer using the pure Ruby implementation by default (you can still opt in per query via `.mongory.c`).
37
+ mc.enable_c_extension_by_default!
38
+
34
39
  # Here to let you use `some_collection.mongory.where(...)` to build mongory query filter.
35
40
  # Or disable it, and use `Mongory.build_query(some_collection).where(...)` instead.
36
41
  mc.register(Array)
@@ -27,7 +27,7 @@ module Mongory
27
27
 
28
28
  # @private
29
29
  # A sentinel value used to indicate absence of a secondary argument.
30
- NOTHING = Utils::SingletonBuilder.new('NOTHING')
30
+ NOTHING = Utils::SingletonBuilder.new('NOTHING').freeze
31
31
 
32
32
  # Initializes the builder with a label and optional configuration block.
33
33
  def initialize
@@ -76,14 +76,15 @@ module Mongory
76
76
  # @return [void]
77
77
  def configure
78
78
  yield self
79
- freeze
80
79
  end
81
80
 
82
- # Freezes all internal registries.
81
+ # Freezes the converter and all internal registries.
83
82
  #
84
- # @return [void]
83
+ # @return [self]
85
84
  def freeze
85
+ @registries.each(&:freeze)
86
86
  @registries.freeze
87
+ super
87
88
  end
88
89
 
89
90
  # Registers a conversion rule for a given class.
@@ -100,7 +101,7 @@ module Mongory
100
101
  if converter.is_a?(Symbol)
101
102
  register(klass) { |*args, &bl| send(converter, *args, &bl) }
102
103
  elsif block.is_a?(Proc)
103
- @registries.unshift(Registry.new(klass, block))
104
+ @registries.unshift(Registry.new(klass, block).freeze)
104
105
  @convert_strategy_map[klass] = block
105
106
  else
106
107
  raise 'Support Symbol and block only.'
@@ -51,11 +51,11 @@ module Mongory
51
51
 
52
52
  # Freezes internal converters to prevent further modification.
53
53
  #
54
- # @return [void]
54
+ # @return [self]
55
55
  def freeze
56
- super
57
56
  key_converter.freeze
58
57
  value_converter.freeze
58
+ super
59
59
  end
60
60
 
61
61
  undef_method :register
@@ -38,7 +38,7 @@ module Mongory
38
38
  # This is used instead of nil to distinguish between missing keys and nil values.
39
39
  #
40
40
  # @api private
41
- KEY_NOT_FOUND = SingletonBuilder.new('KEY_NOT_FOUND')
41
+ KEY_NOT_FOUND = SingletonBuilder.new('KEY_NOT_FOUND').freeze
42
42
 
43
43
  # Defines a lazily-evaluated matcher accessor with instance-level caching.
44
44
  # This is used to create cached accessors for submatcher instances.
@@ -18,11 +18,11 @@ module Mongory
18
18
  class AbstractMultiMatcher < AbstractMatcher
19
19
  # A Proc that always returns true, used as a default for empty AND conditions
20
20
  # @return [Proc] A proc that always returns true
21
- TRUE_PROC = Proc.new { |_| true }
21
+ TRUE_PROC = Proc.new { |_| true }.freeze
22
22
 
23
23
  # A Proc that always returns false, used as a default for empty OR conditions
24
24
  # @return [Proc] A proc that always returns false
25
- FALSE_PROC = Proc.new { |_| false }
25
+ FALSE_PROC = Proc.new { |_| false }.freeze
26
26
 
27
27
  # Enables auto-unwrap logic.
28
28
  # When used, `.build` may unwrap to first matcher if only one is present.
@@ -59,13 +59,17 @@ module Mongory
59
59
  result.sort_by(&:priority)
60
60
  end
61
61
 
62
+ ELEM_MATCH_OPERATORS = %w($gt $gte $lt $lte $regex).freeze
63
+
62
64
  private
63
65
 
64
66
  # Parses the original condition hash into a normalized structure suitable for HashConditionMatcher.
65
67
  #
66
68
  # This method classifies keys in the condition hash as:
67
69
  # - Numeric (integers or numeric strings): treated as index-based field matchers
68
- # - Operator keys (e.g., `$size`, `$type`): retained at the top level
70
+ # - Element-level comparison operators (`$gt`, `$gte`, `$lt`, `$lte`, `$regex`, non-array `$eq`):
71
+ # grouped under `$elemMatch`
72
+ # - Container-level operator keys (e.g., `$size`, `$in`, `$nin`, `$every`, `$ne`): retained at the top level
69
73
  # - All other keys: grouped under a `$elemMatch` clause for element-wise comparison
70
74
  #
71
75
  # @return [Hash] A normalized condition hash, potentially containing `$elemMatch`
@@ -73,21 +77,29 @@ module Mongory
73
77
  h_parsed = {}
74
78
  h_elem_match = {}
75
79
  @condition.each_pair do |key, value|
76
- case key
77
- when Integer, FieldMatcher::INTEGER_INDEX_REGEX
78
- h_parsed[key.to_i] = value
79
- when '$elemMatch'
80
- h_elem_match.merge!(value)
81
- when *Matchers.operators
82
- h_parsed[key] = value
83
- else
84
- h_elem_match[key] = value
85
- end
80
+ parse_condition_pair(key, value, h_parsed, h_elem_match)
86
81
  end
87
82
 
88
83
  h_parsed['$elemMatch'] = h_elem_match if is_present?(h_elem_match)
89
84
  h_parsed
90
85
  end
86
+
87
+ def parse_condition_pair(key, value, h_parsed, h_elem_match)
88
+ case key
89
+ when Integer, FieldMatcher::INTEGER_INDEX_REGEX
90
+ h_parsed[key.to_i] = value
91
+ when '$elemMatch'
92
+ value.is_a?(Hash) ? h_elem_match.merge!(value) : h_parsed[key] = value
93
+ when *Matchers.operators
94
+ elem_match_operator?(key, value) ? h_elem_match[key] = value : h_parsed[key] = value
95
+ else
96
+ h_elem_match[key] = value
97
+ end
98
+ end
99
+
100
+ def elem_match_operator?(key, value)
101
+ ELEM_MATCH_OPERATORS.include?(key) || (key == '$eq' && !value.is_a?(Array))
102
+ end
91
103
  end
92
104
  end
93
105
  end
@@ -28,6 +28,8 @@ module Mongory
28
28
  data_converter = Mongory.data_converter
29
29
 
30
30
  Proc.new do |collection|
31
+ next false unless collection.is_a?(Array)
32
+
31
33
  collection.any? do |record|
32
34
  record = data_converter.convert(record) if need_convert
33
35
  super_proc.call(record)
@@ -4,7 +4,8 @@ module Mongory
4
4
  module Matchers
5
5
  # EqMatcher matches values using the equality operator `==`.
6
6
  #
7
- # It inherits from AbstractMatcher and defines its operator as `:==`.
7
+ # If the target record is an `Array`, it matches when either the array itself
8
+ # equals the condition or any element in the array equals the condition.
8
9
  #
9
10
  # Used for conditions like:
10
11
  # - { age: { '$eq' => 30 } }
@@ -15,6 +16,7 @@ module Mongory
15
16
  # @example
16
17
  # matcher = EqMatcher.build(42)
17
18
  # matcher.match?(42) #=> true
19
+ # matcher.match?([10, 42]) #=> true
18
20
  # matcher.match?("42") #=> false
19
21
  #
20
22
  # @note This matcher is also used as the fallback for non-operator literal values,
@@ -32,7 +34,7 @@ module Mongory
32
34
  condition = @condition
33
35
 
34
36
  Proc.new do |record|
35
- record == condition
37
+ record == condition || (record.is_a?(Array) && record.include?(condition))
36
38
  end
37
39
  end
38
40
 
@@ -38,18 +38,19 @@ module Mongory
38
38
  # Returns the list of matchers for each key-value pair in the condition.
39
39
  #
40
40
  # For each pair:
41
+ # - `$regex` with a sibling `$options` builds a RegexMatcher with those flags
41
42
  # - If the key is a registered operator, uses the corresponding matcher
43
+ # - An unknown `$` key raises, as MongoDB rejects unknown operators
42
44
  # - Otherwise, wraps the value in a FieldMatcher for field path matching
43
45
  #
44
46
  # @return [Array<AbstractMatcher>] List of matchers for each condition
47
+ # @raise [TypeError] for an unknown operator or a `$options` without `$regex`
45
48
  define_instance_cache_method(:matchers) do
46
49
  @condition.map do |key, value|
47
- if (matcher_class = Matchers.lookup(key))
48
- matcher_class.build(value, context: @context)
49
- else
50
- FieldMatcher.build(key, value, context: @context)
51
- end
52
- end.sort_by(&:priority)
50
+ next if key == '$options' && @condition.key?('$regex')
51
+
52
+ build_matcher(key, value)
53
+ end.compact.sort_by(&:priority)
53
54
  end
54
55
 
55
56
  def check_validity!
@@ -57,6 +58,22 @@ module Mongory
57
58
 
58
59
  raise TypeError, 'condition needs a Hash.'
59
60
  end
61
+
62
+ private
63
+
64
+ def build_matcher(key, value)
65
+ if key == '$regex' && @condition.key?('$options')
66
+ RegexMatcher.build(RegexMatcher.apply_options(value, @condition['$options']), context: @context)
67
+ elsif (matcher_class = Matchers.lookup(key))
68
+ matcher_class.build(value, context: @context)
69
+ elsif key == '$options'
70
+ raise TypeError, '$options needs a sibling $regex'
71
+ elsif key.to_s.start_with?('$')
72
+ raise TypeError, "unknown operator #{key}"
73
+ else
74
+ FieldMatcher.build(key, value, context: @context)
75
+ end
76
+ end
60
77
  end
61
78
  end
62
79
  end
@@ -37,7 +37,7 @@ module Mongory
37
37
  #
38
38
  # @return [Proc] a Proc that performs the in-matching operation
39
39
  def raw_proc
40
- condition = Set.new(@condition)
40
+ condition = build_condition_set
41
41
 
42
42
  Proc.new do |record|
43
43
  if record.is_a?(Array)
@@ -61,6 +61,22 @@ module Mongory
61
61
 
62
62
  raise TypeError, '$in needs an array or range'
63
63
  end
64
+
65
+ private
66
+
67
+ def build_condition_set
68
+ Set.new(@condition).tap do |set|
69
+ @condition.each do |item|
70
+ if item.is_a?(Integer)
71
+ float_val = item.to_f
72
+ set.add(float_val) if float_val == item
73
+ elsif item.is_a?(Float) && item.finite?
74
+ int_val = item.to_i
75
+ set.add(int_val) if int_val == item
76
+ end
77
+ end
78
+ end
79
+ end
64
80
  end
65
81
 
66
82
  register(:in, '$in', InMatcher)
@@ -5,14 +5,15 @@ module Mongory
5
5
  # NeMatcher implements the `$ne` (not equal) operator.
6
6
  #
7
7
  # It returns true if the record is *not equal* to the condition.
8
- #
9
- # This matcher inherits its logic from AbstractMatcher
10
- # and uses Ruby's `!=` operator for comparison.
8
+ # If the record is an `Array`, it returns false if either the array itself
9
+ # equals the condition or any element in the array equals the condition.
11
10
  #
12
11
  # @example
13
12
  # matcher = NeMatcher.build(42)
14
- # matcher.match?(41) #=> true
15
- # matcher.match?(42) #=> false
13
+ # matcher.match?(41) #=> true
14
+ # matcher.match?(42) #=> false
15
+ # matcher.match?([10, 42]) #=> false
16
+ # matcher.match?([10, 20]) #=> true
16
17
  #
17
18
  # @see AbstractMatcher
18
19
  class NeMatcher < AbstractMatcher
@@ -24,7 +25,7 @@ module Mongory
24
25
  condition = @condition
25
26
 
26
27
  Proc.new do |record|
27
- record != condition
28
+ record != condition && !(record.is_a?(Array) && record.include?(condition))
28
29
  end
29
30
  end
30
31
 
@@ -23,7 +23,7 @@ module Mongory
23
23
  # matcher.match?([4, 5]) #=> false
24
24
  #
25
25
  # @see AbstractMatcher
26
- class NinMatcher < AbstractMatcher
26
+ class NinMatcher < InMatcher
27
27
  def self.build(condition, context: Context.new)
28
28
  return super unless condition.is_a?(Range)
29
29
 
@@ -37,7 +37,7 @@ module Mongory
37
37
  #
38
38
  # @return [Proc] A proc that performs not-in matching
39
39
  def raw_proc
40
- condition = Set.new(@condition)
40
+ condition = build_condition_set
41
41
 
42
42
  Proc.new do |record|
43
43
  if record.is_a?(Array)
@@ -48,10 +48,6 @@ module Mongory
48
48
  end
49
49
  end
50
50
 
51
- def priority
52
- 1 + Math.log(@condition.size + 1, 1.5)
53
- end
54
-
55
51
  # Ensures the condition is a valid array or range.
56
52
  #
57
53
  # @raise [TypeError] if the condition is not an array nor a range
@@ -31,6 +31,35 @@ module Mongory
31
31
  #
32
32
  # @see AbstractMatcher
33
33
  class RegexMatcher < AbstractMatcher
34
+ # MongoDB `$options` flags mapped to Ruby. Ruby's `^`/`$` always match at
35
+ # line boundaries, so `m` needs no flag; Ruby's MULTILINE is MongoDB's `s`.
36
+ OPTION_FLAGS = {
37
+ 'i' => Regexp::IGNORECASE,
38
+ 'm' => 0,
39
+ 's' => Regexp::MULTILINE
40
+ }.freeze
41
+
42
+ # Compiles a `$regex` pattern string with MongoDB `$options` flags.
43
+ #
44
+ # @param pattern [String, Regexp, Object] the `$regex` value
45
+ # @param options [Object] the `$options` value
46
+ # @return [Regexp, Object] the compiled Regexp, or a non-string pattern
47
+ # unchanged so that check_validity! reports it
48
+ # @raise [TypeError] if options is invalid or pattern is already a Regexp
49
+ def self.apply_options(pattern, options)
50
+ raise TypeError, '$options needs a string' unless options.is_a?(String)
51
+
52
+ flags = options.each_char.reduce(0) do |result, char|
53
+ raise TypeError, "unsupported $options flag #{char.inspect}" unless OPTION_FLAGS.key?(char)
54
+
55
+ result | OPTION_FLAGS[char]
56
+ end
57
+ raise TypeError, '$options cannot modify a Regexp' if pattern.is_a?(Regexp)
58
+ return pattern unless pattern.is_a?(String)
59
+
60
+ Regexp.new(pattern, flags)
61
+ end
62
+
34
63
  # Initializes the matcher with a regex pattern.
35
64
  # Converts string patterns to Regexp objects.
36
65
  #
@@ -16,6 +16,7 @@ module Mongory
16
16
  module Matchers
17
17
  @operator_mapping = {}
18
18
  @registries = []
19
+ @enable_symbol_snippets = false
19
20
 
20
21
  # Registers a matcher class for a given operator and method symbol.
21
22
  #
@@ -26,11 +27,11 @@ module Mongory
26
27
  # @raise [ArgumentError] if validations fail
27
28
  def self.register(method_sym, operator, klass)
28
29
  Validator.validate_method(method_sym)
29
- Validator.validate_operator(operator)
30
+ Validator.validate_operator(operator, klass)
30
31
  Validator.validate_class(klass)
31
32
 
32
33
  @operator_mapping[operator] = klass
33
- registry = Registry.new(method_sym, operator)
34
+ registry = Registry.new(method_sym, operator).freeze
34
35
  @registries << registry
35
36
  return unless @enable_symbol_snippets
36
37
 
@@ -62,9 +63,10 @@ module Mongory
62
63
  end
63
64
 
64
65
  def self.freeze
65
- super
66
+ @registries.each(&:freeze)
66
67
  @operator_mapping.freeze
67
68
  @registries.freeze
69
+ super
68
70
  end
69
71
 
70
72
  # @private
@@ -85,9 +87,10 @@ module Mongory
85
87
  # Warns on duplicate registration.
86
88
  #
87
89
  # @param operator [String]
90
+ # @param klass [Class, nil]
88
91
  # @return [void]
89
92
  # @raise [Mongory::TypeError] if operator format is invalid
90
- def self.validate_operator(operator)
93
+ def self.validate_operator(operator, klass = nil)
91
94
  if Matchers.lookup(operator)
92
95
  warn "Duplicate operator registration: #{operator} (#{Matchers.lookup(operator)} vs #{klass})"
93
96
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Mongory
4
- VERSION = '0.8.2'
4
+ VERSION = '0.9.0'
5
5
  end