Skip to content

[7.x] Add the ability to create indexes as expressions#32411

Merged
taylorotwell merged 1 commit intolaravel:7.xfrom
reinink:7.x
Apr 17, 2020
Merged

[7.x] Add the ability to create indexes as expressions#32411
taylorotwell merged 1 commit intolaravel:7.xfrom
reinink:7.x

Conversation

@reinink
Copy link
Copy Markdown
Contributor

@reinink reinink commented Apr 17, 2020

This PR adds the ability to create indexes as expressions. Previously (to the best of my knowledge), the only way to do this was using DB::statement(). For example:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->date('birth_date')->nullable();
        $table->timestamps();
    });

    DB::statement('ALTER TABLE users ADD INDEX birthday_index ((date_format(birth_date, "%m-%d")))');
}

Not only does this look awful, it also doesn't take advantage of any platform specific grammar (should the expressions themselves be cross platform, of course).

This PR adds a new rawIndex() method to the Blueprint class, which allows for a much more Laravel-style syntax for creating expression indexes. For example:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->date('birth_date')->nullable();
        $table->timestamps();

        $table->rawIndex('(date_format(birth_date, "%m-%d"))', 'birthday_index');
    });
}

The other method name I considered was $table->expressionIndex(), but I felt this was probably more appropriate, since it's essentially using a raw expression under the hood.

This method requires an index name as the second argument, since there isn't a nice way to autogenerate the name.

I've tested this on MySQL, Postgres, and SQLite, and it works great. I haven't tested on it on SQL Server (no access to it), but I'm pretty confident it will work.

Compatibility:

  • Postgres has had functional index support since version 7.2 - (2002).
  • SQLite has had functional index support since version 3.9.0 - (2015).
  • MySQL has had functional index support since version 8.0.13 - (2018).

@reinink reinink changed the title Add the ability to create indexes as expressions [7.x] Add the ability to create indexes as expressions Apr 17, 2020
@taylorotwell taylorotwell merged commit cc179b8 into laravel:7.x Apr 17, 2020
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 this pull request may close these issues.

2 participants