       and r.target == ^target
     )
 
-    {count, something} = repo().delete_all(query)
-    {:ok, flag} = get(flag_name)
-
-    publish_change(flag_name)
-
-    {:ok, flag}
-    # {:error, "reason"}
+    try do
+      {_count, _} = repo().delete_all(query)
+      {:ok, flag} = get(flag_name)
+      publish_change(flag_name)
+      {:ok, flag}
+    rescue
+      e in [Ecto.QueryError] -> {:error, e}
+    end
   end
 
 
-  # Deletes an entire Flag's Redis hash and removes its name from the Redis set.
+  # Deletes all of of this flags' gates from the toggles table, thus deleting
+  # the entire flag.
   # Deleting flags is idempotent and deleting unknown flags is safe.
   # After the operation fetching the now-deleted flag will return the default
   # empty flag structure.

      where: r.flag_name == ^flag_name
    )

    {count, something} = repo().delete_all(query)
    {:ok, flag} = get(flag_name)

    publish_change(flag_name)

    {:ok, flag}
    # {:error, "reason"}
  end




  def get(flag_name) do
    name_string = to_string(flag_name)
    query = from(r in Record, where: r.flag_name == ^name_string)
    try do
      results = repo().all(query)
      flag = deserialize(flag_name, results)
      {:ok, flag}
    rescue
      e in [Ecto.QueryError] -> {:error, e}
    end
  end


  def put(flag_name, gate = %Gate{}) do
    changeset = Record.build(flag_name, gate)
    options = [
      on_conflict: [set: [enabled: gate.enabled]],
      conflict_target: [:flag_name, :gate_type, :target] # the unique index
    ]

    case repo().insert(changeset, options) do
      {:ok, _struct} ->
        {:ok, flag} = get(flag_name)
        publish_change(flag_name)
