Skip to content

Commit 1e4507b

Browse files
MONGOID-5752 Add #to_mql (#5895)
1 parent fc9b658 commit 1e4507b

File tree

3 files changed

+106
-0
lines changed

3 files changed

+106
-0
lines changed

.rubocop.yml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,9 @@ RSpec/BeforeAfterAll:
7878
RSpec/DescribeClass:
7979
Enabled: false
8080

81+
RSpec/ExampleLength:
82+
Max: 10
83+
8184
RSpec/ImplicitExpect:
8285
EnforcedStyle: is_expected
8386

lib/mongoid/criteria/queryable.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,17 @@ def initialize_copy(other)
8686
@selector = other.selector.__deep_copy__
8787
@pipeline = other.pipeline.__deep_copy__
8888
end
89+
90+
# Returns selector and options of the criteria in form of MongoDB command.
91+
#
92+
# @return [ Hash ] The command.
93+
def to_mql
94+
{
95+
:'$db' => database_name,
96+
find: collection.name,
97+
filter: selector
98+
}.merge(options)
99+
end
89100
end
90101
end
91102
end
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
# frozen_string_literal:true
2+
3+
require 'spec_helper'
4+
5+
describe Mongoid::Criteria::Queryable do
6+
let(:db) do
7+
Mongoid.default_client.database.name
8+
end
9+
10+
let(:collection) do
11+
Band.collection_name.to_s
12+
end
13+
14+
shared_examples 'translatable to mql' do
15+
it 'returns mql' do
16+
expect(criteria.to_mql).to eq(mql)
17+
end
18+
end
19+
20+
describe '#to_mql' do
21+
context 'when simple where' do
22+
let(:criteria) do
23+
Band.where(name: 'Depeche Mode')
24+
end
25+
26+
let(:mql) do
27+
{
28+
'$db': db,
29+
find: collection,
30+
filter: { 'name' => 'Depeche Mode' }
31+
}
32+
end
33+
34+
it_behaves_like 'translatable to mql'
35+
end
36+
37+
context 'with storage field name' do
38+
let(:criteria) do
39+
Band.where(:origin.ne => 'UK')
40+
.in(years: [ 1995, 1996 ])
41+
end
42+
43+
let(:mql) do
44+
{
45+
'$db': db,
46+
find: collection,
47+
filter: {
48+
'origin' => { '$ne' => 'UK' },
49+
'y' => { '$in' => [ 1995, 1996 ] }
50+
}
51+
}
52+
end
53+
54+
it_behaves_like 'translatable to mql'
55+
end
56+
57+
context 'with alias attribute' do
58+
let(:criteria) do
59+
Band.where(d: true)
60+
end
61+
62+
let(:mql) do
63+
{
64+
'$db': db,
65+
find: collection,
66+
filter: { 'deleted' => true }
67+
}
68+
end
69+
70+
it_behaves_like 'translatable to mql'
71+
end
72+
73+
context 'with options' do
74+
let(:criteria) do
75+
Band.where(genres: %w[rock hip-hop]).order(founded: 1).limit(100).skip(200)
76+
end
77+
78+
let(:mql) do
79+
{
80+
'$db': db,
81+
find: collection,
82+
filter: { 'genres' => %w[rock hip-hop] },
83+
limit: 100,
84+
skip: 200,
85+
sort: { 'founded' => 1 }
86+
}
87+
end
88+
89+
it_behaves_like 'translatable to mql'
90+
end
91+
end
92+
end

0 commit comments

Comments
 (0)