Arjun Singh
Arjun Singh

Reputation: 697

Use interpolation in constraint function inside Ecto migrations.

I have the following migration in one of my applications

use Ecto.Migration
  alias SnitchPayments.PaymentMethodCode

  @code PaymentMethodCode.hosted_payment() |> to_charlist() # this evaulautes to 'hpm'

  def change do
    create table("snitch_hosted_payments", comment: "payments made via hosted payments") do
      add(:transaction_id, :string)
      add(:payment_source, :string)
      add(:raw_response, :map)
      add(:payment_id, references("snitch_payments", on_delete: :delete_all), null: false)
      timestamps()
    end

    create unique_index("snitch_hosted_payments", :payment_id,
      comment: "one-to-one relationship")

    create constraint("snitch_hosted_payments",
      :hosted_payment_exclusivity,
      check: "payment_exclusivity(payment_id, #{@code}) = 1")
  end

As you can see I am trying to interpolate in this line "payment_exclusivity(payment_id, #{@code}) = 1". But, on running the migration I am getting the error

** (Postgrex.Error) ERROR 42703 (undefined_column): column "hpm" does not exist

"payment_exclusivity()" is a function in postgres which is I am calling with the given params.

The following works if I do:

create constraint("snitch_hosted_payments",
          :hosted_payment_exclusivity,
          check: "payment_exclusivity(payment_id, 'hpm') = 1")

What could be the right way to do this interpolation? I don't want to hardcode the value here.

Upvotes: 0

Views: 114

Answers (1)

Abdullah Esmail
Abdullah Esmail

Reputation: 230

For the sake of completeness, I'll write the solution that worked for OP here as an answer to this question can be marked as "answered".

The suggested solution was surrounding #{@code} with single quotes:

check: "payment_exclusivity(payment_id, '#{@code}') = 1")

which worked for Arjun.

Upvotes: 0

Related Questions