Adds callbacks to record changes to habtm associations such that on save
 the previous version of the association (if changed) can be reconstructed.
350970
def setup_callbacks_for_habtm(join_tables)
      @model_class.send :attr_accessor, :paper_trail_habtm
      @model_class.class_attribute :paper_trail_save_join_tables
      @model_class.paper_trail_save_join_tables = Array.wrap(join_tables)
      habtm_assocs_not_skipped.each(&method(:setup_habtm_change_callbacks))
    end
1273442
public function postSave()
    {

        // check if the model already exists
        if ((!isset($this->revisionEnabled) || $this->revisionEnabled) && $this->updating) {
            // if it does, it means we're updating

            $changes_to_record = $this->changedRevisionableFields();

            $revisions = array();

            foreach ($changes_to_record as $key => $change) {
                $revisions[] = array(
                    'revisionable_type'     => $this->getMorphClass(),
                    'revisionable_id'       => $this->getKey(),
                    'key'                   => $key,
                    'old_value'             => array_get($this->originalData, $key),
                    'new_value'             => $this->updatedData[$key],
                    'user_id'               => $this->getSystemUserId(),
                    'created_at'            => new \DateTime(),
                    'updated_at'            => new \DateTime(),
                );
            }

            if (count($revisions) > 0) {
                $revision = static::newModel();
                \DB::table($revision->getTable())->insert($revisions);
            }
        }
    }
1213341
public function saveHandler()
    {
        if ($this->changed) {
            $class = $this->getRemoteClass();
            (new $class)->entity->updateRelatedThroughTable($this->table, $this->remoteAttributeName, $this->relatedAttributeName, $this->getIds(), $this->model, $this->filterList);
        }
    }
1156717
def polymorphic_update_timestamp(session, flush_context, instances):
    
    for obj in session.dirty:
        if not isinstance(obj, Entity):
            continue
        state = sa.inspect(obj)
        history = state.attrs["updated_at"].history
        if not any((history.added, history.deleted)):
            obj.updated_at = datetime.utcnow()
1024512
def update(self, *args, **kwargs):
        """"""

        self.augment_args(args, kwargs)

        kwargs['log_action'] = kwargs.get('log_action', 'update')

        if not self.rec:
            return self.add(**kwargs)
        else:
            for k, v in kwargs.items():

                # Don't update object; use whatever was set in the original record
                if k not in ('source', 's_vid', 'table', 't_vid', 'partition', 'p_vid'):
                    setattr(self.rec, k, v)

            self._session.merge(self.rec)
            if self._logger:
                self._logger.info(self.rec.log_str)
            self._session.commit()

            self._ai_rec_id = None
            return self.rec.id
273462
def pre_save(sender, instance, raw, using, update_fields, **kwargs):
    """"""
    if raw:
        # Return if loading Fixtures
        return

    try:
        with transaction.atomic():
            if not should_audit(instance):
                return False
            try:
                object_json_repr = serializers.serialize("json", [instance])
            except Exception:
                # We need a better way for this to work. ManyToMany will fail on pre_save on create
                return None

            if instance.pk is None:
                created = True
            else:
                created = False

            # created or updated?
            if not created:
                old_model = sender.objects.get(pk=instance.pk)
                delta = model_delta(old_model, instance)
                changed_fields = json.dumps(delta)
                event_type = CRUDEvent.UPDATE

            # user
            try:
                user = get_current_user()
                # validate that the user still exists
                user = get_user_model().objects.get(pk=user.pk)
            except:
                user = None

            if isinstance(user, AnonymousUser):
                user = None

            # callbacks
            kwargs['request'] = get_current_request()  # make request available for callbacks
            create_crud_event = all(
                callback(instance, object_json_repr, created, raw, using, update_fields, **kwargs)
                for callback in CRUD_DIFFERENCE_CALLBACKS if callable(callback))
            # create crud event only if all callbacks returned True
            if create_crud_event and not created:
                c_t = ContentType.objects.get_for_model(instance)
                sid = transaction.savepoint()
                try:
                    with transaction.atomic():
                        crud_event = CRUDEvent.objects.create(
                            event_type=event_type,
                            object_repr=str(instance),
                            object_json_repr=object_json_repr,
                            changed_fields=changed_fields,
                            content_type_id=c_t.id,
                            object_id=instance.pk,
                            user_id=getattr(user, 'id', None),
                            datetime=timezone.now(),
                            user_pk_as_string=str(user.pk) if user else user
                        )
                except Exception as e:
                    logger.exception(
                        "easy audit had a pre-save exception on CRUDEvent creation. instance: {}, instance pk: {}".format(
                            instance, instance.pk))
                    transaction.savepoint_rollback(sid)
    except Exception:
        logger.exception('easy audit had a pre-save exception.')
211972
def tracking_save(sender, instance, raw, using, update_fields, **kwargs):
    
    if _has_changed(instance):
        if instance._original_fields['pk'] is None:
            # Create
            _create_create_tracking_event(instance)
        else:
            # Update
            _create_update_tracking_event(instance)
    if _has_changed_related(instance):
        # Because an object need to be saved before being related,
        # it can only be an update
        _create_update_tracking_related_event(instance)
    if _has_changed(instance) or _has_changed_related(instance):
        _set_original_fields(instance)
1319196
def save(self, *args, **kwargs):
        
        from tracked_model.models import History, RequestInfo
        if self.pk:
            action = ActionType.UPDATE
            changes = None
        else:
            action = ActionType.CREATE
            changes = serializer.dump_model(self)

        request = kwargs.pop('request', None)
        track_token = kwargs.pop('track_token', None)

        super().save(*args, **kwargs)
        if not changes:
            changes = self._tracked_model_diff()

        if changes:
            hist = History()
            hist.model_name = self._meta.model.__name__
            hist.app_label = self._meta.app_label
            hist.table_name = self._meta.db_table
            hist.table_id = self.pk
            hist.change_log = serializer.to_json(changes)
            hist.action_type = action
            if request:
                if request.user.is_authenticated():
                    hist.revision_author = request.user
                req_info = RequestInfo.create_or_get_from_request(request)
                hist.revision_request = req_info
            elif track_token:
                hist.revision_author_id = track_token.user_pk
                hist.revision_request_id = track_token.request_pk

            hist.save()

        self._tracked_model_initial_state = serializer.dump_model(self)
1270396
def modify_record(durable_model, current_revision, arn, event_time, diff_func):
    """"""
    # We want the newest items first.
    # See: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html
    items = list(durable_model.query(
        arn,
        (durable_model.eventTime <= event_time),
        scan_index_forward=False,
        limit=1,
        consistent_read=True))

    if items:
        latest_revision = items[0]

        latest_config = latest_revision._get_json()[1]['attributes']    # pylint: disable=W0212
        current_config = current_revision._get_json()[1]['attributes']  # pylint: disable=W0212

        # Determine if there is truly a difference, disregarding Ephemeral Paths
        diff = diff_func(latest_config, current_config)
        if diff:
            LOG.debug(
                f'[~] Difference found saving new revision to durable table. Arn: {arn} LatestConfig: {latest_config} '
                f'CurrentConfig: {json.dumps(current_config)}')
            current_revision.save()
    else:
        current_revision.save()
        LOG.info(f'[?] Got modify event but no current revision found. Arn: {arn}')
1040295
def update(self, commit=True, **kwargs):
        

        for (attr, value) in kwargs.iteritems():
            setattr(self, attr, value)
        return commit and self.save() or self
1275401
def <<(record)
      load
      record.save! if record.new?
      result = true
      result = false if include?(record)
      @owner.update_association_cache_for(@association, record, :add)
      record.update_association_cache_for(record.associations.find!(@owner).link_field, @owner, :add)
      result && self
    end
536064
def do_add_existing
      parent_record = nested_parent_record(:update)
      @record = active_scaffold_config.model.find(params[:associated_id])
      if parent_record && @record
        parent_record.send(nested.association.name) << @record
        parent_record.save
      else
        false
      end
    end
399039
def _set_timestamps_on_attach(self, record, exists=False):
        
        fresh = self._parent.fresh_timestamp()

        if not exists and self._has_pivot_column(self.created_at()):
            record[self.created_at()] = fresh

        if self._has_pivot_column(self.updated_at()):
            record[self.updated_at()] = fresh

        return record
122090
def _track_changes(self):
        
        if self._field and getattr(self._parent, '_track_changes',
                                   None) is not None and self.untrack is False:
            self._parent._track_changes.add(self._field)
21211
def record_unchanged?(record_new, record_old)
      # NOTE: Using the dirty state would be great here, but it doesn't keep track of
      # in-place changes.

      allow_indexing?(record_old) == allow_indexing?(record_new) &&
        !@fields.map { |field| record_old.send(field) == record_new.send(field) }.include?(false)
    end
440100
def update
      return false if new_record?
      run_callbacks :save do
        run_callbacks :update do
          httparty = self.class.put(self[:@url], request_options.merge(:body => to_json))
          handle_save_response(httparty)
        end
      end
    end
902586
def save_modified_attributes!(opts={})
    options = { :validate => true }.merge(opts)
    if options[:validate]
      # Complain if we aren't valid
      raise InvalidRecord, @errors.full_messages.join(", ") unless valid?
    end
    # Send the save request
    response = self.class.session.connection.set_entry(self.class._module.name, serialize_modified_attributes)
    # Complain if we don't get a parseable response back
    raise RecordsaveFailed, "Failed to save record: #{self}.  Response was not a Hash" unless response.is_a? Hash
    # Complain if we don't get a valid id back
    raise RecordSaveFailed, "Failed to save record: #{self}.  Response did not contain a valid 'id'." if response["id"].nil?
    # Save the id to the record, if it's a new record
    @attributes[:id] = response["id"] if new?
    raise InvalidRecord, "Failed to update id for: #{self}." if id.nil?
    # Clear the modified attributes Hash
    @modified_attributes = {}
    true
  end