Increment change is incrementing counter by 2

I have this action in my resource:

  update :bump_shared_count do
      description "Bump the template shared count by 1"

      accept []

      change optimistic_lock(:shared_count)
      change increment(:shared_count)
    end

I expect it to increment the count always by one, but when I run this:

Template.bump_shared_count!(template, actor: actor)

It always increment the counter by 2.

This is the query it created:

UPDATE "templates" AS t0
SET "shared_count" = (
  CASE WHEN (
         CASE WHEN t0."shared_count"::bigint = $1::bigint
              THEN t0."shared_count"::bigint + $2
              ELSE ash_raise_error($3::jsonb, NULL::bigint)
         END)::bigint + $4::bigint IS NULL
       THEN ash_raise_error($5::jsonb, NULL::bigint)
       ELSE (
         CASE WHEN t0."shared_count"::bigint = $6::bigint
              THEN t0."shared_count"::bigint + $7
              ELSE ash_raise_error($8::jsonb, NULL::bigint)
         END)::bigint + $9
  END)::bigint,
"updated_at" = $10::timestamp::timestamp
WHERE (t0."id"::uuid = $11::uuid)
RETURNING t0."id", t0."name", t0."male_content", t0."male_processed_content", t0."male_custom_fields", t0."female_content", t0."female_processed_content", t0."female_custom_fields", t0."shared?", t0."shared_count", t0."inserted_at", t0."updated_at", t0."organization_id", t0."school_id", t0."class_id", t0."lesson_id", t0."from_template_id", t0."teacher_id"
[2,1,"{\"input\":{\"filter\":{\"shared_count\":2},\"resource\":\"Core.Feedbacks.Template\",\"field\":\"shared_count\"},\"exception\":\"Ash.Error.Changes.StaleRecord\"}",1,"{\"input\":{\"type\":\"attribute\",\"resource\":\"Elixir.Core.Feedbacks.Template\",\"field\":\"shared_count\"},\"exception\":\"Ash.Error.Changes.Required\"}",2,1,"{\"input\":{\"filter\":{\"shared_count\":2},\"resource\":\"Core.Feedbacks.Template\",\"field\":\"shared_count\"},\"exception\":\"Ash.Error.Changes.StaleRecord\"}",1,~U[2024-09-05 18:16:32.981936Z],"0191bf3c-2dbf-7963-84ef-2cc1f6e7e2f9"]

optimistic_lock does the incrementing already internally. So you don’t need the increment.

1 Like