From 23a273cd1b935c6402f46d5eeef358e38e83b8d5 Mon Sep 17 00:00:00 2001 From: luanfreitasdev Date: Sat, 4 May 2024 13:00:25 -0300 Subject: [PATCH] improve queries --- src/DataSource/Builder.php | 40 +++++++++++++++++++++++++++++++------- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/src/DataSource/Builder.php b/src/DataSource/Builder.php index db49b91c..9deb46d7 100644 --- a/src/DataSource/Builder.php +++ b/src/DataSource/Builder.php @@ -5,7 +5,7 @@ use Illuminate\Database\Eloquent\{Builder as EloquentBuilder, RelationNotFoundException}; use Illuminate\Database\Query\Builder as QueryBuilder; use Illuminate\Support\Arr; -use Illuminate\Support\Facades\{Cache, DB, Schema}; +use Illuminate\Support\Facades\{Cache, Schema}; use PowerComponents\LivewirePowerGrid\Components\Filters\{Builders\Number}; use PowerComponents\LivewirePowerGrid\{Column, Components\Filters\Builders\Boolean, @@ -147,16 +147,16 @@ public function filterContains(): Builder $search = $this->getBeforeSearchMethod($field, $search); - $hasColumn = in_array($field, $columnList, true); + $hasColumn = isset($columnList[$field]); - $query->when($search, function () use ($column, $query, $search, $table, $field, $hasColumn) { + $query->when($search != '', function () use ($column, $query, $search, $table, $field, $hasColumn) { if (($sqlRaw = strval(data_get($column, 'searchableRaw')))) { $query->orWhereRaw($sqlRaw . ' ' . Sql::like($query) . ' \'%' . $search . '%\''); } - if ($hasColumn && blank(data_get($column, 'searchableRaw')) && $search) { + if ($hasColumn && blank(data_get($column, 'searchableRaw'))) { try { - $columnType = DB::getSchemaBuilder()->getColumnType($table, $field); + $columnType = $this->getColumnType($table, $field); /** @phpstan-ignore-next-line */ $driverName = $query->getConnection()->getConfig('driver'); @@ -299,11 +299,37 @@ private function splitField(string $field): array return [$table, $field]; } + private function getColumnType(string $modelTable, string $field = null): ?string + { + try { + return $this->getColumnList($modelTable)[$field]; + } catch (\Throwable $throwable) { + logger()->warning('PowerGrid [getColumnType] warning: ', [ + 'table' => $modelTable, + 'field' => $field, + 'throwable' => $throwable->getTrace(), + ]); + + return null; + } + } + private function getColumnList(string $modelTable): array { try { - return (array) Cache::remember('powergrid_columns_in_' . $modelTable, 600, fn () => Schema::getColumnListing($modelTable)); - } catch (\Exception) { + return (array) Cache::remember( + 'powergrid_columns_in_' . $modelTable, + 60 * 60 * 3, + fn () => collect(Schema::getColumns($modelTable)) + ->pluck('type', 'name') + ->toArray() + ); + } catch (\Throwable $throwable) { + logger()->warning('PowerGrid [getColumnList] warning: ', [ + 'table' => $modelTable, + 'throwable' => $throwable->getTrace(), + ]); + return Schema::getColumnListing($modelTable); } }