           do_insert(flag_name, changeset)
       end
     end
-
-    case out do
-      {:ok, {:ok, result}} ->
-        publish_change(flag_name)
-        {:ok, result}
-      {:error, _} = error ->
-        error
-    end
-  end
-
-
-  def put(flag_name, gate = %Gate{}) do
-    changeset = Record.build(flag_name, gate)
-    options = upsert_options(gate)
-
-    case do_insert(flag_name, changeset, options) do
-      {:ok, flag} ->
-        publish_change(flag_name)
-        {:ok, flag}
-      other ->
-        other
+  end
+
+  defp _put_percentage_mysql(flag_name, gate, find_one_q) do
+    @repo.transaction fn() ->
+      if mysql_lock!() do
+        try do
+          case @repo.one(find_one_q) do
+            record = %Record{} ->
+              changeset = Record.update_target(record, gate)
+              do_update(flag_name, changeset)
+            nil ->
+              changeset = Record.build(flag_name, gate)
+              do_insert(flag_name, changeset)
+          end
+        rescue
+          e ->
+            @repo.rollback("Exception: #{inspect(e)}")
+        else
+          {:error, reason} ->
+            @repo.rollback("Error while upserting the gate: #{inspect(reason)}")
+          {:ok, value} ->
+            {:ok, value}
+        after
+          mysql_unlock!()
+        end
+      else
+        Logger.error("Couldn't acquire lock with 'SELECT GET_LOCK()' after #{@mysql_lock_timeout_s} seconds")
+        @repo.rollback("couldn't acquire lock")
+      end
     end
   end
 

  end


  defp table_lock! do
    Ecto.Adapters.SQL.query!(
      @repo,
      "LOCK TABLE fun_with_flags_toggles IN SHARE ROW EXCLUSIVE MODE;"
    )
  end




  import Ecto.Query

  require Logger

  @repo Config.ecto_repo()
  @mysql_lock_timeout_s 3

  def worker_spec do
    nil
