mongory 0.9.1 → 2.0.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.
Files changed (90) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +25 -0
  3. data/README.md +115 -420
  4. data/SUBMODULE_INTEGRATION.md +7 -20
  5. data/docs/clang_bridge.md +28 -63
  6. data/docs/migration.md +17 -0
  7. data/docs/performance.md +14 -51
  8. data/examples/benchmark.rb +10 -26
  9. data/ext/mongory_ext/extconf.rb +1 -1
  10. data/ext/mongory_ext/mongory-core/include/mongory-core/adapters/json.h +62 -0
  11. data/ext/mongory_ext/mongory-core/include/mongory-core/foundations/config.h +31 -0
  12. data/ext/mongory_ext/mongory-core/include/mongory-core/foundations/error.h +3 -0
  13. data/ext/mongory_ext/mongory-core/include/mongory-core/foundations/memory_pool.h +20 -0
  14. data/ext/mongory_ext/mongory-core/include/mongory-core/matchers/matcher.h +31 -4
  15. data/ext/mongory_ext/mongory-core/src/foundations/array.c +48 -6
  16. data/ext/mongory_ext/mongory-core/src/foundations/config.c +30 -2
  17. data/ext/mongory_ext/mongory-core/src/foundations/error.c +10 -0
  18. data/ext/mongory_ext/mongory-core/src/foundations/memory_pool.c +78 -19
  19. data/ext/mongory_ext/mongory-core/src/foundations/string_buffer.c +73 -19
  20. data/ext/mongory_ext/mongory-core/src/foundations/table.c +8 -3
  21. data/ext/mongory_ext/mongory-core/src/foundations/utils.c +44 -55
  22. data/ext/mongory_ext/mongory-core/src/foundations/utils.h +7 -0
  23. data/ext/mongory_ext/mongory-core/src/foundations/value.c +3 -0
  24. data/ext/mongory_ext/mongory-core/src/matchers/base_matcher.c +68 -0
  25. data/ext/mongory_ext/mongory-core/src/matchers/base_matcher.h +14 -0
  26. data/ext/mongory_ext/mongory-core/src/matchers/compare_matcher.c +9 -4
  27. data/ext/mongory_ext/mongory-core/src/matchers/composite_matcher.c +132 -29
  28. data/ext/mongory_ext/mongory-core/src/matchers/composite_matcher.h +1 -1
  29. data/ext/mongory_ext/mongory-core/src/matchers/{existance_matcher.c → existence_matcher.c} +10 -12
  30. data/ext/mongory_ext/mongory-core/src/matchers/{existance_matcher.h → existence_matcher.h} +4 -4
  31. data/ext/mongory_ext/mongory-core/src/matchers/external_matcher.c +18 -6
  32. data/ext/mongory_ext/mongory-core/src/matchers/{array_record_matcher.c → implicit_array_matcher.c} +57 -38
  33. data/ext/mongory_ext/mongory-core/src/matchers/{array_record_matcher.h → implicit_array_matcher.h} +5 -5
  34. data/ext/mongory_ext/mongory-core/src/matchers/inclusion_matcher.c +8 -10
  35. data/ext/mongory_ext/mongory-core/src/matchers/matcher.c +337 -96
  36. data/ext/mongory_ext/mongory-core/src/matchers/matcher_explainable.c +59 -21
  37. data/ext/mongory_ext/mongory-core/src/matchers/matcher_explainable.h +7 -1
  38. data/ext/mongory_ext/mongory-core/src/matchers/matcher_traversable.c +4 -4
  39. data/ext/mongory_ext/mongory-core/src/matchers/matcher_traversable.h +1 -1
  40. data/ext/mongory_ext/mongory-core/src/matchers/{literal_matcher.c → value_matcher.c} +104 -60
  41. data/ext/mongory_ext/mongory-core/src/matchers/{literal_matcher.h → value_matcher.h} +13 -13
  42. data/ext/mongory_ext/mongory_ext.c +2 -2
  43. data/ext/mongory_ext/mongory_ext_internal.h +2 -3
  44. data/ext/mongory_ext/{rb_mongory_cmatcher.c → rb_mongory_matcher.c} +145 -91
  45. data/ext/mongory_ext/rb_mongory_value.c +67 -0
  46. data/lib/generators/mongory/install/templates/initializer.rb.erb +0 -5
  47. data/lib/generators/mongory/matcher/templates/matcher.rb.erb +4 -15
  48. data/lib/mongory/converters/condition_converter.rb +1 -1
  49. data/lib/mongory/converters/converted.rb +28 -6
  50. data/lib/mongory/converters/key_converter.rb +2 -0
  51. data/lib/mongory/matcher.rb +50 -0
  52. data/lib/mongory/matchers/abstract_matcher.rb +18 -192
  53. data/lib/mongory/matchers.rb +68 -84
  54. data/lib/mongory/query_builder.rb +29 -42
  55. data/lib/mongory/utils/context.rb +10 -15
  56. data/lib/mongory/utils/tree_renderer.rb +98 -0
  57. data/lib/mongory/utils.rb +2 -67
  58. data/lib/mongory/version.rb +1 -1
  59. data/lib/mongory.rb +9 -59
  60. data/script/bench.rb +54 -0
  61. data/scripts/build_with_core.sh +0 -1
  62. metadata +13 -37
  63. data/lib/mongory/c_matcher.rb +0 -57
  64. data/lib/mongory/c_query_builder.rb +0 -44
  65. data/lib/mongory/matchers/abstract_multi_matcher.rb +0 -150
  66. data/lib/mongory/matchers/and_matcher.rb +0 -73
  67. data/lib/mongory/matchers/array_record_matcher.rb +0 -105
  68. data/lib/mongory/matchers/elem_match_matcher.rb +0 -57
  69. data/lib/mongory/matchers/eq_matcher.rb +0 -48
  70. data/lib/mongory/matchers/every_matcher.rb +0 -56
  71. data/lib/mongory/matchers/exists_matcher.rb +0 -53
  72. data/lib/mongory/matchers/field_matcher.rb +0 -160
  73. data/lib/mongory/matchers/gt_matcher.rb +0 -41
  74. data/lib/mongory/matchers/gte_matcher.rb +0 -41
  75. data/lib/mongory/matchers/hash_condition_matcher.rb +0 -80
  76. data/lib/mongory/matchers/in_matcher.rb +0 -84
  77. data/lib/mongory/matchers/literal_matcher.rb +0 -126
  78. data/lib/mongory/matchers/lt_matcher.rb +0 -41
  79. data/lib/mongory/matchers/lte_matcher.rb +0 -41
  80. data/lib/mongory/matchers/ne_matcher.rb +0 -39
  81. data/lib/mongory/matchers/nin_matcher.rb +0 -64
  82. data/lib/mongory/matchers/not_matcher.rb +0 -40
  83. data/lib/mongory/matchers/or_matcher.rb +0 -69
  84. data/lib/mongory/matchers/present_matcher.rb +0 -55
  85. data/lib/mongory/matchers/regex_matcher.rb +0 -109
  86. data/lib/mongory/matchers/size_matcher.rb +0 -54
  87. data/lib/mongory/query_matcher.rb +0 -93
  88. data/lib/mongory/rails.rb +0 -15
  89. data/lib/mongory/utils/debugger.rb +0 -125
  90. data/lib/mongory/utils/rails_patch.rb +0 -22
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 4fda12c4aa0f03636e531de082809cf139c123f68a1044be094a403dc394471a
4
- data.tar.gz: '058a2cede75cbb43442022e2dbbba613effc689e7bbbddc4d80b542c100baded'
3
+ metadata.gz: 8c2072dcf73aedcefd0dea480bb582fad714ed573cf7b79e4d5910d1c3569f34
4
+ data.tar.gz: 63a82ffa6e27ad051cf2eac736c415744c6d040f13d0bcd4577fa0ff075254c7
5
5
  SHA512:
6
- metadata.gz: 80b3a04cfbaad438ad02504ad2e7ebbbc315adb4c0404037e3b732b224ea5cb77594eae1905201ed03383a8ba8058e7cbcb9ae3309d8494eb9a26afbd36557ff
7
- data.tar.gz: a1c7537a050ce4ff521b94f343229f14dfb293d4f3da66a550bc6fa972d1912fccf80349d1569b3cb7f6fcf31ff2849ce6821704cf1dd07ec58e7df50b4fc9b2
6
+ metadata.gz: d461d1941649106c503740b3041afcb07d85e84f09c335b9bc56d214e426a70bef032db378806b0d206c05f54553ca39bc528f8afcd6a591344c4ae52c0906d3
7
+ data.tar.gz: a388c24d319743edaae107a64f9b3d1afa6c598c26bfeb55f7ac00267a62cddb78b1a45b89eba3de7ede9c28beaa5ecfa704e6a497527f19bf96884abf286614
data/CHANGELOG.md CHANGED
@@ -1,5 +1,30 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.0.1] - 2026-11-22
4
+
5
+ Aligns with `mongory-core` `v0.3.0` and finishes v2.0.0 cleanup.
6
+
7
+ ### Fixes
8
+ - **C Extension (`rb_mongory_value.c`)**: Zero-initialize `rb_mongory_table_t` and `rb_mongory_array_t` lazy wrappers with OOM `NULL` guards and implement `.each` vtable methods (`rb_hash_foreach` / `RARRAY`) so every `mongory-core` container traversal contract is satisfied.
9
+
10
+ ### Cleanup
11
+ - Removed stateful `Matcher#enable_trace`, `#disable_trace`, `#print_trace`, and no-op `Matcher.trace_result_colorful=` (all tracing uses stateless, thread-safe `#trace` / `#trace_tree`).
12
+ - Removed remaining legacy Pure-Ruby dead code (`TreeRenderer.mark_skipped`, `Utils::Context#need_convert`, `QueryBuilder#fast`, and stale `cJSON` comments).
13
+ - Synced `ext/mongory_ext/mongory-core` submodule to `v0.3.0`.
14
+
15
+ ## [2.0.0] - 2026-11-22
16
+
17
+ Unifies `mongory-rb` on the `mongory-core` C99 native extension as the sole matching engine, eliminating Pure-Ruby dual-engine maintenance.
18
+
19
+ ### Breaking Changes
20
+ - **C Extension Only (No Pure-Ruby Fallback)**: Removed the 22 built-in Pure-Ruby matchers, `Mongory::QueryMatcher`, `Mongory::CQueryBuilder`, and `Mongory::Utils::Debugger` (`Mongory.debugger`). Loading `mongory` now requires the compiled `mongory_ext` native extension directly.
21
+ - **Renamed `Mongory::CMatcher` → `Mongory::Matcher`**: `Mongory.build_matcher(condition)` now always returns `Mongory::Matcher`, and `Mongory.build_query(records)` / `.mongory` always return `Mongory::QueryBuilder` backed by `Mongory::Matcher`.
22
+ - **Removed C-Extension Toggle APIs**: Removed `Mongory.enable_c_extension_by_default!`, `Mongory.use_c_extension_by_default!`, `Mongory.disable_c_extension_by_default!`, `Mongory.c_extension_by_default?`, and `QueryBuilder#c`.
23
+ - **Custom Matchers Preserved**: `Mongory::Matchers::AbstractMatcher`, `Mongory::Matchers.register`, `Mongory.enable_symbol_snippets!`, and all `Converters` remain supported and bridge directly into `mongory-core`.
24
+
25
+ ### Core & Maintenance
26
+ - Updated `ext/mongory_ext/mongory-core` submodule to latest `main` (`ac678b3`: OOM hardening, `MaxDepth`/`MaxNodes` safety limits, sanitizer/fuzzing CI, and macOS Universal Binary CI).
27
+
3
28
  ## [0.9.1] - 2026-11-18
