Skip to content

A free open source IT asset/license management system

Fixed #19918 - memoize schema queries

snipe6e5fecd40238
diff --git a/app/Models/Company.php b/app/Models/Company.php
index 54175617ce..7476b75577 100644
--- a/app/Models/Company.php
+++ b/app/Models/Company.php
@@ -170,6 +170,54 @@ final class Company extends SnipeModel
*/
private static array $companyIdsCache = [];
+ /**
+ * Per-process memoization for Schema::hasColumn(). Keyed by "table::column".
+ * Called on every row from isCurrentUserHasAccess() and every scoped query
+ * from scopeCompanyablesDirectly(). Laravel 12 does not cache hasColumn, so
+ * without this each call issues a separate information_schema.columns query.
+ * Schema cannot change inside a request, so a plain static map is enough.
+ * Reset in tests via flushCompanyColumnCache(). Reported in #19918.
+ *
+ * @var array<string, bool>
+ */
+ private static array $hasCompanyColumnCache = [];
+
+ /**
+ * Per-request memoization for User-target visibility in isCurrentUserHasAccess().
+ * Keyed by "actor_id::target_id" because CompanyableScope resolves against the
+ * currently authenticated user. Transformers call Gate::allows() per row for
+ * every User reference (created_by, assigned_to, manager, etc.), and without
+ * this each call issues the FMCS pivot-subquery exists() check again against
+ * the same target id. Reset in tests via flushUserVisibilityCache(). #19918.
+ *
+ * @var array<string, bool>
+ */
+ private static array $userIsVisibleCache = [];
+
+ /**
+ * Return hasColumn($table, $column) from the per-process memo. Only
+ * consulted inside the FMCS hot path, which only ever asks about the
+ * company_id column, but the signature stays generic so the two call
+ * sites can share one entry.
+ */
+ private static function tableHasCompanyColumn(string $table, string $column = 'company_id'): bool
+ {
+ return self::$hasCompanyColumnCache[$table.'::'.$column]
+ ??= Schema::hasColumn($table, $column);
+ }
+
+ /**
+ * Return whether $target is visible to the current actor, from the
+ * per-request memo. Falls back to the FMCS pivot-subquery exists()
+ * check on first lookup. Only called from the User branch of
+ * isCurrentUserHasAccess() with an authenticated non-superuser actor.
+ */
+ private static function userIsVisibleToActor(int $actorId, int $targetId): bool
+ {
+ return self::$userIsVisibleCache[$actorId.'::'.$targetId]
+ ??= User::where('users.id', $targetId)->exists();
+ }
+
/**
* Return the current user's company IDs by querying the pivot table directly.
*
@@ -221,6 +269,25 @@ final class Company extends SnipeModel
self::$companyIdsCache = [];
}
+ /**
+ * Reset the per-process hasColumn memo. Called from TestCase::setUp(). The
+ * schema is stable at runtime, but migrations can add or drop columns in
+ * tests, so wipe between cases.
+ */
+ public static function flushCompanyColumnCache(): void
+ {
+ self::$hasCompanyColumnCache = [];
+ }
+
+ /**
+ * Reset the per-request user-visibility memo. Called from TestCase::setUp()
+ * for the same test-isolation reason as flushCompanyIdsCache().
+ */
+ public static function flushUserVisibilityCache(): void
+ {
+ self::$userIsVisibleCache = [];
+ }
+
/**
* Return the set of company IDs a user viewing $companyId should see items
* from when "hierarchy expansion" is requested — the company itself, its
@@ -401,7 +468,7 @@ final class Company extends SnipeModel
// This is primarily for the gate:allows-check in location->isDeletable()
// Locations don't have a company_id so without this it isn't possible to delete locations with FullMultipleCompanySupport enabled
// because this function is called by SnipePermissionsPolicy->before()
- if (! Schema::hasColumn($company_table, 'company_id')) {
+ if (! self::tableHasCompanyColumn($company_table)) {
return true;
}
@@ -424,7 +491,7 @@ final class Company extends SnipeModel
// per-target path, which left actors able to see users they
// couldn't then edit. One check, one query, same logic as the list.
if ($companyable instanceof User) {
- return User::where('users.id', $companyable->id)->exists();
+ return self::userIsVisibleToActor((int) auth()->id(), (int) $companyable->id);
}
$userCompanyIds = self::getCurrentUserCompanyIds();
@@ -726,7 +793,7 @@ final class Company extends SnipeModel
}
// If the column exists in the table, use it to scope the query
- if ($query && $query->getModel() && Schema::hasColumn($query->getModel()->getTable(), $column)) {
+ if ($query && $query->getModel() && self::tableHasCompanyColumn($query->getModel()->getTable(), $column)) {
$table = ($table_name) ? $table_name.'.' : $query->getModel()->getTable().'.';
if (empty($companyIds)) {
diff --git a/tests/Feature/QueryCountBenchmarkTest.php b/tests/Feature/QueryCountBenchmarkTest.php
index 62dbd0faee..a76bdb3b61 100644
--- a/tests/Feature/QueryCountBenchmarkTest.php
+++ b/tests/Feature/QueryCountBenchmarkTest.php
@@ -32,6 +32,7 @@ namespace Tests\Feature;
use App\Models\Asset;
use App\Models\AssetModel;
use App\Models\Category;
+use App\Models\Company;
use App\Models\Location;
use App\Models\Statuslabel;
use App\Models\User;
@@ -248,4 +249,73 @@ class QueryCountBenchmarkTest extends TestCase
}
}
}
+
+ // ---------------------------------------------------------------------------
+ // FMCS isCurrentUserHasAccess memoizes
+ // ---------------------------------------------------------------------------
+
+ // Regression for #19918. 8.8.0 removed the hasColumn early-return for User
+ // targets (users.company_id was renamed to legacy_company_id as part of the
+ // parent-company feature). Non-superuser callers in FMCS mode then paid two
+ // round-trips per transformer row: one information_schema.columns probe for
+ // every non-User target, and one FMCS pivot-subquery exists() check per User
+ // target. Both are deterministic within a request, so memoize.
+
+ public function test_fmcs_has_column_lookup_is_memoized_across_is_current_user_has_access_calls(): void
+ {
+ $this->settings->enableMultipleFullCompanySupport();
+
+ $actingCompany = Company::factory()->create();
+ $actingUser = $actingCompany->users()->save(User::factory()->make());
+ $this->actingAs($actingUser);
+
+ $assets = Asset::factory()->count(10)->create();
+ Company::flushCompanyColumnCache();
+
+ DB::flushQueryLog();
+ DB::enableQueryLog();
+ foreach ($assets as $asset) {
+ Company::isCurrentUserHasAccess($asset);
+ }
+ $queries = DB::getQueryLog();
+ DB::disableQueryLog();
+
+ $schemaProbes = array_filter($queries, fn ($q) => stripos($q['query'], 'information_schema.columns') !== false
+ || stripos($q['query'], 'show columns') !== false
+ || stripos($q['query'], 'pragma table_info') !== false);
+
+ $this->assertLessThanOrEqual(1, count($schemaProbes),
+ 'isCurrentUserHasAccess fired '.count($schemaProbes).' schema-probe queries across 10 identical calls. '
+ .'Company::$hasCompanyColumnCache should memoize this to one lookup per table per request.');
+ }
+
+ public function test_fmcs_user_target_visibility_is_memoized_per_actor_target(): void
+ {
+ $this->settings->enableMultipleFullCompanySupport();
+
+ [$companyA] = Company::factory()->count(2)->create();
+ $actingUser = $companyA->users()->save(User::factory()->make());
+ $this->actingAs($actingUser);
+
+ $target = $companyA->users()->save(User::factory()->make());
+ Company::flushUserVisibilityCache();
+
+ DB::flushQueryLog();
+ DB::enableQueryLog();
+ for ($i = 0; $i < 10; $i++) {
+ Company::isCurrentUserHasAccess($target);
+ }
+ $queries = DB::getQueryLog();
+ DB::disableQueryLog();
+
+ // The pivot-subquery check is the exists() against users scoped by
+ // CompanyableScope. Match on the exists shape against the users table.
+ $existsProbes = array_filter($queries, fn ($q) => stripos($q['query'], 'select exists') !== false
+ && stripos($q['query'], 'users') !== false
+ && stripos($q['query'], 'users.id') !== false);
+
+ $this->assertLessThanOrEqual(1, count($existsProbes),
+ 'isCurrentUserHasAccess fired '.count($existsProbes).' pivot-subquery exists() checks across 10 identical calls. '
+ .'Company::$userIsVisibleCache should memoize this to one lookup per actor/target pair.');
+ }
}
diff --git a/tests/TestCase.php b/tests/TestCase.php
index 0fb5e1c5a2..2dee21cad3 100644
--- a/tests/TestCase.php
+++ b/tests/TestCase.php
@@ -54,6 +54,8 @@ abstract class TestCase extends BaseTestCase
// increment may hand the same id to a different test's user with a
// different pivot set.
Company::flushCompanyIdsCache();
+ Company::flushCompanyColumnCache();
+ Company::flushUserVisibilityCache();
// Sync-adapter instance cache is another static that would hold
// rolled-back model references between tests otherwise.