Skip to content

Tapioca v0.17.9 generates incorrect signatures for ActiveRecord #upsert / #upsert_all #2425

@olivier-thatch

Description

@olivier-thatch

#2421 updated the ActiveRecord relations compiler to generate signatures for #upsert and #upsert_all (as well as many other methods). Howver, the signatures are incorrect:

    sig do
      params(
        attributes: Hash,
        returning: T.nilable(T.any(T::Array[Symbol], FalseClass)),
        unique_by: T.nilable(T.any(T::Array[Symbol], Symbol))
      ).returns(ActiveRecord::Result)
    end
    def upsert(attributes, returning: nil, unique_by: nil); end

    sig do
      params(
        attributes: T::Array[Hash],
        returning: T.nilable(T.any(T::Array[Symbol], FalseClass)),
        unique_by: T.nilable(T.any(T::Array[Symbol], Symbol))
      ).returns(ActiveRecord::Result)
    end
    def upsert_all(attributes, returning: nil, unique_by: nil); end

There are multiple issues:

  • The signatures are missing some valid arguments: on_duplicate, update_only, and record_timestamps (cf. Rails docs and source)

  • returning is typed as T.nilable(T.any(T::Array[Symbol], FalseClass)), but it can also be a String or a T::Array[String]. Some examples:

    Commodity.upsert_all(
      [
        { id: 2, name: "Copper", price: 4.84, created_at: Time.now, updated_at: Time.now  },
        { id: 4, name: "Gold", price: 1380.87, created_at: Time.now, updated_at: Time.now  },
        { id: 8, name: "Steel", price: 1.35, created_at: Time.now, updated_at: Time.now  }
      ],
      returning: Arel.sql("id, (xmax = '0') as inserted, name as new_name") # Arel.sql returns a String
    )
    
    Commodity.upsert_all(
      [
        { id: 2, name: "Copper", price: 4.84, created_at: Time.now, updated_at: Time.now  },
        { id: 4, name: "Gold", price: 1380.87, created_at: Time.now, updated_at: Time.now  },
        { id: 8, name: "Steel", price: 1.35, created_at: Time.now, updated_at: Time.now  }
      ],
      on_duplicate: Arel.sql("price = GREATEST(commodities.price, EXCLUDED.price)"),
      returning: ["price"] # Need to use String to reference dynamic SQL "columns"
    )

I'm also curious why these signatures were added to the compiler in the first place. Since they don't reference the model class, it seems like they could be omitted from the compiler and handled via annotations for ActiveRecord instead.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions