pdphilip / laravel-opensearch

An OpenSearch implementation of Laravel's Eloquent ORM
https://opensearch.pdphilip.com/
MIT License
23 stars 2 forks source link

How to test when using sqlite #8

Closed msieprawski-di closed 5 days ago

msieprawski-di commented 5 days ago

Hi! Thanks for great package!

I've created a Laravel project where main database is a opensearch database. It works great, but the problem is around testing. In tests I'm using sqlite connection, but the problem is that my User model extends from opensearch Model and when I try to create a user for tests it fails as it wants to create a user in opensearch database.

I tried to change the connection right after creating model instance but I got the same issue:

$user = \App\Models\User::factory()
    ->connection('sqlite')
    ->create([
        'email' => 'email@example.com',
        'password' => bcrypt('password'),
    ]);

triggers:

  Invalid connection settings; expected "elasticsearch", got "sqlite"

  at vendor/pdphilip/opensearch/src/Eloquent/Model.php:387
    383▕         $connection = $this->getConnection();
    384▕         if (!($connection instanceof Connection)) {
    385▕             $config = $connection->getConfig() ?? null;
    386▕             if (!empty($config['driver'])) {
  ➜ 387▕                 throw new RuntimeException('Invalid connection settings; expected "elasticsearch", got "'.$config['driver'].'"');
    388▕             } else {
    389▕                 throw new RuntimeException('Invalid connection settings; expected "elasticsearch"');
    390▕             }
    391▕         }
pdphilip commented 5 days ago

Hey @msieprawski-di

Seems like your User model is extending PDPhilip\OpenSearch\Eloquent\Model - try setting that back to extend Laravel's Model class.

Also try setting the sqlite connection directly in the User model: protected $connection = 'sqlite'; if it's not there.

If it's still an issue, then please show your User model.

Side note: The elasticsearch message wrong, it's expecting opensearch

msieprawski-di commented 5 days ago

That's correct. My User model extends from PDPhilip\OpenSearch\Eloquent\Model as I want to keep users in opensearch. I just want to keep them in sqlite during tests.

pdphilip commented 5 days ago

There won't be a way to do that with the same Model. The package extends Laravel's Eloquent but then commits to an Opensearch context (where tables are indexes, query methods get prepared for OS, etc).

Not sure about your set up, but I'd consider setting up a second OS connection (with a different index_prefix) for running tests. If your User model will connect to OS it's a good idea to test it in it's OS context.

Good luck with your project