Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support UUID as PKs in associations #87

Merged
merged 1 commit into from
Jan 19, 2024
Merged

Support UUID as PKs in associations #87

merged 1 commit into from
Jan 19, 2024

Conversation

solnic
Copy link
Member

@solnic solnic commented Jan 19, 2024

This adds support for PKs generated by the factory. A common example is using UUIDs as PKs.

ROM.container(:sql, conn) do |conf|
  conf.default.create_table(:workers) do
    column :id, :uuid, primary_key: true
    column :name, String
  end

  conf.default.create_table(:jobs) do
    column :id, :uuid, primary_key: true
    foreign_key :worker_id, :workers, type: :uuid
    column :name, String
  end

  conf.relation(:workers) do
    schema(infer: true) do
      associations do
        has_many :jobs
      end
    end
  end

  conf.relation(:jobs) do
    schema(infer: true) do
      attribute :worker_id, ROM::SQL::Types.ForeignKey(:workers, ROM::SQL::Types::String)

      associations do
        belongs_to :worker
      end
    end
  end
end

factories.define(:worker) do |f|
  f.id { fake(:internet, :uuid) }
  f.name "Test Worker"

  f.association(:jobs, count: 0)

  f.trait(:with_jobs) do |t|
    t.association(:jobs, count: 2)
  end
end

factories.define(:job) do |f|
  f.id { fake(:internet, :uuid) }
  f.name "Test Job"

  f.association :worker
end

Bonus

This also improves returning persisted structs when RETURNING can't work as expected (ie in Sqlite or in case of PKs generated on the Ruby side).

@solnic solnic force-pushed the uuid-as-pks branch 4 times, most recently from 32c8b84 to e7d91a7 Compare January 19, 2024 10:32
@solnic solnic merged commit 1a16eb4 into main Jan 19, 2024
11 checks passed
@solnic solnic deleted the uuid-as-pks branch January 19, 2024 10:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant