Skip to content

[5.x]: Alternate DB connection not used in getSlice of the QueryBatcher #16579

@roland-d

Description

@roland-d

What happened?

Description

I am building a batched job that pulls data from an external database and this did not seem to work completely. I believe I have found a bug in the QueryBatcher.php. In the QueryBatcher class you can pass along a Connection variable called $db. In that class the count() function does use the $this->db to pass along to the query. However the getSlice() function does not use the $this->db in the ->all() function. The result is that the Count() is done on connection A but the getSlice() is done on connection B. Which in my opinion is incorrect. For now I created my own QueryBatcher class so I can continue my development.

Steps to reproduce

  1. In the app.php add an alternative connection
        'legacydb' => [
     		'class' => yii\db\Connection::class,
     		'dsn' => 'mysql:host=' . App::env('LEGACY_DB_SERVER') . ';dbname=' . App::env('LEGACY_DB_DATABASE') . ';port=' . App::env('LEGACY_DB_PORT'),
     		'username' => App::env('LEGACY_DB_USER'),
     		'password' => App::env('LEGACY_DB_PASSWORD'),
     		'tablePrefix' => App::env('LEGACY_DB_TABLE_PREFIX'),
     		'charset' => 'utf8',
     	],
    
  2. Create a job class that extends the BaseBatchedJob
  3. In the loadData() function get the alternative connection using $connection = Craft::$app->get('legacydb');
  4. Return the QueryBatcher with a connection return new QueryBatcher($query, $connection);
  5. Set a breakpoint on line 82 with the code $slice = $query
  6. Inspect the value of $slice this should not be the expected data

The fix is to change line 85 from:
->all();
to
->all($this->db);

Expected behavior

The QueryBatcher::getSlice uses the provided connection to perform the query on.

Actual behavior

The QueryBatcher::getSlice uses the default connection to perform the query on.

Craft CMS version

5.6.1

PHP version

8.2.7

Operating system and version

Linux 6.6.65-1-MANJARO

Database type and version

MySQL 8.0.21

Image driver and version

GD 8.2.7

Installed plugins and versions

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions