Skip to content

Commit

Permalink
Fix index migration on Postgres
Browse files Browse the repository at this point in the history
Fixes #105
  • Loading branch information
frasmage committed May 16, 2024
1 parent b59bd14 commit 3ff6247
Showing 1 changed file with 24 additions and 7 deletions.
31 changes: 24 additions & 7 deletions migrations/2024_04_14_000000_add_meta_search_columns.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<?php

use Illuminate\Database\Connection;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
Expand All @@ -22,15 +23,27 @@ public function up()
$table->index(['key', 'metable_type', 'numeric_value']);

$stringIndexLength = (int)config('metable.stringValueIndexLength', 255);
if ($stringIndexLength > 0 && $driver = $this->detectDriverName()) {
$connection = $this->detectConnectionInUse();
if ($stringIndexLength > 0 && $driver = $connection?->getDriverName()) {
$grammar = $connection->getQueryGrammar();
if (in_array($driver, ['mysql', 'mariadb'])) {
$table->rawIndex(
"`metable_type`, `key`, `value`($stringIndexLength)",
sprintf("%s, %s, %s(%d)",
$grammar->wrap('metable_type'),
$grammar->wrap('key'),
$grammar->wrap('value'),
$stringIndexLength
),
'value_string_prefix_index'
);
} elseif (in_array($driver, ['pgsql', 'sqlite'])) {
$table->rawIndex(
"`metable_type`, `key`, SUBSTR(`value`, 1, $stringIndexLength)",
sprintf("%s, %s, SUBSTR(%s, 1, %d)",
$grammar->wrap('metable_type'),
$grammar->wrap('key'),
$grammar->wrap('value'),
$stringIndexLength
),
'value_string_prefix_index'
);
}
Expand All @@ -48,7 +61,9 @@ public function down()
Schema::table('meta', function (Blueprint $table) {
$stringIndexLength = (int)config('metable.stringValueIndexLength', 255);
if ($stringIndexLength > 0
&& in_array($this->detectDriverName(), ['mysql', 'mariadb', 'pgsql', 'sqlite'])
&& in_array($this->detectConnectionInUse()?->getDriverName(),
['mysql', 'mariadb', 'pgsql', 'sqlite']
)
) {
$table->dropIndex('value_string_prefix_index');
}
Expand All @@ -61,7 +76,7 @@ public function down()
});
}

private function detectDriverName(): ?string
private function detectConnectionInUse(): ?Connection
{
/** @var \Illuminate\Database\Migrations\Migrator $migrator */
$migrator = app('migrator');
Expand All @@ -73,8 +88,10 @@ private function detectDriverName(): ?string
$resolver = DB::getFacadeRoot();
}

return $resolver->connection(
$connection = $resolver->connection(
$this->getConnection() ?? $migrator->getConnection()
)->getDriverName();
);

return $connection instanceof Connection ? $connection : null;
}
};

0 comments on commit 3ff6247

Please sign in to comment.