Search code examples
laravelphpunitfull-text-search

Laravel PHPUnit error mysql fulltext index


Just got an error while running PHPUnit in Laravel after add FULLTEXT index

Doctrine\DBAL\Driver\PDOException: SQLSTATE[HY000]: General error: 1 near "name": syntax error

After investigating, the error caused by migration that I've added

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddFulltextIndexToProductName extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        DB::statement('ALTER TABLE products ADD FULLTEXT fulltext_index(name)');
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        DB::statement('DROP INDEX `fulltext_index`');
    }
}

If I remove that migration code, the test running gracefully

Has anyone experienced this problem?


Solution

  • Usually Laravel tests are using in memory sqlite database and this statement in your migration will not work. You can check how to create sqlite full text index here: https://www.sqlitetutorial.net/sqlite-full-text-search/

    Since Laravel doesn't support full text search out of the box I assume you have written custom function which probably also will not work in tests.

    To overcome the issue you can:

    • use mysql for test (not recommended since it is slow)
    • use repositories pattern
    • skip the migration when in tests (if you are not testing the search - you don't need it). You can check with if(env('APP_ENV') === 'testing')
    • use laravel scout for search