mongory 2.1.0-x86_64-linux → 2.2.0-x86_64-linux

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 (76) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +30 -0
  3. data/README.md +55 -73
  4. data/docs/clang_bridge.md +2 -2
  5. data/docs/performance.md +43 -7
  6. data/lib/core/2.6/mongory_ext.so +0 -0
  7. data/lib/core/2.7/mongory_ext.so +0 -0
  8. data/lib/core/3.0/mongory_ext.so +0 -0
  9. data/lib/core/3.1/mongory_ext.so +0 -0
  10. data/lib/core/3.2/mongory_ext.so +0 -0
  11. data/lib/core/3.3/mongory_ext.so +0 -0
  12. data/lib/core/3.4/mongory_ext.so +0 -0
  13. data/lib/core/4.0/mongory_ext.so +0 -0
  14. data/lib/mongory/converters/abstract_converter.rb +5 -5
  15. data/lib/mongory/converters/converted.rb +0 -4
  16. data/lib/mongory/converters/key_converter.rb +13 -36
  17. data/lib/mongory/converters/value_converter.rb +4 -4
  18. data/lib/mongory/matchers.rb +8 -7
  19. data/lib/mongory/query_builder.rb +9 -0
  20. data/lib/mongory/utils/context.rb +0 -6
  21. data/lib/mongory/utils/singleton_builder.rb +1 -4
  22. data/lib/mongory/version.rb +1 -1
  23. data/lib/mongory.rb +0 -1
  24. data/mongory.gemspec +13 -12
  25. data/script/bench.rb +77 -4
  26. data/script/coverage.rb +84 -0
  27. metadata +9 -54
  28. data/ext/mongory_ext/extconf.rb +0 -115
  29. data/ext/mongory_ext/mongory-core/include/mongory-core/adapters/json.h +0 -62
  30. data/ext/mongory_ext/mongory-core/include/mongory-core/foundations/array.h +0 -122
  31. data/ext/mongory_ext/mongory-core/include/mongory-core/foundations/config.h +0 -217
  32. data/ext/mongory_ext/mongory-core/include/mongory-core/foundations/error.h +0 -82
  33. data/ext/mongory_ext/mongory-core/include/mongory-core/foundations/memory_pool.h +0 -115
  34. data/ext/mongory_ext/mongory-core/include/mongory-core/foundations/table.h +0 -127
  35. data/ext/mongory_ext/mongory-core/include/mongory-core/foundations/value.h +0 -175
  36. data/ext/mongory_ext/mongory-core/include/mongory-core/matchers/matcher.h +0 -103
  37. data/ext/mongory_ext/mongory-core/include/mongory-core.h +0 -12
  38. data/ext/mongory_ext/mongory-core/src/foundations/array.c +0 -336
  39. data/ext/mongory_ext/mongory-core/src/foundations/array_private.h +0 -20
  40. data/ext/mongory_ext/mongory-core/src/foundations/config.c +0 -335
  41. data/ext/mongory_ext/mongory-core/src/foundations/config_private.h +0 -49
  42. data/ext/mongory_ext/mongory-core/src/foundations/error.c +0 -48
  43. data/ext/mongory_ext/mongory-core/src/foundations/memory_pool.c +0 -406
  44. data/ext/mongory_ext/mongory-core/src/foundations/memory_pool_private.h +0 -45
  45. data/ext/mongory_ext/mongory-core/src/foundations/string_buffer.c +0 -117
  46. data/ext/mongory_ext/mongory-core/src/foundations/string_buffer.h +0 -43
  47. data/ext/mongory_ext/mongory-core/src/foundations/table.c +0 -502
  48. data/ext/mongory_ext/mongory-core/src/foundations/utils.c +0 -206
  49. data/ext/mongory_ext/mongory-core/src/foundations/utils.h +0 -77
  50. data/ext/mongory_ext/mongory-core/src/foundations/value.c +0 -548
  51. data/ext/mongory_ext/mongory-core/src/matchers/base_matcher.c +0 -193
  52. data/ext/mongory_ext/mongory-core/src/matchers/base_matcher.h +0 -117
  53. data/ext/mongory_ext/mongory-core/src/matchers/compare_matcher.c +0 -241
  54. data/ext/mongory_ext/mongory-core/src/matchers/compare_matcher.h +0 -83
  55. data/ext/mongory_ext/mongory-core/src/matchers/composite_matcher.c +0 -730
  56. data/ext/mongory_ext/mongory-core/src/matchers/composite_matcher.h +0 -131
  57. data/ext/mongory_ext/mongory-core/src/matchers/existence_matcher.c +0 -158
  58. data/ext/mongory_ext/mongory-core/src/matchers/existence_matcher.h +0 -48
  59. data/ext/mongory_ext/mongory-core/src/matchers/external_matcher.c +0 -199
  60. data/ext/mongory_ext/mongory-core/src/matchers/external_matcher.h +0 -58
  61. data/ext/mongory_ext/mongory-core/src/matchers/implicit_array_matcher.c +0 -204
  62. data/ext/mongory_ext/mongory-core/src/matchers/implicit_array_matcher.h +0 -47
  63. data/ext/mongory_ext/mongory-core/src/matchers/inclusion_matcher.c +0 -124
  64. data/ext/mongory_ext/mongory-core/src/matchers/inclusion_matcher.h +0 -46
  65. data/ext/mongory_ext/mongory-core/src/matchers/matcher.c +0 -529
  66. data/ext/mongory_ext/mongory-core/src/matchers/matcher_explainable.c +0 -117
  67. data/ext/mongory_ext/mongory-core/src/matchers/matcher_explainable.h +0 -29
  68. data/ext/mongory_ext/mongory-core/src/matchers/matcher_traversable.c +0 -61
  69. data/ext/mongory_ext/mongory-core/src/matchers/matcher_traversable.h +0 -23
  70. data/ext/mongory_ext/mongory-core/src/matchers/value_matcher.c +0 -416
  71. data/ext/mongory_ext/mongory-core/src/matchers/value_matcher.h +0 -97
  72. data/ext/mongory_ext/mongory_ext.c +0 -66
  73. data/ext/mongory_ext/mongory_ext_internal.h +0 -74
  74. data/ext/mongory_ext/rb_mongory_adapters.c +0 -140
  75. data/ext/mongory_ext/rb_mongory_matcher.c +0 -440
  76. data/ext/mongory_ext/rb_mongory_value.c +0 -327
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b2f42ef3e29de6eddae44a1f6a89f4131080d6caaabe91feac496c66b65793f4
4
- data.tar.gz: 635eb9ae306c9ed61ec67afc12d7ecdb123d5ed621ba8ff61435fc05388b156f
3
+ metadata.gz: '0969168a61c2c0936894de179b27482a6d3a1186f7443d309242fc960d594ba8'
4
+ data.tar.gz: 6c44950a2ecdbc43a7033ec3ac0f3e06d869f3636bca8cdbe230bb3f62e5343e
5
5
  SHA512:
