Skip to content

Support multiple database ( secondary database transaction ) #47

@hamajyotan

Description

@hamajyotan

Currently, it always functions as transaction control for the primary database, but I would like to change this.
Specifically, I would like to achieve transaction control for models connected to databases other than the primary database.

class Foo < ApplicationRecord; end

class Bar < ApplicationRecord; end

class Baz < SecondarynRecord; end
# connect to primary database.

Model.new(Foo.new).save!

# ApplicationRecord.transaction do
#   foo.save!
# end

Model.new(Foo.new, Bar.new).save!

# ApplicationRecord.transaction do
#   bar.save!
# end


# connect to secondary database.

Model.new(Baz.new).save!

# SecondaryRecord.transaction do
#   baz.save!
# end

This makes it easier to use in applications with multiple database connections.

One thing to note is that it is difficult to update a model that has multiple connections.
Due to the characteristics of the activerecord API supported by Rails, a full two-phase commit does not exist.
At the end of the day, nothing more can be done than nested transactions like the one below.

# If primary/secondary are mixed, the following behavior will occur:

Model.new(Foo.new, Bar.new, Baz.new).save!

# ApplicationRecord.transaction do
#   SecondaryRecord.transaction do
#     foo.save!
#     bar.save!
#     baz.save!
#   end
# end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions