Class: Parse::Query
- Inherits:
-
Object
- Object
- Parse::Query
- Extended by:
- ActiveModel::Callbacks
- Includes:
- Enumerable, Client::Connectable, Parse::QueryFieldAliasScope::DirectMethods
- Defined in:
- lib/parse/query.rb,
lib/parse/model/core/actions.rb
Overview
The Query class provides the lower-level querying interface for your Parse collections by utilizing the REST Querying interface. This is the main engine behind making Parse queries on remote collections. It takes a set of constraints and generates the proper hash parameters that are passed to an API request in order to retrieve matching results. The querying design pattern is inspired from DataMapper where symbols are overloaded with specific methods with attached values.
At the core of each item is a Operation. An operation is made up of a field name and an operator. Therefore calling something like :name.eq, defines an equality operator on the field name. Using Operations with values, we can build different types of constraints, known as Constraints.
This component can be used on its own without defining your models as all results are provided in hash form.
Field-Formatter
By convention in Ruby (see
Style Guide),
symbols and variables are expressed in lower_snake_case form. Parse, however,
prefers column names in String#columnize format (ex. objectId,
createdAt and updatedAt). To keep in line with the style
guides between the languages, we do the automatic conversion of the field
names when compiling the query. This feature can be overridden by changing the
value of Query.field_formatter.
# default uses :columnize
query = Parse::User.query :field_one => 1, :FieldTwo => 2, :Field_Three => 3
query.compile_where # => {"fieldOne"=>1, "fieldTwo"=>2, "fieldThree"=>3}
# turn off
Parse::Query.field_formatter = nil
query = Parse::User.query :field_one => 1, :FieldTwo => 2, :Field_Three => 3
query.compile_where # => {"field_one"=>1, "FieldTwo"=>2, "Field_Three"=>3}
# force everything camel case
Parse::Query.field_formatter = :camelize
query = Parse::User.query :field_one => 1, :FieldTwo => 2, :Field_Three => 3
query.compile_where # => {"FieldOne"=>1, "FieldTwo"=>2, "FieldThree"=>3}
Most of the constraints supported by Parse are available to Parse::Query.
Assuming you have a column named field, here are some examples. For an
explanation of the constraints, please see
Parse Query Constraints documentation.
You can build your own custom query constraints by creating a Parse::Constraint
subclass. For all these where clauses assume q is a Parse::Query object.
Defined Under Namespace
Classes: MongoDirectRequired, PointerShapeError
Constant Summary collapse
- BUILT_IN_PARSE_CLASSES =
Built-in Parse classes always considered known, independent of the server schema. Used both as the seed for the dynamic list and as the transient fallback when the schema fetch fails.
%w[ _User _Role _Session _Installation _Audience User Role Session Installation Audience ].freeze
- FIELD_ALIAS_SCOPE_KEY =
Fiber-local scope used by format_field to honor a model's explicit
field:names while a query compiles. Stored in inheritable fiber storage (Fiber[]), so a fiber or thread started while a query compiles sees the same names, and an assignment in the child never leaks back to the parent. The value is a FieldAliasFrame (or nil when no query is compiling). The frame is closed when the block that opened it returns, so a long-lived thread started during a compile stops using that query's names afterwards. :parse_query_field_alias_scope- EMPTY_FIELD_ALIASES =
{}.freeze
- FIELD_ALIAS_CACHE_MAX =
1_000- FIELD_ALIAS_CACHE_MUTEX =
Mutex.new
- FIELD_ALIAS_BUILTINS =
System fields with their own handling, never treated as aliases.
%w[id created_at updated_at acl].freeze
- QUERY_OPTION_KEYS =
The set of symbol keys that #conditions treats as query-shape options (cache TTL, ordering, limits, ACL convenience helpers, session/master-key overrides) rather than as field-name constraints. External callers that need to partition a user-supplied constraints Hash into "real constraints vs query options" — most notably
Parse::Object.first_or_create!andParse::Object.create_or_update!, which must hand a Hash containing ONLY constraint key/value pairs toParse::CreateLock.canonicalize_attrs— consult this set via option_key?.Keep this list in sync with the option branches at the top of #conditions. Anything
conditions()extracts as a query parameter rather than a constraint belongs here. [ :order, :keys, :key, :skip, :limit, :include, :includes, :cache, :use_master_key, :session, :read_preference, :readable_by, :writable_by, :readable_by_role, :writable_by_role, :publicly_readable, :publicly_writable, :privately_readable, :master_key_read_only, :privately_writable, :master_key_write_only, :private_acl, :master_key_only, :not_publicly_readable, :not_publicly_writable, ].to_set.freeze
- COUPLED_OPERATOR_GROUPS =
Operators whose meaning depends on a partner operator in the same hash. Two hashes that both use one of a group are never merged.
[ %w[$regex $options], %w[$near $nearSphere $maxDistance $maxDistanceInRadians $maxDistanceInMiles $maxDistanceInKilometers $geoWithin $geoIntersects $within], %w[$text $search], ].freeze
- HINT_UNSET =
Set a MongoDB index hint for this query. Forces Parse Server (and the underlying MongoDB driver) to use the named index instead of the query planner's choice. Useful for benchmarking or for working around sub-optimal plan selection. The hint is emitted in the compiled REST query body as the
hintparameter (supported by Parse Server 7.4.0+) AND forwarded to the mongo-direct path —results_direct/count_direct/distinct_directpass it to MongoDB.aggregate/MongoDB.find as the Mongohintoption, so a plan diagnosed with #explain can be corrected on either path. :_hint_unset_- RESERVED_EXCLUDE_KEYS =
Reserved fields that #redact_excluded_keys! never strips: dropping these would break #decode (objectId / className / __type) or remove the required Parse envelope. Both the Parse-format names (objectId, createdAt, updatedAt, ACL) and their Mongo storage-form counterparts (_id, _created_at, _updated_at, _acl) are guarded, so the redaction is safe even if it is ever pointed at a raw Mongo document, and a caller can't break reconstruction by excluding e.g.
:_id. This is an SDK safety choice, not an assertion about which fields Parse Server's RESTexcludeKeysstrips. %w[ objectId className __type createdAt updatedAt ACL _id _created_at _updated_at _acl ].freeze
- DIRECT_SUBQUERY_OPERATORS =
Subquery operators the mongo-direct path compiles into
$lookupjoins. MongoDB has no equivalent; passed through verbatim they fail with "unknown operator". %w[$inQuery $notInQuery $select $dontSelect].freeze
- DIRECT_LOGICAL_OPERATORS =
Logical operators whose clauses may hold subquery constraints.
%w[$and $or $nor].freeze
- BLOCKED_PIPELINE_STAGES =
Deprecated.
Retained for backwards compatibility. The canonical list now lives in PipelineSecurity::DENIED_OPERATORS and is enforced recursively, not only at the top-level stage.
Create an Aggregation object for executing arbitrary MongoDB pipelines Pipeline stages that are blocked to prevent data exfiltration or destructive operations.
Parse::PipelineSecurity::DENIED_OPERATORS
Class Attribute Summary collapse
-
.allow_scope_introspection ⇒ Symbol
The method to use when converting field names to Parse column names.
-
.field_formatter ⇒ Symbol
The method to use when converting field names to Parse column names.
Instance Attribute Summary collapse
-
#acl_role ⇒ Parse::Role, ...
readonly
The role the query was scoped to via #scope_to_role, or nil.
-
#acl_user ⇒ Parse::User, ...
readonly
The user the query was scoped to via #scope_to_user, or nil for unscoped queries.
-
#cache ⇒ Boolean, Integer
Set whether this query should be cached and for how long.
-
#client ⇒ Parse::Client
The client to use for making the API request.
-
#key ⇒ String
This parameter is used to support
selectqueries where you have to pass akeyparameter for matching different tables. -
#read_preference ⇒ Symbol, String
Set the MongoDB read preference for this query.
-
#session_token ⇒ Object
Returns the value of attribute session_token.
-
#table ⇒ String
The name of the Parse collection to query against.
-
#use_master_key ⇒ Boolean
True or false on whether we should send the master key in this request.
-
#verbose_aggregate ⇒ Object
Returns the value of attribute verbose_aggregate.
Class Method Summary collapse
-
.all(table, constraints = { limit: :max }) ⇒ Query
Helper method to create a query with constraints for a specific Parse collection.
-
.and(*queries) ⇒ Parse::Query
Combines multiple queries with AND logic using full pipeline approach Each query's complete constraint set is ANDed together.
-
.compile_markers(where) ⇒ Hash
Return the un-stripped reduced hash so the routing/pipeline layer can inspect
__-prefixed markers (e.g."__mongo_direct_only","__aggregation_pipeline"). - .compile_where(where) ⇒ Object
-
.field_aliases_for(table) ⇒ Hash{String => String}
The explicit remote names a model declares: every
field_mapentry whose remote name differs from what Query.format_field would produce for the Ruby name. -
.format_field(str) ⇒ String
Formatted string using Query.field_formatter.
-
.known_parse_classes ⇒ Object
Known Parse classes for fast validation - dynamically loaded from schema.
-
.option_key?(key) ⇒ Boolean
Whether
keyis one of the QUERY_OPTION_KEYS that #conditions absorbs as a query-shape option rather than a field-name constraint. -
.or(*queries) ⇒ Parse::Query
Combines multiple queries with OR logic using full pipeline approach Each query's complete constraint set becomes one branch of the OR condition.
-
.parse_keys_to_nested_keys(keys) ⇒ Hash
Parses keys patterns to build a map of nested fetched keys.
-
.pointer_shape_warned ⇒ Object
Process-wide
[table, field]cache for warn-once dedup in #handle_unresolvable_pointer_in_array!. -
.reset_known_parse_classes! ⇒ Object
Allow resetting the cached known classes (useful for testing).
-
.to_snake_case(str) ⇒ String
Convert camelCase string to snake_case.
-
.with_field_aliases(table) ⇒ Object
Run the block with
table's explicit field aliases in effect for Query.format_field.
Instance Method Summary collapse
-
#add_constraint(operator, value = nil, opts = {}) ⇒ self
Add a constraint to the query.
-
#add_constraints(list) ⇒ self
Combine a list of Constraint objects.
-
#after_prepare { ... } ⇒ Object
A callback called after the query is compiled.
- #aggregate(pipeline, verbose: nil, mongo_direct: nil, rewrite_lookups: nil, raw_values: false, raw_field_names: false, window_before_pipeline: false) ⇒ Object (also: #aggregate_pipeline)
-
#aggregate_from_query(additional_stages = [], verbose: nil, mongo_direct: nil) ⇒ Aggregation
Converts the current query into an aggregate pipeline and executes it.
-
#all(expressions = { limit: :max }) { ... } ⇒ Array<Hash>, Array<Parse::Object>
Similar to #results but takes an additional set of conditions to apply.
- #as_json(*args) ⇒ Hash
-
#atlas_autocomplete(query, field:, **options) ⇒ Parse::AtlasSearch::AutocompleteResult
Execute an autocomplete search using MongoDB Atlas Search.
-
#atlas_facets(query, facets, **options) ⇒ Parse::AtlasSearch::FacetedResult
Execute a faceted search using MongoDB Atlas Search.
-
#atlas_search(query = nil, **options) {|SearchBuilder| ... } ⇒ Parse::AtlasSearch::SearchResult
Execute a full-text search using MongoDB Atlas Search.
-
#average(field) ⇒ Float
(also: #avg)
Calculate the average of values for a specific field.
-
#before_prepare { ... } ⇒ Object
A callback called before the query is compiled.
-
#build_aggregation_pipeline ⇒ Array
Build the complete aggregation pipeline from constraints Pipeline order: $match (regular) -> $lookup (subqueries) -> $match (post-lookup) -> $match (aggregation) -> non-$match stages -> limit/skip.
-
#build_direct_mongodb_pipeline ⇒ Array<Hash>
private
Build an aggregation pipeline optimized for direct MongoDB execution.
-
#build_filter_condition(where) ⇒ Hash
Build a $filter condition expression from where constraints.
-
#build_include_lookup_stages(includes) ⇒ Array<Hash>
private
Build $lookup stages for included pointer fields in direct MongoDB queries.
-
#clause(clause_name = :where) ⇒ Object
returns the query clause for the particular clause.
-
#clear(item = :results) ⇒ self
Clear a specific clause of this query.
-
#clone ⇒ Parse::Query
Creates a deep copy of this query object, allowing independent modifications.
-
#compile(encode: true, includeClassName: false) ⇒ Hash
Complies the query and runs all prepare callbacks.
-
#compile_rest_where ⇒ Hash
The where clause as sent to Parse Server over REST or LiveQuery: #compile_where with bare objectIds on declared pointer fields rewritten into Pointer hashes, so they match the stored pointer.
-
#compile_where ⇒ Hash
A hash representing just the
whereclause of this query, with SDK-internal routing markers stripped. -
#conditions(expressions = {}) ⇒ self
(also: #query, #append)
Add a set of query expressions and constraints.
- #constraints(raw = false) ⇒ Array<Parse::Constraint>, Hash
-
#convert_addfields_for_direct_mongodb(spec) ⇒ Object
private
Convert a $addFields / $set stage for direct MongoDB.
-
#convert_constraints_for_direct_mongodb(constraints) ⇒ Hash
private
Convert constraints for direct MongoDB execution.
-
#convert_field_for_direct_mongodb(field) ⇒ String
private
Convert a field name for direct MongoDB access.
-
#convert_group_for_direct_mongodb(group) ⇒ Object
private
Convert $group stage for direct MongoDB.
-
#convert_match_for_direct_mongodb(match) ⇒ Object
private
Convert a $match stage for direct MongoDB.
-
#convert_projection_for_direct_mongodb(projection) ⇒ Object
private
Convert projection fields for direct MongoDB.
-
#convert_replace_root_for_direct_mongodb(spec) ⇒ Object
private
Convert a $replaceRoot stage for direct MongoDB.
-
#convert_sort_for_direct_mongodb(sort) ⇒ Object
private
Convert sort specification for direct MongoDB.
-
#convert_stage_for_direct_mongodb(stage) ⇒ Hash
private
Convert an aggregation stage for direct MongoDB execution.
-
#convert_value_for_direct_mongodb(field, value) ⇒ Object
private
Convert a value for direct MongoDB execution.
-
#count(mongo_direct: false) ⇒ Integer
Perform a count query.
-
#count_direct(session_token: nil, master: nil, acl_user: nil, acl_role: nil, client: nil) ⇒ Integer
Execute a count query directly against MongoDB, bypassing Parse Server.
-
#count_distinct(field) ⇒ Integer
Perform a count distinct query using MongoDB aggregation pipeline.
-
#cursor(limit: 100, order: nil) ⇒ Parse::Cursor
Create a cursor-based paginator for efficiently traversing large datasets.
-
#declared_column_for_direct_mongodb(field_str) ⇒ String?
private
The storage column for a name the query's model declares, by its Ruby property name or its declared server name, or nil for any other name.
-
#decode(list) ⇒ Array<Parse::Object>
Builds objects based on the set of Parse JSON hashes in an array.
-
#deduplicate_consecutive_match_stages(pipeline) ⇒ Array<Hash>
private
Merge consecutive $match stages in an aggregation pipeline.
-
#direct_merge_clause!(out, key, clauses) ⇒ Object
private
Add a translated logical clause to
outwithout overwriting one that is already there under the same operator. -
#direct_subquery_lookup(field, op, spec, temp) ⇒ Object
private
Build the
$lookupstage for one subquery operator. -
#direct_subquery_present?(constraints) ⇒ Boolean
private
True when a subquery operator appears anywhere in the constraints, at any depth.
-
#direct_subquery_stages(constraints) ⇒ Array(Hash, Array<Hash>)
private
Split compiled constraints into a MongoDB
$matchand the extra stages that implement subquery operators. -
#direct_translate_subquery_clause(clause, lookups, temps) ⇒ Object
private
Translate one clause of a logical operator into a MongoDB filter that reads the join results.
-
#direct_translate_subquery_pair(field, value, plain, out, lookups, temps) ⇒ Object
private
Translate one
field => valueconstraint. -
#distinct(field, return_pointers: false, mongo_direct: false, order: nil) ⇒ Object
Queries can be made using distinct, allowing you find unique values for a specified field.
-
#distinct_direct(field, return_pointers: false, order: nil, session_token: nil, master: nil, acl_user: nil, acl_role: nil, client: nil) ⇒ Array
Execute a distinct query directly against MongoDB, bypassing Parse Server.
-
#distinct_direct_pointers(field, order: nil, session_token: nil, master: nil, acl_user: nil, acl_role: nil, client: nil) ⇒ Array
Convenience method for distinct_direct that always returns Parse::Pointer objects for pointer fields.
-
#distinct_objects(field, return_pointers: false) ⇒ Array
Enhanced distinct method that automatically populates Parse pointer objects at the server level.
-
#distinct_pointers(field, order: nil) ⇒ Array
Convenience method for distinct queries that always return Parse::Pointer objects for pointer fields.
-
#distinct_query_is_scoped? ⇒ Boolean
private
Whether this query carries a non-master-key auth scope.
- #each { ... } ⇒ Array
-
#exclude_keys(*fields) ⇒ self
Set a server-side field denylist for this query.
-
#execute_aggregation_pipeline ⇒ Aggregation
Execute an aggregation pipeline for queries with pipeline constraints.
-
#explain ⇒ Hash
Returns the query execution plan from MongoDB.
-
#extract_subquery_to_lookup_stages(constraints) ⇒ Hash
Extract $inQuery and $notInQuery constraints and build $lookup stages for them.
-
#fetch!(compiled_query) ⇒ Parse::Response
(also: #execute!)
Performs the fetch request for the query.
- #first(limit_or_constraints = 1, mongo_direct: false, **options) ⇒ Object
-
#first_direct(limit_or_constraints = 1) ⇒ Parse::Object, ...
Execute the query directly against MongoDB and return the first result.
-
#get(object_id) ⇒ Parse::Object
Retrieve a single object by its objectId.
-
#get_pointer_target_class(field) ⇒ String?
private
Get the target class name for a pointer field from model references.
-
#group_by(field, flatten_arrays: false, sortable: false, return_pointers: false, mongo_direct: false) ⇒ GroupBy, SortableGroupBy
Group results by a specific field and return a GroupBy object for chaining aggregations.
-
#group_by_date(field, interval, sortable: false, return_pointers: false, timezone: nil, mongo_direct: false) ⇒ GroupByDate, SortableGroupByDate
Group results by a date field at specified time intervals.
-
#group_objects_by(field, return_pointers: false) ⇒ Hash
Group Parse objects by a field value and return arrays of actual objects.
-
#has_subquery_constraints?(constraints) ⇒ Boolean
Check if constraints contain $inQuery or $notInQuery that need resolution.
-
#include(*fields) ⇒ Object
alias for includes.
-
#includes(*fields) ⇒ self
Set a list of Parse Pointer columns to be fetched for matching records.
-
#initialize(table, constraints = {}) ⇒ Query
constructor
Constructor method to create a query with constraints for a specific Parse collection.
-
#inspect ⇒ String
Like the default
inspect, but never prints the session token, which would otherwise reach logs and error reports. -
#keys(*fields) ⇒ self
(also: #select_fields)
Restrict the fields returned by the query.
-
#last_updated(limit = 1, **options) ⇒ Parse::Object+
Returns the most recently updated object(s) (ordered by updated_at descending).
-
#latest(limit = 1, **options) ⇒ Parse::Object+
Returns the most recently created object(s) (ordered by created_at descending).
-
#limit(count) ⇒ self
Limit the number of objects returned by the query.
- #map { ... } ⇒ Array
-
#match_all! ⇒ self
protected
Drop every where constraint, so the query matches all rows.
-
#max(field) ⇒ Object
Find the maximum value for a specific field.
-
#merge_or_scope!(other) ⇒ Object
protected
Combine
other's authority with this query's for an OR. -
#min(field) ⇒ Object
Find the minimum value for a specific field.
-
#not_publicly_readable(mongo_direct: nil) ⇒ Parse::Query
Find objects that are NOT publicly readable.
-
#not_publicly_writable(mongo_direct: nil) ⇒ Parse::Query
Find objects that are NOT publicly writable.
-
#not_readable_by(permission, mongo_direct: nil) ⇒ Parse::Query
Find objects that are NOT readable by the given principal — i.e.
-
#not_writable_by(permission, mongo_direct: nil) ⇒ Parse::Query
Find objects that are NOT writable by the given principal.
-
#or_application_client ⇒ Parse::Client?
protected
The client set on this query when it is a real Parse client other than the default one, or nil.
-
#or_application_identity ⇒ Array<String>?
protected
The application this query runs against, as [application id, server URL], from its own client or the default client.
-
#or_effective_scope ⇒ Hash
protected
The authority this query runs under, as one comparable Hash: the session token, the scoped user id, the scoped role name, and an explicit master-key flag.
-
#or_explicit_client ⇒ Parse::Client?
protected
The client set on this query when it is not the default client, or nil.
-
#or_where(where_clauses = []) ⇒ Query
Combine two where clauses into an OR constraint.
-
#order(*ordering) ⇒ self
Add a sorting order for the query.
-
#pipeline ⇒ Array
Returns the aggregation pipeline for this query if it contains pipeline-based constraints.
-
#pipeline_uses_internal_fields?(pipeline) ⇒ Boolean
Check if the pipeline references internal Parse fields that require MongoDB direct access.
-
#pluck(field) ⇒ Array
Extract values for a specific field from all matching objects.
-
#prepared(includeClassName: false) ⇒ Hash
Returns a compiled query without encoding the where clause.
-
#pretty ⇒ String
Retruns a formatted JSON string representing the query, useful for debugging.
-
#private_acl(mongo_direct: nil) ⇒ Parse::Query
(also: #master_key_only)
Find objects with completely private ACL (no read AND no write permissions).
-
#privately_readable(mongo_direct: nil) ⇒ Parse::Query
(also: #master_key_read_only)
Find objects with no read permissions (master key only).
-
#privately_writable(mongo_direct: nil) ⇒ Parse::Query
(also: #master_key_write_only)
Find objects with no write permissions (master key only).
-
#publicly_readable(mongo_direct: nil) ⇒ Parse::Query
Find objects that are publicly readable (anyone can read).
-
#publicly_writable(mongo_direct: nil) ⇒ Parse::Query
Find objects that are publicly writable (anyone can write).
-
#raise_scoped_aggregation_requires_mongo_direct! ⇒ Object
private
Fail closed for a scoped aggregation that would otherwise fall back to REST /aggregate.
-
#raw { ... } ⇒ Array<Hash>
Returns raw unprocessed results from the query (hash format).
-
#read_pref(preference) ⇒ self
Set the MongoDB read preference for this query.
-
#readable_by(permission, mongo_direct: nil, strict: false) ⇒ Parse::Query
Filter by ACL read permissions using exact permission strings.
-
#readable_by_role(role_name, mongo_direct: nil, strict: false) ⇒ Parse::Query
Filter by ACL read permissions using role names (adds "role:" prefix).
-
#refuse_untranslated_subquery!(node, context: :direct) ⇒ Object
private
Fail closed when a subquery operator is still present after translation.
- #related_to(field, pointer) ⇒ Object
-
#requires_aggregation? ⇒ Boolean
Check if this query requires aggregation pipeline execution.
-
#requires_aggregation_pipeline? ⇒ Boolean
Check if this query contains constraints that require aggregation pipeline processing.
-
#requires_mongo_direct? ⇒ Boolean
Check if this query contains a constraint that can only be answered via mongo-direct (e.g.
$geoIntersectswith a full$geometryagainst a non-GeoPoint column — an operator Parse Server's REST find layer does not expose). -
#result_pointers { ... } ⇒ Array<Parse::Pointer>
(also: #results_pointers)
Returns only pointer objects for all matching results This is memory efficient for large result sets where you only need pointers.
-
#results(raw: false, return_pointers: false, mongo_direct: false) { ... } ⇒ Array<Hash>, Array<Parse::Object>
(also: #result)
Executes the query and builds the result set of Parse::Objects that matched.
-
#results_direct(raw: false, max_time_ms: nil, session_token: nil, master: nil, acl_user: nil, acl_role: nil, client: nil) { ... } ⇒ Array<Parse::Object>, Array<Hash>
Execute the query directly against MongoDB, bypassing Parse Server.
- #rewrite_contained_by_for_direct(value) ⇒ Object private
-
#rewrite_expression_for_direct_mongodb(expr) ⇒ Object
private
Recursively rewrite field references inside an aggregation expression to their direct-MongoDB column names.
-
#scope_to_role(role) ⇒ self
Role-based ACL scoping for service-account-style queries that need "what would a user holding this role see" without minting a session token or naming a specific user.
-
#scope_to_user(user) ⇒ self
Scope a query to a specific user's row-level ACL when it auto-routes through mongo-direct.
- #select { ... } ⇒ Array
-
#skip(amount) ⇒ self
Use with limit to paginate through results.
-
#subscribe(fields: nil, keys: nil, watch: nil, session_token: nil, client: nil, use_master_key: false) {|subscription| ... } ⇒ Parse::LiveQuery::Subscription
Subscribe to real-time updates for objects matching this query.
-
#sum(field) ⇒ Numeric
Calculate the sum of values for a specific field.
- #to_a ⇒ Array
-
#to_pointers(list, field = nil) ⇒ Array<Parse::Pointer>
Builds Parse::Pointer objects based on the set of Parse JSON hashes in an array.
-
#to_table(columns = nil, format: :ascii, headers: nil, sort_by: nil, sort_order: :asc) ⇒ String
Convert query results to a formatted table display.
-
#translate_pipeline_for_direct_mongodb(pipeline) ⇒ Array<Hash>
private
Apply the direct-MongoDB stage converter to every stage in a pipeline.
-
#validate_no_where_operator!(hash) ⇒ Object
deprecated
Deprecated.
Retained for backwards compatibility. Use PipelineSecurity.validate_filter! for new code.
-
#validate_pipeline!(pipeline) ⇒ Object
Validates that a pipeline does not contain dangerous operators.
-
#where(expressions = nil, opts = {}) ⇒ self
Add additional query constraints to the
whereclause. -
#where_constraints ⇒ Hash
Formats the current set of Parse::Constraint instances in the where clause as an expression hash.
-
#where_not_between(field, value) ⇒ self
Add a "field is NOT between" condition — the logical negation of
.where(field.between => value):field < min OR field > maxfor a fully-bounded Range/Array, or a single one-sided comparison when the Range is beginless/endless (mirroring how Constraint::BetweenConstraint itself only constrains the side that is present). -
#writable_by(permission, mongo_direct: nil, strict: false) ⇒ Parse::Query
Filter by ACL write permissions using exact permission strings.
-
#writable_by_role(role_name, mongo_direct: nil, strict: false) ⇒ Parse::Query
Filter by ACL write permissions using role names (adds "role:" prefix).
-
#|(other_query) ⇒ Query
Combine two queries with OR.
Constructor Details
#new(table) ⇒ Query #new(parseSubclass) ⇒ Query
Constructor method to create a query with constraints for a specific Parse collection.
Also sets the default limit count to :max.
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 |
# File 'lib/parse/query.rb', line 801 def initialize(table, constraints = {}) table = table.to_s.to_parse_class if table.is_a?(Symbol) table = table.parse_class if table.respond_to?(:parse_class) raise ArgumentError, "First parameter should be the name of the Parse class (table)" unless table.is_a?(String) @count = 0 #non-zero/1 implies a count query request @where = [] @order = [] @keys = [] @exclude_keys = [] @includes = [] @limit = nil @skip = 0 @table = table @cache = Parse.default_query_cache # Tri-state: `nil` means "no caller preference" — the request layer # then applies the master-key default, the `Parse.client_mode` flag, # and the `Parse.with_session` ambient as configured. Explicit # `true` / `false` (set via `use_master_key=` or the `use_master_key:` # constraint key) wins over both. A `true` default here would # silently smuggle the master-key header past every client-mode # query, so we deliberately leave the decision to the request layer # unless the caller said otherwise. @use_master_key = nil @verbose_aggregate = false @hint = nil conditions constraints end |
Class Attribute Details
.allow_scope_introspection ⇒ Symbol
The method to use when converting field names to Parse column names. Default is String#columnize. By convention Parse uses lowercase-first camelcase syntax for field/column names, but ruby uses snakecase. To support this methodology we process all field constraints through the method defined by the field formatter. You may set this to nil to turn off this functionality.
|
|
# File 'lib/parse/query.rb', line 308
|
.field_formatter ⇒ Symbol
The method to use when converting field names to Parse column names. Default is String#columnize. By convention Parse uses lowercase-first camelcase syntax for field/column names, but ruby uses snakecase. To support this methodology we process all field constraints through the method defined by the field formatter. You may set this to nil to turn off this functionality.
322 323 324 |
# File 'lib/parse/query.rb', line 322 def field_formatter @field_formatter end |
Instance Attribute Details
#acl_role ⇒ Parse::Role, ... (readonly)
Returns the role the query was scoped to via #scope_to_role, or nil.
2924 2925 2926 |
# File 'lib/parse/query.rb', line 2924 def acl_role @acl_role end |
#acl_user ⇒ Parse::User, ... (readonly)
Returns the user the query was scoped to via #scope_to_user, or nil for unscoped queries.
2920 2921 2922 |
# File 'lib/parse/query.rb', line 2920 def acl_user @acl_user end |
#cache ⇒ Boolean, Integer
Set whether this query should be cached and for how long. This parameter
is used to cache queries when using Middleware::Caching. If
the caching middleware is configured, all queries will be cached for the
duration allowed by the cache, and therefore some queries could return
cached results. To disable caching and cached results for this specific query,
you may set this field to false. To specify the specific amount of time
you want this query to be cached, set a duration (in number of seconds) that
the caching middleware should cache this request.
211 |
# File 'lib/parse/query.rb', line 211 attr_reader :table, :session_token |
#client ⇒ Parse::Client
Returns the client to use for making the API request.
211 |
# File 'lib/parse/query.rb', line 211 attr_reader :table, :session_token |
#key ⇒ String
This parameter is used to support select queries where you have to
pass a key parameter for matching different tables.
211 |
# File 'lib/parse/query.rb', line 211 attr_reader :table, :session_token |
#read_preference ⇒ Symbol, String
Set the MongoDB read preference for this query. This allows directing read queries to secondary replicas for load balancing.
211 |
# File 'lib/parse/query.rb', line 211 attr_reader :table, :session_token |
#session_token ⇒ Object
Returns the value of attribute session_token.
211 |
# File 'lib/parse/query.rb', line 211 attr_reader :table, :session_token |
#table ⇒ String
Returns the name of the Parse collection to query against.
211 212 213 |
# File 'lib/parse/query.rb', line 211 def table @table end |
#use_master_key ⇒ Boolean
True or false on whether we should send the master key in this request. If You have provided the master_key when initializing Parse, then all requests will send the master key by default. This feature is useful when you want to make a particular query be performed with public credentials, or on behalf of a user using a #session_token. Default is set to true.
211 |
# File 'lib/parse/query.rb', line 211 attr_reader :table, :session_token |
#verbose_aggregate ⇒ Object
Returns the value of attribute verbose_aggregate.
212 213 214 |
# File 'lib/parse/query.rb', line 212 def verbose_aggregate @verbose_aggregate end |
Class Method Details
.all(table, constraints = { limit: :max }) ⇒ Query
Helper method to create a query with constraints for a specific Parse collection.
Also sets the default limit count to :max.
530 531 532 |
# File 'lib/parse/query.rb', line 530 def all(table, constraints = { limit: :max }) self.new(table, constraints.reverse_merge({ limit: :max })) end |
.and(*queries) ⇒ Parse::Query
Combines multiple queries with AND logic using full pipeline approach Each query's complete constraint set is ANDed together
7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 |
# File 'lib/parse/query.rb', line 7369 def self.and(*queries) queries = queries.flatten.compact return nil if queries.empty? # Get the table from the first query table = queries.first.table # Ensure all queries are for the same table unless queries.all? { |q| q.table == table } raise ArgumentError, "All queries passed to Parse::Query.and must be for the same Parse class." end # Start with an empty query for this table result = self.new(table) # Filter to only queries that have constraints queries = queries.filter { |q| q.where.present? && !q.where.empty? } # Add each query's complete constraint set with AND logic # Multiple constraints in a query are implicitly ANDed together by Parse queries.each do |query| # Compile the where constraints to check if they result in empty conditions compiled_where = Parse::Query.compile_where(query.where) unless compiled_where.empty? # Directly append constraints to result's where array # (where method only accepts Hash, but query.where returns Array<Constraint>) result.instance_variable_get(:@where).concat(query.where) end end result end |
.compile_markers(where) ⇒ Hash
Return the un-stripped reduced hash so the routing/pipeline layer
can inspect __-prefixed markers (e.g. "__mongo_direct_only",
"__aggregation_pipeline"). These markers are SDK-internal hints
and must never be sent to Parse REST or MongoDB — that's what
compile_where is for.
569 570 571 |
# File 'lib/parse/query.rb', line 569 def compile_markers(where) constraint_reduce(where) end |
.compile_where(where) ⇒ Object
558 559 560 |
# File 'lib/parse/query.rb', line 558 def compile_where(where) constraint_reduce(where).reject { |k, _| k.is_a?(String) && k.start_with?("__") } end |
.field_aliases_for(table) ⇒ Hash{String => String}
The explicit remote names a model declares: every field_map entry
whose remote name differs from what format_field would produce
for the Ruby name. Maps both the Ruby name and the remote name to the
remote name, so where(account_id:) and where("account_id" =>)
both compile to the declared column. Names the model does not alias
are absent, so they keep the default formatting.
Cached per table. An entry is reused until a model is defined, a
parse_class is set, or a field is declared (see
Model.model_generation), or until the model's field_map
grows (associations add entries there directly).
432 433 434 |
# File 'lib/parse/query.rb', line 432 def field_aliases_for(table) field_alias_scope_for(table).aliases end |
.format_field(str) ⇒ String
Returns formatted string using field_formatter.
While a query is compiling, a name the query's model declares with
an explicit field: (for example property :account_id, field:
:account_id or field: :authId_sub) is returned exactly as
declared, whether the caller used the Ruby name or the remote name.
336 337 338 339 340 341 342 343 344 345 346 |
# File 'lib/parse/query.rb', line 336 def format_field(str) res = str.to_s.strip frame = Fiber[FIELD_ALIAS_SCOPE_KEY] if frame && frame.open && (mapped = frame.aliases[res]) return mapped end if field_formatter.present? && res.respond_to?(field_formatter) res = res.send(field_formatter) end res end |
.known_parse_classes ⇒ Object
Known Parse classes for fast validation - dynamically loaded from schema.
The successful result is memoized; a failed schema fetch is NOT cached — it returns the built-in fallback for this call only, so a transient server outage during boot doesn't permanently strip every application- defined class from the known set (which would make class-accessibility checks reject custom classes for the process lifetime). The narrowed rescue logs the failure instead of swallowing it silently.
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
# File 'lib/parse/query.rb', line 93 def self.known_parse_classes cached = @known_parse_classes return cached if cached @known_parse_classes_mutex.synchronize do # Re-check under the lock: a racing caller may have populated it. return @known_parse_classes if @known_parse_classes begin response = Parse.client.schemas schema_classes = response.success? ? response.results.map { |cls| cls["className"] } : [] @known_parse_classes = (BUILT_IN_PARSE_CLASSES + schema_classes).uniq.freeze rescue Parse::Error, Faraday::Error => e # Don't cache the fallback — let the next call retry the fetch once # the server is reachable again. warn "[Parse::Query] schema fetch failed (#{e.class}: #{e.}); " \ "falling back to built-in classes for this check only." BUILT_IN_PARSE_CLASSES end end end |
.option_key?(key) ⇒ Boolean
QUERY_OPTION_KEYS must be kept in sync with the
option-branch keys recognized at the top of #conditions.
When adding a new query option, update BOTH places — this
predicate is the public-facing source of truth for callers
that partition query_attrs into constraints vs options
(notably Object.first_or_create! and
Object.create_or_update! for lock canonicalization),
and the option-branch in conditions is what actually
absorbs the option onto the query.
Whether key is one of the QUERY_OPTION_KEYS that #conditions
absorbs as a query-shape option rather than a field-name
constraint. Accepts Symbol or String; returns false for any
other type (including Parse::Operation, which is always a
constraint).
300 301 302 303 |
# File 'lib/parse/query.rb', line 300 def option_key?(key) return false unless key.is_a?(Symbol) || key.is_a?(String) QUERY_OPTION_KEYS.include?(key.to_sym) end |
.or(*queries) ⇒ Parse::Query
Combines multiple queries with OR logic using full pipeline approach Each query's complete constraint set becomes one branch of the OR condition
7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 |
# File 'lib/parse/query.rb', line 7329 def self.or(*queries) queries = queries.flatten.compact return nil if queries.empty? # Get the table from the first query table = queries.first.table # Ensure all queries are for the same table unless queries.all? { |q| q.table == table } raise ArgumentError, "All queries passed to Parse::Query.or must be for the same Parse class." end # Start with an empty query for this table, carrying the members' # common auth scope (raises when two members set different scopes). result = self.new(table) # Run against the members' application: seed the client from the # first member that sets one (the members are then checked to agree). seed = queries.lazy.map { |q| q.send(:or_application_client) }.find(&:itself) result.instance_variable_set(:@client, seed) if seed queries.each { |query| result.send(:merge_or_scope!, query) } # Refuse pipeline-only constraints in any member first, so one is # never dropped or widened. queries.each { |query| compile_or_branch(query.where) } # A query with no constraints matches every row, so an OR that # includes one does too. return result if queries.any? { |q| match_all?(q.where) } # Add each query's complete constraint set as an OR branch queries.each { |query| result.or_where(query.where) } result end |
.parse_keys_to_nested_keys(keys) ⇒ Hash
Parses keys patterns to build a map of nested fetched keys. Handles arbitrary nesting depth (e.g., "a.b.c.d" creates entries for a, b, c). For example, ["project.name", "project.status", "author.email"] becomes: { project: [:name, :status], author: [:email] }
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 |
# File 'lib/parse/query.rb', line 498 def parse_keys_to_nested_keys(keys) return {} if keys.nil? || keys.empty? nested_map = {} keys.each do |key_path| parts = key_path.to_s.split(".") # Skip keys without dots - they're top-level fields, not nested next if parts.length < 2 # Process each level of nesting # For path "a.b.c.d": a gets b, b gets c, c gets d parts.each_with_index do |part, index| field_name = part.to_sym nested_map[field_name] ||= [] # If there's a next part, add it to this field's nested keys if index < parts.length - 1 next_field = parts[index + 1].to_sym nested_map[field_name] << next_field unless nested_map[field_name].include?(next_field) end end end nested_map end |
.pointer_shape_warned ⇒ Object
Process-wide [table, field] cache for warn-once dedup in
#handle_unresolvable_pointer_in_array!.
326 327 328 |
# File 'lib/parse/query.rb', line 326 def pointer_shape_warned @pointer_shape_warned ||= {} end |
.reset_known_parse_classes! ⇒ Object
Allow resetting the cached known classes (useful for testing)
116 117 118 |
# File 'lib/parse/query.rb', line 116 def self.reset_known_parse_classes! @known_parse_classes = nil end |
.to_snake_case(str) ⇒ String
Convert camelCase string to snake_case
488 489 490 |
# File 'lib/parse/query.rb', line 488 def to_snake_case(str) str.to_s.underscore end |
.with_field_aliases(table) ⇒ Object
Run the block with table's explicit field aliases in effect for
format_field. Always sets the scope (possibly to an empty map), so
a subquery on another class, compiled inside an outer query, uses its
own model's names. Re-entering for the table already in scope just
yields. The scope lives in inheritable fiber storage, so concurrent
queries on other threads or fibers are isolated.
357 358 359 360 361 362 363 364 365 366 367 368 369 370 |
# File 'lib/parse/query.rb', line 357 def with_field_aliases(table) table = table.to_s unless table.nil? || table.is_a?(String) previous = Fiber[FIELD_ALIAS_SCOPE_KEY] return yield if table == (previous && previous.open ? previous.scope.table : nil) scope = field_alias_scope_for(table) frame = FieldAliasFrame.new(scope, scope.aliases, true) begin Fiber[FIELD_ALIAS_SCOPE_KEY] = frame yield ensure frame.open = false Fiber[FIELD_ALIAS_SCOPE_KEY] = previous end end |
Instance Method Details
#add_constraint(operator, value = nil, opts = {}) ⇒ self
Add a constraint to the query. This is mainly used internally for compiling constraints.
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 |
# File 'lib/parse/query.rb', line 1431 def add_constraint(operator, value = nil, opts = {}) @where ||= [] constraint = operator # assume Parse::Constraint unless constraint.is_a?(Parse::Constraint) constraint = Parse::Constraint.create(operator, value) end return unless constraint.is_a?(Parse::Constraint) # to support select queries where you have to pass a `key` parameter for matching # different tables. if constraint.operand == :key || constraint.operand == "key" @key = constraint.value return end unless opts[:filter] == false constraint.operand = Query.format_field(constraint.operand) end reject_vector_constraint!(constraint) merge_subquery_scopes!(constraint.value) @where.push constraint @results = nil self #chaining end |
#add_constraints(list) ⇒ self
Combine a list of Constraint objects
1408 1409 1410 1411 1412 1413 |
# File 'lib/parse/query.rb', line 1408 def add_constraints(list) list = Array.wrap(list).select { |m| m.is_a?(Parse::Constraint) } list.each { |c| merge_subquery_scopes!(c.value) } @where = @where + list self end |
#after_prepare { ... } ⇒ Object
A callback called after the query is compiled
130 |
# File 'lib/parse/query.rb', line 130 define_model_callbacks :prepare, only: [:after, :before] |
#aggregate(pipeline, verbose: nil, mongo_direct: nil, rewrite_lookups: nil, raw_values: false, raw_field_names: false, window_before_pipeline: false) ⇒ Object Also known as: aggregate_pipeline
4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 |
# File 'lib/parse/query.rb', line 4988 def aggregate(pipeline, verbose: nil, mongo_direct: nil, rewrite_lookups: nil, raw_values: false, raw_field_names: false, window_before_pipeline: false) validate_pipeline!(pipeline) # Auto-rewrite LLM-style $lookup stages against logical Parse class # names into the Parse-on-Mongo column form (_p_*/parseReference) when # the foreign class declares parse_reference. Idempotent on already- # rewritten input. Controlled by Parse.rewrite_lookups (default true) # or the per-call `rewrite_lookups:` kwarg. pipeline = Parse::LookupRewriter.auto_rewrite( pipeline, class_name: @table, enabled: rewrite_lookups, ) # Automatically prepend query constraints as pipeline stages complete_pipeline = [] lookup_stages = [] # Track if we have $inQuery constraints # Add $match stage from where constraints if any exist unless @where.empty? # `compile_where` is marker-free; `compile_markers` carries the # __aggregation_pipeline stages we need to extract below. where_clause = compile_where markers = compile_markers if where_clause.any? || markers.key?("__aggregation_pipeline") # Collect match conditions and stages initial_match_conditions = [] aggregation_match_conditions = [] non_match_stages = [] post_lookup_match = {} # `where_clause` is already marker-free; treat as regular constraints. regular_constraints = where_clause if regular_constraints.any? # Handle dates first date_converted = convert_dates_for_aggregation(regular_constraints) # Extract $inQuery/$notInQuery and convert to $lookup stages if has_subquery_constraints?(date_converted) lookup_result = extract_subquery_to_lookup_stages(date_converted) date_converted = lookup_result[:constraints] lookup_stages = lookup_result[:lookup_stages] post_lookup_match = lookup_result[:post_lookup_match] end # Convert field names for aggregation context and handle pointers if date_converted.any? match_stage = convert_constraints_for_aggregation(date_converted) initial_match_conditions << match_stage end end # Extract aggregation pipeline stages from the marker view. if markers.key?("__aggregation_pipeline") markers["__aggregation_pipeline"].each do |stage| if stage.is_a?(Hash) && stage.key?("$match") aggregation_match_conditions << stage["$match"] else non_match_stages << stage end end end # Stage 1: Initial $match with regular constraints if initial_match_conditions.any? if initial_match_conditions.length == 1 complete_pipeline << { "$match" => initial_match_conditions.first } else complete_pipeline << { "$match" => { "$and" => initial_match_conditions } } end end # Stage 2: $lookup stages for subqueries ($addFields, $lookup) if lookup_stages.any? lookup_stages.each do |stage| next if stage.key?("$project") complete_pipeline << stage end # Stage 3: Post-lookup $match if post_lookup_match.any? complete_pipeline << { "$match" => post_lookup_match } end # Note: Skip cleanup $project stage - see build_aggregation_pipeline for reasoning end # Stage 5: Aggregation $match conditions if aggregation_match_conditions.any? if aggregation_match_conditions.length == 1 complete_pipeline << { "$match" => aggregation_match_conditions.first } else complete_pipeline << { "$match" => { "$and" => aggregation_match_conditions } } end end # Stage 6: Non-$match stages from aggregation pipeline complete_pipeline.concat(non_match_stages) end end if window_before_pipeline # The query's order / skip / limit select the rows the pipeline # (a `$group` from sum, average, group_by, ...) runs over. Leading # `$match` stages of the pipeline filter rows, so they run first. leading = pipeline.take_while { |stage| stage.is_a?(Hash) && stage.keys == ["$match"] } complete_pipeline.concat(leading) complete_pipeline.concat(query_window_stages) complete_pipeline.concat(pipeline.drop(leading.size)) else # Append the provided pipeline stages complete_pipeline.concat(pipeline) # Add $sort stage from order constraints if any exist sort = query_sort_stage complete_pipeline << sort if sort # Add $skip stage if specified if @skip > 0 complete_pipeline << { "$skip" => @skip } end # Add $limit stage if specified if @limit.is_a?(Numeric) && @limit > 0 complete_pipeline << { "$limit" => @limit } end end # Optimize pipeline by merging consecutive $match stages complete_pipeline = deduplicate_consecutive_match_stages(complete_pipeline) # Auto-detect whether this aggregation must run via the direct-MongoDB # path instead of Parse Server's REST /aggregate endpoint. Three # independent triggers, each of which REST /aggregate cannot serve: # # * $inQuery / $notInQuery → $lookup stages (the original trigger). # * An SDK-injected ACL $match on the internal _rperm / _wperm columns # (readable_by / publicly_readable / writable_by and friends). Parse # Server's REST aggregate rejects a $match on those columns. # * A scoped query (session_token / scope_to_user / scope_to_role). # REST /aggregate is master-key-only and enforces NEITHER ACL NOR # CLP, so a scoped aggregate sent over REST silently runs unscoped # as the master key — leaking sums/min/max/distinct over rows the # caller cannot read. This is the same enforcement asymmetry the # #distinct / #count / #results auto-routes already guard against; # the scalar terminals (sum/average/min/max/count_distinct) all # funnel through here, so routing them here fixes every one. # # `allow_internal_fields` is forwarded for internal-field pipelines: the # caller-supplied `pipeline` arg was validated above (line ~3343) with # the internal-fields denylist active, so any _rperm/_wperm reference in # the merged pipeline is provably SDK-injected, never user input. uses_internal_fields = pipeline_uses_internal_fields?(complete_pipeline) scoped = distinct_query_is_scoped? mongo_ready = defined?(Parse::MongoDB) && Parse::MongoDB.enabled? use_mongo_direct = mongo_direct if scoped # A scoped aggregation (session_token / scope_to_user / scope_to_role) # must NEVER reach Parse Server's REST /aggregate endpoint — it is # master-key-only and enforces NEITHER ACL NOR CLP, so it would run # unscoped as the master key. This holds even when the caller # explicitly passes `mongo_direct: false`: an explicit false cannot # opt a scoped query out of ACL/CLP enforcement. Promote to mongo- # direct, or fail closed when direct Mongo is unavailable (refuse # rather than leak unscoped rows). if mongo_ready use_mongo_direct = true else raise_scoped_aggregation_requires_mongo_direct! end elsif use_mongo_direct.nil? # Unscoped auto-routing: $inQuery/$notInQuery → $lookup pipelines and # SDK-injected internal-field ($rperm/_wperm) pipelines can't be served # by REST /aggregate, so prefer mongo-direct when available. An unscoped # internal-field pipeline keeps the REST fallback (a master-key # correctness edge, not an enforcement bypass). if (lookup_stages && lookup_stages.any?) || uses_internal_fields use_mongo_direct = true if mongo_ready end end # When the pipeline is bound for direct MongoDB, translate every stage # through the direct-MongoDB field rewriter so user-supplied stages # (which use logical Parse field names like `$author`) reach the # correct on-disk columns (`$_p_author`). The Parse Server route does # not need this — Parse Server applies its own translation on the # aggregate endpoint — so the rewrite is gated on use_mongo_direct. if use_mongo_direct complete_pipeline = translate_pipeline_for_direct_mongodb(complete_pipeline) end Aggregation.new(self, complete_pipeline, verbose: verbose, mongo_direct: use_mongo_direct || false, allow_internal_fields: uses_internal_fields, raw_values: raw_values, raw_field_names: raw_field_names) end |
#aggregate_from_query(additional_stages = [], verbose: nil, mongo_direct: nil) ⇒ Aggregation
Converts the current query into an aggregate pipeline and executes it. This method automatically converts all query constraints (where, order, limit, skip, etc.) into MongoDB aggregation pipeline stages.
5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 |
# File 'lib/parse/query.rb', line 5273 def aggregate_from_query(additional_stages = [], verbose: nil, mongo_direct: nil) # Build pipeline from current query constraints pipeline, has_lookup_stages = build_query_aggregate_pipeline # `allow_internal_fields` is computed from the SDK-built portion ONLY # (before appending caller stages): build_query_aggregate_pipeline emits # the _rperm/_wperm $match for readable_by/etc., but `additional_stages` # is caller-supplied and NOT validated here, so we must not sanction an # internal-field reference the caller smuggled in. A scoped query still # routes to mongo-direct regardless (so ACL/CLP enforcement runs). uses_internal_fields = pipeline_uses_internal_fields?(pipeline) # Append any additional stages pipeline.concat(additional_stages) if additional_stages.any? # Same routing contract as #aggregate: $lookup subqueries, an SDK ACL # $match, or a scoped query each require the direct-MongoDB path (REST # /aggregate cannot express _rperm/_wperm and is master-key-only/ # unenforced). A scoped query fails closed when mongo-direct is # unavailable rather than silently running unscoped as master. scoped = distinct_query_is_scoped? mongo_ready = defined?(Parse::MongoDB) && Parse::MongoDB.enabled? use_mongo_direct = mongo_direct if scoped # A scoped aggregation must never reach REST /aggregate (master-key- # only, unenforced) — not even when the caller explicitly passes # mongo_direct: false. Promote to mongo-direct, or fail closed. if mongo_ready use_mongo_direct = true else raise_scoped_aggregation_requires_mongo_direct! end elsif use_mongo_direct.nil? if has_lookup_stages || uses_internal_fields use_mongo_direct = true if mongo_ready end end # Create Aggregation directly to avoid double-applying constraints Aggregation.new(self, pipeline, verbose: verbose, mongo_direct: use_mongo_direct || false, allow_internal_fields: uses_internal_fields) end |
#all(expressions = { limit: :max }) { ... } ⇒ Array<Hash>, Array<Parse::Object>
Similar to #results but takes an additional set of conditions to apply. This method helps support the use of class and instance level scopes.
5755 5756 5757 5758 5759 |
# File 'lib/parse/query.rb', line 5755 def all(expressions = { limit: :max }, &block) conditions(expressions) return results(&block) if block_given? results end |
#as_json(*args) ⇒ Hash
5887 5888 5889 |
# File 'lib/parse/query.rb', line 5887 def as_json(*args) compile.as_json end |
#atlas_autocomplete(query, field:, **options) ⇒ Parse::AtlasSearch::AutocompleteResult
Execute an autocomplete search using MongoDB Atlas Search. Provides search-as-you-type functionality for a specific field.
3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 |
# File 'lib/parse/query.rb', line 3816 def atlas_autocomplete(query, field:, **) require_relative "atlas_search" unless Parse::AtlasSearch.available? raise Parse::AtlasSearch::NotAvailable, "Atlas Search is not available. " \ "Call Parse::AtlasSearch.configure(enabled: true) after configuring Parse::MongoDB." end # Merge query constraints as filter, converted to Mongo storage form # first (see #atlas_search for the reasoning — a raw Parse::Pointer # fails BSON serialization and un-prefixed pointer fields target the # wrong column). compiled_where = compile_where if compiled_where.present? regular_constraints = compiled_where.reject { |f, _| f == "__aggregation_pipeline" } if regular_constraints.any? mongo_constraints = convert_constraints_for_direct_mongodb(regular_constraints) [:filter] = ([:filter] || {}).merge(mongo_constraints) end end # Use query limit if set and no explicit limit provided [:limit] ||= (@limit.is_a?(Numeric) && @limit > 0 ? @limit : 10) [:class_name] = @table # The query's client travels with its identity here too. Without it a # `q.client = other` query reached Atlas Search as the default # application. See #atlas_search_auth_kwargs. .merge!(mongo_direct_client_kwarg) unless .key?(:client) # Forward the query's read_preference (set via `#read_pref`). # See #atlas_search for the parity rationale. if @read_preference && !.key?(:read_preference) [:read_preference] = @read_preference end Parse::AtlasSearch.autocomplete(@table, query, field: field, **) end |
#atlas_facets(query, facets, **options) ⇒ Parse::AtlasSearch::FacetedResult
Execute a faceted search using MongoDB Atlas Search. Returns search results along with aggregated facet counts for filtering.
3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 |
# File 'lib/parse/query.rb', line 3882 def atlas_facets(query, facets, **) require_relative "atlas_search" unless Parse::AtlasSearch.available? raise Parse::AtlasSearch::NotAvailable, "Atlas Search is not available. " \ "Call Parse::AtlasSearch.configure(enabled: true) after configuring Parse::MongoDB." end # Merge query constraints as filter compiled_where = compile_where if compiled_where.present? regular_constraints = compiled_where.reject { |f, _| f == "__aggregation_pipeline" } [:filter] = ([:filter] || {}).merge(regular_constraints) if regular_constraints.any? end # Use query limit/skip if set [:limit] ||= (@limit.is_a?(Numeric) && @limit > 0 ? @limit : 100) [:skip] ||= (@skip > 0 ? @skip : 0) [:class_name] = @table # The query's client travels with its identity here too. Without it a # `q.client = other` query reached Atlas Search as the default # application. See #atlas_search_auth_kwargs. .merge!(mongo_direct_client_kwarg) unless .key?(:client) # Forward the query's read_preference (set via `#read_pref`). # See #atlas_search for the parity rationale. if @read_preference && !.key?(:read_preference) [:read_preference] = @read_preference end Parse::AtlasSearch.faceted_search(@table, query, facets, **) end |
#atlas_search(query = nil, **options) {|SearchBuilder| ... } ⇒ Parse::AtlasSearch::SearchResult
Execute a full-text search using MongoDB Atlas Search. Combines existing query constraints with Atlas Search capabilities.
Supports both simple options hash API and builder block for complex queries.
3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 |
# File 'lib/parse/query.rb', line 3684 def atlas_search(query = nil, **, &block) require_relative "atlas_search" unless Parse::AtlasSearch.available? raise Parse::AtlasSearch::NotAvailable, "Atlas Search is not available. " \ "Call Parse::AtlasSearch.configure(enabled: true) after configuring Parse::MongoDB." end # Determine limit and skip from query or options limit = [:limit] || (@limit.is_a?(Numeric) && @limit > 0 ? @limit : 100) skip_val = [:skip] || (@skip > 0 ? @skip : 0) if block_given? # Builder-block mode: the caller configures the $search stage # directly via the yielded SearchBuilder. Route through # Parse::AtlasSearch.search_with_stage so the SAME SDK-side # enforcement chain as the options API runs — scope resolution, # CLP `find`, the ACL $match placed AFTER $search (not prepended # to stage 0), protectedFields/pointerFields redaction, and the # $expr protected-field oracle guard on the caller filter. # # The previous implementation called Parse::MongoDB.aggregate # with `allow_internal_fields: true` and NO auth forwarding: it # both ran unscoped (resolved to :public / master, no ACL) and, # because that helper prepends the ACL $match at position 0, was # rejected outright by Atlas (which requires $search at stage 0). # It was non-functional under both supported security configs. index_name = [:index] || Parse::AtlasSearch.default_index builder = Parse::AtlasSearch::SearchBuilder.new(index_name: index_name) yield builder # Carry the query's existing constraints as the caller filter, # interpolated into a post-$search $match. The constraints MUST be # converted to Mongo storage form first: `compile_where` yields the # Parse REST shape (pointer keys like `owner`, values that are live # Parse::Pointer objects / Parse date dicts). Fed to a `$match` # verbatim, a Parse::Pointer fails BSON serialization and dates/ids # target the wrong field (`owner` vs `_p_owner`). `convert_- # constraints_for_direct_mongodb` rewrites keys/values to storage # form — the same conversion the mongo-direct path applies, and the # one the pre-5.5.5 block path used before this branch was rewritten. filter = [:filter] compiled_where = compile_where if compiled_where.present? regular_constraints = compiled_where.reject { |f, _| f == "__aggregation_pipeline" } if regular_constraints.any? mongo_constraints = convert_constraints_for_direct_mongodb(regular_constraints) filter = (filter || {}).merge(mongo_constraints) end end search_opts = { filter: filter, limit: limit, skip: skip_val, class_name: @table, raw: [:raw], **atlas_search_auth_kwargs(), } rp = .key?(:read_preference) ? [:read_preference] : @read_preference search_opts[:read_preference] = rp unless rp.nil? search_opts[:max_time_ms] = [:max_time_ms] if .key?(:max_time_ms) Parse::AtlasSearch.search_with_stage(@table, builder.build, **search_opts) else # Simple options API - delegate to AtlasSearch module raise ArgumentError, "query string is required when not using a block" if query.nil? # Merge query constraints as filter. Convert to Mongo storage form # first (same reasoning as the block branch above): compile_where # yields the Parse REST shape (live Parse::Pointer objects, Parse # date dicts, un-prefixed pointer field names) which a raw $match # cannot serialize / would target the wrong column. compiled_where = compile_where if compiled_where.present? regular_constraints = compiled_where.reject { |f, _| f == "__aggregation_pipeline" } if regular_constraints.any? mongo_constraints = convert_constraints_for_direct_mongodb(regular_constraints) [:filter] = ([:filter] || {}).merge(mongo_constraints) end end [:class_name] = @table [:limit] = limit [:skip] = skip_val # The query's client travels with its identity here too. Without it a # `q.client = other` query reached Atlas Search as the default # application. See #atlas_search_auth_kwargs. .merge!(mongo_direct_client_kwarg) unless .key?(:client) # Forward the query's read_preference (set via `#read_pref`). # Without this, Atlas Search calls reached through the Query # bridge silently fall back to the client default even though # the query explicitly opted in to a secondary read — the # mongo-direct path (`#results_direct`) honors it, this one # used to drop it on the floor. if @read_preference && !.key?(:read_preference) [:read_preference] = @read_preference end Parse::AtlasSearch.search(@table, query, **) end end |
#average(field) ⇒ Float Also known as: avg
Calculate the average of values for a specific field.
6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 |
# File 'lib/parse/query.rb', line 6110 def average(field) if field.nil? || !field.respond_to?(:to_s) raise ArgumentError, "Invalid field name passed to `average`." end # Format field name according to Parse conventions formatted_field = format_aggregation_field(field) # Build the aggregation pipeline pipeline = [ { "$group" => { "_id" => nil, "avg" => { "$avg" => "$#{formatted_field}" } } }, ] execute_basic_aggregation(pipeline, "average", field, "avg") end |
#before_prepare { ... } ⇒ Object
A callback called before the query is compiled
130 |
# File 'lib/parse/query.rb', line 130 define_model_callbacks :prepare, only: [:after, :before] |
#build_aggregation_pipeline ⇒ Array
Build the complete aggregation pipeline from constraints Pipeline order: $match (regular) -> $lookup (subqueries) -> $match (post-lookup) -> $match (aggregation) -> non-$match stages -> limit/skip
5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 |
# File 'lib/parse/query.rb', line 5509 def build_aggregation_pipeline pipeline = [] # `compile_where` is already marker-free; `compile_markers` retains # the __aggregation_pipeline marker we need to extract stages from. compiled_where = compile_where markers = compile_markers has_lookup_stages = false # Collect match conditions and stages initial_match_conditions = [] aggregation_match_conditions = [] non_match_stages = [] lookup_stages = [] post_lookup_match = {} # `compiled_where` is already marker-free; use as-is. regular_constraints = compiled_where # Process regular constraints if regular_constraints.any? # Convert symbols to strings and handle date objects for MongoDB aggregation stringified_constraints = convert_dates_for_aggregation(JSON.parse(regular_constraints.to_json)) # Extract $inQuery/$notInQuery and convert to $lookup stages if has_subquery_constraints?(stringified_constraints) lookup_result = extract_subquery_to_lookup_stages(stringified_constraints) stringified_constraints = lookup_result[:constraints] lookup_stages = lookup_result[:lookup_stages] post_lookup_match = lookup_result[:post_lookup_match] has_lookup_stages = lookup_stages.any? end # Convert remaining pointer field names and values to MongoDB aggregation format if stringified_constraints.any? stringified_constraints = convert_constraints_for_aggregation(stringified_constraints) initial_match_conditions << stringified_constraints end end # Extract aggregation pipeline stages (from empty_or_nil, set_equals, etc.) if markers.key?("__aggregation_pipeline") markers["__aggregation_pipeline"].each do |stage| if stage.is_a?(Hash) && stage.key?("$match") # Aggregation $match conditions go after lookup aggregation_match_conditions << stage["$match"] else # Non-$match stages go directly to pipeline non_match_stages << stage end end end # Stage 1: Initial $match with regular constraints (before lookup) # This filters down the dataset before the expensive $lookup if initial_match_conditions.any? if initial_match_conditions.length == 1 pipeline << { "$match" => initial_match_conditions.first } else pipeline << { "$match" => { "$and" => initial_match_conditions } } end end # Stage 2: $lookup stages for subqueries ($addFields, $lookup) # These join with related collections and filter based on subquery conditions if lookup_stages.any? # Add $addFields and $lookup stages (skip $project stages) lookup_stages.each do |stage| next if stage.key?("$project") pipeline << stage end # Stage 3: Post-lookup $match to filter based on lookup results if post_lookup_match.any? pipeline << { "$match" => post_lookup_match } end # Note: We intentionally skip cleanup $project stage because: # 1. Parse Server's aggregation result processing ignores unknown fields # 2. Using $project with exclusions can cause issues in some MongoDB versions # 3. The temporary lookup fields (_lookup_*_id, _lookup_*_result) won't affect the output end # Stage 5: Aggregation $match conditions (from empty_or_nil, set_equals, etc.) if aggregation_match_conditions.any? if aggregation_match_conditions.length == 1 pipeline << { "$match" => aggregation_match_conditions.first } else pipeline << { "$match" => { "$and" => aggregation_match_conditions } } end end # Stage 6: Non-$match stages from aggregation pipeline pipeline.concat(non_match_stages) # Stage 7: Add limit if specified if @limit.is_a?(Numeric) && @limit > 0 pipeline << { "$limit" => @limit } end # Stage 8: Add skip if specified if @skip > 0 pipeline << { "$skip" => @skip } end # Optimize pipeline by merging consecutive $match stages pipeline = deduplicate_consecutive_match_stages(pipeline) [pipeline, has_lookup_stages] end |
#build_direct_mongodb_pipeline ⇒ Array<Hash>
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Build an aggregation pipeline optimized for direct MongoDB execution. This differs from build_aggregation_pipeline in that it uses MongoDB's native field names (id, _created_at, _updated_at, _p* for pointers).
3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 |
# File 'lib/parse/query.rb', line 3921 def build_direct_mongodb_pipeline pipeline = [] # Mirror the REST compile() behavior: ensure each top-level included field # is also in @keys so the $project stage below does not strip the pointer # that the $lookup stage is supposed to expand. merge_includes_into_keys! # Compile the where clause and convert for direct MongoDB access. # `compile_where` already strips `__`-prefixed routing markers; use # `compile_markers` to recover the unfiltered hash for the # __aggregation_pipeline extraction below. compiled_where = compile_where markers = compile_markers # Note: the `_rperm` injection for scope_to_user no longer # happens here. It moved to Parse::MongoDB.aggregate via the # acl_user: kwarg so the same three-layer ACL simulation # (top-level $match + $lookup rewriter + post-fetch redactor) # runs for scope_to_user, session_token, and the public-only # fallback alike. See {#mongo_direct_auth_kwargs}. if compiled_where.present? # Convert field names and values for direct MongoDB access. # `compiled_where` is already marker-free, so no further # reject pass is required. Subquery constraints (`$inQuery`, # `$notInQuery`, `$select`, `$dontSelect`) have no MongoDB # equivalent and are compiled into `$lookup` joins plus a # post-join `$match`; see #direct_subquery_stages. mongo_constraints, subquery_stages = direct_subquery_stages(compiled_where) pipeline << { "$match" => mongo_constraints } if mongo_constraints.any? pipeline.concat(subquery_stages) end # Handle aggregation pipeline stages (from empty_or_nil, set_equals, etc.) if markers.key?("__aggregation_pipeline") markers["__aggregation_pipeline"].each do |stage| pipeline << convert_stage_for_direct_mongodb(stage) end end # Add sort stage if order is specified if @order.any? sort_spec = {} @order.each do |order_clause| # Handle both Parse::Order objects and string representations if order_clause.is_a?(Parse::Order) field = order_clause.field.to_s direction = order_clause.direction == :desc ? -1 : 1 sort_spec[convert_field_for_direct_mongodb(field)] = direction elsif order_clause.is_a?(String) # Parse order clause (e.g., "-createdAt" or "name") if order_clause.start_with?("-") field = order_clause[1..-1] sort_spec[convert_field_for_direct_mongodb(field)] = -1 else sort_spec[convert_field_for_direct_mongodb(order_clause)] = 1 end end end pipeline << { "$sort" => sort_spec } if sort_spec.any? end # Add include/eager loading $lookup stages if @includes is populated # These stages resolve pointer fields to full objects if @includes.any? include_stages = build_include_lookup_stages(@includes) pipeline.concat(include_stages) end # Add skip stage if specified pipeline << { "$skip" => @skip } if @skip > 0 # Add limit stage if specified pipeline << { "$limit" => @limit } if @limit.is_a?(Numeric) && @limit > 0 # Add $project stage if specific keys are requested # Always include required fields: _id, _created_at, _updated_at, _acl if @keys.any? project_stage = { "_id" => 1, "_created_at" => 1, "_updated_at" => 1, "_acl" => 1, } @keys.each do |key| # A dotted key (`meta.k`, `owner.name`) selects its top-level # column on REST: Parse Server keeps the whole `meta` object, or # the whole `owner` pointer. Projecting the dotted path would # return a partial sub-document REST never produces. top = key.to_s.split(".", 2).first next if top.nil? || top.empty? mongo_field = convert_field_for_direct_mongodb(top) project_stage[mongo_field] = 1 end # Keep each include's `$lookup` output. Without it the joined # document was projected away and the field decoded as a bare # pointer even though the caller asked for it to be included. @includes.each do |inc| base = inc.to_s.split(".", 2).first next if base.nil? || base.empty? project_stage["_included_#{base}"] = 1 if get_pointer_target_class(base.to_sym) end pipeline << { "$project" => project_stage } end # Optimize pipeline by merging consecutive $match stages deduplicate_consecutive_match_stages(pipeline) end |
#build_filter_condition(where) ⇒ Hash
Build a $filter condition expression from where constraints
5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 |
# File 'lib/parse/query.rb', line 5714 def build_filter_condition(where) conditions = where.map do |field, value| if value.is_a?(Hash) # Handle operators like $gt, $lt, etc. value.map do |op, val| { op => ["$$item.#{field}", val] } end else # Simple equality { "$eq" => ["$$item.#{field}", value] } end end.flatten if conditions.length == 1 conditions.first else { "$and" => conditions } end end |
#build_include_lookup_stages(includes) ⇒ Array<Hash>
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Build $lookup stages for included pointer fields in direct MongoDB queries. This enables eager loading of related objects when using results_direct.
4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 |
# File 'lib/parse/query.rb', line 4037 def build_include_lookup_stages(includes) return [] if includes.nil? || includes.empty? stages = [] includes.each do |field| # Handle nested includes (e.g., 'artist.label') - only process first level field_str = field.to_s base_field = field_str.split(".").first.to_sym # Get target class from model references target_class = get_pointer_target_class(base_field) next unless target_class # MongoDB pointer field name mongo_pointer_field = "_p_#{base_field}" lookup_result_field = "_included_#{base_field}" lookup_id_field = "_include_id_#{base_field}" # Stage 1: Extract objectId from pointer string using $split # Parse pointers are stored as "ClassName$objectId" stages << { "$addFields" => { lookup_id_field => { "$arrayElemAt" => [ { "$split" => ["$#{mongo_pointer_field}", { "$literal" => "$" }] }, 1, ], }, }, } # Stage 2: $lookup to join with target collection stages << { "$lookup" => { "from" => target_class, "localField" => lookup_id_field, "foreignField" => "_id", "as" => lookup_result_field, }, } # Stage 3: Collapse the `$lookup` array to its single document. # An include that resolves to nothing (dangling pointer, or a row the # scope cannot read, which the ACL rewriter filters out of the # join) becomes an explicit null, so the row converter can drop the # field the way REST does instead of leaving a bare pointer. stages << { "$addFields" => { lookup_result_field => { "$ifNull" => [{ "$arrayElemAt" => ["$#{lookup_result_field}", 0] }, nil], }, }, } # Stage 4: Clean up temporary lookup ID field stages << { "$unset" => lookup_id_field, } end stages end |
#clause(clause_name = :where) ⇒ Object
returns the query clause for the particular clause
1054 1055 1056 1057 |
# File 'lib/parse/query.rb', line 1054 def clause(clause_name = :where) return unless [:keys, :where, :order, :includes, :limit, :skip].include?(clause_name) instance_variable_get "@#{clause_name}".to_sym end |
#clear(item = :results) ⇒ self
Clear a specific clause of this query. This can be one of: :where, :order, :includes, :skip, :limit, :count, :keys or :results.
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 |
# File 'lib/parse/query.rb', line 760 def clear(item = :results) case item when :where # an array of Parse::Constraint subclasses @where = [] when :order # an array of Parse::Order objects @order = [] when :includes @includes = [] when :skip @skip = 0 when :limit @limit = nil when :count @count = 0 when :keys @keys = [] end @results = nil self # chaining end |
#clone ⇒ Parse::Query
The @results instance variable is not cloned. A client that sets the query's authority (session-bound or without a master key) is kept by reference; otherwise the copy uses the default client.
Creates a deep copy of this query object, allowing independent modifications
7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 |
# File 'lib/parse/query.rb', line 7409 def clone cloned_query = Parse::Query.new(self.instance_variable_get(:@table)) # Note: :client is intentionally excluded - it contains non-serializable objects # (Redis connections, Faraday connections) and should be obtained lazily # The auth scope and read routing travel with the copy, so a cloned or # combined query never runs under a broader authority than the # original. [:count, :where, :order, :keys, :exclude_keys, :includes, :limit, :skip, :cache, :use_master_key, :hint, :session_token, :acl_user, :acl_role, :read_preference, :key, :acl_query_mongo_direct, :_or_branch_scope, :_or_branch_app].each do |param| if instance_variable_defined?(:"@#{param}") value = instance_variable_get(:"@#{param}") if value.is_a?(Array) || value.is_a?(Hash) # Use Marshal for deep copy of complex constraint objects begin cloned_value = Marshal.load(Marshal.dump(value)) rescue => e # Fallback to shallow copy if Marshal fails puts "[Parse::Query.clone] Marshal failed for #{param}: #{e.}, falling back to dup" cloned_value = value.dup end else cloned_value = value end cloned_query.instance_variable_set(:"@#{param}", cloned_value) end end # A client set on the query (one from Parse::Client#become or # #anonymous, or a client for another application) decides where the # query's session token and authority are sent, so the copy keeps it. # Only the memoized default client is resolved lazily again. own_client = or_application_client cloned_query.instance_variable_set(:@client, own_client) if own_client cloned_query.instance_variable_set(:@results, nil) cloned_query end |
#compile(encode: true, includeClassName: false) ⇒ Hash
Complies the query and runs all prepare callbacks.
5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 |
# File 'lib/parse/query.rb', line 5905 def compile(encode: true, includeClassName: false) # Validate includes vs keys before compiling validate_includes_vs_keys # When a `keys` allowlist is set alongside `include`, the parent pointer # field must also be in `keys` or Parse Server strips it before expanding # the include. Auto-add the top-level segment of each include so partial # fetches don't silently drop included pointers. merge_includes_into_keys! run_callbacks :prepare do q = {} #query # An explicit `limit(0)` is sent as 0 (no rows). Omitting it would let # the server apply its default page size. q[:limit] = @limit if @limit.is_a?(Numeric) && @limit >= 0 q[:skip] = @skip if @skip > 0 q[:include] = @includes.join(",") unless @includes.empty? q[:keys] = @keys.join(",") unless @keys.empty? q[:excludeKeys] = @exclude_keys.join(",") if encode && @exclude_keys&.any? q[:order] = @order.join(",") unless @order.empty? unless @where.empty? q[:where] = coerce_rest_pointer_ids(Parse::Query.compile_where(@where)) q[:where] = q[:where].to_json if encode end if @count && @count > 0 # if count is requested q[:limit] = 0 q[:count] = 1 end # Read preference must ride the REST query body (restOptions), NOT a # header: Parse Server's middleware does not map any # `X-Parse-Read-Preference` header into request options, so the # header alone is silently ignored and the read always hits the # primary. `RestQuery` reads `readPreference` from restOptions, so # emitting it here is what actually routes the read. (The header is # still sent for any intermediary that honors it; it is harmless.) if encode && (pref = normalized_read_preference) q[:readPreference] = pref end q[:hint] = @hint if @hint if includeClassName q[:className] = @table end q end end |
#compile_rest_where ⇒ Hash
Returns the where clause as sent to Parse Server over REST or LiveQuery: #compile_where with bare objectIds on declared pointer fields rewritten into Pointer hashes, so they match the stored pointer.
5964 5965 5966 5967 |
# File 'lib/parse/query.rb', line 5964 def compile_rest_where refuse_pipeline_only!("a LiveQuery subscription or push target") coerce_rest_pointer_ids(compile_where) end |
#compile_where ⇒ Hash
Returns a hash representing just the where clause of this
query, with SDK-internal routing markers stripped.
5956 5957 5958 |
# File 'lib/parse/query.rb', line 5956 def compile_where self.class.compile_where(@where || []) end |
#conditions(expressions = {}) ⇒ self Also known as: query, append
Add a set of query expressions and constraints.
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 |
# File 'lib/parse/query.rb', line 835 def conditions(expressions = {}) # Apply `:or` last, so a `:session` or `:use_master_key` in the same # Hash is in place before the branches' authority is compared. if expressions.is_a?(Hash) && expressions.key?(:or) && expressions.keys.last != :or expressions = expressions.reject { |k, _| k == :or }.merge(or: expressions[:or]) end expressions.each do |expression, value| # Normalize to symbol for comparison (handles both string and symbol keys) expr_sym = expression.respond_to?(:to_sym) ? expression.to_sym : expression # SEC-06: privilege/auth control options must NOT be settable from an # untrusted, string-keyed conditions hash. `use_master_key` via a # forwarded params hash (e.g. `Query.new(Cls, {"use_master_key" => # true, "ownerId" => "victim"})`) is an ACL/CLP-bypass mass- # assignment; `session` swaps the query's auth principal. Honor these # two ONLY when the caller passed a Symbol key (code-authored). A # string form is treated as an ordinary field constraint — fail-safe: # it matches a literal field of that name and never elevates. if !expression.is_a?(Symbol) && (expr_sym == :use_master_key || expr_sym == :session) warn "[Parse::Query] Ignoring string-keyed control option " \ "#{expression.inspect}; auth/privilege options (:use_master_key, " \ ":session) are honored only as symbol keys to prevent " \ "mass-assignment from untrusted params. Treating it as a field " \ "constraint. Set it via the query method (e.g. `use_master_key: " \ "true` as a symbol) if you intended to control authentication." add_constraint(expression, value) next end if expr_sym == :order order value elsif expr_sym == :keys keys value elsif expr_sym == :key keys [value] elsif expr_sym == :skip skip value elsif expr_sym == :limit limit value elsif expr_sym == :include || expr_sym == :includes includes(value) elsif expr_sym == :cache self.cache = value elsif expr_sym == :use_master_key self.use_master_key = value elsif expr_sym == :session # you can pass a session token or a Parse::Session self.session_token = value elsif expr_sym == :read_preference self.read_preference = value # ACL convenience query options elsif expr_sym == :readable_by readable_by(value) elsif expr_sym == :writable_by writable_by(value) elsif expr_sym == :readable_by_role readable_by_role(value) elsif expr_sym == :writable_by_role writable_by_role(value) elsif expr_sym == :publicly_readable publicly_readable if value elsif expr_sym == :publicly_writable publicly_writable if value elsif expr_sym == :privately_readable || expr_sym == :master_key_read_only privately_readable if value elsif expr_sym == :privately_writable || expr_sym == :master_key_write_only privately_writable if value elsif expr_sym == :private_acl || expr_sym == :master_key_only private_acl if value elsif expr_sym == :not_publicly_readable not_publicly_readable if value elsif expr_sym == :not_publicly_writable not_publicly_writable if value elsif expression == :or # Symbol key only: a string "or" stays a literal field name. add_or_branches(value) else add_constraint(expression, value) end end # each self #chaining end |
#constraints(raw = false) ⇒ Array<Parse::Constraint>, Hash
1521 1522 1523 |
# File 'lib/parse/query.rb', line 1521 def constraints(raw = false) raw ? where_constraints : @where end |
#convert_addfields_for_direct_mongodb(spec) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Convert a $addFields / $set stage for direct MongoDB. Same shape
as $project: { aliasName => <expression> }. Output aliases pass
through verbatim; each value is walked as an aggregation
expression so storage-column references inside reach the correct
column via the schema-aware #convert_field_for_direct_mongodb.
4740 4741 4742 4743 4744 4745 4746 4747 4748 |
# File 'lib/parse/query.rb', line 4740 def convert_addfields_for_direct_mongodb(spec) return spec unless spec.is_a?(Hash) result = {} spec.each do |field, value| result[field] = rewrite_expression_for_direct_mongodb(value) end result end |
#convert_constraints_for_direct_mongodb(constraints) ⇒ Hash
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Convert constraints for direct MongoDB execution.
4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 |
# File 'lib/parse/query.rb', line 4374 def convert_constraints_for_direct_mongodb(constraints) return constraints unless constraints.is_a?(Hash) # $relatedTo resolves a Parse Relation, which is stored in the # `_Join:<key>:<ParentClass>` collection — a join the SDK does NOT # translate on the mongo-direct path. Passed through verbatim it reaches # MongoDB as an unknown `$match` operator and fails with an opaque error; # and any future attempt to rewrite it into a `$lookup` would have to # re-implement the `_rperm` / protectedFields enforcement that the rest of # this path applies post-fetch. Parse Server's own `$relatedTo` was found # to bypass exactly that enforcement (GHSA-wmwx-jr2p-4j4r), so fail closed # here with a clear message rather than risk a silent leak: this query # must run via REST (the default), where Parse Server resolves the # relation under its own ACL / CLP enforcement. if constraints.key?("$relatedTo") || constraints.key?(:"$relatedTo") raise ArgumentError, "[Parse::Query] $relatedTo cannot run on the mongo-direct path; a " \ "Parse Relation is resolved server-side via its join collection. Run " \ "this query via REST (omit `mongo_direct:` / `.results_direct` and any " \ "direct-only constraint), or express the membership as an `$inQuery` " \ "against the relation's join collection." end result = {} constraints.each do |field, value| field_str = field.to_s # Skip special operators if field_str.start_with?("$") # Recursively convert nested constraints in $and, $or, $nor if value.is_a?(Array) && %w[$and $or $nor].include?(field_str) result[field_str] = value.map { |v| convert_constraints_for_direct_mongodb(v) } else result[field_str] = value end next end # Convert field name for MongoDB mongo_field = convert_field_for_direct_mongodb(field_str) # Bare objectIds against a pointer column use the storage form. value = (field_str, value, arrays: true) # `$containedBy` (every array element is in the list) has no MongoDB # operator. Parse Server's equivalent is "no element outside the # list". value = rewrite_contained_by_for_direct(value) # Convert value result[mongo_field] = convert_value_for_direct_mongodb(field_str, value) end result end |
#convert_field_for_direct_mongodb(field) ⇒ String
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Convert a field name for direct MongoDB access.
4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 |
# File 'lib/parse/query.rb', line 4442 def convert_field_for_direct_mongodb(field) field_str = field.to_s # Any field name starting with underscore is non-user-facing and is # passed through verbatim. Parse user-facing properties never start # with `_` (the SDK columnizes snake_case to camelCase before save, # and Parse Server reserves the leading-underscore namespace), so a # field that does is one of: # - a MongoDB/Parse Server internal column (`_id`, `_created_at`, # `_acl`, `_rperm`, `_wperm`, `_hashed_password`, # `_session_token`, `_email_verify_token`, ...) # - a Parse-on-Mongo pointer storage column (`_p_<field>`) # - an SDK-built pipeline-temp alias such as the # `_lookup_<field>_result` / `_lookup_<field>_id` aliases that # `extract_subquery_to_lookup_stages` introduces when an # `$inQuery` constraint compiles to a `$lookup` stage # Columnizing any of these would corrupt the reference: the # previous behavior of routing `_lookup_project_result` through # `format_field` produced `lookupProjectResult` (leading underscore # stripped, snake_case to camelCase), and the post-lookup # `$match` then asked MongoDB for a column that didn't exist, so # every document silently satisfied the constraint. return field_str if field_str.start_with?("_") # A name the model declares, either its Ruby property name or its # declared server name (`belongs_to :owner_ref, field: "OwnerRef"` # takes both `owner_ref` and `OwnerRef`), resolves to the declared # column whether or not a query's field alias scope is active. Left # to the formatter, an unscoped `OwnerRef` columnizes to `ownerRef`, # which no property declares, so it passed through as `OwnerRef` # instead of `_p_OwnerRef`, and a `$ne` / `$nin` / `$exists: false` # on that missing column matched every row. Undeclared names (the # pipeline-local aliases described below) are not affected. declared = declared_column_for_direct_mongodb(field_str) return declared if declared # Apply field formatting for regular fields formatted = Query.format_field(field) case formatted when "objectId" "_id" when "createdAt" "_created_at" when "updatedAt" "_updated_at" else # Schema-aware passthrough: only rewrite names that correspond # to a declared Parse property (or the universal built-ins # handled above). Anything else is treated as a pipeline-local # alias — `$group` accumulator name, `$project` computed field, # `$addFields` output — and the literal text passes through so # the reference matches the output key the upstream stage # produced. # # Concretely: `$status` on a class that declares `status` # remains `status` (`format_field` is a no-op for already- # camelCase names); `$author` on a class that declares a # pointer `author` becomes `$_p_author`; `$contributor_set` # (an alias the caller introduced in `$group`) stays # `$contributor_set` because no such property exists in the # schema. Callers reading the result row by `row[alias_name]` # see exactly the spelling they wrote into the pipeline. # # @note Two documented limitations of the schema-aware rule: # # 1. **Alias shadowing.** An alias whose name shadows a # declared Parse property (`$group { author: ... }` where # `author` is a pointer) is treated as the property — # downstream `$author` references resolve to `$_p_author`, # the storage column, not the alias. Avoid alias names that # collide with declared property names. The same naming # constraint MongoDB aggregation pipelines have generally; # not unique to parse-stack. # # 2. **Undeclared server columns.** Conversely, a `$field` # reference whose name corresponds to a column that exists # on the server but is NOT declared as a property on the # Ruby model passes through verbatim. The schema we consult # is the SDK-side property registry; we do not introspect # the live server schema on every translation. If you need # references in mongo-direct pipelines to translate # snake_case → camelCase or take a `_p_*` prefix, declare # the corresponding property on the Ruby model. Workaround # without declaring: write the storage-column name directly # (`$_p_author`, `$companyName`), which short-circuits the # walker via the leading-underscore / already-formatted # paths. return field_str unless field_is_known_to_schema?(formatted) if field_is_pointer?(formatted) "_p_#{formatted}" else formatted end end end |
#convert_group_for_direct_mongodb(group) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Convert $group stage for direct MongoDB. Output-alias keys
(_id, accumulator names like contributor_set) pass through
verbatim so the result row uses whatever spelling the caller
wrote. Each value — the _id group-key expression and every
accumulator expression — is walked as an aggregation expression
so $field references inside reach the correct storage column
(_p_* for pointers, _id/_created_at/_updated_at for
built-ins, untouched for unknown names i.e. pipeline-local
aliases) via the schema-aware
#convert_field_for_direct_mongodb.
4724 4725 4726 4727 4728 4729 4730 4731 4732 |
# File 'lib/parse/query.rb', line 4724 def convert_group_for_direct_mongodb(group) return group unless group.is_a?(Hash) result = {} group.each do |field, value| result[field] = rewrite_expression_for_direct_mongodb(value) end result end |
#convert_match_for_direct_mongodb(match) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Convert a $match stage for direct MongoDB. Rewrites top-level field-name keys via #convert_constraints_for_direct_mongodb and additionally walks the value of a top-level $expr as an aggregation expression so nested $fieldName references are rewritten.
4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 |
# File 'lib/parse/query.rb', line 4668 def convert_match_for_direct_mongodb(match) converted = convert_constraints_for_direct_mongodb(match) return converted unless converted.is_a?(Hash) # The constraint converter passes $expr through unchanged. Rewrite # its value here so e.g. {$expr: {$eq: ["$author", "$approver"]}} # becomes {$expr: {$eq: ["$_p_author", "$_p_approver"]}}. expr_key = converted.key?("$expr") ? "$expr" : (converted.key?(:"$expr") ? :"$expr" : nil) return converted unless expr_key result = converted.dup result[expr_key] = rewrite_expression_for_direct_mongodb(converted[expr_key]) result end |
#convert_projection_for_direct_mongodb(projection) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Convert projection fields for direct MongoDB. Output-key aliases
pass through verbatim — what the caller writes is what the result
row will be keyed by. Values that are aggregation expressions
(e.g. { "$cond": [...] }) are walked recursively so nested
$fieldName references reach the correct storage column via the
schema-aware rewriter in #convert_field_for_direct_mongodb.
4690 4691 4692 4693 4694 4695 4696 4697 4698 |
# File 'lib/parse/query.rb', line 4690 def convert_projection_for_direct_mongodb(projection) return projection unless projection.is_a?(Hash) result = {} projection.each do |field, value| result[field] = rewrite_expression_for_direct_mongodb(value) end result end |
#convert_replace_root_for_direct_mongodb(spec) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Convert a $replaceRoot stage for direct MongoDB. Argument shape is
{ newRoot: <expression> }; only the newRoot value is an
expression. (Use #rewrite_expression_for_direct_mongodb directly
for $replaceWith, whose argument is the expression itself.)
4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 |
# File 'lib/parse/query.rb', line 4755 def convert_replace_root_for_direct_mongodb(spec) return rewrite_expression_for_direct_mongodb(spec) unless spec.is_a?(Hash) new_root_key = spec.key?("newRoot") ? "newRoot" : (spec.key?(:newRoot) ? :newRoot : nil) return rewrite_expression_for_direct_mongodb(spec) unless new_root_key result = spec.dup result[new_root_key] = rewrite_expression_for_direct_mongodb(spec[new_root_key]) result end |
#convert_sort_for_direct_mongodb(sort) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Convert sort specification for direct MongoDB.
4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 |
# File 'lib/parse/query.rb', line 4702 def convert_sort_for_direct_mongodb(sort) return sort unless sort.is_a?(Hash) result = {} sort.each do |field, direction| mongo_field = convert_field_for_direct_mongodb(field) result[mongo_field] = direction end result end |
#convert_stage_for_direct_mongodb(stage) ⇒ Hash
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Convert an aggregation stage for direct MongoDB execution.
Projection-shape stages ($project, $addFields, $set, $replaceRoot, $replaceWith) and accumulator/grouping stages ($group) carry aggregation expressions that can reference fields via $fieldName strings. These references must be rewritten to the direct-MongoDB column form (camelCase, p* for pointers, _id/_created_at/_updated_at for built-ins). The rewrite walks recursively into $cond / $eq / $switch / $expr argument arrays so a nested reference is not missed. See #rewrite_expression_for_direct_mongodb.
$match is special: its top-level keys are field-name constraints (rewritten via the constraint converter), but the value of a top-level $expr is an aggregation expression that must also be walked.
4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 |
# File 'lib/parse/query.rb', line 4635 def convert_stage_for_direct_mongodb(stage) return stage unless stage.is_a?(Hash) result = {} stage.each do |operator, value| case operator.to_s when "$match" result[operator] = convert_match_for_direct_mongodb(value) when "$project" result[operator] = convert_projection_for_direct_mongodb(value) when "$sort" result[operator] = convert_sort_for_direct_mongodb(value) when "$group" result[operator] = convert_group_for_direct_mongodb(value) when "$addFields", "$set" result[operator] = convert_addfields_for_direct_mongodb(value) when "$replaceRoot" result[operator] = convert_replace_root_for_direct_mongodb(value) when "$replaceWith" # $replaceWith's argument is the new-root expression directly. result[operator] = rewrite_expression_for_direct_mongodb(value) else result[operator] = value end end result end |
#convert_value_for_direct_mongodb(field, value) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Convert a value for direct MongoDB execution.
4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 |
# File 'lib/parse/query.rb', line 4575 def convert_value_for_direct_mongodb(field, value) case value when Hash # Handle both string and symbol keys for __type checks type_value = value["__type"] || value[:__type] if type_value == "Pointer" # Convert Parse pointer to MongoDB pointer string format class_name = value["className"] || value[:className] object_id = value["objectId"] || value[:objectId] "#{class_name}$#{object_id}" elsif type_value == "Date" # Convert Parse Date format to Time object for BSON Date iso_value = value["iso"] || value[:iso] Time.parse(iso_value).utc else # Recursively convert nested hash (for operators like $gt, $in, etc.) # Convert symbol keys to strings for MongoDB converted = {} value.each do |k, v| key_str = k.to_s converted[key_str] = convert_value_for_direct_mongodb(field, v) end converted end when Parse::Pointer "#{value.parse_class}$#{value.id}" when Parse::Date # Parse::Date extends DateTime - convert to Time for BSON Date value.to_time.utc when Time value.utc when DateTime value.to_time.utc when Date value.to_time.utc when Array value.map { |v| convert_value_for_direct_mongodb(field, v) } else value end end |
#count(mongo_direct: false) ⇒ Integer
Perform a count query.
2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 |
# File 'lib/parse/query.rb', line 2150 def count(mongo_direct: false) # Use direct MongoDB query if requested return count_direct if mongo_direct # Auto-route to mongo-direct when the compiled where contains a # direct-only constraint. Same gate as #results. if requires_mongo_direct? assert_mongo_direct_routable! return count_direct(**mongo_direct_auth_kwargs) end # Check if this query requires aggregation pipeline processing if requires_aggregation_pipeline? # Build aggregation pipeline with $count stage pipeline, has_lookup_stages = build_aggregation_pipeline pipeline << { "$count" => "count" } # Auto-detect if MongoDB direct is needed. Mirror the routing in # #execute_aggregation_pipeline: a pipeline that references internal # ACL columns (_rperm/_wperm via readable_by/publicly_readable and # friends) MUST run mongo-direct — Parse Server's REST aggregate # endpoint cannot express a $match on those columns — and the # mongo-direct sink must be told the references are sanctioned so # the PipelineSecurity internal-fields denylist lets them through. uses_internal_fields = pipeline_uses_internal_fields?(pipeline) scoped = distinct_query_is_scoped? use_mongo_direct = false if defined?(@acl_query_mongo_direct) && !@acl_query_mongo_direct.nil? use_mongo_direct = @acl_query_mongo_direct elsif (scoped || has_lookup_stages || uses_internal_fields) && defined?(Parse::MongoDB) && Parse::MongoDB.enabled? use_mongo_direct = true elsif scoped # Same fail-closed contract as #aggregate / #aggregate_from_query: # a scoped count must not fall back to REST /aggregate, which # would drop the scope and count rows the caller cannot read. raise_scoped_aggregation_requires_mongo_direct! end # Execute aggregation aggregation = Aggregation.new(self, pipeline, verbose: @verbose_aggregate, mongo_direct: use_mongo_direct, allow_internal_fields: uses_internal_fields) response = aggregation.execute! # Extract count from aggregation result if use_mongo_direct # MongoDB direct returns raw array return 0 if response.nil? || response.empty? response.first["count"] || 0 else return 0 if response.error? || !response.result.is_a?(Array) || response.result.empty? response.result.first["count"] || 0 end else # Use standard count endpoint for non-aggregation queries old_value = @count @count = 1 res = client.find_objects(@table, compile.as_json, **_opts).count @count = old_value res end end |
#count_direct(session_token: nil, master: nil, acl_user: nil, acl_role: nil, client: nil) ⇒ Integer
This is a read-only operation. Direct MongoDB queries cannot modify data.
Execute a count query directly against MongoDB, bypassing Parse Server. This is useful for performance-critical count operations.
3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 |
# File 'lib/parse/query.rb', line 3460 def count_direct(session_token: nil, master: nil, acl_user: nil, acl_role: nil, client: nil) enforce_explicit_auth_against_or_scope!(session_token: session_token, master: master, acl_user: acl_user, acl_role: acl_role, client: client) require_relative "mongodb" Parse::MongoDB.require_gem! unless Parse::MongoDB.available? raise Parse::MongoDB::NotEnabled, "Direct MongoDB queries are not enabled. " \ "Call Parse::MongoDB.configure(uri: 'mongodb://...', enabled: true) first." end # A query already owns a client. Defaulting to it means a query built # from a secondary client does not have to repeat itself, and cannot # silently authorize against the default application by omission. # # Resolved defensively: `#client` lazily constructs the DEFAULT client # and raises ConnectionError when none is configured. Argument # validation below must still be able to raise ArgumentError in a # process that never called Parse.setup, so a missing client is left # nil here and resolved at the authorization boundary instead. client ||= (self.client rescue nil) # Build the aggregation pipeline for direct MongoDB execution pipeline = build_direct_mongodb_pipeline # Remove limit and skip for count (we want total count) pipeline = pipeline.reject { |stage| stage.key?("$limit") || stage.key?("$skip") } # Add count stage pipeline << { "$count" => "count" } # When no explicit auth kwargs are provided, derive them from the # query's own auth state — same fallback as results_direct. if session_token.nil? && master.nil? && acl_user.nil? && acl_role.nil? auth = mongo_direct_auth_kwargs session_token = auth[:session_token] master = auth[:master] acl_user = auth[:acl_user] acl_role = auth[:acl_role] end # SDK-built pipeline only — see results_direct for rationale. # ACL simulation runs inside Parse::MongoDB.aggregate when # session_token: or master: is supplied. raw_results = Parse::MongoDB.aggregate(@table, pipeline, allow_internal_fields: true, session_token: session_token, master: master, acl_user: acl_user, acl_role: acl_role, client: client, read_preference: @read_preference, hint: @hint) # Extract count from result return 0 if raw_results.empty? raw_results.first["count"] || 0 end |
#count_distinct(field) ⇒ Integer
This feature requires MongoDB aggregation pipeline support in Parse Server.
Perform a count distinct query using MongoDB aggregation pipeline. This counts the number of distinct values for a given field.
2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 |
# File 'lib/parse/query.rb', line 2226 def count_distinct(field) if field.nil? || !field.respond_to?(:to_s) raise ArgumentError, "Invalid field name passed to `count_distinct`." end # Format field name according to Parse conventions # Handle special MongoDB field mappings for aggregation formatted_field = case field.to_s when "created_at", "createdAt" "_created_at" when "updated_at", "updatedAt" "_updated_at" else Query.format_field(field) end # Build the aggregation pipeline pipeline = [ { "$group" => { "_id" => "$#{formatted_field}" } }, { "$count" => "distinctCount" }, ] # `limit(0)` selects no rows. return 0 if @limit == 0 # Use the Aggregation class to execute # The aggregate method will automatically handle where conditions, # and the query's order / skip / limit pick the rows before `$group`. aggregation = aggregate(pipeline, verbose: @verbose_aggregate, window_before_pipeline: true) raw_results = aggregation.raw # Extract the count from the response if raw_results.is_a?(Array) && raw_results.first raw_results.first["distinctCount"] || 0 else 0 end end |
#cursor(limit: 100, order: nil) ⇒ Parse::Cursor
Create a cursor-based paginator for efficiently traversing large datasets.
Cursor-based pagination is more efficient than skip/offset pagination for large datasets because it uses the last seen objectId to fetch the next page, rather than skipping over records.
4833 4834 4835 |
# File 'lib/parse/query.rb', line 4833 def cursor(limit: 100, order: nil) Parse::Cursor.new(self, limit: limit, order: order) end |
#declared_column_for_direct_mongodb(field_str) ⇒ String?
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
The storage column for a name the query's model declares, by its Ruby
property name or its declared server name, or nil for any other name.
A pointer resolves to _p_<server name>. Built-in system fields and
server names that start with _ are left to the default handling.
4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 |
# File 'lib/parse/query.rb', line 4548 def declared_column_for_direct_mongodb(field_str) return nil if field_str.empty? || field_str.include?(".") klass = table_model_class return nil unless klass.respond_to?(:field_map) && klass.respond_to?(:fields) fmap = klass.field_map sym = field_str.to_sym local = if fmap.key?(sym) sym else fmap.find { |_k, remote| remote.to_s == field_str }&.first end return nil if local.nil? return nil if Query::FIELD_ALIAS_BUILTINS.include?(local.to_s) remote = fmap[local].to_s return nil if remote.empty? || remote.start_with?("_") return nil if %w[objectId createdAt updatedAt ACL].include?(remote) type = klass.fields[local] || klass.fields[remote.to_sym] type == :pointer ? "_p_#{remote}" : remote rescue NameError nil end |
#decode(list) ⇒ Array<Parse::Object>
Builds objects based on the set of Parse JSON hashes in an array.
5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 |
# File 'lib/parse/query.rb', line 5764 def decode(list) # Pass fetched keys for partial fetch tracking (only if keys were specified) fetch_keys = @keys.present? && @keys.any? ? @keys : nil # Parse keys (not includes) to build nested fetched keys map # Keys like ["project.name", "project.status"] define which subfields to fetch on nested objects nested_keys = Parse::Query.parse_keys_to_nested_keys(@keys) if @keys.present? built = list.map { |m| Parse::Object.build(m, @table, fetched_keys: fetch_keys, nested_fetched_keys: nested_keys) }.compact # Record session owners against the client that fetched them, so a # later delete of an already-gone session can still drop its owner's # cached identities. Parse::Session._remember_owners!(built, client) if @table == Parse::Model::CLASS_SESSION && defined?(Parse::Session) built end |
#deduplicate_consecutive_match_stages(pipeline) ⇒ Array<Hash>
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Merge consecutive $match stages in an aggregation pipeline. This optimization combines redundant stages that can occur when building pipelines from multiple constraint sources. Identical stages are deduplicated, and non-identical consecutive $match stages are merged using $and.
4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 |
# File 'lib/parse/query.rb', line 4937 def deduplicate_consecutive_match_stages(pipeline) return pipeline if pipeline.empty? result = [] pipeline.each do |stage| if stage.is_a?(Hash) && stage.key?("$match") && result.last.is_a?(Hash) && result.last.key?("$match") prev_match = result.last["$match"] curr_match = stage["$match"] # Skip if identical next if prev_match == curr_match # Merge the two $match stages using $and # Handle cases where either side might already have $and prev_conditions = prev_match.key?("$and") ? prev_match["$and"] : [prev_match] curr_conditions = curr_match.key?("$and") ? curr_match["$and"] : [curr_match] # Replace the previous $match with the merged version result[-1] = { "$match" => { "$and" => prev_conditions + curr_conditions } } else result << stage end end result end |
#direct_merge_clause!(out, key, clauses) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Add a translated logical clause to out without overwriting one that
is already there under the same operator.
4248 4249 4250 4251 4252 4253 4254 4255 |
# File 'lib/parse/query.rb', line 4248 def direct_merge_clause!(out, key, clauses) if out.key?(key) existing = out.delete(key) out["$and"] = Array(out.delete("$and")) + [{ key => existing }, { key => clauses }] else out[key] = clauses end end |
#direct_subquery_lookup(field, op, spec, temp) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Build the $lookup stage for one subquery operator.
4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 |
# File 'lib/parse/query.rb', line 4307 def direct_subquery_lookup(field, op, spec, temp) spec = (spec || {}).transform_keys(&:to_s) if op == "$select" || op == "$dontSelect" query = (spec["query"] || {}) query = query.transform_keys(&:to_s) if query.is_a?(Hash) class_name = query["className"].to_s where = query["where"] || {} key = (spec["key"] || field).to_s else class_name = spec["className"].to_s where = spec["where"] || {} key = nil end if class_name.empty? raise ArgumentError, "[Parse::Query] #{op} on '#{field}' is missing the subquery className." end sub = Parse::Query.new(class_name) sub_match, sub_stages = Parse::Query.with_field_aliases(class_name) do sub.send(:direct_subquery_stages, where.is_a?(Hash) ? where : {}) end local = convert_field_for_direct_mongodb(field) if key.nil? # `$inQuery` / `$notInQuery` compare a pointer column, stored as # `Class$objectId`, with the subquery row's `_id`. local = "_p_#{Query.format_field(field)}" unless local.start_with?("_p_") pipeline = [ { "$match" => { "$expr" => { "$eq" => ["$_id", "$$subquery_id"] } } }, ] pipeline << { "$match" => sub_match } if sub_match.any? pipeline.concat(sub_stages) pipeline << { "$limit" => 1 } { "$lookup" => { "from" => class_name, "let" => { "subquery_id" => { "$arrayElemAt" => [{ "$split" => ["$#{local}", { "$literal" => "$" }] }, 1], }, }, "pipeline" => pipeline, "as" => temp, }, } else foreign = Parse::Query.with_field_aliases(class_name) { sub.send(:convert_field_for_direct_mongodb, key) } pipeline = [] pipeline << { "$match" => sub_match } if sub_match.any? pipeline.concat(sub_stages) pipeline << { "$match" => { "$expr" => { "$eq" => ["$#{foreign}", "$$subquery_value"] } } } pipeline << { "$limit" => 1 } { "$lookup" => { "from" => class_name, "let" => { "subquery_value" => "$#{local}" }, "pipeline" => pipeline, "as" => temp, }, } end end |
#direct_subquery_present?(constraints) ⇒ Boolean
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Returns true when a subquery operator appears anywhere in the constraints, at any depth.
4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 |
# File 'lib/parse/query.rb', line 4292 def direct_subquery_present?(constraints) case constraints when Hash constraints.any? do |key, value| DIRECT_SUBQUERY_OPERATORS.include?(key.to_s) || direct_subquery_present?(value) end when Array constraints.any? { |child| direct_subquery_present?(child) } else false end end |
#direct_subquery_stages(constraints) ⇒ Array(Hash, Array<Hash>)
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Split compiled constraints into a MongoDB $match and the extra
stages that implement subquery operators.
$inQuery/$notInQuery:$lookupthe pointed-to row in the subquery's class, filtered by the subquery'swhere, then keep rows whose join is non-empty (or empty).$select/$dontSelect:$lookuprows of the subquery's class matching itswherewhosekeyequals this row's field, then keep rows whose join is non-empty (or empty).
A subquery inside $and / $or / $nor (at any depth, as
or_where produces) gets its own $lookup too. The logical clause
holding it moves to the post-join $match, with the subquery replaced
by a test on its join result, so $or keeps its meaning. Constraints
with no subquery stay in the first $match, ahead of the joins. A
subquery in any other position (under $not, $elemMatch, $expr)
cannot be translated and raises ArgumentError rather than reaching
MongoDB as an unknown operator.
The joins run through Parse::MongoDB.aggregate, so the ACL rewriter
filters the joined rows by _rperm, the joined class's CLP is
checked, and a where on the joined class's protectedFields is
refused, as Parse Server does for its subqueries. Temporary join
columns are removed with $unset.
4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 |
# File 'lib/parse/query.rb', line 4169 def direct_subquery_stages(constraints) unless direct_subquery_present?(constraints) return [convert_constraints_for_direct_mongodb(constraints), []] end plain = {} post = {} lookups = [] temps = [] constraints.each do |field, value| direct_translate_subquery_pair(field, value, plain, post, lookups, temps) end match = convert_constraints_for_direct_mongodb(plain) refuse_untranslated_subquery!(match) refuse_untranslated_subquery!(post) stages = lookups stages << { "$match" => post } if post.any? stages << { "$unset" => temps } if temps.any? [match, stages] end |
#direct_translate_subquery_clause(clause, lookups, temps) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Translate one clause of a logical operator into a MongoDB filter that reads the join results.
4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 |
# File 'lib/parse/query.rb', line 4227 def direct_translate_subquery_clause(clause, lookups, temps) unless clause.is_a?(Hash) raise ArgumentError, "[Parse::Query] a logical operator clause holding a subquery must be a Hash, got #{clause.class}." end plain = {} out = {} clause.each do |field, value| direct_translate_subquery_pair(field, value, plain, out, lookups, temps) end converted = convert_constraints_for_direct_mongodb(plain) return converted.merge(out) if (converted.keys & out.keys).empty? # The same operator appeared twice (a String and a Symbol key). # Keep both by matching them together rather than letting one # overwrite the other. { "$and" => [converted, out] } end |
#direct_translate_subquery_pair(field, value, plain, out, lookups, temps) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Translate one field => value constraint. A constraint with no
subquery is collected into plain unchanged (converted later by the
caller). A subquery operator adds a $lookup to lookups and a test
on its join result to out. A logical operator holding a subquery is
rebuilt clause by clause into out.
4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 |
# File 'lib/parse/query.rb', line 4197 def direct_translate_subquery_pair(field, value, plain, out, lookups, temps) key = field.to_s if DIRECT_LOGICAL_OPERATORS.include?(key) && value.is_a?(Array) if direct_subquery_present?(value) direct_merge_clause!(out, key, value.map { |clause| direct_translate_subquery_clause(clause, lookups, temps) }) else plain[field] = value end return end ops = value.is_a?(Hash) ? value.keys.map(&:to_s) & DIRECT_SUBQUERY_OPERATORS : [] if ops.empty? plain[field] = value return end others = value.reject { |k, _| DIRECT_SUBQUERY_OPERATORS.include?(k.to_s) } plain[field] = others if others.any? ops.each do |op| spec = value.key?(op) ? value[op] : value[op.to_sym] temp = "_subquery_#{temps.size}_#{key.gsub(/[^A-Za-z0-9_]/, "_")}" temps << temp lookups << direct_subquery_lookup(key, op, spec, temp) out[temp] = %w[$inQuery $select].include?(op) ? { "$ne" => [] } : { "$eq" => [] } end end |
#distinct(field, return_pointers: false, mongo_direct: false, order: nil) ⇒ Object
This feature requires use of the Master Key in the API.
Queries can be made using distinct, allowing you find unique values for a specified field. For this to be performant, please remember to index your database.
2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 |
# File 'lib/parse/query.rb', line 2028 def distinct(field, return_pointers: false, mongo_direct: false, order: nil) # Explicit opt-in to direct MongoDB if mongo_direct return distinct_direct(field, return_pointers: return_pointers, order: order, **mongo_direct_auth_kwargs) end # Auto-route to mongo-direct when the compiled where contains a # direct-only constraint. Same gate as #count / #results. if requires_mongo_direct? assert_mongo_direct_routable! return distinct_direct(field, return_pointers: return_pointers, order: order, **mongo_direct_auth_kwargs) end # Auto-route scoped queries (session_token / acl_user / acl_role) to # mongo-direct: Parse Server's REST `/aggregate` endpoint is # master-key-only and enforces neither ACL nor CLP, so a scoped # `.distinct` call against REST would silently return unscoped # values. The mongo-direct path runs ACLScope + CLPScope before # `$group`, so distinct values reflect only ACL-readable rows. if distinct_query_is_scoped? && defined?(Parse::MongoDB) && Parse::MongoDB.enabled? return distinct_direct(field, return_pointers: return_pointers, order: order, **mongo_direct_auth_kwargs) end if field.nil? || !field.respond_to?(:to_s) || field.is_a?(Hash) || field.is_a?(Array) raise ArgumentError, "Invalid field name passed to `distinct`." end sort_dir = distinct_sort_direction(order) # Format field for aggregation formatted_field = format_aggregation_field(field) # Build the aggregation pipeline for distinct values pipeline = [{ "$group" => { "_id" => "$#{formatted_field}" } }] pipeline << { "$sort" => { "_id" => sort_dir } } if sort_dir pipeline << { "$project" => { "_id" => 0, "value" => "$_id" } } # Add match stage if there are where conditions compiled_where = compile_where if compiled_where.present? # Convert field names for aggregation context and handle dates aggregation_where = convert_constraints_for_aggregation(compiled_where) stringified_where = convert_dates_for_aggregation(aggregation_where) pipeline.unshift({ "$match" => stringified_where }) end # Use the Aggregation class to execute aggregation = aggregate(pipeline, verbose: @verbose_aggregate) raw_results = aggregation.raw # Extract values from the results values = raw_results.map { |item| item["value"] }.compact # Use schema-based approach to handle pointer field results parse_class = table_model_class is_pointer = parse_class && is_pointer_field?(parse_class, field, formatted_field) if is_pointer && values.any? # Convert all values using schema information converted_values = values.map do |value| convert_pointer_value_with_schema(value, field, return_pointers: return_pointers) end converted_values elsif return_pointers # Explicit conversion requested - try to convert using schema or fallback to string detection if values.any? && values.first.is_a?(String) && values.first.include?("$") to_pointers(values, field) else values.map { |value| convert_pointer_value_with_schema(value, field, return_pointers: true) } end else # Fallback to original string detection for backward compatibility if values.any? && values.first.is_a?(String) && values.first.include?("$") && values.first.match(/^[A-Za-z]\w*\$\w+$/) first_class_name = values.first.split("$", 2)[0] if values.all? { |v| v.is_a?(String) && v.start_with?("#{first_class_name}$") } values.map { |value| value.split("$", 2)[1] } else values end else values end end end |
#distinct_direct(field, return_pointers: false, order: nil, session_token: nil, master: nil, acl_user: nil, acl_role: nil, client: nil) ⇒ Array
This is a read-only operation. Direct MongoDB queries cannot modify data.
Execute a distinct query directly against MongoDB, bypassing Parse Server. Returns unique values for the specified field.
3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 |
# File 'lib/parse/query.rb', line 3538 def distinct_direct(field, return_pointers: false, order: nil, session_token: nil, master: nil, acl_user: nil, acl_role: nil, client: nil) enforce_explicit_auth_against_or_scope!(session_token: session_token, master: master, acl_user: acl_user, acl_role: acl_role, client: client) require_relative "mongodb" Parse::MongoDB.require_gem! unless Parse::MongoDB.available? raise Parse::MongoDB::NotEnabled, "Direct MongoDB queries are not enabled. " \ "Call Parse::MongoDB.configure(uri: 'mongodb://...', enabled: true) first." end # A query already owns a client. Defaulting to it means a query built # from a secondary client does not have to repeat itself, and cannot # silently authorize against the default application by omission. # # Resolved defensively: `#client` lazily constructs the DEFAULT client # and raises ConnectionError when none is configured. Argument # validation below must still be able to raise ArgumentError in a # process that never called Parse.setup, so a missing client is left # nil here and resolved at the authorization boundary instead. client ||= (self.client rescue nil) if field.nil? || !field.respond_to?(:to_s) || field.is_a?(Hash) || field.is_a?(Array) raise ArgumentError, "Invalid field name passed to `distinct_direct`." end sort_dir = distinct_sort_direction(order) # Convert field name for direct MongoDB access mongo_field = convert_field_for_direct_mongodb(Query.format_field(field)) # Build the base pipeline with match constraints pipeline = [] # Add match stage from query constraints. `compile_where` already # strips `__`-prefixed routing markers, so the result is safe to # forward to MongoDB. compiled_where = compile_where if compiled_where.present? mongo_constraints = convert_constraints_for_direct_mongodb(compiled_where) pipeline << { "$match" => mongo_constraints } if mongo_constraints.any? end # Add group, optional sort, and project stages for distinct pipeline << { "$group" => { "_id" => "$#{mongo_field}" } } pipeline << { "$sort" => { "_id" => sort_dir } } if sort_dir pipeline << { "$project" => { "_id" => 0, "value" => "$_id" } } # SDK-built pipeline only — see results_direct for rationale. # Forward auth kwargs so Parse::MongoDB.aggregate runs the # three-layer ACL + CLP + protectedFields simulation for scoped # agents. Without this, distinct silently returns the unscoped # universe (CLP-1 enforcement asymmetry vs. #count / #results). # When no explicit auth kwargs are provided, derive from the # query's own auth state — same fallback as results_direct. if session_token.nil? && master.nil? && acl_user.nil? && acl_role.nil? auth = mongo_direct_auth_kwargs session_token = auth[:session_token] master = auth[:master] acl_user = auth[:acl_user] acl_role = auth[:acl_role] end raw_results = Parse::MongoDB.aggregate(@table, pipeline, allow_internal_fields: true, read_preference: @read_preference, hint: @hint, session_token: session_token, master: master, acl_user: acl_user, acl_role: acl_role, client: client) # Extract values from results values = raw_results.map { |doc| doc["value"] }.compact # Handle pointer conversion if needed if return_pointers || field_is_pointer?(Query.format_field(field)) values = values.map do |value| if value.is_a?(String) && value.include?("$") # MongoDB pointer format: "ClassName$objectId" class_name, object_id = value.split("$", 2) Parse::Pointer.new(class_name, object_id) else value end end end values end |
#distinct_direct_pointers(field, order: nil, session_token: nil, master: nil, acl_user: nil, acl_role: nil, client: nil) ⇒ Array
Convenience method for distinct_direct that always returns Parse::Pointer objects for pointer fields.
3637 3638 3639 3640 3641 3642 3643 |
# File 'lib/parse/query.rb', line 3637 def distinct_direct_pointers(field, order: nil, session_token: nil, master: nil, acl_user: nil, acl_role: nil, client: nil) distinct_direct(field, return_pointers: true, order: order, session_token: session_token, master: master, acl_user: acl_user, acl_role: acl_role, client: client) end |
#distinct_objects(field, return_pointers: false) ⇒ Array
Enhanced distinct method that automatically populates Parse pointer objects at the server level. Uses aggregation pipeline to efficiently populate objects instead of post-processing.
6381 6382 6383 6384 6385 6386 6387 6388 |
# File 'lib/parse/query.rb', line 6381 def distinct_objects(field, return_pointers: false) if field.nil? || !field.respond_to?(:to_s) raise ArgumentError, "Invalid field name passed to `distinct_objects`." end # Use aggregation pipeline to get distinct values with populated objects execute_distinct_with_population(field, return_pointers: return_pointers) end |
#distinct_pointers(field, order: nil) ⇒ Array
Convenience method for distinct queries that always return Parse::Pointer objects for pointer fields. This is equivalent to calling distinct(field, return_pointers: true).
2121 2122 2123 |
# File 'lib/parse/query.rb', line 2121 def distinct_pointers(field, order: nil) distinct(field, return_pointers: true, order: order) end |
#distinct_query_is_scoped? ⇒ Boolean
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Whether this query carries a non-master-key auth scope. Used by
#distinct (and group_by aggregations) to decide whether to
auto-promote the REST aggregate path to mongo-direct so the SDK's
ACLScope / CLPScope enforcement actually runs. Also detects the
fiber-local ambient session set by Parse.with_session so that
aggregations inside a with_session block are treated as scoped —
consistent with how Parse::Client#request already scopes REST calls.
2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 |
# File 'lib/parse/query.rb', line 2796 def distinct_query_is_scoped? return true if @session_token.is_a?(String) && !@session_token.empty? return true if @acl_user return true if @acl_role # An ambient Parse.with_session counts as scope ONLY when the query did # not explicitly request master-key mode — mirroring Parse::Client#request, # where an explicit use_master_key: true is a deliberate admin call that # skips the ambient session. Otherwise an admin aggregation inside a # with_session block would be wrongly forced to mongo-direct / fail-closed. unless use_master_key == true ambient = ambient_session_token return true if ambient.is_a?(String) && !ambient.empty? # A client bound to a user's session (`become`, `session_client`, # a webhook `user_client`) is scoped the same way. return true if client_bound_session_token end false end |
#each { ... } ⇒ Array
2268 2269 2270 2271 |
# File 'lib/parse/query.rb', line 2268 def each(&block) return results.enum_for(:each) unless block_given? # Sparkling magic! results.each(&block) end |
#exclude_keys(*fields) ⇒ self
On the REST query path (encode: true in #compile) this maps to
Parse Server's path-scoped excludeKeys. On the mongo-direct path
(explicit .results_direct, an auto-route, or an aggregation that
auto-promotes — e.g. an $inQuery pointer constraint that rewrites to
a $lookup) the pipeline can only project the #keys allowlist, so
the SDK honors the denylist as a post-fetch sanitize over the returned
results instead. That mongo-direct sanitize is recursive by name: it
strips EVERY key with a matching name at any depth, so excluding a
field also removes a same-named field inside included/nested objects —
broader than the REST path's top-level/dotted scoping. Reserved
envelope fields (objectId, className, __type, createdAt,
updatedAt, ACL and their Mongo storage-form names) are never
stripped, so object reconstruction is unaffected. The raw aggregation
accessor (aggregate(...).raw) returns unredacted documents — the
sanitize applies to the object/decoded result paths. excludeKeys is a
projection convenience, not an ACL/CLP boundary, so it does not affect
access control.
Set a server-side field denylist for this query.
When set, Parse Server excludes the named fields from each returned
object, complementing the #keys allowlist. The two options can be
combined: Parse Server first applies the #keys allowlist, then
strips any field names listed in excludeKeys.
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 |
# File 'lib/parse/query.rb', line 1119 def exclude_keys(*fields) @exclude_keys ||= [] fields.flatten.each do |field| if field.nil? == false && field.respond_to?(:to_s) @exclude_keys.push Query.format_field(field).to_sym end end @exclude_keys.uniq! @results = nil if fields.count > 0 self # chaining end |
#execute_aggregation_pipeline ⇒ Aggregation
Execute an aggregation pipeline for queries with pipeline constraints
5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 |
# File 'lib/parse/query.rb', line 5455 def execute_aggregation_pipeline pipeline, has_lookup_stages = build_aggregation_pipeline # Determine if MongoDB direct should be used: # 1. Explicit opt-in via @acl_query_mongo_direct = true # 2. Auto-detect when lookup stages use $split with $literal (to parse pointer format), # Parse Server's REST API can't handle it correctly # 3. Auto-detect when querying internal fields like _rperm or _wperm (ACL fields), # Parse Server blocks these for security - must use MongoDB direct use_mongo_direct = false # When the SDK-built pipeline references internal ACL columns # (_rperm/_wperm via readable_by/writable_by/publicly_readable and # friends, or _acl), the mongo-direct sink must be told these # references are sanctioned so the PipelineSecurity internal-fields # denylist lets them through. The pipeline here is built entirely # from SDK constraint translation (no caller-supplied stages), so # this is safe — same posture as results_direct/count_direct. uses_internal_fields = pipeline_uses_internal_fields?(pipeline) scoped = distinct_query_is_scoped? # Check for explicit mongo_direct preference first if defined?(@acl_query_mongo_direct) && !@acl_query_mongo_direct.nil? use_mongo_direct = @acl_query_mongo_direct elsif defined?(Parse::MongoDB) && Parse::MongoDB.enabled? # Auto-detect based on pipeline contents and query scope if scoped || has_lookup_stages || uses_internal_fields use_mongo_direct = true end elsif scoped # Same fail-closed contract as #aggregate / #aggregate_from_query: # a scoped pipeline must not fall back to REST /aggregate, which # would drop the scope and return rows the caller cannot read. raise_scoped_aggregation_requires_mongo_direct! end # Create Aggregation directly to avoid double-applying constraints # The aggregate() method would redundantly add where constraints again Aggregation.new(self, pipeline, verbose: @verbose_aggregate, mongo_direct: use_mongo_direct, allow_internal_fields: uses_internal_fields) end |
#explain ⇒ Hash
This feature requires MongoDB explain support in Parse Server. The format of the returned plan depends on the MongoDB version.
Returns the query execution plan from MongoDB. This is useful for analyzing query performance and understanding which indexes are being used.
4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 |
# File 'lib/parse/query.rb', line 4908 def explain warn_if_public_explain_restricted! compiled_query = compile compiled_query[:explain] = true response = client.find_objects(@table, compiled_query.as_json, headers: _headers, **_opts) if response.error? # Parse Server 9.0+ defaults `allowPublicExplain` to false, so a # non-master explain that worked on 8.x now returns a permission # error. Surface that as actionable guidance instead of a bare 403. if response.respond_to?(:permission_denied?) && response. puts "[ParseQuery:Explain] #{Parse::TerminalSafe.sanitize_line(response.error)} — Parse Server 9.0+ defaults " \ "`allowPublicExplain` to false; query explain now requires the master key " \ "(use_master_key: true) or `allowPublicExplain: true` in the server's " \ "databaseOptions." else puts "[ParseQuery:Explain] #{Parse::TerminalSafe.sanitize_line(response.error)}" end return {} end response.result end |
#extract_subquery_to_lookup_stages(constraints) ⇒ Hash
Extract $inQuery and $notInQuery constraints and build $lookup stages for them. This converts Parse subquery constraints into MongoDB $lookup stages that join with the related collection and filter based on the subquery conditions. Uses raw MongoDB field names (_p_field) and returns results via .raw aggregation.
5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 |
# File 'lib/parse/query.rb', line 5625 def extract_subquery_to_lookup_stages(constraints) return { constraints: constraints, lookup_stages: [], post_lookup_match: {} } unless constraints.is_a?(Hash) remaining_constraints = {} lookup_stages = [] post_lookup_match = {} constraints.each do |field, value| # Check for both string and symbol keys has_in_query = value.is_a?(Hash) && (value.key?("$inQuery") || value.key?(:"$inQuery")) has_not_in_query = value.is_a?(Hash) && (value.key?("$notInQuery") || value.key?(:"$notInQuery")) if has_in_query || has_not_in_query is_in_query = has_in_query # Get the subquery config using the correct key type in_query_key = value.key?("$inQuery") ? "$inQuery" : :"$inQuery" not_in_query_key = value.key?("$notInQuery") ? "$notInQuery" : :"$notInQuery" subquery_config = value[is_in_query ? in_query_key : not_in_query_key] # Handle both string and symbol keys in the subquery config class_name = subquery_config["className"] || subquery_config[:className] where_clause = subquery_config["where"] || subquery_config[:where] || {} # Format field name for the pointer formatted_field = Query.format_field(field) mongo_pointer_field = "_p_#{formatted_field}" lookup_result_field = "_lookup_#{formatted_field}_result" lookup_id_field = "_lookup_#{formatted_field}_id" # Stage 1: Extract objectId from the pointer field using $split # Parse Server stores pointers as _p_fieldName with format "ClassName$objectId" # Use $literal to escape the $ character in the delimiter lookup_stages << { "$addFields" => { lookup_id_field => { "$arrayElemAt" => [ { "$split" => ["$#{mongo_pointer_field}", { "$literal" => "$" }] }, 1, ], }, }, } # Stage 2: $lookup to join with the related collection # Build pipeline to match on _id and apply where conditions lookup_pipeline = [ { "$match" => { "$expr" => { "$eq" => ["$_id", "$$lookupId"] } } }, ] # Add where conditions to lookup pipeline if present if where_clause.any? converted_where = convert_dates_for_aggregation(where_clause) converted_where = convert_constraints_for_aggregation(converted_where) lookup_pipeline << { "$match" => converted_where } end lookup_stages << { "$lookup" => { "from" => class_name, "let" => { "lookupId" => "$#{lookup_id_field}" }, "pipeline" => lookup_pipeline, "as" => lookup_result_field, }, } # Match based on whether lookup returned results if is_in_query # $inQuery: keep documents where lookup found matches post_lookup_match[lookup_result_field] = { "$ne" => [] } else # $notInQuery: keep documents where lookup found no matches post_lookup_match[lookup_result_field] = { "$eq" => [] } end else # A subquery nested anywhere else (under `$or` / `$and` / `$nor`, # `$not`, `$elemMatch`) is not translated on this path. Lifting it # into the post-join `$match` would drop the enclosing operator and # change the query's meaning, and leaving it in place hands MongoDB # an operator it does not have. The scan below refuses it. remaining_constraints[field] = value end end refuse_untranslated_subquery!(remaining_constraints, context: :aggregate) { constraints: remaining_constraints, lookup_stages: lookup_stages, post_lookup_match: post_lookup_match } end |
#fetch!(compiled_query) ⇒ Parse::Response Also known as: execute!
Performs the fetch request for the query.
2664 2665 2666 2667 2668 2669 2670 |
# File 'lib/parse/query.rb', line 2664 def fetch!(compiled_query) response = client.find_objects(@table, compiled_query.as_json, headers: _headers, **_opts) if response.error? puts "[ParseQuery] #{Parse::TerminalSafe.sanitize_line(response.error)}" end response end |
#first(limit = 1) ⇒ Parse::Object #first(constraints = {}) ⇒ Parse::Object
Supports all constraint options like :keys, :includes, :order, etc.
2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 |
# File 'lib/parse/query.rb', line 2304 def first(limit_or_constraints = 1, mongo_direct: false, **) # Use direct MongoDB query if requested if mongo_direct return first_direct(limit_or_constraints) end # Fetch on a temporary state: the limit, constraints, and cached # results set for this call never stay on the query. with_temporary_query_state do if limit_or_constraints.is_a?(Hash) conditions(limit_or_constraints) # Check if limit was set in constraints, otherwise use 1 # Handle :max case - if @limit is :max, default to 1 for first() fetch_count = (@limit.is_a?(Numeric) ? @limit : nil) || 1 else fetch_count = case limit_or_constraints when Numeric then limit_or_constraints.to_i when String unless limit_or_constraints =~ /\A-?\d+\z/ raise ArgumentError, "Invalid first() argument #{limit_or_constraints.inspect}. " \ "Expected an Integer, a numeric String, or a Hash of constraints." end limit_or_constraints.to_i else raise ArgumentError, "Invalid first() argument #{limit_or_constraints.inspect}. " \ "Expected an Integer, a numeric String, or a Hash of constraints." end end @results = nil if @limit != fetch_count @limit = fetch_count # Apply any additional keyword options as conditions (e.g., keys:, includes:) conditions() unless .empty? fetch_count == 1 ? results.first : results.first(fetch_count) end end |
#first_direct(limit_or_constraints = 1) ⇒ Parse::Object, ...
This is a read-only operation. Direct MongoDB queries cannot modify data.
Execute the query directly against MongoDB and return the first result. This is useful for performance-critical single-object lookups.
3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 |
# File 'lib/parse/query.rb', line 3411 def first_direct(limit_or_constraints = 1) if limit_or_constraints.is_a?(Hash) conditions(limit_or_constraints) limit_or_constraints = 1 end count = case limit_or_constraints when Numeric then limit_or_constraints.to_i when String unless limit_or_constraints =~ /\A-?\d+\z/ raise ArgumentError, "Invalid first_direct() argument #{limit_or_constraints.inspect}. " \ "Expected an Integer, a numeric String, or a Hash of constraints." end limit_or_constraints.to_i else raise ArgumentError, "Invalid first_direct() argument #{limit_or_constraints.inspect}. " \ "Expected an Integer, a numeric String, or a Hash of constraints." end count = 1 if count <= 0 # Set limit for single/few results original_limit = @limit @limit = count items = begin results_direct ensure @limit = original_limit end count == 1 ? items.first : items.first(count) end |
#get(object_id) ⇒ Parse::Object
Retrieve a single object by its objectId.
2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 |
# File 'lib/parse/query.rb', line 2417 def get(object_id) response = client.fetch_object(@table, object_id) if response.error? raise Parse::Error.new(response.code, response.error) end # Pass the table name through as-is rather than pre-resolving it to # a Class: `Object.build` does its own `Parse::Model.find_class` # lookup against the String, which correctly honors `parse_class` # aliasing. Resolving to a Class first and handing that back to # `build` broke aliased lookups, since `find_class` would then # stringify the Ruby constant name (e.g. "Musician") instead of # matching the declared alias (e.g. "Artist"). Parse::Object.build(response.result, @table) end |
#get_pointer_target_class(field) ⇒ String?
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Get the target class name for a pointer field from model references. Uses the model's references hash which maps field names to target class names.
4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 |
# File 'lib/parse/query.rb', line 4106 def get_pointer_target_class(field) begin klass = Parse::Model.find_class(@table) return nil unless klass.respond_to?(:references) references = klass.references return nil if references.nil? || references.empty? # Check both the field name and its formatted Parse field name formatted_field = Query.format_field(field).to_sym # Try direct lookup first, then formatted field target = references[field] || references[formatted_field] # Also check field_map for aliased fields if target.nil? && klass.respond_to?(:field_map) mapped_field = klass.field_map[field] target = references[mapped_field] if mapped_field end target rescue NameError, StandardError nil end end |
#group_by(field, flatten_arrays: false, sortable: false, return_pointers: false, mongo_direct: false) ⇒ GroupBy, SortableGroupBy
Group results by a specific field and return a GroupBy object for chaining aggregations.
6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 |
# File 'lib/parse/query.rb', line 6193 def group_by(field, flatten_arrays: false, sortable: false, return_pointers: false, mongo_direct: false) if field.nil? || !field.respond_to?(:to_s) raise ArgumentError, "Invalid field name passed to `group_by`." end if sortable SortableGroupBy.new(self, field, flatten_arrays: flatten_arrays, return_pointers: return_pointers, mongo_direct: mongo_direct) else GroupBy.new(self, field, flatten_arrays: flatten_arrays, return_pointers: return_pointers, mongo_direct: mongo_direct) end end |
#group_by_date(field, interval, sortable: false, return_pointers: false, timezone: nil, mongo_direct: false) ⇒ GroupByDate, SortableGroupByDate
Group results by a date field at specified time intervals.
6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 |
# File 'lib/parse/query.rb', line 6353 def group_by_date(field, interval, sortable: false, return_pointers: false, timezone: nil, mongo_direct: false) if field.nil? || !field.respond_to?(:to_s) raise ArgumentError, "Invalid field name passed to `group_by_date`." end unless [:year, :month, :week, :day, :hour, :minute, :second].include?(interval.to_sym) raise ArgumentError, "Invalid interval. Must be one of: :year, :month, :week, :day, :hour, :minute, :second" end if sortable SortableGroupByDate.new(self, field, interval.to_sym, return_pointers: return_pointers, timezone: timezone, mongo_direct: mongo_direct) else GroupByDate.new(self, field, interval.to_sym, return_pointers: return_pointers, timezone: timezone, mongo_direct: mongo_direct) end end |
#group_objects_by(field, return_pointers: false) ⇒ Hash
Group Parse objects by a field value and return arrays of actual objects. Unlike group_by which uses aggregation for counts/sums, this fetches all objects and groups them in Ruby, returning the actual Parse object instances.
6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 |
# File 'lib/parse/query.rb', line 6227 def group_objects_by(field, return_pointers: false) if field.nil? || !field.respond_to?(:to_s) raise ArgumentError, "Invalid field name passed to `group_objects_by`." end # Fetch all objects that match the query objects = results(return_pointers: return_pointers) # Group objects by the specified field value grouped = {} objects.each do |obj| # Get the field value for grouping field_value = if obj.respond_to?(:attributes) # For Parse objects, try multiple field access patterns obj.attributes[field.to_s] || obj.attributes[Query.format_field(field).to_s] || (obj.respond_to?(field) ? obj.send(field) : nil) elsif obj.is_a?(Hash) # For raw JSON objects, try multiple field access patterns obj[field.to_s] || obj[Query.format_field(field).to_s] || obj[field.to_sym] || obj[Query.format_field(field).to_sym] else # Fallback - try to access as method obj.respond_to?(field) ? obj.send(field) : nil end # Handle nil field values group_key = field_value.nil? ? "null" : field_value # Convert Parse pointer values to readable format for grouping key if group_key.is_a?(Hash) && group_key["__type"] == "Pointer" group_key = "#{group_key["className"]}##{group_key["objectId"]}" end # Initialize array if this is the first object for this group grouped[group_key] ||= [] grouped[group_key] << obj end grouped end |
#has_subquery_constraints?(constraints) ⇒ Boolean
Check if constraints contain $inQuery or $notInQuery that need resolution
5737 5738 5739 5740 5741 5742 5743 5744 |
# File 'lib/parse/query.rb', line 5737 def has_subquery_constraints?(constraints) return false unless constraints.is_a?(Hash) # Any subquery operator at any depth (string or symbol keys, inside # logical-operator arrays too), so a nested one reaches # {#extract_subquery_to_lookup_stages} and is refused there rather # than passed to MongoDB verbatim. direct_subquery_present?(constraints) end |
#include(*fields) ⇒ Object
alias for includes
1401 1402 1403 |
# File 'lib/parse/query.rb', line 1401 def include(*fields) includes(*fields) end |
#includes(*fields) ⇒ self
Set a list of Parse Pointer columns to be fetched for matching records.
You may chain multiple columns with the . operator.
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 |
# File 'lib/parse/query.rb', line 1388 def includes(*fields) @includes ||= [] fields.flatten.each do |field| if field.nil? == false && field.respond_to?(:to_s) @includes.push Query.format_field(field).to_sym end end @includes.uniq! @results = nil if fields.count > 0 self # chaining end |
#inspect ⇒ String
Like the default inspect, but never prints the session token, which
would otherwise reach logs and error reports.
3243 3244 3245 3246 3247 3248 3249 3250 |
# File 'lib/parse/query.rb', line 3243 def inspect ivars = instance_variables.map do |ivar| value = instance_variable_get(ivar) shown = ivar == :@session_token && value ? "[FILTERED]" : value.inspect "#{ivar}=#{shown}" end "#<#{self.class.name} #{ivars.join(", ")}>" end |
#keys(*fields) ⇒ self Also known as: select_fields
Use this feature with caution when working with the results, as values for the fields not specified in the query will be omitted in the resulting object.
Restrict the fields returned by the query. This is useful for larger query results set where some of the data will not be used, which reduces network traffic and deserialization performance.
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 |
# File 'lib/parse/query.rb', line 1073 def keys(*fields) @keys ||= [] fields.flatten.each do |field| if field.nil? == false && field.respond_to?(:to_s) @keys.push Query.format_field(field).to_sym end end @keys.uniq! @results = nil if fields.count > 0 self # chaining end |
#last_updated(limit = 1, **options) ⇒ Parse::Object+
Supports all constraint options like :keys, :includes, :limit, etc. The query itself is not changed, as with #latest.
Returns the most recently updated object(s) (ordered by updated_at descending).
2370 2371 2372 |
# File 'lib/parse/query.rb', line 2370 def last_updated(limit = 1, **) newest_by(:updated_at, limit, **) end |
#latest(limit = 1, **options) ⇒ Parse::Object+
Supports all constraint options like :keys, :includes, :limit, etc.
The query itself is not changed: the order, limit, and constraints
apply to this call only. createdAt descending is the primary sort;
an existing order on other fields breaks ties.
Returns the most recently created object(s) (ordered by created_at descending).
2355 2356 2357 |
# File 'lib/parse/query.rb', line 2355 def latest(limit = 1, **) newest_by(:created_at, limit, **) end |
#limit(count) ⇒ self
Limit the number of objects returned by the query. The default is 100, with
Parse allowing a maximum of 1000. The framework also allows a value of
:max. Utilizing this will have the framework continually intelligently
utilize :skip to continue to paginate through results until no more results
match the query criteria. When utilizing all(), :max is the default
option for :limit.
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 |
# File 'lib/parse/query.rb', line 1305 def limit(count) case count when nil @limit = nil when Numeric @limit = [0, count.to_i].max when :max @limit = :max when String unless count =~ /\A-?\d+\z/ raise ArgumentError, "Invalid limit #{count.inspect}. Expected an Integer, :max, " \ "a numeric String, or nil." end @limit = [0, count.to_i].max else raise ArgumentError, "Invalid limit #{count.inspect}. Expected an Integer, :max, " \ "a numeric String, or nil." end @results = nil self #chaining end |
#map { ... } ⇒ Array
2276 2277 2278 2279 |
# File 'lib/parse/query.rb', line 2276 def map(&block) return results.enum_for(:map) unless block_given? # Sparkling magic! results.map(&block) end |
#match_all! ⇒ self (protected)
Drop every where constraint, so the query matches all rows.
1923 1924 1925 1926 1927 |
# File 'lib/parse/query.rb', line 1923 def match_all! @where = [] @results = nil self end |
#max(field) ⇒ Object
Find the maximum value for a specific field.
6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 |
# File 'lib/parse/query.rb', line 6150 def max(field) if field.nil? || !field.respond_to?(:to_s) raise ArgumentError, "Invalid field name passed to `max`." end # Format field name according to Parse conventions formatted_field = format_aggregation_field(field) # Build the aggregation pipeline pipeline = [ { "$group" => { "_id" => nil, "max" => { "$max" => "$#{formatted_field}" } } }, ] execute_basic_aggregation(pipeline, "max", field, "max") end |
#merge_or_scope!(other) ⇒ Object (protected)
Combine other's authority with this query's for an OR. Both must
run under the same authority: a query with the default authority
adopts the other's, and two different authorities (a session and a
scoped user, a session and the master key, two users) raise. The
resulting authority is then pinned whichever side carried it, so a
later change to this query's
session, master-key flag, or scope raises instead of running the
other query's rows under a different principal. Read preference is
carried over but a mismatch keeps this query's value.
1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 |
# File 'lib/parse/query.rb', line 1736 def merge_or_scope!(other) merge_or_application!(other) theirs = other.or_effective_scope if theirs.empty? # The other query has the default authority: pin this query's own # authority, so the result does not depend on operand order. mine = or_effective_scope unless mine.empty? @_or_branch_scope = mine @_or_branch_app = or_application_identity end else mine = or_effective_scope if mine.empty? OR_SCOPE_IVARS.each do |ivar| instance_variable_set(:"@#{ivar}", other.instance_variable_get(:"@#{ivar}")) end adopt_or_client!(other, theirs) # Fail closed if the adopted state still does not reproduce the # other query's authority. unless or_effective_scope == theirs raise ArgumentError, "Cannot combine with OR a query running under #{Parse::Query.describe_or_scope(theirs)} " \ "through its own client. Run the queries separately." end elsif mine != theirs raise ArgumentError, "Queries combined with OR must run under the same authority " \ "(#{Parse::Query.describe_or_scope(mine)} vs #{Parse::Query.describe_or_scope(theirs)}). " \ "Run them separately, or set the same scope on each." end @_or_branch_scope = theirs @_or_branch_app = or_application_identity end @read_preference ||= other.read_preference self end |
#min(field) ⇒ Object
Find the minimum value for a specific field.
6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 |
# File 'lib/parse/query.rb', line 6131 def min(field) if field.nil? || !field.respond_to?(:to_s) raise ArgumentError, "Invalid field name passed to `min`." end # Format field name according to Parse conventions formatted_field = format_aggregation_field(field) # Build the aggregation pipeline pipeline = [ { "$group" => { "_id" => nil, "min" => { "$min" => "$#{formatted_field}" } } }, ] execute_basic_aggregation(pipeline, "min", field, "min") end |
#not_publicly_readable(mongo_direct: nil) ⇒ Parse::Query
Find objects that are NOT publicly readable. Matches objects where _rperm does NOT contain "*".
7657 7658 7659 7660 7661 |
# File 'lib/parse/query.rb', line 7657 def not_publicly_readable(mongo_direct: nil) @acl_query_mongo_direct = mongo_direct unless mongo_direct.nil? where(:ACL.not_readable_by => "*") self end |
#not_publicly_writable(mongo_direct: nil) ⇒ Parse::Query
Find objects that are NOT publicly writable. Matches objects where _wperm does NOT contain "*".
7670 7671 7672 7673 7674 |
# File 'lib/parse/query.rb', line 7670 def not_publicly_writable(mongo_direct: nil) @acl_query_mongo_direct = mongo_direct unless mongo_direct.nil? where(:ACL.not_writable_by => "*") self end |
#not_readable_by(permission, mongo_direct: nil) ⇒ Parse::Query
Find objects that are NOT readable by the given principal — i.e. hidden
from them. Excludes rows readable by the principal directly, via any role
they inherit, OR publicly (a public row is readable by everyone), and
excludes rows with a missing _rperm (public by absence).
7629 7630 7631 7632 7633 |
# File 'lib/parse/query.rb', line 7629 def not_readable_by(, mongo_direct: nil) @acl_query_mongo_direct = mongo_direct unless mongo_direct.nil? where(:ACL.not_readable_by => ) self end |
#not_writable_by(permission, mongo_direct: nil) ⇒ Parse::Query
Find objects that are NOT writable by the given principal. See #not_readable_by for the exclusion semantics (direct, role, public).
7644 7645 7646 7647 7648 |
# File 'lib/parse/query.rb', line 7644 def not_writable_by(, mongo_direct: nil) @acl_query_mongo_direct = mongo_direct unless mongo_direct.nil? where(:ACL.not_writable_by => ) self end |
#or_application_client ⇒ Parse::Client? (protected)
The client set on this query when it is a real Parse client other than the default one, or nil.
1779 1780 1781 1782 1783 |
# File 'lib/parse/query.rb', line 1779 def or_application_client own = or_explicit_client return nil unless own.respond_to?(:application_id) && own.respond_to?(:server_url) own end |
#or_application_identity ⇒ Array<String>? (protected)
The application this query runs against, as [application id, server URL], from its own client or the default client. nil when no client can be resolved.
1791 1792 1793 1794 1795 1796 1797 1798 1799 |
# File 'lib/parse/query.rb', line 1791 def or_application_identity target = or_application_client || begin self.class.client rescue StandardError nil end return nil unless target.respond_to?(:application_id) && target.respond_to?(:server_url) [target.application_id.to_s, target.server_url.to_s.chomp("/")] end |
#or_effective_scope ⇒ Hash (protected)
The authority this query runs under, as one comparable Hash: the
session token, the scoped user id, the scoped role name, and an
explicit master-key flag. An explicit use_master_key = false beside
a session, user, or role adds nothing, since those already run without
the master key. An empty Hash is the default authority.
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 |
# File 'lib/parse/query.rb', line 1660 def or_effective_scope scope = {} scope[:session] = @session_token unless @session_token.nil? # A client from Parse::Client#become sends its bound session on every # request that names no token and does not ask for the master key, # so it counts as that session. A non-default client with neither a # session nor a master key runs without the master key. own_client = or_explicit_client if own_client && @session_token.nil? && @use_master_key != true bound = own_client.respond_to?(:session_token) ? own_client.session_token : nil if bound.is_a?(String) && !bound.strip.empty? scope[:session] = bound elsif !(own_client.respond_to?(:master_key) && own_client.master_key.present?) scope[:master] = false end end scope[:user] = Parse::Query.or_scope_value(:acl_user, @acl_user) unless @acl_user.nil? scope[:role] = Parse::Query.or_scope_value(:acl_role, @acl_role) unless @acl_role.nil? unless @use_master_key.nil? || (@use_master_key == false && !scope.empty?) scope[:master] = @use_master_key end scope.delete(:master) if scope[:master] == false && scope.size > 1 scope end |
#or_explicit_client ⇒ Parse::Client? (protected)
The client set on this query when it is not the default client, or nil. Read from the instance variable so it never memoizes the default.
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 |
# File 'lib/parse/query.rb', line 1690 def or_explicit_client own = @client return nil if own.nil? default = begin self.class.client rescue StandardError nil end return nil if default && own.equal?(default) own end |
#or_where(where_clauses = []) ⇒ Query
Combine two where clauses into an OR constraint. Equivalent to the $or
Parse query operation. This is useful if you want to find objects that
match several queries. We overload the | operator in order to have a
clean syntax for joining these or operations.
1571 1572 1573 |
# File 'lib/parse/query.rb', line 1571 def or_where(where_clauses = []) with_or_rollback { or_where_unguarded(where_clauses) } end |
#order(*ordering) ⇒ self
Add a sorting order for the query.
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 |
# File 'lib/parse/query.rb', line 1190 def order(*ordering) @order ||= [] # Don't flatten through Hashes — flatten only unpacks Arrays. ordering.flatten.each do |entry| case entry when Order entry.field = Query.format_field(entry.field) push_order(entry) when String if entry.include?(",") # The REST sort string lists several fields: "title,-plays". order(*entry.split(",").map(&:strip).reject(&:empty?)) next end push_order(parse_order_string(entry)) when Symbol push_order(parse_order_string(entry)) when Hash entry.each do |field, direction| dir_sym = direction.is_a?(String) ? direction.downcase.to_sym : direction unless dir_sym == :asc || dir_sym == :desc raise ArgumentError, "Invalid order direction #{direction.inspect} for field " \ "#{field.inspect}. Expected :asc or :desc." end o = Order.new(field, dir_sym) o.field = Query.format_field(o.field) push_order(o) end else raise ArgumentError, "Invalid order argument #{entry.inspect}. Expected a Symbol, " \ "String, Parse::Order (e.g. :field.asc / :field.desc), or " \ "Hash of {field => :asc | :desc}." end end @results = nil if ordering.count > 0 self #chaining end |
#pipeline ⇒ Array
Returns the aggregation pipeline for this query if it contains pipeline-based constraints
6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 |
# File 'lib/parse/query.rb', line 6060 def pipeline pipeline_stages = [] # Check if any constraints generate aggregation pipelines @where.each do |constraint| if constraint.respond_to?(:as_json) constraint_json = constraint.as_json if constraint_json.is_a?(Hash) && constraint_json.has_key?("__aggregation_pipeline") pipeline_stages.concat(constraint_json["__aggregation_pipeline"]) end end end pipeline_stages end |
#pipeline_uses_internal_fields?(pipeline) ⇒ Boolean
Check if the pipeline references internal Parse fields that require MongoDB direct access
5500 5501 5502 5503 5504 |
# File 'lib/parse/query.rb', line 5500 def pipeline_uses_internal_fields?(pipeline) internal_fields = %w[_rperm _wperm _acl] pipeline_json = pipeline.to_json internal_fields.any? { |field| pipeline_json.include?(field) } end |
#pluck(field) ⇒ Array
Extract values for a specific field from all matching objects. This is similar to keys() but returns an array of the actual field values instead of objects with only those fields selected.
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 |
# File 'lib/parse/query.rb', line 1148 def pluck(field) if field.nil? || !field.respond_to?(:to_s) raise ArgumentError, "Invalid field name passed to `pluck`." end # Use keys to select only the field we want for efficiency query_with_field = self.dup.keys(field) # Get the results and extract the field values objects = query_with_field.results formatted_field = Query.format_field(field) objects.map do |obj| if obj.respond_to?(:attributes) # For Parse objects, get the attribute value obj.attributes[field.to_s] || obj.attributes[formatted_field.to_s] elsif obj.is_a?(Hash) # For raw JSON objects obj[field.to_s] || obj[formatted_field.to_s] else # Fallback - try to access as method obj.respond_to?(field) ? obj.send(field) : nil end end end |
#prepared(includeClassName: false) ⇒ Hash
Returns a compiled query without encoding the where clause.
5895 5896 5897 |
# File 'lib/parse/query.rb', line 5895 def prepared(includeClassName: false) compile(encode: false, includeClassName: includeClassName) end |
#pretty ⇒ String
Retruns a formatted JSON string representing the query, useful for debugging.
6084 6085 6086 |
# File 'lib/parse/query.rb', line 6084 def pretty JSON.pretty_generate(as_json) end |
#private_acl(mongo_direct: nil) ⇒ Parse::Query Also known as: master_key_only
Find objects with completely private ACL (no read AND no write permissions). Only accessible with master key.
7611 7612 7613 7614 |
# File 'lib/parse/query.rb', line 7611 def private_acl(mongo_direct: nil) privately_readable(mongo_direct: mongo_direct) privately_writable(mongo_direct: mongo_direct) end |
#privately_readable(mongo_direct: nil) ⇒ Parse::Query Also known as: master_key_read_only
Find objects with no read permissions (master key only). Matches objects where _rperm is empty or doesn't exist.
7583 7584 7585 |
# File 'lib/parse/query.rb', line 7583 def privately_readable(mongo_direct: nil) readable_by("none", mongo_direct: mongo_direct) end |
#privately_writable(mongo_direct: nil) ⇒ Parse::Query Also known as: master_key_write_only
Find objects with no write permissions (master key only). Matches objects where _wperm is empty or doesn't exist.
7597 7598 7599 |
# File 'lib/parse/query.rb', line 7597 def privately_writable(mongo_direct: nil) writable_by("none", mongo_direct: mongo_direct) end |
#publicly_readable(mongo_direct: nil) ⇒ Parse::Query
Find objects that are publicly readable (anyone can read). Matches objects where _rperm contains "*".
7559 7560 7561 |
# File 'lib/parse/query.rb', line 7559 def publicly_readable(mongo_direct: nil) readable_by("*", mongo_direct: mongo_direct) end |
#publicly_writable(mongo_direct: nil) ⇒ Parse::Query
Find objects that are publicly writable (anyone can write). Matches objects where _wperm contains "*". Useful for security audits to find potentially insecure objects.
7571 7572 7573 |
# File 'lib/parse/query.rb', line 7571 def publicly_writable(mongo_direct: nil) writable_by("*", mongo_direct: mongo_direct) end |
#raise_scoped_aggregation_requires_mongo_direct! ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Fail closed for a scoped aggregation that would otherwise fall back to REST /aggregate. That endpoint is master-key-only and enforces neither ACL nor CLP, so letting a scoped query through would silently run it unscoped as the master key. Every aggregation terminal that routes a scoped query (aggregate, aggregate_from_query, count, execute_aggregation_pipeline) raises through here.
2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 |
# File 'lib/parse/query.rb', line 2823 def raise_scoped_aggregation_requires_mongo_direct! raise MongoDirectRequired, "[Parse::Query] This scoped aggregation (session_token / " \ "scope_to_user / scope_to_role, or an active Parse.with_session " \ "block) requires mongo-direct so the SDK can enforce ACL/CLP. " \ "Parse Server's REST /aggregate endpoint is master-key-only and " \ "enforces neither, so routing it there would silently run unscoped " \ "as the master key. Enable mongo-direct via " \ "Parse::MongoDB.configure(...), or rewrite without the " \ "aggregation terminal." end |
#raw { ... } ⇒ Array<Hash>
Returns raw unprocessed results from the query (hash format)
3273 3274 3275 |
# File 'lib/parse/query.rb', line 3273 def raw(&block) results(raw: true, &block) end |
#read_pref(preference) ⇒ self
Set the MongoDB read preference for this query. This allows directing read queries to secondary replicas for load balancing.
1338 1339 1340 1341 |
# File 'lib/parse/query.rb', line 1338 def read_pref(preference) @read_preference = preference self end |
#readable_by(permission, mongo_direct: nil, strict: false) ⇒ Parse::Query
This uses MongoDB aggregation pipeline because Parse Server restricts direct queries on internal ACL fields (_rperm/_wperm).
Filter by ACL read permissions using exact permission strings. Strings are used as-is (user IDs or "role:RoleName" format). Use "public" for public access, "none" or [] for no read permissions.
7479 7480 7481 7482 7483 |
# File 'lib/parse/query.rb', line 7479 def readable_by(, mongo_direct: nil, strict: false) @acl_query_mongo_direct = mongo_direct unless mongo_direct.nil? where((strict ? :ACL.readable_by_exact : :ACL.readable_by) => ) self end |
#readable_by_role(role_name, mongo_direct: nil, strict: false) ⇒ Parse::Query
Filter by ACL read permissions using role names (adds "role:" prefix).
7496 7497 7498 7499 7500 |
# File 'lib/parse/query.rb', line 7496 def readable_by_role(role_name, mongo_direct: nil, strict: false) @acl_query_mongo_direct = mongo_direct unless mongo_direct.nil? where((strict ? :ACL.readable_by_role_exact : :ACL.readable_by_role) => role_name) self end |
#refuse_untranslated_subquery!(node, context: :direct) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Fail closed when a subquery operator is still present after
translation. MongoDB has no such operator, and a subquery in a
position the SDK cannot join (under $not, $elemMatch, $expr)
must not run as some other filter.
4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 |
# File 'lib/parse/query.rb', line 4263 def refuse_untranslated_subquery!(node, context: :direct) case node when Hash node.each do |key, value| if DIRECT_SUBQUERY_OPERATORS.include?(key.to_s) if context == :aggregate raise ArgumentError, "[Parse::Query] #{key} cannot be translated into an aggregation pipeline in " \ "this position. Aggregations translate only top-level $inQuery / $notInQuery " \ "field constraints into joins. Use results_direct / count_direct, which also " \ "translate subqueries inside $and / $or / $nor, or run the query via REST." end raise ArgumentError, "[Parse::Query] #{key} cannot run on the mongo-direct path in this position. " \ "A subquery is translated into a join only as a field constraint, at the top " \ "level or inside $and / $or / $nor. Run this query via REST, or move the " \ "subquery out of the enclosing operator." end refuse_untranslated_subquery!(value, context: context) end when Array node.each { |child| refuse_untranslated_subquery!(child, context: context) } end nil end |
#related_to(field, pointer) ⇒ Object
1369 1370 1371 1372 1373 |
# File 'lib/parse/query.rb', line 1369 def (field, pointer) raise ArgumentError, "Object value must be a Parse::Pointer type" unless pointer.is_a?(Parse::Pointer) add_constraint field.to_sym., pointer self #chaining end |
#requires_aggregation? ⇒ Boolean
Check if this query requires aggregation pipeline execution
6078 6079 6080 |
# File 'lib/parse/query.rb', line 6078 def requires_aggregation? !pipeline.empty? end |
#requires_aggregation_pipeline? ⇒ Boolean
Check if this query contains constraints that require aggregation pipeline processing
3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 |
# File 'lib/parse/query.rb', line 3254 def requires_aggregation_pipeline? return false if @where.empty? # Markers (including __aggregation_pipeline) are stripped from the # public compile_where path; consult the marker view explicitly. markers = compile_markers # Check if the marker hash itself has aggregation pipeline marker return true if markers.key?("__aggregation_pipeline") # Check if any of the constraint values has aggregation pipeline marker markers.values.any? { |constraint| constraint.is_a?(Hash) && constraint.key?("__aggregation_pipeline") } end |
#requires_mongo_direct? ⇒ Boolean
Check if this query contains a constraint that can only be answered
via mongo-direct (e.g. $geoIntersects with a full $geometry
against a non-GeoPoint column — an operator Parse Server's REST
find layer does not expose). Direct-only constraints emit a
"__mongo_direct_only" marker which this predicate detects.
2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 |
# File 'lib/parse/query.rb', line 2776 def requires_mongo_direct? return false if @where.empty? # Read from the un-stripped marker hash — `compile_where` removes # `__`-prefixed routing markers before they ship to Parse / Mongo. markers = compile_markers return true if markers.key?("__mongo_direct_only") markers.values.any? do |constraint| constraint.is_a?(Hash) && constraint.key?("__mongo_direct_only") end end |
#result_pointers { ... } ⇒ Array<Parse::Pointer> Also known as: results_pointers
Returns only pointer objects for all matching results This is memory efficient for large result sets where you only need pointers
3281 3282 3283 |
# File 'lib/parse/query.rb', line 3281 def result_pointers(&block) results(return_pointers: true, &block) end |
#results(raw: false, return_pointers: false, mongo_direct: false) { ... } ⇒ Array<Hash>, Array<Parse::Object> Also known as: result
Executes the query and builds the result set of Parse::Objects that matched. When this method is passed a block, the block is yielded for each matching item in the result, and the items are not returned. This methodology is more performant as large quantifies of objects are fetched in batches and all of them do not have to be kept in memory after the query finishes executing. This is the recommended method of processing large result sets.
2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 |
# File 'lib/parse/query.rb', line 2697 def results(raw: false, return_pointers: false, mongo_direct: false, &block) # `limit(0)` asks for no rows: answer without a request. Sending no # limit would return the server default page of 100. return [] if @limit == 0 # Use direct MongoDB query if requested if mongo_direct return results_direct(raw: raw, **mongo_direct_auth_kwargs, &block) end # Auto-route to mongo-direct when the compiled where contains a # constraint that Parse Server's REST find layer cannot express # (e.g. $geoIntersects with a full $geometry against a non-Point # column). Mirrors the existing aggregation auto-route at line # ~1321 below — the constraint emits a marker, the query layer # detects it, and routing happens transparently. The auth # context (use_master_key, scope_to_user, or session_token) # decides how ACL simulation runs through mongo-direct. if requires_mongo_direct? assert_mongo_direct_routable! return results_direct(raw: raw, **mongo_direct_auth_kwargs, &block) end if @results.nil? if block_given? max_results(raw: raw, return_pointers: return_pointers, &block) elsif @limit.is_a?(Numeric) || requires_aggregation_pipeline? # Check if this query requires aggregation pipeline processing if requires_aggregation_pipeline? # Use Aggregation class which handles both Parse Server and MongoDB direct aggregation = execute_aggregation_pipeline if raw items = aggregation.raw elsif return_pointers items = to_pointers(aggregation.raw) else items = aggregation.results end return items.each(&block) if block_given? @results = items else response = fetch!(compile) return [] if response.error? items = if raw response.results elsif return_pointers to_pointers(response.results) else decode(response.results) end return items.each(&block) if block_given? @results = items end else @results = max_results(raw: raw, return_pointers: return_pointers) end end @results end |
#results_direct(raw: false, max_time_ms: nil, session_token: nil, master: nil, acl_user: nil, acl_role: nil, client: nil) { ... } ⇒ Array<Parse::Object>, Array<Hash>
This is a read-only operation. Direct MongoDB queries cannot modify data.
Execute the query directly against MongoDB, bypassing Parse Server. This is useful for performance-critical read operations.
3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 |
# File 'lib/parse/query.rb', line 3310 def results_direct(raw: false, max_time_ms: nil, session_token: nil, master: nil, acl_user: nil, acl_role: nil, client: nil, &block) enforce_explicit_auth_against_or_scope!(session_token: session_token, master: master, acl_user: acl_user, acl_role: acl_role, client: client) # `limit(0)` asks for no rows. MongoDB rejects `$limit: 0`, and # omitting the stage would return every row. return [] if @limit == 0 require_relative "mongodb" Parse::MongoDB.require_gem! unless Parse::MongoDB.available? raise Parse::MongoDB::NotEnabled, "Direct MongoDB queries are not enabled. " \ "Call Parse::MongoDB.configure(uri: 'mongodb://...', enabled: true) first." end # A query already owns a client. Defaulting to it means a query built # from a secondary client does not have to repeat itself, and cannot # silently authorize against the default application by omission. # # Resolved defensively: `#client` lazily constructs the DEFAULT client # and raises ConnectionError when none is configured. Argument # validation below must still be able to raise ArgumentError in a # process that never called Parse.setup, so a missing client is left # nil here and resolved at the authorization boundary instead. client ||= (self.client rescue nil) # Build the aggregation pipeline for direct MongoDB execution pipeline = build_direct_mongodb_pipeline # When no explicit auth kwargs are provided by the caller, derive them # from the query's own auth state (session_token, acl_user, acl_role, or # master key) via mongo_direct_auth_kwargs — exactly the same fallback # used by distinct_direct, count_direct, and the requires_mongo_direct? # auto-route in results(). Without this, a plain .results_direct call on # a master-key client would resolve as anonymous and have the ACL match # stage filter out every row whose _rperm is [] (the default for objects # created without an explicit public-read ACL). if session_token.nil? && master.nil? && acl_user.nil? && acl_role.nil? auth = mongo_direct_auth_kwargs session_token = auth[:session_token] master = auth[:master] acl_user = auth[:acl_user] acl_role = auth[:acl_role] end # Execute the aggregation directly on MongoDB. The pipeline was built # entirely from SDK constraint translation (no user-supplied stages), # so legitimate `_rperm`/`_wperm` references emitted by # {#readable_by_role} and friends are sanctioned. The DENIED_OPERATORS # walk still runs at the MongoDB layer. When `session_token:` or # `master:` is supplied, Parse::MongoDB.aggregate adds the # three-layer ACL simulation (top-level $match, $lookup rewriter, # post-fetch redactor) before/after the pipeline executes. raw_results = Parse::MongoDB.aggregate(@table, pipeline, max_time_ms: max_time_ms, allow_internal_fields: true, session_token: session_token, master: master, acl_user: acl_user, acl_role: acl_role, client: client, read_preference: @read_preference, hint: @hint) # Convert MongoDB documents to Parse format parse_results = Parse::MongoDB.convert_documents_to_parse(raw_results, @table) # Honor exclude_keys on the mongo-direct path: the pipeline can only # project the keys allowlist, so apply the denylist here as a post-fetch # sanitize over the Parse-format hashes (before the raw/decode fork so # both shapes are redacted). Does not alter the MongoDB query. redact_excluded_keys!(parse_results) if raw return parse_results.each(&block) if block_given? return parse_results end # Convert to Parse objects items = decode(parse_results) return items.each(&block) if block_given? items end |
#rewrite_contained_by_for_direct(value) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
4429 4430 4431 4432 4433 4434 4435 4436 |
# File 'lib/parse/query.rb', line 4429 def rewrite_contained_by_for_direct(value) return value unless value.is_a?(Hash) key = value.key?("$containedBy") ? "$containedBy" : (value.key?(:$containedBy) ? :$containedBy : nil) return value if key.nil? list = value[key] rest = value.reject { |k, _| k == key } rest.merge("$not" => { "$elemMatch" => { "$nin" => Array(list) } }) end |
#rewrite_expression_for_direct_mongodb(expr) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Recursively rewrite field references inside an aggregation expression to their direct-MongoDB column names.
Walks Strings, Arrays, and Hashes:
- A String starting with
$(but not$$, which denotes aletvariable or system variable like$$ROOT) is treated as a field reference. Its root path segment is rewritten via #convert_field_for_direct_mongodb, preserving any dot-delimited tail. Already-rewritten$_p_*references pass through unchanged. - Arrays and Hashes are recursed into, with one exception: the
argument of
$literalis a string constant, not a field reference, and must not be rewritten.
4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 |
# File 'lib/parse/query.rb', line 4781 def rewrite_expression_for_direct_mongodb(expr) case expr when String return expr unless expr.start_with?("$") # $$varName (let bindings) and $$ROOT / $$CURRENT / $$NOW etc. return expr if expr.start_with?("$$") # Split off the root path segment so `$user.name` rewrites only # the root: `$_p_user.name`. Internal helper handles _p_* and # built-in passthroughs idempotently. head, sep, tail = expr[1..-1].partition(".") "$#{convert_field_for_direct_mongodb(head)}#{sep}#{tail}" when Array expr.map { |e| rewrite_expression_for_direct_mongodb(e) } when Hash result = {} expr.each do |k, v| # `$literal` wraps a string constant; its argument is not a # field reference and must be preserved verbatim. result[k] = k.to_s == "$literal" ? v : rewrite_expression_for_direct_mongodb(v) end result else expr end end |
#scope_to_role(role) ⇒ self
Role-based ACL scoping for service-account-style queries that
need "what would a user holding this role see" without minting a
session token or naming a specific user. The SDK uses
Parse::Role#all_parent_role_names to expand the role's
inheritance chain so passing "scope:admin" includes any role
"scope:admin" inherits from (e.g. "scope:user").
The resulting permission set is ["*", "role:<name>", ...] —
no user_id slot. Documents whose _rperm would only grant a
specific user (and not any of the role names) are filtered out
of both the top-level result set and embedded sub-documents.
Same routing rules as #scope_to_user: the query auto-routes
through mongo-direct when the where clause contains a
direct-only constraint, and the three-layer ACL simulation
(top-level $match, $lookup rewriter, post-fetch redactor)
runs through ACLScope.
2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 |
# File 'lib/parse/query.rb', line 2906 def scope_to_role(role) unless role.is_a?(Parse::Role) || role.is_a?(String) || role.is_a?(Symbol) raise ArgumentError, "[Parse::Query] scope_to_role requires a Parse::Role or role-name String." end # Normalize Symbol at the boundary so downstream # Parse::ACLScope#resolve_for_role only ever sees Parse::Role or # String. Without normalization, any String-only operation # (e.g. #start_with?, #sub) silently NoMethodErrors on Symbol. guard_or_scope_change { @acl_role = role.is_a?(Symbol) ? role.to_s : role } self end |
#scope_to_user(user) ⇒ self
Scope a query to a specific user's row-level ACL when it auto-routes
through mongo-direct. The SDK records the user, computes the
effective _rperm allow-set (user objectId + "*" + every role
name the user inherits via Role.all_for_user), and prepends
a { _rperm: { $in: ... } } $match to the mongo-direct pipeline
at execution time.
What this does NOT replicate: class-level permissions (CLP),
anonymous-user public-access nuances, beforeFind/afterFind
cloud triggers, or any field-level redaction Parse Server might
otherwise apply. This is a row-ACL floor, not full enforcement
parity with the Parse Server REST path. The intended use case is
"I need this mongo-direct-only query from a session-tokened
context, and I accept the row-ACL floor as my filter."
Edge case — objects with missing _rperm: Parse Server only
writes _rperm when an explicit ACL is applied; rows saved with
master-key access and no explicit ACL leave the field unset.
The injected filter is {$or: [{_rperm: {$exists: false}},
{_rperm: {$in: perms}}]}, treating missing-_rperm rows as
public-readable. Apps that store row-level ACL on every object
are unaffected by this fallback; apps that mix ACL'd and
public-default rows will see both classes of row through the
scoped query.
The query MUST still satisfy #assert_mongo_direct_routable! —
either use_master_key: true OR scope_to_user is set. A call to
scope_to_user is treated as opt-in to mongo-direct routing for
the direct-only constraints in the where clause.
2872 2873 2874 2875 2876 |
# File 'lib/parse/query.rb', line 2872 def scope_to_user(user) raise ArgumentError, "[Parse::Query] scope_to_user requires a Parse::User or User Pointer." unless user.respond_to?(:id) && user.id.is_a?(String) guard_or_scope_change { @acl_user = user } self end |
#select { ... } ⇒ Array
2284 2285 2286 2287 |
# File 'lib/parse/query.rb', line 2284 def select(&block) return results.enum_for(:select) unless block_given? # Sparkling magic! results.select(&block) end |
#skip(amount) ⇒ self
Use with limit to paginate through results. Default is 0.
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 |
# File 'lib/parse/query.rb', line 1268 def skip(amount) coerced = case amount when nil then 0 when Numeric then amount.to_i when String unless amount =~ /\A-?\d+\z/ raise ArgumentError, "Invalid skip #{amount.inspect}. Expected an Integer, " \ "a numeric String, or nil." end amount.to_i else raise ArgumentError, "Invalid skip #{amount.inspect}. Expected an Integer, " \ "a numeric String, or nil." end @skip = [0, coerced].max @results = nil self #chaining end |
#subscribe(fields: nil, keys: nil, watch: nil, session_token: nil, client: nil, use_master_key: false) {|subscription| ... } ⇒ Parse::LiveQuery::Subscription
Subscribe to real-time updates for objects matching this query. Uses Parse LiveQuery WebSocket connection to receive push notifications when objects are created, updated, deleted, or enter/leave the query results.
4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 |
# File 'lib/parse/query.rb', line 4876 def subscribe(fields: nil, keys: nil, watch: nil, session_token: nil, client: nil, use_master_key: false, &block) require_relative "live_query" lq_client = client || Parse::LiveQuery.client lq_client.subscribe( @table, where: compile_rest_where, fields: fields, keys: keys, watch: watch, session_token: live_query_session_token(session_token, live_query_client: lq_client), use_master_key: use_master_key, &block ) end |
#sum(field) ⇒ Numeric
Calculate the sum of values for a specific field.
6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 |
# File 'lib/parse/query.rb', line 6091 def sum(field) if field.nil? || !field.respond_to?(:to_s) raise ArgumentError, "Invalid field name passed to `sum`." end # Format field name according to Parse conventions formatted_field = format_aggregation_field(field) # Build the aggregation pipeline pipeline = [ { "$group" => { "_id" => nil, "total" => { "$sum" => "$#{formatted_field}" } } }, ] execute_basic_aggregation(pipeline, "sum", field, "total") end |
#to_pointers(list, field = nil) ⇒ Array<Parse::Pointer>
Builds Parse::Pointer objects based on the set of Parse JSON hashes in an array.
5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 |
# File 'lib/parse/query.rb', line 5849 def to_pointers(list, field = nil) list.map do |m| if field # Use schema-based conversion when field is provided converted = convert_pointer_value_with_schema(m, field, return_pointers: true) if converted.is_a?(Parse::Pointer) converted elsif m.is_a?(String) && m.include?("$") # Fallback to string parsing if schema conversion didn't work class_name, object_id = m.split("$", 2) if class_name && object_id Parse::Pointer.new(class_name, object_id) end else nil end else # Original logic for backward compatibility if m.is_a?(Hash) if m["__type"] == "Pointer" && m["className"] && m["objectId"] # Parse pointer object - use the className from the pointer Parse::Pointer.new(m["className"], m["objectId"]) elsif m["objectId"] # Standard Parse object with objectId - use the query table name Parse::Pointer.new(@table, m["objectId"]) end elsif m.is_a?(String) && m.include?("$") # Handle MongoDB pointer string format: "ClassName$objectId" class_name, object_id = m.split("$", 2) if class_name && object_id Parse::Pointer.new(class_name, object_id) end end end end.compact end |
#to_table(columns = nil, format: :ascii, headers: nil, sort_by: nil, sort_order: :asc) ⇒ String
Convert query results to a formatted table display.
6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 |
# File 'lib/parse/query.rb', line 6306 def to_table(columns = nil, format: :ascii, headers: nil, sort_by: nil, sort_order: :asc) objects = results return format_empty_table(format) if objects.empty? # Auto-detect columns if not provided if columns.nil? columns = auto_detect_columns(objects.first) end # Build table data table_data = build_table_data(objects, columns, headers) # Sort table data if sort_by is specified if sort_by sort_table_data!(table_data, sort_by, sort_order) end # Format based on requested format case format when :ascii format_ascii_table(table_data) when :csv format_csv_table(table_data) when :json format_json_table(table_data) else raise ArgumentError, "Unsupported format: #{format}. Use :ascii, :csv, or :json" end end |
#translate_pipeline_for_direct_mongodb(pipeline) ⇒ Array<Hash>
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Apply the direct-MongoDB stage converter to every stage in a pipeline.
Idempotent on already-translated input (the per-stage converter
passes _p_* references through unchanged).
5220 5221 5222 5223 |
# File 'lib/parse/query.rb', line 5220 def translate_pipeline_for_direct_mongodb(pipeline) return pipeline unless pipeline.is_a?(Array) pipeline.map { |stage| convert_stage_for_direct_mongodb(stage) } end |
#validate_no_where_operator!(hash) ⇒ Object
Retained for backwards compatibility. Use PipelineSecurity.validate_filter! for new code.
5251 5252 5253 5254 5255 |
# File 'lib/parse/query.rb', line 5251 def validate_no_where_operator!(hash) Parse::PipelineSecurity.validate_filter!(hash) rescue Parse::PipelineSecurity::Error => e raise ArgumentError, e. end |
#validate_pipeline!(pipeline) ⇒ Object
Permissive mode does NOT block $lookup, $graphLookup, or
$unionWith — these are legitimate read stages but can cross
collection boundaries that Parse ACL/CLP does not enforce. Do not
pass raw attacker-controlled input into #aggregate; construct the
pipeline in SDK code and interpolate only validated values.
Validates that a pipeline does not contain dangerous operators. Uses the permissive mode of PipelineSecurity (recursive denylist for $where, $function, $accumulator, $out, $merge, $collMod, $createIndex, $dropIndex) so that user code passing uncommon-but-legitimate read stages like $densify or $fill continues to work. Strict allowlist validation is available via PipelineSecurity.validate_pipeline! for callers that want to opt in.
5241 5242 5243 5244 5245 |
# File 'lib/parse/query.rb', line 5241 def validate_pipeline!(pipeline) Parse::PipelineSecurity.validate_filter!(pipeline) rescue Parse::PipelineSecurity::Error => e raise ArgumentError, e. end |
#where(expressions = nil, opts = {}) ⇒ self
Add additional query constraints to the where clause. The where clause
is based on utilizing a set of constraints on the defined column names in
your Parse classes. The constraints are implemented as method operators on
field names that are tied to a value. Any symbol/string that is not one of
the main expression keywords described here will be considered as a type of
query constraint for the where clause in the query.
1546 1547 1548 1549 1550 1551 1552 1553 |
# File 'lib/parse/query.rb', line 1546 def where(expressions = nil, opts = {}) return @where if expressions.nil? if expressions.is_a?(Hash) # Route through conditions to handle special keywords like :keys, :include, etc. conditions(expressions) end self #chaining end |
#where_constraints ⇒ Hash
Formats the current set of Parse::Constraint instances in the where clause as an expression hash.
1528 1529 1530 |
# File 'lib/parse/query.rb', line 1528 def where_constraints @where.reduce({}) { |memo, constraint| memo[constraint.operation] = constraint.value; memo } end |
#where_not_between(field, value) ⇒ self
Add a "field is NOT between" condition — the logical negation of
.where(field.between => value): field < min OR field > max for a
fully-bounded Range/Array, or a single one-sided comparison when the
Range is beginless/endless (mirroring how Constraint::BetweenConstraint
itself only constrains the side that is present).
Not available as a field.not_between => value symbol constraint,
unlike .between: a between-style range is inherently an OR of two
comparisons, and a single Constraint's #build can only
safely contribute an AND'd clause to a query. A constraint that
unilaterally emitted a top-level $or would collide with (and
silently clobber, or be clobbered by) any other $or this query
already produces via #or_where / | / another where_not_between
call, since only one $or group merges correctly per query. This
method instead composes the negation the same way and
does — concatenating compiled constraint arrays — which correctly
nests the OR inside the query's existing AND'd conditions instead of
replacing them the way #or_where would.
1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 |
# File 'lib/parse/query.rb', line 1971 def where_not_between(field, value) field = field.to_sym min_value, max_value, exclude_max = Parse::Constraint::BetweenConstraint.extract_bounds(value) if min_value.nil? && max_value.nil? raise ArgumentError, "Query#where_not_between: Range must have a begin, an end, or both (ex. 5.., ..25, 5..25)." end # A fully-bounded range needs its own `$or` group (`field < min OR # field > max`). Only ONE `$or` group survives the plain-Hash merge # every constraint's compiled output goes through (`constraint_reduce` # deep-merges compiled hashes; a second top-level `$or` key silently # overwrites the first rather than combining with it — the same # constraint that makes `field.not_between => value` unsafe as a # symbol constraint, see above). Fail loudly here instead of quietly # dropping half the query if this query already has one, from # `#or_where`, `|`, or an earlier `where_not_between` call. if min_value && max_value && @where.any? { |c| c.is_a?(Parse::Constraint::CompoundQueryConstraint) } raise ArgumentError, "Query#where_not_between: this query already has an `$or` group (from `or_where`, `|`, " \ "or a prior `where_not_between` call). Only one `$or` group can be safely merged per " \ "query. Compose the two queries with Parse::Query.and(...) instead." end negated = if min_value.nil? Parse::Query.new(@table).where(field.public_send(exclude_max ? :gte : :gt) => max_value) elsif max_value.nil? Parse::Query.new(@table).where(field.lt => min_value) else lower = Parse::Query.new(@table).where(field.lt => min_value) upper = Parse::Query.new(@table).where(field.public_send(exclude_max ? :gte : :gt) => max_value) Parse::Query.or(lower, upper) end @where = @where + negated.where @results = nil self end |
#writable_by(permission, mongo_direct: nil, strict: false) ⇒ Parse::Query
This uses MongoDB aggregation pipeline because Parse Server restricts direct queries on internal ACL fields (_rperm/_wperm).
Filter by ACL write permissions using exact permission strings. Strings are used as-is (user IDs or "role:RoleName" format). Use "public" for public access, "none" or [] for no write permissions.
7524 7525 7526 7527 7528 |
# File 'lib/parse/query.rb', line 7524 def writable_by(, mongo_direct: nil, strict: false) @acl_query_mongo_direct = mongo_direct unless mongo_direct.nil? where((strict ? :ACL.writable_by_exact : :ACL.writable_by) => ) self end |
#writable_by_role(role_name, mongo_direct: nil, strict: false) ⇒ Parse::Query
Filter by ACL write permissions using role names (adds "role:" prefix).
7541 7542 7543 7544 7545 |
# File 'lib/parse/query.rb', line 7541 def writable_by_role(role_name, mongo_direct: nil, strict: false) @acl_query_mongo_direct = mongo_direct unless mongo_direct.nil? where((strict ? :ACL.writable_by_role_exact : :ACL.writable_by_role) => role_name) self end |
#|(other_query) ⇒ Query
Combine two queries with OR. The result is a copy of the receiver (its limit, order, keys and includes) whose where is the OR of both.
- A receiver with no constraints is a starting point, the same as
#or_where:
Model.query | qgives an OR whose only branch isq, so[q1, q2].reduce(Model.query, :|)givesq1 OR q2. - A right-hand side with no constraints is a branch that matches
every row, so
q | Model.queryhas no constraints.
The auth scope (session token, master-key flag, scope_to_user,
scope_to_role) carries over from whichever side set it. Two
different scopes raise ArgumentError, since the OR could only run
under one of them.
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 |
# File 'lib/parse/query.rb', line 1634 def |(other_query) raise ArgumentError, "Parse queries must be of the same class #{@table}." unless @table == other_query.table copy_query = self.clone copy_query.send(:merge_or_scope!, other_query) if Parse::Query.match_all?(other_query.where) # Still refuse a pipeline-only receiver rather than silently # widening it. Parse::Query.compile_or_branch(@where) copy_query.match_all! else copy_query.or_where other_query.where end copy_query end |