Module: Parse::Core::Actions::ClassMethods

Defined in:
lib/parse/model/core/actions.rb

Overview

Class methods applied to Parse::Object subclasses.

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#raise_on_save_failure ⇒ Boolean

By default, we return true or false for save and destroy operations. If you prefer to have Parse::Object raise an exception instead, you can tell to do so either globally or on a per-model basis. When a save fails, it will raise a RecordNotSaved.

When enabled, if an error is returned by Parse due to saving or destroying a record, due to your before_save or before_delete validation cloud code triggers, Parse::Object will return the a RecordNotSaved exception type. This exception has an instance method of #object which contains the object that failed to save.

Examples:

# globally across all models
Parse::Model.raise_on_save_failure = true
Song.raise_on_save_failure = true # per-model

# or per-instance raise on failure
song.save!

Returns:

  • (Boolean) —

    whether to raise a RecordNotSaved when an object fails to save.



622
# File 'lib/parse/model/core/actions.rb', line 622

attr_writer :raise_on_save_failure

Instance Method Details

#create!(attrs = {}) ⇒ Parse::Object

Creates a new object with the given attributes and saves it. This is equivalent to calling new(attrs).save!.

Examples:

song = Song.create!(title: "New Song", artist: "Artist")

Parameters:

  • attrs (Hash) (defaults to: {}) —

    the attributes for the new object.

Returns:

Raises:



752
753
754
755
756
# File 'lib/parse/model/core/actions.rb', line 752

def create!(attrs = {})
  obj = new(attrs)
  obj.save!
  obj
end

#create_or_update!(query_attrs = {}, resource_attrs = {}, synchronize: nil, session: nil, master_key: nil) ⇒ Parse::Object

Finds the first object matching the query conditions and updates it with the attributes, or creates a new saved object with the attributes. Saves new objects or existing objects with changes. See #first_or_create! for the synchronize-create lock semantics — they apply identically here.

Examples:

Parse::User.create_or_update!({ ..query conditions..}, {.. resource_attrs ..})

Parameters:

  • query_attrs (Hash) (defaults to: {}) —

    a set of query constraints that also are applied.

  • resource_attrs (Hash) (defaults to: {}) —

    a set of attribute values to be applied to found objects or used for creation.

  • synchronize (Boolean, Hash, nil) (defaults to: nil) —

    override the synchronize-create lock. nil (default) defers to the per-class synchronize_create_default or the module-level Parse.synchronize_create_default. true enables with defaults; false opts out; a Hash enables with custom options merged over Parse.synchronize_create_options.

  • session (String, Parse::User, nil) (defaults to: nil) —

    session token (or object answering :session_token) threaded through both the query and the save so the entire find→create flow runs under one auth identity.

  • master_key (Boolean, nil) (defaults to: nil) —

    when explicitly false, disables master key for both halves.

Returns:

  • (Parse::Object) —

    a Parse::Object, whether found by the query or newly created.

Raises:



770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
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
828
829
830
831
832
# File 'lib/parse/model/core/actions.rb', line 770

def create_or_update!(query_attrs = {}, resource_attrs = {}, synchronize: nil, session: nil, master_key: nil)
  query_attrs = query_attrs.symbolize_keys
  resource_attrs = resource_attrs.symbolize_keys

  enabled, sync_opts = _resolve_synchronize_flag(synchronize)
  return _create_or_update_unsynchronized!(query_attrs, resource_attrs, session: session, master_key: master_key) unless enabled

  _assert_synchronize_class_allowed!
  options = _merged_synchronize_options(sync_opts)
  session_token = _extract_session_token(session)

  # See #first_or_create! for the partition rationale — strip
  # Parse::Query option keys before lock canonicalization.
  lock_attrs = query_attrs.reject { |k, _| Parse::Query.option_key?(k) }
  _assert_lock_attrs_have_constraints!(query_attrs, lock_attrs)

  Parse::CreateLock.synchronize(
    parse_class: parse_class,
    query_attrs: lock_attrs,
    options: options,
    session_token: session_token,
    master_key: master_key,
  ) do
    obj = _scoped_first(query_attrs, session: session, master_key: master_key)

    if obj.nil?
      obj = self.new query_attrs.merge(resource_attrs)
      begin
        session ? obj.save!(session: session) : obj.save!
      rescue Parse::RecordNotSaved => e
        winner = _recover_from_duplicate_value(e, query_attrs, session: session, master_key: master_key)
        raise unless winner
        obj = winner
      rescue Parse::Error::DuplicateRequestError
        # See #first_or_create! — recover the row a retried create
        # already landed (it already carries resource_attrs).
        winner = _recover_from_duplicate_request(query_attrs, session: session, master_key: master_key)
        raise unless winner
        obj = winner
      end
    end

    if !obj.new? && !resource_attrs.empty?
      has_changes = resource_attrs.any? do |key, value|
        obj.respond_to?(key) && obj.send(key) != value
      end
      if has_changes
        obj.apply_attributes!(resource_attrs, dirty_track: true)
        begin
          session ? obj.save!(session: session) : obj.save!
        rescue Parse::Error::DuplicateRequestError
          # A retried update (PUT) landed but lost its response; re-find
          # the now-updated row and return it.
          winner = _recover_from_duplicate_request(query_attrs, session: session, master_key: master_key)
          raise unless winner
          obj = winner
        end
      end
    end

    obj
  end
end

#first_or_create(query_attrs = {}, resource_attrs = {}) ⇒ Parse::Object

Finds the first object matching the query conditions, or creates a new unsaved object with the attributes. This method takes the possibility of two hashes, therefore make sure you properly wrap the contents of the input with {}.

Examples:

Parse::User.first_or_create({ ..query conditions..})
Parse::User.first_or_create({ ..query conditions..}, {.. resource_attrs ..})

Parameters:

  • query_attrs (Hash) (defaults to: {}) —

    a set of query constraints that also are applied.

  • resource_attrs (Hash) (defaults to: {}) —

    a set of additional attribute values to be applied only if an object was not found.

Returns:

  • (Parse::Object) —

    a Parse::Object, whether found by the query or newly created.



638
639
640
641
642
643
644
645
646
647
648
649
650
651
# File 'lib/parse/model/core/actions.rb', line 638

def first_or_create(query_attrs = {}, resource_attrs = {})
  query_attrs = query_attrs.symbolize_keys
  resource_attrs = resource_attrs.symbolize_keys
  obj = query(query_attrs).first

  if obj.blank?
    # Object not found, create new one with query_attrs + resource_attrs
    merged_attrs = query_attrs.merge(resource_attrs)
    obj = self.new merged_attrs
  end
  # If object exists, return it as-is without any modifications

  obj
end

#first_or_create!(query_attrs = {}, resource_attrs = {}, synchronize: nil, session: nil, master_key: nil) ⇒ Parse::Object

Finds the first object matching the query conditions, or creates a new saved object with the attributes. This method is similar to #first_or_create but will also Parse::Core::Actions#save! the object if it was newly created.

When synchronize: is enabled (per-call, per-class via synchronize_create_default, or globally via Parse.synchronize_create_default), the find→create→save sequence is serialized through Parse::CreateLock so concurrent callers with identical query_attrs cannot both create. The lock requires a Moneta cache store (Redis recommended); on a process-local store the lock degrades to a per-key Mutex. A MongoDB unique index on the constrained fields is the correctness floor — on Parse code 137 (DuplicateValue) the wrapper re-queries inside the held lock and returns the winner.

Examples:

obj = Parse::User.first_or_create!({ ..query conditions..})
obj = Parse::User.first_or_create!({ ..query conditions..}, {.. resource_attrs ..})

Per-call lock opt-in

User.first_or_create!({ email: e }, { name: n }, synchronize: true)

Per-call with tuning

User.first_or_create!({ email: e }, {}, synchronize: { ttl: 5, wait: 1.0 })

Auth-context threading

User.first_or_create!({ email: e }, {}, session: current_user.session_token)

Parameters:

  • query_attrs (Hash) (defaults to: {}) —

    a set of query constraints that also are applied.

  • resource_attrs (Hash) (defaults to: {}) —

    a set of attribute values to be applied if an object was not found.

  • synchronize (Boolean, Hash, nil) (defaults to: nil) —

    override the synchronize-create lock. nil (default) defers to the per-class synchronize_create_default or the module-level Parse.synchronize_create_default. true enables with defaults; false opts out; a Hash enables with custom options merged over Parse.synchronize_create_options.

  • session (String, Parse::User, nil) (defaults to: nil) —

    session token (or object answering :session_token) threaded through both the query and the save so the entire find→create flow runs under one auth identity.

  • master_key (Boolean, nil) (defaults to: nil) —

    when explicitly false, disables master key for both halves.

Returns:

  • (Parse::Object) —

    a Parse::Object, whether found by the query or newly created.