6
- metadata.gz: 97e169a3eefa07d0910458382dd3c41711e33a77a4b28e5285b0cb65c676b0d971fa3b3bfbe5aeab568942ee247747ed081c6e506f4c1ed7a1c82359a61dcecb
7
- data.tar.gz: 6691a6abad840bd78933d985d9e4d317626ec205e0ea2b35a49146ae133044750963f460b600acb3db698cb450a0fad2b5a5ea61b968012603ba7a42e8fa937a
6
+ metadata.gz: 6d1e4484683ed8b4a30f3ef468e000d5934042c0730cc8d2e0073fc9b9936387445a646b4c4109bd8f5b639e48e84d52f6403b03c5a49e93a939c47d84f7e58d
7
+ data.tar.gz: 5d717dfaa2a2ae8b36f6e2e7281e20b92c9f87052e028d32b24913045d2b92c8d1b5b4eae5fed348da16d418ee1eda1bd30a084e225947fa9f7ce6c22c04910e
data/CHANGELOG.md CHANGED
@@ -1,5 +1,35 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.2.0] - 2026-12-04
4
+
5
+ ### Added
6
+ - **`$nor` operator**: `$nor` via `mongory-core`, plus `QueryBuilder#nor`.
7
+ - **Memory accounting**: native matchers report their pool memory to the Ruby GC (`TypedData` `dsize`).
8
+
9
+ ### Changed
10
+ - **`null` means explicit `nil` or a missing key (`mongory-spec v0.5.0`)**: `{ a: { '$eq' => nil } }` and `{ a: { '$in' => [nil] } }` now match a missing key, like `{ a: nil }`. `{ a: { '$ne' => nil } }` and `$nin` with `nil` no longer match a missing key, and on a path through an array they fail when any element lacks the key.
11
+ - **Missing parents**: a nested field whose parent is missing or not a Hash or Array now counts as missing for every operator (for example `{ 'profile.address' => { '$present' => false } }` matches `{}`).
12
+ - Bumped the `ext/mongory_ext/mongory-core` submodule to `v0.4.0`.
13
+ - Dotted-key expansion is delegated to `mongory-core`.
14
+
15
+ ### Fixed
16
+ - An explicit empty `$elemMatch` on an array field no longer matches an empty array.
17
+ - Hardened GC/trace safety, custom matcher `NULL` values, and converter edge cases.
18
+
19
+ ### Packaging
20
+ - Release builds true per-arch native gems and smoke-tests a clean-room install on all 8 platforms.
21
+
22
+ ### Docs
23
+ - README links the full [Differences from MongoDB](https://github.com/mongoryhq/mongory-spec/blob/main/docs/mongodb-differences.md) page.
24
+
25
+ ## [2.1.1] - 2026-11-25
26
+
27
+ ### Performance
28
+ - **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).
29
+
30
+ ### Docs & Benchmarks
31
+ - Added optional `Mongoid::Matcher` comparison to `script/bench.rb` and updated `docs/performance.md`.
32
+
3
33
  ## [2.1.0] - 2026-11-23
4
34
 
5
35
  ### Added
data/README.md CHANGED
@@ -1,21 +1,19 @@
1
1
  # Mongory (Ruby)
2
2
 
