Prepare_query wont pass updated options to preloaded sub sequent calls from main query

I am trying to implement soft delete using this library ecto_soft_delete/soft_delete_repo.ex at master · revelrylabs/ecto_soft_delete · GitHub 's module This has prepare_query method implemented which will not fetch all soft deleted records which is fine. But the problem is, it will also not fetch preloaded records if they are soft deleted. eg if I am a user with salary of type monthly. if monthly salary type got soft deleted. it will not show/fetch any salary type at all… Main query shouldn’t fetch soft deleted records which is fine but all preloaded records despite of soft deleted or not should be fetched…
so I tried to modify this query a bit

def prepare_query(_operation, query, opts) do
        schema_module = get_schema_module_from_query(query)
        fields = if schema_module, do: schema_module.__schema__(:fields), else: []
        soft_deactivateable? = Enum.member?(fields, :deactivated_at)

        if has_include_deactivated_at_clause?(query) || opts[:with_deactivated] ||
             !soft_deactivateable? do
          {query, opts}
          query = from(x in query, where: is_nil(x.deactivated_at))
          IO.inspect opts
          # I am trying put with_deactivated for all sub-sequent calls but sub-sequent calls dont receive this option
          opts = Keyword.put(opts, :with_deactivated, false)
          {query, opts}

prepare_query will get called two times. one for the main user query and one for salary_type… but second query(which is for preload) should always fetch record means with with_deactivated: false but i am unable to differentiate which query is the main one and which query is for preload in prepare_query

That project hasn’t seem much change lately, and there are 2-year-old somewhat-contradictory issues that seem related:

What you’re looking for sounds like it would be better achieved by explicitly filtering on deleted_at in the main query and preloading normally otherwise; approaches like prepare_query are hard to opt-out of.

1 Like