4
29
 
5
30
  Aligns with `mongory-core` `v0.2.1`.
data/README.md CHANGED
@@ -1,221 +1,156 @@
1
1
  # Mongory (Ruby)
2
2
 
3
- **Cross-language, in-memory Mongo-style rule engine & query matcher with built-in Explain & Trace debugging** — optional C99 acceleration ([`mongory-core`](https://github.com/mongoryhq/mongory-core)), pure Ruby fallback, and cross-language parity via [`mongory-spec`](https://github.com/mongoryhq/mongory-spec).
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).
4
4
 
5
5
  **[Try the Interactive Playground & Visual Explain/Trace Debugger ↗](https://mongoryhq.github.io/mongory-central/)**
6
6
 
7
7
  [![Mongory Playground & Visual Trace](https://mongoryhq.github.io/mongory-central/playground-trace.png)](https://mongoryhq.github.io/mongory-central/)
8
8
 
9
- > **Zero database required:** Mongory evaluates MongoDB-style conditions (`$gte`, `$elemMatch`, `$every`, `$present`, `$regex`, etc.) directly against in-memory Ruby objects, hashes, and ActiveRecord relations.
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
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)
11
11
 
12
- ## Table of Contents
13
-
14
- - Overview & Positioning
15
- - [Positioning](#positioning)
16
- - Getting Started
17
- - [Requirements](#requirements)
18
- - [Installation & Quick Start](#installation--quick-start)
19
- - [Integration with MongoDB](#integration-with-mongodb)
20
- - Usage & Concepts
21
- - [Creating Custom Matchers](#creating-custom-matchers)
22
- - [Core Concepts & API Reference](#core-concepts--api-reference)
23
- - [Handling Dots in Field Names](docs/field_names.md)
24
- - [Advanced Usage](docs/advanced_usage.md)
25
- - [Debugging](#debugging)
26
- - [Clang Bridge (C Extension)](docs/clang_bridge.md)
27
- - Performance
28
- - [Performance & Benchmarks](docs/performance.md)
29
- - [Supported Operators](#supported-operators)
30
- - Guides
31
- - [Best Practices](#best-practices)
32
- - [Limitations](#limitations)
33
- - [FAQ](#faq)
34
- - [Troubleshooting](#troubleshooting)
35
- - [Migration Guide](docs/migration.md)
36
- - Project
37
- - [Contributing](#contributing)
38
- - [Code of Conduct](#code-of-conduct)
39
- - [License](#license)
40
-
41
- ## Requirements
42
-
43
- - Ruby >= 2.6.0
44
- - No external database required
45
-
46
- ## Installation & Quick Start
47
-
48
- ### Installation
49
- Install manually:
50
- ```bash
51
- gem install mongory
52
- ```
53
-
54
- Or add to your Gemfile:
55
- ```ruby
56
- gem 'mongory'
57
- ```
12
+ ## Features
58
13
 
59
- #### Before installing: install build tools
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`).
60
19
 
61
- Mongory ships with an optional native C extension.
62
- Before installing Mongory, make sure these following precompiled package support your platform:
63
- - x86_64-linux-musl (Linux)
64
- - aarch64-linux-musl (Linux)
65
- - x86_64-linux (Linux)
66
- - aarch64-linux (Linux)
67
- - x86_64-darwin (MacOS Intel)
68
- - arm64-darwin (MacOS Apple Silicon)
69
- - x64-mingw32 (Windows)
70
- - x64-mingw-ucrt (Windows)
20
+ ## Installation
71
21
 
72
- If your platform excludes, make sure your system has a C build toolchain (gcc/clang and make). Install the toolchain with the following commands for your platform:
73
-
74
- - Debian/Ubuntu (including ruby:*-slim base images)
75
- ```bash
76
- apt-get update && apt-get install -y build-essential
77
- ```
78
-
79
- - Alpine
80
22
  ```bash
81
- apk add --no-cache build-base
23
+ gem install mongory
24
+ # or in Gemfile:
25
+ gem 'mongory'
82
26
  ```
83
27
 
84
- - CentOS/RHEL
85
- ```bash
86
- yum groupinstall -y "Development Tools"
87
- ```
28
+ In a Rails project, generate the initializer (`config/initializers/mongory.rb`):
88
29
 
89
- - Fedora
90
30
  ```bash
91
- dnf groupinstall -y "Development Tools"
31
+ rails g mongory:install
92
32
  ```
93
33
 
94
- - Amazon Linux
95
- ```bash
96
- yum groupinstall -y "Development Tools"
97
- ```
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.
98
35
 
99
- - macOS
100
- ```bash
101
- xcode-select --install
102
- ```
36
+ ## Quick Start
103
37
 
104
- ### Basic Usage
105
38
  ```ruby
39
+ require 'mongory'
40
+ require 'json'
41
+
42
+ Mongory.register(Array)
43
+ Mongory.enable_symbol_snippets!
44
+
106
45
  records = [
107
- { 'name' => 'Jack', 'age' => 18, 'gender' => 'M' },
108
- { 'name' => 'Jill', 'age' => 15, 'gender' => 'F' },
109
- { 'name' => 'Bob', 'age' => 21, 'gender' => 'M' },
110
- { 'name' => 'Mary', 'age' => 18, 'gender' => 'F' }
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 }
111
49
  ]
112
50
 
113
- # Basic query with conditions
114
- result = records.mongory
115
- .where(:age.gte => 18)
116
- .or({ :name => /J/ }, { :name.eq => 'Bob' })
51
+ # 1. Chainable DSL with symbol operator snippets
52
+ matched = records.mongory
53
+ .where(:age.gte => 18, :active => true)
54
+ .any_of({ :tags => 'ruby' }, { :name => /^J/ })
117
55
  .to_a
56
+ # => [{ "name" => "Jack", ... }]
118
57
 
119
- # Or input condition via json string from front-end
120
- result = records.mongory
121
- .where(JSON.parse('{
122
- "age": {"$gt": 18},
123
- "$or": [
124
- {"name": {"$regex": "J"}},
125
- {"name": "Bob"}
126
- ]
127
- }'))
128
- .to_a
129
-
130
- # Using limit to restrict results
131
- # Note: limit executes immediately and affects subsequent conditions
132
- limited = records.mongory
133
- .limit(2) # Only process first 2 records
134
- .where(:age.gte => 18) # Conditions apply to limited set
58
+ # 2. Direct JSON condition (e.g. rule payload from API / front-end)
59
+ rule = JSON.parse('{"age": {"$gte": 18}, "$or": [{"name": {"$regex": "^J"}}, {"name": "Bob"}]}')
60
+ records.mongory.where(rule).pluck('name')
61
+ # => ["Jack", "Bob"]
135
62
  ```
136
63
 
137
- #### Rails Generator
138
-
139
- You can install a starter configuration with:
64
+ ### Query Builder Methods
140
65
 
141
- ```bash
142
- rails g mongory:install
143
- ```
144
-
145
- This will generate `config/initializers/mongory.rb` and set up:
146
- - Optional symbol operator snippets (e.g. `:age.gt => 18`)
147
- - Class registration (e.g. `Array`, `ActiveRecord::Relation`, etc.)
148
- - Custom value/key converters for your ORM
149
-
150
- ## Positioning
151
-
152
- Mongory is designed to serve two types of users:
66
+ | Method | Description | Example |
67
+ |--------|-------------|---------|
68
+ | `where` | Adds an `$and` filter condition | `where(:age.gte => 18, status: 'active')` |
69
+ | `any_of` | Adds an `$or` branch inside the current `$and` | `any_of({ role: 'admin' }, { :score.gte => 90 })` |
70
+ | `or` | Combines the current query with `$or` conditions | `or({ age: 18 }, { name: 'Bob' })` |
71
+ | `and` | Combines conditions with `$and` | `and({ :age.gte => 18 }, { active: true })` |
72
+ | `not` | Negates a condition (`$not`) | `not(:status => 'banned')` |
73
+ | `in` / `nin` | Matches values in / not in a list | `in(role: %w[admin editor])` |
74
+ | `limit` | Limits processed records (executes at its position in the chain) | `limit(10)` |
75
+ | `pluck` | Extracts one or more fields from matching records | `pluck(:name)` |
76
+ | `with_context` | Passes shared context/options to matchers | `with_context(tenant: current_tenant)` |
153
77
 
154
- 1. For MongoDB users:
155
- - Seamless integration with familiar query syntax
156
- - Extends query capabilities for non-indexed fields
157
- - No additional learning cost
78
+ ## Debugging: `explain`, `trace`, `explain_tree` & `trace_tree`
158
79
 
159
- 2. For non-MongoDB users:
160
- - Initial learning cost for MongoDB-style syntax
161
- - Long-term benefits:
162
- - Improved code readability
163
- - Better development efficiency
164
- - Lower maintenance costs
165
- - Ideal for teams valuing code quality and maintainability
80
+ 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:
166
81
 
167
- ### Integration with MongoDB
82
+ ```ruby
83
+ query = records.mongory
84
+ .where(:age.gte => 18)
85
+ .any_of({ status: 'active' }, { :name.regex => /^J/ })
168
86
 
169
- Mongory is designed to complement MongoDB, not replace it. Here's how to use them together:
87
+ # Structured explain tree (Hash)
88
+ plan = query.explain_tree
89
+ # => { name: "Query", condition: ..., priority: ..., children: [...] }
170
90
 
171
- 1. Use MongoDB for:
172
- - Queries with indexes
173
- - Persistent data operations
174
- - Large-scale data processing
91
+ # Prints the explain tree to STDOUT
92
+ query.explain
93
+ ```
175
94
 
176
- 2. Use Mongory for:
177
- - Queries without indexes
178
- - Complex in-memory calculations
179
- - Temporary data filtering needs
95
+ ```text
96
+ And: {"age"=>{"$gte"=>18}, "$or"=>[{"status"=>"active"}, {"name"=>{"$regex"=>/^J/}}]}
97
+ ├─ Field: "age" to match: {"$gte"=>18}
98
+ │ └─ Gte: 18
99
+ └─ Or: [{"status"=>"active"}, {"name"=>{"$regex"=>/^J/}}]
100
+ ├─ Field: "status" to match: "active"
101
+ │ └─ Eq: "active"
102
+ └─ Field: "name" to match: {"$regex"=>/^J/}
103
+ └─ Regex: /^J/
104
+ ```
180
105
 
181
- Example:
182
106
  ```ruby
183
- # First use MongoDB for indexed queries
184
- users = User.where(status: 'active') # Uses MongoDB index
107
+ # Structured trace trees across all records (Array<Hash>);
108
+ # short-circuited branches are recursively expanded with result: :skip.
109
+ trees = query.trace_tree
110
+ # => [
111
+ # {
112
+ # name: "Query",
113
+ # condition: ...,
114
+ # record: { "name" => "Bob", "age" => 15, "status" => "inactive" },
115
+ # result: :fail, # :pass | :fail | :skip
116
+ # priority: ...,
117
+ # children: [...]
118
+ # },
119
+ # ...
120
+ # ]
185
121
 
186
- # Then use Mongory for non-indexed fields
187
- active_users = users.mongory
188
- .where(:last_login.gte => 1.week.ago) # No index on last_login
189
- .where(:tags.elem_match => { :name => 'ruby' }) # Complex array query
122
+ # Prints each record's trace tree to STDOUT and yields matching records
123
+ query.trace { |record| puts record['name'] }
190
124
  ```
191
125
 
192
- ### Creating Custom Matchers
193
- #### Using the Generator
126
+ Single-record structured tracing is also available on matchers directly via `matcher.explain_tree` and `matcher.trace_tree(record)` on `Mongory::Matcher`.
194
127
 
195
- You can generate a new matcher using:
128
+ ## Supported Operators
196
129
 
197
- ```bash
198
- rails g mongory:matcher class_in
199
- ```
130
+ | Category | Operators | Notes |
131
+ |----------|-----------|-------|
132
+ | Comparison | `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte` | Cross-type `Integer`/`Float` equality; implicit `$elemMatch` on arrays |
133
+ | Inclusion | `$in`, `$nin` | Scalar membership or array intersection |
134
+ | Logical | `$and`, `$or`, `$not` | Priority-sorted sibling evaluation with dynamic re-sorting |
135
+ | Array | `$elemMatch`, `$every`, `$size` | `$every` requires a non-empty array where all elements match; `$size` accepts an integer or range object |
136
+ | Existence | `$exists`, `$present` | `$present` checks non-nil and non-empty (`String`, `Array`, `Hash`) |
137
+ | Regex | `$regex` (`$options`: `i`, `m`, `s`) | Accepts `Regexp` or pattern string with optional `$options` |
138
+
139
+ > **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).
200
140
 
201
- This will:
202
- 1. Create a new matcher file at `lib/mongory/matchers/class_in_matcher.rb`
203
- 2. Create a spec file at `spec/mongory/matchers/class_in_matcher_spec.rb`
204
- 3. Update `config/initializers/mongory.rb` to require the new matcher
141
+ ## Custom Matchers & Configuration
205
142
 
206
- The generated matcher will:
207
- - Be named `ClassInMatcher`
208
- - Register the operator as `$classIn` makes it available in queries
209
- - Enable `:field.class_in` query snippet (If symbol snippet enabled)
143
+ Configure registered collection classes and converters in `Mongory.configure`:
210
144
 
211
- Example usage of the generated matcher:
212
145
  ```ruby
213
- records.mongory.where(:value.class_in => [Integer, String])
146
+ Mongory.configure do |mc|
147
+ mc.enable_symbol_snippets!
148
+ mc.register(Array)
149
+ mc.register(ActiveRecord::Relation)
150
+ end
214
151
  ```
215
152
 
216
- #### Manual Creation
217
-
218
- If you prefer to create matchers manually, here's an example:
153
+ Define a custom operator with `Mongory::Matchers::AbstractMatcher` (or run `rails g mongory:matcher class_in`):
219
154
 
220
155
  ```ruby
221
156
  class ClassInMatcher < Mongory::Matchers::AbstractMatcher
@@ -224,264 +159,24 @@ class ClassInMatcher < Mongory::Matchers::AbstractMatcher
224
159
  end
225
160
 
226
161
  def check_validity!
227
- raise TypeError, '$classIn needs an array.' unless @condition.is_a?(Array)
228
- @condition.each do |klass|
229
- raise TypeError, '$classIn needs an array of class.' unless klass.is_a?(Class)
230
- end
162
+ raise Mongory::TypeError, '$classIn needs an Array of Classes' unless
163
+ @condition.is_a?(Array) && @condition.all? { |k| k.is_a?(Class) }
231
164
  end
232
165
  end
233
166
 
234
167
  Mongory::Matchers.register(:class_in, '$classIn', ClassInMatcher)
235
-
236
- [{a: 1}].mongory.where(:a.class_in => [Integer]).first
237
- # => { a: 1 }
238
168
  ```
239
169
 
240
- You can define any matcher behavior and attach it to a `$operator` of your choice.
241
- Matchers can be composed, validated, and traced just like built-in ones.
170
+ ## Guides & Further Reading
242
171
 
243
- ## Core Concepts & API Reference
244
- #### Registering Models
172
+ - [Handling Dots in Field Names](docs/field_names.md)
173
+ - [Advanced Usage & Converters](docs/advanced_usage.md)
174
+ - [Clang Bridge (C Extension Internals)](docs/clang_bridge.md)
175
+ - [Performance & Benchmarks](docs/performance.md)
176
+ - [Migration Guide](docs/migration.md)
245
177
 
246
- To allow calling `.mongory` on collections, use `register`:
178
+ ## Contributing & License
247
179
 
248
- ```ruby
249
- Mongory.register(Array)
250
- Mongory.register(ActiveRecord::Relation)
251
- User.where(status: 'active').mongory.where(:age.gte => 18, :name.regex => "^S.+")
252
- ```
253
-
254
- This injects a `.mongory` method via an internal extension module.
255
- Internally, the query is compiled into a matcher tree.
256
-
257
- | Method | Description | Example |
258
- |--------|-------------|---------|
259
- | `where` | Adds a condition to filter records | `where(age: { :$gte => 18 })` |
260
- | `not` | Adds a negated condition | `not(age: { :$lt => 18 })` |
261
- | `and` | Combines conditions with `$and` | `and({ age: { :$gte => 18 } }, { name: /J/ })` |
262
- | `or` | Combines conditions with `$or` | `or({ age: { :$gte => 18 } }, { name: /J/ })` |
263
- | `any_of` | Combines conditions with `$or` inside an `$and` block | `any_of({ age: { :$gte => 18 } }, { name: /J/ })` |
264
- | `in` | Checks if a value is in a set | `in(age: [18, 19, 20])` |
265
- | `nin` | Checks if a value is not in a set | `nin(age: [18, 19, 20])` |
266
- | `limit` | Limits the number of records returned. This method executes immediately and affects subsequent conditions. | `limit(2)` |
267
- | `pluck` | Extracts selected fields from matching records | `pluck(:name)` |
268
- | `with_context` | Sets a custom context for the query. Useful for controlling data conversion and sharing configuration across matchers. | `with_context(merchant: merchant)` |
269
-
270
- #### Context Configuration
271
-
272
- The `with_context` method allows you to customize the query execution environment:
273
-
274
- ```ruby
275
- # Share configuration across matchers
276
- records.mongory
277
- .with_context(custom_option: true)
278
- .where(:status => 'active')
279
- .where(:age.gte => 18)
280
- ```
281
-
282
- This will share a mutatable, but stable context object to all matchers in matcher tree.
283
- To get your custom option, using `@context.config` in your custom matcher.
284
-
285
- ## Debugging
286
-
287
- You can use `explain` to visualize the matcher tree structure:
288
- ```ruby
289
- records = [
290
- { name: 'John', age: 25, status: 'active' },
291
- { name: 'Jane', age: 30, status: 'inactive' }
292
- ]
293
-
294
- query = records.mongory
295
- .where(:age.gte => 18)
296
- .any_of(
297
- { :status => 'active' },
298
- { :name.regex => /^J/ }
299
- )
300
-
301
- query.explain
302
- ```
303
- Output:
304
- ```
305
- And: {"age"=>{"$gte"=>18}, "$or"=>[{"status"=>"active"}, {"name"=>{"$regex"=>/^J/}}]}
306
- ├─ Field: "age" to match: {"$gte"=>18}
307
- │ └─ Gte: 18
308
- └─ Or: [{"status"=>"active"}, {"name"=>{"$regex"=>/^J/}}]
309
- ├─ Field: "status" to match: "active"
310
- │ └─ Eq: "active"
311
- └─ Field: "name" to match: {"$regex"=>/^J/}
312
- └─ Regex: /^J/
313
- ```
314
-
315
- This helps you understand how your query is being processed and can be useful for debugging complex conditions.
316
-
317
- Or use trace for detailed matching process:
318
- ```ruby
319
- # Execute your query
320
- query = Mongory.build_query(users).where(age: { :$gt => 18 })
321
- query.trace do |user|
322
- puts user
323
- end
324
- ```
325
-
326
- The debug output will show detailed matching process with full class names:
327
- ```
328
- QueryMatcher Matched, condition: {"age"=>{"$gt"=>18}}, record: {"age"=>25}
329
- AndMatcher Matched, condition: {"age"=>{"$gt"=>18}}, record: {"age"=>25}
330
- FieldMatcher Matched, condition: {"$gt"=>18}, field: "age", record: {"age"=>25}
331
- GtMatcher Matched, condition: 18, record: 25
332
- ```
333
-
334
- The debug output includes:
335
- - The matcher tree structure with full class names
336
- - Each matcher's condition and record value
337
- - Color-coded results (green for matched, red for mismatched, purple for errors)
338
- - Field names highlighted in gray background
339
- - Detailed matching process for each record
340
-
341
- ### Supported Operators
342
-
343
- | Category | Operators |
344
- |--------------|-------------------------------------|
345
- | Comparison | `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte` |
346
- | Set | `$in`, `$nin` |
347
- | Boolean | `$and`, `$or`, `$not` |
348
- | Pattern | `$regex` |
349
- | Presence | `$exists`, `$present` |
350
- | Nested Match | `$elemMatch`, `$every` |
351
- | Other | `$size` |
352
-
353
- Note: Some operators are Mongory-specific and not available in MongoDB:
354
- - `$present`: Checks if a field is considered "present" (not nil, not empty, not KEY_NOT_FOUND)
355
- - Similar to `$exists` but evaluates truthiness of the value
356
- - Example: `where(:name.present => true)`
357
- - `$every`: Checks if all elements in an array match the given condition
358
- - Similar to `$elemMatch` but requires all elements to match
359
- - At least one element in an array, or returns false
360
- - Example: `where(:tags.every => { :priority.gt => 5 })`
361
-
362
- Example:
363
- ```ruby
364
- # $present: Check if field is present (not nil, not empty)
365
- records.mongory.where(:name.present => true) # name is present
366
- records.mongory.where(:name.present => false) # name is not present
367
-
368
- # $every: Check if all array elements match condition
369
- records.mongory.where(:tags.every => { :priority.gt => 5 }) # all tags have priority > 5
370
- ```
371
-
372
- ## FAQ
373
-
374
- ### Q: How does Mongory compare to MongoDB?
375
- A: Mongory provides similar query syntax but operates entirely in memory. It's ideal for:
376
- - Small to medium datasets
377
- - Complex in-memory filtering
378
- - Testing MongoDB-like queries without a database
379
-
380
- ### Q: Can I use Mongory with large datasets?
381
- A: Yes, but consider:
382
- - Memory usage
383
- - Query complexity
384
- - Caching strategies
385
- - Using `limit` early in the chain
386
-
387
- ### Q: How do I handle errors?
388
- ```ruby
389
- begin
390
- result = records.mongory.where(invalid: :condition)
391
- rescue Mongory::Error => e
392
- # Handle error
393
- end
394
- ```
180
+ 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).
395
181
 
396
- ## Troubleshooting
397
-
398
- 1. **Debugging Queries**
399
- ```ruby
400
- records.mongory.where(:age => 18).trace.to_a
401
- ```
402
- If using C extension:
403
- ```ruby
404
- records.mongory.c.where(:age => 18).trace.to_a
405
- ```
406
-
407
- 2. **Common Issues**
408
- - Symbol snippets not working? Call `Mongory.enable_symbol_snippets!`
409
- - Complex queries slow? Use `explain` to analyze
410
- - Memory issues? Consider pagination or streaming
411
-
412
- ## Best Practices
413
-
414
- 1. **Query Composition**
415
- ```ruby
416
- # Good: Use method chaining
417
- records.mongory
418
- .where(:age.gte => 18)
419
- .where(:status => 'active')
420
- .limit(10)
421
-
422
- # Bad: Avoid redundant query creation
423
- query = records.mongory.where(:age.gte => 18)
424
- query = query.where(:status => 'active') # Unnecessary
425
- ```
426
-
427
- 2. **Performance Tips**
428
- ```ruby
429
- # Use limit to restrict result set
430
- records.mongory.limit(100).where(:age.gte => 18)
431
-
432
- # Use fast mode for better performance
433
- records.mongory.where(:age.gte => 18).fast
434
-
435
- # Use explain to analyze complex queries
436
- query = records.mongory.where(:$or => [...])
437
- query.explain
438
- ```
439
-
440
- 3. **Code Organization**
441
- ```ruby
442
- # Encapsulate common queries as methods
443
- class User
444
- def active_adults
445
- friends.mongory
446
- .where(:age.gte => 18)
447
- .where(:status => 'active')
448
- end
449
- end
450
- ```
451
-
452
- ## Limitations
453
-
454
- 1. **Data Size**
455
- - Suitable for small to medium datasets
456
- - Large datasets may impact performance
457
- - Proc-based implementation helps with memory usage
458
- - Context system provides better resource management
459
-
460
- 2. **Query Complexity**
461
- - Complex queries may affect performance
462
- - Not all MongoDB operators are supported
463
- - Proc-based implementation improves complex query performance
464
- - Context system allows better control over query execution
465
-
466
- 3. **Memory Usage**
467
- - All operations are performed in memory
468
- - Consider memory constraints
469
-
470
- ## Contributing
471
-
472
- Contributions are welcome! Here's how you can help:
473
-
474
- 1. **Fork the repository**.
475
- 2. **Create a new branch** for each significant change.
476
- 3. **Write tests** for your changes.
477
- 4. **Send a pull request**.
478
-
479
- Please ensure your code adheres to the project's style guide and that all tests pass before submitting.
480
-
481
- ## Code of Conduct
482
-
483
- Everyone interacting in the Mongory-rb project's codebases, issue trackers, chat rooms, and mailing lists is expected to follow the [code of conduct](https://github.com/mongoryhq/mongory-rb/blob/main/CODE_OF_CONDUCT.md).
484
-
485
- ## License
486
-
487
- MIT. See LICENSE file.
182
+ Released under the [MIT License](LICENSE).