3
- **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).
3
+ [![Gem Version](https://img.shields.io/gem/v/mongory)](https://rubygems.org/gems/mongory)
4
+ [![API Docs](https://img.shields.io/badge/API%20Docs-YARD-CC342D)](https://mongoryhq.github.io/mongory-rb/)
5
+ [![CI](https://github.com/mongoryhq/mongory-rb/actions/workflows/main.yml/badge.svg)](https://github.com/mongoryhq/mongory-rb/actions/workflows/main.yml)
6
+ [![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)
7
+ ![Ruby](https://img.shields.io/badge/Ruby-2.6%2B-CC342D)
8
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
4
9
 
5
- **[Try the Interactive Playground & Visual Explain/Trace Debugger ↗](https://mongoryhq.github.io/mongory-central/)**
10
+ **Zero-dependency, C99-backed in-memory MongoDB-style query and rule engine for Ruby**, with built-in `explain` / `trace` debugging and cross-language parity via [`mongory-spec`](https://github.com/mongoryhq/mongory-spec).
6
11
 
7
- [![Mongory Playground & Visual Trace](https://mongoryhq.github.io/mongory-central/playground-trace.png)](https://mongoryhq.github.io/mongory-central/)
12
+ **[Try the Interactive Playground & Visual Explain/Trace Debugger ↗](https://mongoryhq.github.io/mongory-central/?ref=mongory-rb-readme)**
8
13
 
9
- > **Zero database required:** Evaluate MongoDB-style conditions (`$gte`, `$elemMatch`, `$every`, `$present`, `$regex`, etc.) directly against in-memory Ruby Arrays, Hashes, custom objects, and ActiveRecord/Mongoid relations.
10
- > **Ecosystem:** [Interactive Playground](https://mongoryhq.github.io/mongory-central/) · [`mongory-go` (Go)](https://github.com/mongoryhq/mongory-go) · [`mongory-js` (TypeScript/JS)](https://github.com/mongoryhq/mongory-js) · [`mongory-core` (C99)](https://github.com/mongoryhq/mongory-core) · [`mongory-spec`](https://github.com/mongoryhq/mongory-spec)
14
+ [![Mongory Playground & Visual Trace](https://mongoryhq.github.io/mongory-central/playground-trace.png)](https://mongoryhq.github.io/mongory-central/?ref=mongory-rb-readme)
11
15
 
12
- ## Features
13
-
14
- - **Chainable Ruby DSL & Raw JSON Support**: Compose queries with `.where`, `.any_of`, `.or`, `.not`, and optional Symbol snippets (`:age.gte => 18`), or pass parsed JSON conditions directly from front-end rules.
15
- - **All 17 Mongory Operators**: `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`, `$in`, `$nin`, `$exists`, `$present`, `$and`, `$or`, `$not`, `$elemMatch`, `$every`, `$size`, `$regex` (with `$options`: `i`, `m`, `s`).
16
- - **Priority-Ordered Execution & Visual Debugging**: Automatically sorts sibling conditions so cheaper checks short-circuit before expensive regex or array scans; inspect compiled trees with `.explain` and per-record evaluation with `.trace`.
17
- - **Native C99 Engine (`Mongory::Matcher`)**: Powered directly by `mongory-core` with zero Pure-Ruby engine overhead, while still supporting custom Ruby matchers via `Mongory::Matchers::AbstractMatcher`.
18
- - **Precompiled Native Gems (Ruby 2.6–4.0)**: Ships prebuilt binaries for Linux (`x86_64`/`aarch64`, glibc & musl), macOS (`x86_64`/`arm64`), and Windows (`x64-mingw32`/`ucrt`).
16
+ > **Ecosystem:** [Playground](https://mongoryhq.github.io/mongory-central/?ref=mongory-rb-readme) · [`mongory-go` (Go)](https://github.com/mongoryhq/mongory-go) · [`mongory-js` (TypeScript/JS)](https://github.com/mongoryhq/mongory-js) · [`mongory-py` (Python)](https://github.com/mongoryhq/mongory-py) · [`mongory-core` (C99)](https://github.com/mongoryhq/mongory-core) · [`mongory-spec`](https://github.com/mongoryhq/mongory-spec)
19
17
 
20
18
  ## Installation
21
19
 
@@ -25,13 +23,14 @@ gem install mongory
25
23
  gem 'mongory'
26
24
  ```
27
25
 
28
- In a Rails project, generate the initializer (`config/initializers/mongory.rb`):
26
+ The gem ships precompiled native binaries (Ruby `2.6-4.0`) for Linux (`x86_64`/`aarch64`, glibc and musl), macOS (`x86_64`/`arm64`), and Windows (`x64-mingw32`/`ucrt`). In a Rails project, generate the initializer with `rails g mongory:install`.
29
27
 
30
- ```bash
31
- rails g mongory:install
32
- ```
28
+ <details>
29
+ <summary>Platform note (Apple Silicon system Ruby / source builds)</summary>
33
30
 
34
- > **Note:** Precompiled native gems are installed automatically on supported Linux, macOS, and Windows platforms (Ruby 2.6–4.0). On older Apple Silicon macOS system Ruby (`universal-darwin`), run `gem install mongory --platform arm64-darwin` or `bundle lock --add-platform arm64-darwin`. When compiling from source on other platforms, ensure `gcc`/`clang` and `make` are installed.
31
+ On older Apple Silicon macOS system Ruby (`universal-darwin`), run `gem install mongory --platform arm64-darwin` or `bundle lock --add-platform arm64-darwin`. When compiling from source on other platforms, ensure `gcc`/`clang` and `make` are installed.
32
+
33
+ </details>
35
34
 
36
35
  ## Quick Start
37
36
 
@@ -43,19 +42,19 @@ Mongory.register(Array)
43
42
  Mongory.enable_symbol_snippets!
44
43
 
45
44
  records = [
46
- { 'name' => 'Jack', 'age' => 18, 'tags' => %w[ruby go], 'active' => true },
47
- { 'name' => 'Jill', 'age' => 15, 'tags' => %w[js], 'active' => true },
48
- { 'name' => 'Bob', 'age' => 21, 'tags' => %w[ruby], 'active' => false }
45
+ { 'name' => 'Jack', 'age' => 18, 'tags' => %w(ruby go), 'active' => true },
46
+ { 'name' => 'Jill', 'age' => 15, 'tags' => %w(js), 'active' => true },
47
+ { 'name' => 'Bob', 'age' => 21, 'tags' => %w(ruby), 'active' => false }
49
48
  ]
50
49
 
51
50
  # 1. Chainable DSL with symbol operator snippets
52
- matched = records.mongory
51
+ records.mongory
53
52
  .where(:age.gte => 18, :active => true)
54
53
  .any_of({ :tags => 'ruby' }, { :name => /^J/ })
55
54
  .to_a
56
55
  # => [{ "name" => "Jack", ... }]
57
56
 
58
- # 2. Direct JSON condition (e.g. rule payload from API / front-end)
57
+ # 2. Direct JSON condition (e.g. rule payload from API / database)
59
58
  rule = JSON.parse('{"age": {"$gte": 18}, "$or": [{"name": {"$regex": "^J"}}, {"name": "Bob"}]}')
60
59
  records.mongory.where(rule).pluck('name')
61
60
  # => ["Jack", "Bob"]
@@ -66,35 +65,37 @@ ADULT_RULE.match?(records.first)
66
65
  # => true
67
66
  ```
68
67
 
69
- ### Query Builder Methods
68
+ ## Why Mongory? (and When Not to Use It)
69
+
70
+ - **Use Mongory when**: rules are stored as data (DB/config/API/feature flags), shared between frontend TS and Ruby/Go/Python services, or complex enough that nested `select` blocks become unreadable and hard to debug without `trace`.
71
+ - **Don't use Mongory when**: your filter is a simple static `records.select { |r| r['age'] >= 18 }` hardcoded in Ruby, or when you need full SQL/MongoDB aggregation pipelines (`$group`, `$lookup`, `$project`).
72
+ - **vs `Mongoid::Matcher`**: `mongory` has zero external gem dependencies (no `mongoid`, `mongo`, or `activesupport` required), works on plain `Hash`/PORO/ActiveRecord objects, compiles queries once into C99 (`mongory-core`), and adds `explain`/`trace` trees.
70
73
 
71
- | Method | Description | Example |
72
- |--------|-------------|---------|
73
- | `where` | Adds an `$and` filter condition | `where(:age.gte => 18, status: 'active')` |
74
- | `any_of` | Adds an `$or` branch inside the current `$and` | `any_of({ role: 'admin' }, { :score.gte => 90 })` |
75
- | `or` | Combines the current query with `$or` conditions | `or({ age: 18 }, { name: 'Bob' })` |
76
- | `and` | Combines conditions with `$and` | `and({ :age.gte => 18 }, { active: true })` |
77
- | `not` | Negates a condition (`$not`) | `not(:status => 'banned')` |
78
- | `in` / `nin` | Matches values in / not in a list | `in(role: %w[admin editor])` |
79
- | `limit` | Limits processed records (executes at its position in the chain) | `limit(10)` |
80
- | `pluck` | Extracts one or more fields from matching records | `pluck(:name)` |
81
- | `with_context` | Passes shared context/options to matchers | `with_context(tenant: current_tenant)` |
74
+ ## Benchmark Snapshot
75
+
76
+ Measured on Apple M3 (macOS arm64, Ruby `4.0.5`, `100,000` records x 5 rounds; full details & script in [docs/performance.md](docs/performance.md)):
77
+
78
+ | Case | Plain Ruby `Array#count` | `Mongory::Matcher` (C99) | `Mongoid::Matcher` (`9.1.2`) | `Mongory` vs `Mongoid` |
79
+ |---|---:|---:|---:|---:|
80
+ | `simple` (`age >= 18`) | `63.1 ns/rec` | `77.9 ns/rec` | `3,224.5 ns/rec` | **41.4x faster** |
81
+ | `$or` (`age >= 18` or `status == "active"`) | `71.8 ns/rec` | `127.4 ns/rec` | `3,967.9 ns/rec` | **31.1x faster** |
82
+ | `in_array_field` (`tags $in ["ruby", "rust"]`) | `85.3 ns/rec` | `136.4 ns/rec` | `4,302.1 ns/rec` | **31.5x faster** |
83
+ | `large_in_500` (`name $in [500 items]`) | `62.9 ns/rec` | `115.8 ns/rec` | `97,351.9 ns/rec` | **840.7x faster** |
82
84
 
83
85
  ## Debugging: `explain`, `trace`, `explain_tree` & `trace_tree`
84
86
 
85
- Use `explain_tree` and `trace_tree` to inspect structured Ruby Hashes (for logging, JSON APIs, or UIs), or `explain` and `trace` to print those trees directly to STDOUT:
87
+ Mongory automatically sorts sibling conditions by cost (cheap `$eq`/`$exists` short-circuit before `$regex` or array scans). Inspect compiled plans or per-record `PASS`/`FAIL`/`SKIP` traces in CLI output or structured Ruby Hashes:
86
88
 
87
89
  ```ruby
88
90
  query = records.mongory
89
91
  .where(:age.gte => 18)
90
92
  .any_of({ status: 'active' }, { :name.regex => /^J/ })
91
93
 
92
- # Structured explain tree (Hash)
93
- plan = query.explain_tree
94
- # => { name: "Query", condition: ..., priority: ..., children: [...] }
94
+ query.explain # prints priority-sorted plan tree to STDOUT
95
+ plan = query.explain_tree # structured Hash (for logging / APIs / UIs)
95
96
 
96
- # Prints the explain tree to STDOUT
97
- query.explain
97
+ query.trace { |r| puts r['name'] } # prints per-record PASS/FAIL/SKIP trace
98
+ trees = query.trace_tree # Array<Hash> with :pass | :fail | :skip nodes
98
99
  ```
99
100
 
100
101
  ```text
@@ -108,44 +109,24 @@ And: {"age"=>{"$gte"=>18}, "$or"=>[{"status"=>"active"}, {"name"=>{"$regex"=>/^J
108
109
  └─ Regex: /^J/
109
110
  ```
110
111
 
111
- ```ruby
112
- # Structured trace trees across all records (Array<Hash>);
113
- # short-circuited branches are recursively expanded with result: :skip.
114
- trees = query.trace_tree
115
- # => [
116
- # {
117
- # name: "Query",
118
- # condition: ...,
119
- # record: { "name" => "Bob", "age" => 15, "status" => "inactive" },
120
- # result: :fail, # :pass | :fail | :skip
121
- # priority: ...,
122
- # children: [...]
123
- # },
124
- # ...
125
- # ]
126
-
127
- # Prints each record's trace tree to STDOUT and yields matching records
128
- query.trace { |record| puts record['name'] }
129
- ```
130
-
131
- Single-record structured tracing is also available on matchers directly via `matcher.explain_tree` and `matcher.trace_tree(record)` on `Mongory::Matcher`.
112
+ Single-record tracing is also available directly on matchers via `matcher.explain_tree` and `matcher.trace_tree(record)`.
132
113
 
133
- ## Supported Operators
114
+ ## Operators & Query Builder
134
115
 
135
116
  | Category | Operators | Notes |
136
- |----------|-----------|-------|
117
+ |---|---|---|
137
118
  | Comparison | `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte` | Cross-type `Integer`/`Float` equality; implicit `$elemMatch` on arrays |
138
- | Inclusion | `$in`, `$nin` | Scalar membership or array intersection |
119
+ | Inclusion | `$in`, `$nin` | Scalar membership or array intersection; O(1) hash lookup for `>= 16` items |
139
120
  | Logical | `$and`, `$or`, `$not` | Priority-sorted sibling evaluation with dynamic re-sorting |
140
- | Array | `$elemMatch`, `$every`, `$size` | `$every` requires a non-empty array where all elements match; `$size` accepts an integer or range object |
121
+ | Array | `$elemMatch`, `$every`, `$size` | `$every` requires non-empty array; `$size` accepts integer or nested matcher |
141
122
  | Existence | `$exists`, `$present` | `$present` checks non-nil and non-empty (`String`, `Array`, `Hash`) |
142
123
  | Regex | `$regex` (`$options`: `i`, `m`, `s`) | Accepts `Regexp` or pattern string with optional `$options` |
143
124
 
144
- > **Differences from MongoDB:** `$every` (returns `false` on `[]`) and `$present` are Mongory extensions; `$options` only permits `i`/`m`/`s`; unknown `$` operators raise `Mongory::TypeError`. See [`mongory-spec`](https://github.com/mongoryhq/mongory-spec#37-differences-from-mongodb-query-syntax).
125
+ Query builder methods: `where`, `any_of`, `or`, `and`, `not`, `in` / `nin`, `limit`, `pluck`, `with_context`.
145
126
 
146
- ## Custom Matchers & Configuration
127
+ > **Differences from MongoDB:** Mongory is MongoDB-style, not MongoDB-compatible. A nested object condition matches a subset of fields (use `$eq` for an exact document), several comparisons on one array field must hold for the same element, and negative indexes count from the end of an array. `$every`, `$present`, field-level `$and`/`$or`/`$nor`, and `$size` with operators are Mongory extensions. Full list with examples: [Differences from MongoDB](https://github.com/mongoryhq/mongory-spec/blob/main/docs/mongodb-differences.md). Unknown `$` operators raise `Mongory::TypeError`.
147
128
 
148
- Configure registered collection classes and converters in `Mongory.configure`:
129
+ ## Custom Matchers & Configuration
149
130
 
150
131
  ```ruby
151
132
  Mongory.configure do |mc|
@@ -153,11 +134,7 @@ Mongory.configure do |mc|
153
134
  mc.register(Array)
154
135
  mc.register(ActiveRecord::Relation)
155
136
  end
156
- ```
157
137
 
158
- Define a custom operator with `Mongory::Matchers::AbstractMatcher` (or run `rails g mongory:matcher class_in`):
159
-
160
- ```ruby
161
138
  class ClassInMatcher < Mongory::Matchers::AbstractMatcher
162
139
  def match(subject)
163
140
  @condition.any? { |klass| subject.is_a?(klass) }
@@ -174,12 +151,17 @@ Mongory::Matchers.register(:class_in, '$classIn', ClassInMatcher)
174
151
 
175
152
  ## Guides & Further Reading
176
153
 
154
+ - [Performance & Benchmarks](docs/performance.md)
177
155
  - [Handling Dots in Field Names](docs/field_names.md)
178
156
  - [Advanced Usage & Converters](docs/advanced_usage.md)
179
157
  - [Clang Bridge (C Extension Internals)](docs/clang_bridge.md)
180
- - [Performance & Benchmarks](docs/performance.md)
181
158
  - [Migration Guide](docs/migration.md)
182
159
 
160
+ ## Security & Untrusted Input
161
+
162
+ - **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`).
163
+ - **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.
164
+
183
165
  ## Contributing & License
184
166
 
185
167
  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/clang_bridge.md CHANGED
@@ -6,11 +6,11 @@ As of `mongory-rb v2.0.0`, Mongory uses the C99 [`mongory-core`](https://github.
6
6
  - C99-compatible compiler (`gcc` / `clang`)
7
7
  - CMake >= 3.12 (optional; only needed if you want to build `mongory-core` standalone or run its native tests)
8
8
 
9
- > Note: Precompiled native gems are distributed for Linux, macOS (`arm64` & `x86_64`), and Windows (Ruby 2.6–4.0). When compiling from source, Ruby's `mkmf` (`ext/mongory_ext/extconf.rb`) compiles `mongory-core` sources directly — CMake is not required for gem installation.
9
+ > Note: Precompiled native gems are distributed for Linux, macOS (`arm64` and `x86_64`), and Windows (Ruby 2.6-4.0). When compiling from source, Ruby's `mkmf` (`ext/mongory_ext/extconf.rb`) compiles `mongory-core` sources directly; CMake is not required for gem installation.
10
10
 
11
11
  ## Architecture
12
12
 
13
- The Clang bridge connects the Ruby DSL to `mongory-core` via a compact C layer exposing two key entry points:
13
+ The Clang bridge connects the Ruby DSL to `mongory-core` via a compact C layer exposing two entry points:
14
14
 
15
15
  - `Mongory::Matcher`: the compiled matcher class backed by `mongory-core`.
16
16
  - `Mongory::QueryBuilder`: the chainable Ruby DSL (`records.mongory.where(...)`) backed by `Mongory::Matcher`.
data/docs/performance.md CHANGED
@@ -8,17 +8,53 @@ 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** |
26
+
27
+ ## Code Footprint & Runtime Memory
28
+
29
+ Measured on Apple M3 (`macOS arm64`, Ruby `4.0.5`) using `GC.stat` alongside macOS `malloc_zone_statistics` and `ru_maxrss` so native C heap allocations in `mongory-core` are captured alongside Ruby object allocations:
30
+
31
+ ### 1. Code Size & `require` Overhead (Median of 3 Subprocesses)
32
+
33
+ | Library | Production Source | Native Binary / Deps | `require` RSS Delta | `malloc` / Ruby Live Slots |
34
+ |---|---|---|---:|---:|
35
+ | **`mongory`** (`2.1.1`) | `2,392` LOC binding (26 files) + `7,277` LOC embedded `mongory-core` C99 | `mongory_ext.bundle` **`141.7 KB`**, **0 runtime deps** | **`+0.8 MiB`** | `+277.3 KiB` / **`+1,403` slots** |
36
+ | `mongoid` (`9.1.3`) | `1,743` matcher / `40,890` gem / **`244,692` LOC** across 19 gems | Pure Ruby + `bson`/`json`/`bigdecimal` (**19 gems**) | `+47.3 MiB` | `+23.3 MiB` / `+91,286` slots |
37
+
38
+ ### 2. Dataset & Compiled Matcher Retained Memory
39
+
40
+ - **Dataset Wrapper Overhead (`10,000` records)**: `Mongory::Matcher` evaluates plain Ruby `Hash`es directly (`40,007` live slots for 10k records). `Mongoid::Matcher` requires wrapping records in `Mongoid::Document` instances, adding **`+120,338` Ruby slots** and **`+2,361.6 KiB` malloc (`+241.8 B/rec`)**.
41
+ - **Compiled Matcher Retained Memory (`1,000` retained)**: Each `Mongory::Matcher` keeps a C99 arena + scratch pool (`4,687 B` + 5 slots for `simple`, `8,811 B` + 5 slots for `nested_and`, `137,372 B` + 6 slots for `large_in_500` O(1) hash table). `Mongoid::Matcher` interprets the query `Hash` on every call (`0 B` compiled AST).
42
+
43
+ ### 3. Match-Time Allocations (`10,000` records, GC disabled during single pass)
44
+
45
+ | Case | `Mongory::Matcher` | `Mongoid::Matcher` (`mongoid 9.1.3`) |
46
+ |---|---:|---:|
47
+ | `simple` (`age >= 18`) | **`7` Ruby objs** (`0.00/rec`), C `0.1 KiB` | `113,202` Ruby objs (`11.32/rec`) |
48
+ | `or` | **`2` Ruby objs** (`0.00/rec`), C `0.0 KiB` | `166,534` Ruby objs (`16.65/rec`) |
49
+ | `nested_and` | **`2` Ruby objs** (`0.00/rec`), C `0.0 KiB` | `179,672` Ruby objs (`17.97/rec`) |
50
+ | `in_array_field` | **`2` Ruby objs** (`0.00/rec`), C `0.0 KiB` | `172,502` Ruby objs (`17.25/rec`) |
51
+ | `large_in_500` | **`2` Ruby objs** (`0.00/rec`), C `0.0 KiB` | **`4,796,168` Ruby objs** (`479.62/rec`), `+5.6 MiB` malloc |
52
+ | `regex` | **`2` Ruby objs** (`0.00/rec`), C `0.0 KiB` | `310,002` Ruby objs (`31.00/rec`), `+10.2 MiB` malloc |
17
53
 
18
- > For cross-language benchmarks (`mongory-js`, `mongory-go`), see [Mongory Central](https://mongoryhq.github.io/mongory-central/#benchmarks).
54
+ > For cross-language benchmarks (`mongory-go`, `mongory-js`, `mongory-py`), see [Mongory Central](https://mongoryhq.github.io/mongory-central/?ref=mongory-rb-perf#benchmarks).
19
55
 
20
56
  ## Optimization Tips
21
57
 
22
- - **Reuse `Mongory::Matcher` Instances**: Compile once with `Mongory::Matcher.new(condition)` and call `#match?` across records to avoid recompiling the condition tree.
58
+ - **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
59
  - **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
60
  - **Inspect Plans**: Use `.explain` / `.trace` to verify cheap fields short-circuit early.
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -44,8 +44,8 @@ module Mongory
44
44
  def convert(target, other = NOTHING)
45
45
  convert_strategy = @convert_strategy_map[target.class] ||= find_strategy(target)
46
46
 
47
- return fallback(target, other) if convert_strategy == NOTHING
48
- return target.instance_exec(&convert_strategy) if other == NOTHING
47
+ return fallback(target, other) if NOTHING.equal?(convert_strategy)
48
+ return target.instance_exec(&convert_strategy) if NOTHING.equal?(other)
49
49
 
50
50
  target.instance_exec(other, &convert_strategy)
51
51
  end
@@ -95,14 +95,14 @@ module Mongory
95
95
  # @return [void]
96
96
  # @raise [RuntimeError] if input is invalid
97
97
  def register(klass, converter = nil, &block)
98
- raise 'converter or block is required.' if [converter, block].compact.empty?
99
- raise 'A class or module is reuqired.' unless klass.is_a?(Module)
98
+ raise 'converter or block is required.' unless converter || block
99
+ raise 'A class or module is required.' unless klass.is_a?(Module)
100
100
 
101
101
  if converter.is_a?(Symbol)
102
102
  register(klass) { |*args, &bl| send(converter, *args, &bl) }
103
103
  elsif block.is_a?(Proc)
104
104
  @registries.unshift(Registry.new(klass, block).freeze)
105
- @convert_strategy_map[klass] = block
105
+ @convert_strategy_map.clear
106
106
  else
107
107
  raise 'Support Symbol and block only.'
108
108
  end
@@ -39,10 +39,6 @@ module Mongory
39
39
  end
40
40
  end
41
41
 
42
- def deep_merge(other)
43
- dup.deep_merge!(Hash.new(other))
44
- end
45
-
46
42
  def deep_merge!(other)
47
43
  _deep_merge!(self, Hash.new(other))
48
44
  end
@@ -3,25 +3,21 @@
3
3
  module Mongory
4
4
  module Converters
5
5
  # KeyConverter handles transformation of field keys in query conditions.
6
- # It normalizes symbol keys into string paths, splits dotted keys,
7
- # and delegates to the appropriate converter logic.
6
+ # It normalizes symbol, integer, and QueryOperator keys into string keys;
7
+ # dotted-path expansion and escaped-dot unescaping are handled natively by `mongory-core`.
8
8
  #
9
9
  # This class inherits from AbstractConverter and provides specialized
10
10
  # handling for different key types:
11
- # - String keys with dots are split into nested paths
12
- # - Symbol keys are converted to strings
11
+ # - String keys are preserved verbatim for `mongory-core`
12
+ # - Symbol and Integer keys are converted to strings
13
13
  # - QueryOperator instances are handled via their DSL hooks
14
14
  # - Other types fall back to the parent converter
15
15
  #
16
- # Used by ConditionConverter to build query structures from flat input.
16
+ # Used by ConditionConverter to normalize query keys from Ruby DSL input.
17
17
  #
18
- # - `"a.b.c" => v` becomes `{ "a" => { "b" => { "c" => v } } }`
19
- # - Symbols are stringified and delegated to String logic
20
- # - QueryOperator dispatches to internal DSL hook
21
- #
22
- # @example Convert a dotted string key
18
+ # @example Preserve a dotted string key for `mongory-core`
23
19
  # KeyConverter.instance.convert("user.name", "John")
24
- # # => { "user" => { "name" => "John" } }
20
+ # # => { "user.name" => "John" }
25
21
  #
26
22
  # @example Convert a symbol key
27
23
  # KeyConverter.instance.convert(:status, "active")
@@ -56,33 +52,14 @@ module Mongory
56
52
  { target => other }
57
53
  end
58
54
 
59
- # Converts a dotted string key into nested hash form.
60
- # Splits the key on dots and builds a nested structure.
61
- # Handles escaped dots in the key.
55
+ # Preserves the string key verbatim; dotted path expansion and escaped-dot
56
+ # unescaping are handled natively by `mongory-core`.
62
57
  #
63
- # @param key [String] the dotted key string, e.g. "a.b.c"
64
- # @param value [Object] the value to assign at the deepest level
65
- # @return [Hash] nested hash structure
58
+ # @param key [String] the field key string
59
+ # @param value [Object] the condition value
60
+ # @return [Hash] single-entry hash `{ key => value }`
66
61
  def convert_string_key(key, value)
67
- return { '' => value } if key.empty?
68
-
69
- ret = {}
70
- *sub_keys, last_key = key.split(/(?<!\\)\./)
71
- last_hash = sub_keys.reduce(ret) do |res, sub_key|
72
- next_res = res[normalize_key(sub_key)] = {}
73
- next_res
74
- end
75
- last_hash[normalize_key(last_key)] = value
76
- ret
77
- end
78
-
79
- # Normalizes a key by unescaping escaped dots.
80
- # This allows for literal dots in field names.
81
- #
82
- # @param key [String] the key to normalize
83
- # @return [String] the normalized key
84
- def normalize_key(key)
85
- key.gsub(/\\\./, '.')
62
+ { key => value }
86
63
  end
87
64
  end
88
65
  end
@@ -9,12 +9,12 @@ module Mongory
9
9
  #
10
10
  # - Arrays are recursively converted
11
11
  # - Hashes are interpreted as nested conditions
12
- # - Regex becomes a Mongo-style `$regex` hash
12
+ # - Regexps are passed through as-is
13
13
  # - Strings and Integers are passed through
14
14
  # - Everything else falls back to DataConverter
15
15
  #
16
- # @example Convert a regex
17
- # ValueConverter.instance.convert(/foo/) #=> { "$regex" => "foo" }
16
+ # @example Pass through a regex
17
+ # ValueConverter.instance.convert(/foo/) #=> /foo/
18
18
  #
19
19
  class ValueConverter < AbstractConverter
20
20
  alias_method :super_convert, :convert
@@ -45,7 +45,7 @@ module Mongory
45
45
  #
46
46
  # @return [ConditionConverter] the condition converter instance
47
47
  def condition_converter
48
- @condition_converter ||= Mongory.condition_converter
48
+ Mongory.condition_converter
49
49
  end
50
50
  end
51
51
  end
@@ -26,6 +26,7 @@ module Mongory
26
26
  regex: '$regex',
27
27
  and: '$and',
28
28
  or: '$or',
29
+ nor: '$nor',
29
30
  not: '$not',
30
31
  elem_match: '$elemMatch',
31
32
  every: '$every',
@@ -130,20 +131,20 @@ module Mongory
130
131
  existing = Matchers.lookup(operator) || (Matchers.builtin?(operator) ? 'built-in' : nil)
131
132
  warn "Duplicate operator registration: #{operator} (#{existing} vs #{klass})" if existing
132
133
 
133
- return if operator.is_a?(String) && operator.match?(/^\$[a-z]+([A-Z][a-z]+)*$/)
134
+ return if operator.is_a?(String) && operator.match?(/\A\$[a-z]+([A-Z][a-z]+)*\z/)
134
135
 
135
- raise Mongory::TypeError, "Operator must match /^\$[a-z]+([A-Z][a-z]*)*$/, but got #{operator.inspect}"
136
+ raise Mongory::TypeError, "Operator must match /\\A\\$[a-z]+([A-Z][a-z]*)*\\z/, but got #{operator.inspect}"
136
137
  end
137
138
 
138
- # Validates the matcher class to ensure it is a subclass of AbstractMatcher.
139
+ # Validates the matcher class to ensure it is a named subclass of AbstractMatcher.
139
140
  #
140
141
  # @param klass [Class]
141
142
  # @return [void]
142
143
  # @raise [Mongory::TypeError] if class is not valid
143
144
  def self.validate_class(klass)
144
- return if klass.is_a?(Class) && klass < AbstractMatcher
145
+ return if klass.is_a?(Class) && klass < AbstractMatcher && !klass.name.nil? && !klass.name.empty?
145
146
 
146
- raise Mongory::TypeError, "Matcher class must be a subclass of AbstractMatcher, but got #{klass}"
147
+ raise Mongory::TypeError, "Matcher class must be a named subclass of AbstractMatcher, but got #{klass}"
147
148
  end
148
149
 
149
150
  # Validates the method symbol to ensure it is a valid lowercase underscore symbol (e.g., :gt, :not_match).
@@ -152,9 +153,9 @@ module Mongory
152
153
  # @return [void]
153
154
  # @raise [Mongory::TypeError] if symbol format is invalid
154
155
  def self.validate_method(method_sym)
155
- return if method_sym.is_a?(Symbol) && method_sym.match?(/^([a-z]+_)*[a-z]+$/)
156
+ return if method_sym.is_a?(Symbol) && method_sym.match?(/\A([a-z]+_)*[a-z]+\z/)
156
157
 
157
- raise Mongory::TypeError, "Method symbol must match /^([a-z]+_)*[a-z]+$/, but got #{method_sym.inspect}"
158
+ raise Mongory::TypeError, "Method symbol must match /\\A([a-z]+_)*[a-z]+\\z/, but got #{method_sym.inspect}"
158
159
  end
159
160
  end
160
161
  end
@@ -135,6 +135,15 @@ module Mongory
135
135
  self.and('$or' => conditions)
136
136
  end
137
137
 
138
+ # Adds a `$nor` query combined inside an `$and` block.
139
+ # None of the given conditions may match for a record to be included.
140
+ #
141
+ # @param conditions [Array<Hash>] the conditions to add
142
+ # @return [QueryBuilder] a new builder instance
143
+ def nor(*conditions)
144
+ self.and('$nor' => conditions)
145
+ end
146
+
138
147
  # Adds an `$in` condition to the query.
139
148
  # Matches records where the field value is in the given array.
140
149
  #
@@ -32,12 +32,6 @@ module Mongory
32
32
  new_context.config = @config.dup
33
33
  new_context
34
34
  end
35
-
36
- def to_hash
37
- {
38
- config: @config
39
- }
40
- end
41
35
  end
42
36
  end
43
37
  end
@@ -22,10 +22,7 @@ module Mongory
22
22
  "#<#{@label}>"
23
23
  end
24
24
 
25
- # @return [String] formatted label
26
- def to_s
27
- "#<#{@label}>"
28
- end
25
+ alias_method :to_s, :inspect
29
26
  end
30
27
  end
31
28
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Mongory
4
- VERSION = '2.1.0'
4
+ VERSION = '2.2.0'
5
5
  end
data/lib/mongory.rb CHANGED
@@ -2,7 +2,6 @@
2
2
 
3
3
  require 'time'
4
4
  require 'date'
5
- require 'set'
6
5
  require 'singleton'
7
6
  require_relative 'mongory/version'
8
7
  require_relative 'mongory/utils'