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

DB::usingConnection() doesn't respect read/write type #50804

Closed
SajtiDH opened this issue Mar 28, 2024 · 1 comment · Fixed by #50806
Closed

DB::usingConnection() doesn't respect read/write type #50804

SajtiDH opened this issue Mar 28, 2024 · 1 comment · Fixed by #50806

Comments

@SajtiDH
Copy link
Contributor

SajtiDH commented Mar 28, 2024

Laravel Version

10.48.4

PHP Version

8.2

Database Driver & Version

No response

Description

I wanted to use the mysql write connection by default for all DB operations including selects, to prevent issues caused by replication lag in a Job that is dispatched immediately after a write operation.

For this I used the following code:

        DB::usingConnection('mysql::write', function () {
            // my code
        });

During testing I realized that my Models and even queries executed by the DB facade still using the read connection for selects.

After did some debugging I found out it is because it works like this:

  1. DB::usingConnection() replaces the default connection's name in the DatabaseManager
  2. When DatabaseManager::connection() is used with default connection it doesn't get a $name param and it is resolved within a subsequent call to DatabaseManager::parseConnectionName() and then use only the first $database segment without the type to look for already created connection instance so the ::write part won't take effect.

Steps To Reproduce

Create any db connection config with both write and read type and try to directly connect to the write host using DB::usingConnection()

        DB::usingConnection('mysql::write', function () {
            AnyModel::first(); // This will use the read connection
        });
@driesvints
Copy link
Member

Thanks. Seems you already sent in a PR so let's see how it goes.

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 a pull request may close this issue.

2 participants