Raises:

See Also:



691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
# File 'lib/parse/model/core/actions.rb', line 691

def first_or_create!(query_attrs = {}, resource_attrs = {}, synchronize: nil, session: nil, master_key: nil)
  query_attrs = query_attrs.symbolize_keys
  resource_attrs = resource_attrs.symbolize_keys

  enabled, sync_opts = _resolve_synchronize_flag(synchronize)
  return _first_or_create_unsynchronized!(query_attrs, resource_attrs, session: session, master_key: master_key) unless enabled

  _assert_synchronize_class_allowed!
  options = _merged_synchronize_options(sync_opts)
  session_token = _extract_session_token(session)

  # Split query_attrs into the constraint subset (what
  # determines lock identity) and the query-shape options
  # (`:cache`, `:limit`, `:order`, ACL helpers, …) that
  # `Parse::Query#conditions` absorbs as query parameters.
  # Without this, a caller passing the documented `cache:
  # 30.seconds` escape hatch alongside their constraints
  # tripped `Parse::CreateLock.canonicalize_value` on the
  # `ActiveSupport::Duration` — see 4.4.2 changelog. The
  # original `query_attrs` is still forwarded to
  # `_scoped_first` below; `conditions()` extracts the option
  # keys on the find side, so the cache TTL still applies.
  lock_attrs = query_attrs.reject { |k, _| Parse::Query.option_key?(k) }
  _assert_lock_attrs_have_constraints!(query_attrs, lock_attrs)

  Parse::CreateLock.synchronize(
    parse_class: parse_class,
    query_attrs: lock_attrs,
    options: options,
    session_token: session_token,
    master_key: master_key,
  ) do
    obj = _scoped_first(query_attrs, session: session, master_key: master_key)
    next obj if obj

    obj = self.new query_attrs.merge(resource_attrs)
    begin
      session ? obj.save!(session: session) : obj.save!
      obj
    rescue Parse::RecordNotSaved => e
      winner = _recover_from_duplicate_value(e, query_attrs, session: session, master_key: master_key)
      raise unless winner
      winner
    rescue Parse::Error::DuplicateRequestError
      # A transparently-retried create landed but lost its response;
      # server idempotency rejected the replay. Re-find the row the
      # original attempt created and return it.
      winner = _recover_from_duplicate_request(query_attrs, session: session, master_key: master_key)
      raise unless winner
      winner
    end
  end
end

#save_all(constraints = {}) { ... } ⇒ Boolean

Note:

You cannot use :updated_at as a constraint.

Auto save all objects matching the query constraints. This method is meant to be used with a block. Any objects that are modified in the block will be batched for a save operation. This uses the updated_at field to continue to query for all matching objects that have not been updated. If you need to use :updated_at in your constraints, consider using Querying#all or Querying#each

Examples:


post = Post.first
Comments.save_all( post: post) do |comment|
  # .. modify comment ...
  # it will automatically be saved
end

Parameters:

  • constraints (Hash) (defaults to: {}) —

    a set of query constraints.

Yields:

  • a block which will iterate through each matching object.

Returns:

  • (Boolean) —

    true if all saves succeeded and there were no errors.



1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
# File 'lib/parse/model/core/actions.rb', line 1046

def save_all(constraints = {}, &block)
  invalid_constraints = constraints.keys.any? do |k|
    (k == :updated_at || k == :updatedAt) ||
    (k.is_a?(Parse::Operation) && (k.operand == :updated_at || k.operand == :updatedAt))
  end
  if invalid_constraints
    raise ArgumentError,
      "[#{self}] Special method save_all() cannot be used with an :updated_at constraint."
  end

  force = false
  batch_size = 250
  iterator_block = nil
  if block_given?
    iterator_block = block
  else
    # if no block given, assume you want to just save all objects
    # regardless of modification.
    force = true
  end

  # Work on a copy so the caller's constraints hash is not mutated.
  base_constraints = constraints.dup
  anchor_date = Parse::Date.now
  base_constraints[:updated_at.on_or_before] = anchor_date
  base_constraints[:cache] = false
  # oldest first, so we create a reduction-cycle
  base_constraints[:order] = :updated_at.asc
  base_constraints[:limit] = batch_size

  # Keyset cursor over (updated_at, objectId). Saved objects move past
  # the anchor date and drop out of the query. Objects the block left
  # unchanged keep their updated_at, so each page resumes at the last
  # seen updated_at and excludes the ids already visited at exactly
  # that timestamp. Every page therefore makes progress, and records
  # the block does not modify are visited once instead of ending the
  # run early.
  cursor_time = nil
  seen_at_cursor = []
  has_errors = false
  loop do
    page_constraints = base_constraints.dup
    if cursor_time
      page_constraints[:updated_at.gte] = cursor_time
      page_constraints[:objectId.nin] = seen_at_cursor if seen_at_cursor.any?
    end
    results = query(page_constraints).results

    break if results.empty?

    results.each(&iterator_block) if iterator_block.present?
    # we don't need to refresh the objects in the array with the results
    # since we will be throwing them away. Force determines whether
    # to save these objects regardless of whether they are dirty.
    batch = results.save(merge: false, force: force)
    # Record failures before any break, so a failing last page is
    # reported.
    has_errors ||= batch.error?

    break if results.count < batch_size # we didn't hit a cap on results.

    last_time = results.last.updated_at
    break if last_time.nil?
    if cursor_time && last_time == cursor_time
      seen_at_cursor.concat(results.map(&:id))
    else
      cursor_time = last_time
      seen_at_cursor = results.select { |r| r.updated_at == last_time }.map(&:id)
    end
  end
  not has_errors
end

#transaction(retries: 5, retry_server_errors: false, session: nil) {|Parse::BatchOperation| ... } ⇒ Array<Parse::Response>

Execute a set of operations as an atomic transaction. All operations will be executed in sequence, and if any fail, the entire transaction will be rolled back.

Transactions need MongoDB running as a replica set (or mongos) on the Parse Server side.

Examples:

Basic transaction

Parse::Object.transaction do |batch|
  user = User.first
  user.username = "new_username"
  batch.add(user)

  post = Post.new(author: user, title: "New Post")
  batch.add(post)
end

Using the block return for automatic batching

results = Parse::Object.transaction do
  user1 = User.first
  user1.score = 100

  user2 = User.first(username: "player2")
  user2.score = 200

  [user1, user2]  # Return array of objects to save
end

Parameters:

  • retries (Integer) (defaults to: 5) —

    number of attempts on a transaction conflict (error 251), which Parse Server reports only after rolling back.

  • retry_server_errors (Boolean) (defaults to: false) —

    also resend after a bare HTTP 500 from Parse Server. Parse Server answers both an aborted transaction and a failed commit this way, and a commit can fail after it was applied, so a resend can apply the transaction twice. Off by default; enable it only for writes that are safe to repeat (it works around Parse Server running a transaction's requests concurrently, which MongoDB intermittently rejects).

  • session (String, #session_token, nil) (defaults to: nil) —

    run the transaction as this user (ACL and CLP enforced). Without it, the transaction runs with the credentials of its objects' class client, as a single save does.

Yields:

Returns:

Raises:



446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
# File 'lib/parse/model/core/actions.rb', line 446

def transaction(retries: 5, retry_server_errors: false, session: nil, &block)
  raise ArgumentError, "Block required for transaction" unless block_given?
  session_token = Parse::BatchOperation.session_token_for!(session)

  previous_context = Fiber[TRANSACTION_CONTEXT_KEY]
  transaction_context = { snapshots: {}, created_objects: {} }
  Fiber[TRANSACTION_CONTEXT_KEY] = transaction_context
  original_states = {}
  tracked_objects = []

  begin
    batch = Parse::BatchOperation.new(nil, transaction: true)

    # Wrap the batch to associate the pre-mutation snapshot with each
    # object that actually participates in the transaction.
    batch_wrapper = Object.new
    batch_wrapper.define_singleton_method(:is_a?) do |klass|
      klass == Parse::BatchOperation || super(klass)
    end
    batch_wrapper.define_singleton_method(:kind_of?) do |klass|
      klass == Parse::BatchOperation || super(klass)
    end
    batch_wrapper.define_singleton_method(:instance_of?) do |klass|
      klass == Parse::BatchOperation
    end
    batch_wrapper.define_singleton_method(:add) do |obj|
      # Ruby identity is required because all unsaved Parse objects
      # compare equal while their ids are nil.
      if obj.respond_to?(:attributes) && obj.respond_to?(:id) && !original_states.key?(obj.object_id)
        original_states[obj.object_id] = Parse::Core::Actions.capture_transaction_state(
          obj,
          transaction_context,
          include_created: true,
        )
        tracked_objects << obj
      end
      batch.add(obj)
    end

    # Forward other methods to the real batch.
    batch_wrapper.define_singleton_method(:method_missing) do |method, *args, &method_block|
      batch.send(method, *args, &method_block)
    end
    batch_wrapper.define_singleton_method(:respond_to_missing?) do |method, include_private = false|
      batch.respond_to?(method, include_private)
    end

    result = yield(batch_wrapper)

    # If block returns objects, add them to batch.
    if result.respond_to?(:change_requests)
      batch_wrapper.add(result)
    elsif result.is_a?(Array)
      result.each { |obj| batch_wrapper.add(obj) if obj.respond_to?(:change_requests) }
    end

    if session_token
      batch.requests.each { |r| r.opts[:session_token] = session_token if r.opts.is_a?(Hash) }
    end

    # Submit with retry logic for transaction conflicts.
    # Parse Server reports a write conflict inside a transaction as
    # error code 251, after rolling it back. Retry on that structured
    # code only (a per-request response code, or the code of the
    # response an error carries).
    attempts = 0
    loop do
      attempts += 1
      begin
        responses = batch.submit
      rescue Parse::Error => e
        # A conflict is recognized only from the structured Parse
        # error code in the response, never from message text, so an
        # unrelated "251" in an error message cannot trigger a resend.
        conflict = e.respond_to?(:response) && e.response.respond_to?(:code) &&
                   e.response.code.to_i == TRANSACTION_CONFLICT_CODE
        # A bare 500 does not say whether the transaction was applied:
        # Parse Server answers an aborted transaction and a failed
        # commit (which may have been applied) the same way, and a
        # 502/503/504 comes from a gateway that may have timed out
        # after the commit. Only a 251 conflict is a confirmed
        # rollback; a 500 is resent only when the caller opted in.
        server_500 = e.is_a?(Parse::Error::ServiceUnavailableError) && e.http_status == 500
        if (conflict || (server_500 && retry_server_errors)) && attempts < retries
          sleep(0.1 * attempts)
          next
        end
        # Name the likely causes rather than surfacing only "Internal
        # server error". The original error is the cause.
        if server_500
          raise Parse::Error,
                "Transaction failed: Parse Server answered 500 (#{e.message}) after " \
                "#{attempts} attempt(s). The transaction may or may not have been applied; " \
                "check before resending. Parse Server transactions need MongoDB running as " \
                "a replica set or mongos, and on a standalone server every transaction fails " \
                "this way; otherwise see the Parse Server log. For a non-atomic batch, save " \
                "the objects with Array#save instead."
        end
        raise
      end

      if responses.all?(&:success?)
        # Match responses to objects using the request tag (Ruby object_id).
        objects_by_id = tracked_objects.each_with_object({}) { |o, h| h[o.object_id] = o }
        batch.requests.zip(responses).each do |request, response|
          next unless request && response && response.success?
          result = response.result
          next unless result.is_a?(Hash)

          obj = objects_by_id[request.tag]
          next unless obj

          obj.instance_variable_set(:@id, result["objectId"]) if result["objectId"]
          if result["createdAt"]
            obj.instance_variable_set(:@created_at, Parse::Date.parse(result["createdAt"]))
          end
          if result["updatedAt"]
            obj.instance_variable_set(:@updated_at, Parse::Date.parse(result["updatedAt"]))
          elsif result["createdAt"]
            obj.instance_variable_set(:@updated_at, Parse::Date.parse(result["createdAt"]))
          end

          # Apply any additional attributes returned by beforeSave hooks.
          obj.set_attributes!(result) if obj.respond_to?(:set_attributes!)
          # The transaction carried the record's relation ops too, so
          # settle them as a save does rather than discarding them.
          if obj.respond_to?(:changes_applied!, true)
            obj.send(:changes_applied!)
          elsif obj.respond_to?(:clear_changes!, true)
            obj.send(:clear_changes!)
          end
        end

        return responses
      end

      error_response = responses.find { |response| !response.success? }
      error_code = error_response&.code.to_i
      if error_code == TRANSACTION_CONFLICT_CODE && attempts < retries
        sleep(0.1 * attempts)
        next
      end
      detail = error_response&.error || "unknown error"
      raise Parse::Error, "Transaction failed (code #{error_code}): #{detail}"
    end
  rescue StandardError
    original_states.each_value do |state|
      Parse::Core::Actions.rollback_object_state(state)
    end
    raise
  ensure
    Fiber[TRANSACTION_CONTEXT_KEY] = previous_context
  end
end