Skip to content

Commit

Permalink
feat: optimize queries
Browse files Browse the repository at this point in the history
  • Loading branch information
luilliarcec committed Jul 7, 2024
1 parent e4268a6 commit 2908b8c
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/Concerns/HasUsername.php
Original file line number Diff line number Diff line change
Expand Up @@ -156,13 +156,17 @@ protected function getUsernameRegexSimilarityQuery(Builder $query, string $usern
$driver = $this->getConnection()->getDriverName();

if ($driver === 'mysql') {
$query->where($column, 'regexp', "^{$username}[0-9]*$");
$query
->where($column, 'like', $username)
->orWhere($column, 'regexp', "^{$username}[0-9]");

return;
}

if ($driver === 'pgsql') {
$query->where($column, '~', "^{$username}[0-9]*$");
$query
->where($column, 'like', $username)
->orWhere($column, '~', "^{$username}[0-9]");

return;
}
Expand Down
27 changes: 27 additions & 0 deletions tests/Units/SaveUsernameTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

namespace Tests\Units;

use Illuminate\Support\Benchmark;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Tests\Models\Customer;
use Tests\Models\User;

Expand Down Expand Up @@ -60,3 +63,27 @@
expect($customer->username)
->toBe('LARCEC');
});

it('performs a performance test on the query of similar users', function () {
ini_set('memory_limit', '-1');

$users = User::factory()->count(100_000)->make();

$users
->chunk(500)
->each(function (Collection $chunk) {
$records = $chunk
->map(fn (User $user) => $user->toArray())
->toArray();

DB::table('users')->insert($records);
});

$user = User::factory()->make(['name' => 'Luis Andrés Arce Cárdenas']);

Benchmark::dd(fn () => $user->getUsername(), 10);

// MySQL: 0.851ms
// SQLServer: 7.739ms
// PostgresSQL: 7.739ms
})->skip();

0 comments on commit 2908b8c

Please sign in to comment.