martenframework / marten

The pragmatic web framework.
https://martenframework.com
MIT License
424 stars 24 forks source link

Better handle possible circular dependencies with relationships when generating migrations #70

Closed ellmetha closed 1 year ago

ellmetha commented 1 year ago

Description

There are a few situations where Marten's migrations diff mechanism is not working as expected because the changed models involve circular dependencies. For example, let's consider the following models:

class Foo < Marten::Model
  field :id, :int, primary_key: true, auto: true
  field :title, :string, max_size: 50
  field :bar, :many_to_one, to: Bar
end

class Bar < Marten::Model
  field :id, :int, primary_key: true, auto: true
  field :title, :string, max_size: 50
  field :foo, :many_to_one, to: Foo
end

Foo has a reference to Bar, and Bar has a reference to Foo.

Attempting to generate migrations for such models is currently failing because the migrations diff abstractions is not able to properly deal with the circular dependency. In order to handle this properly, we should probably ensure that relationships fields are created as separate operations, and then "optimized" in order to ensure that relationship fields that don't involve circular dependencies are "merged" in the regular create_table operation for their table.

In this light, the following cases need to be investigated: