From a724bce6356d713781946ff1f20512e45ee35bb8 Mon Sep 17 00:00:00 2001 From: Imani Manyara Date: Tue, 10 Nov 2026 15:30:18 -0500 Subject: [PATCH 1/4] Fix the schema to one shape and make the models the data layer --- .github/workflows/static-analysis.yml | 10 +- .github/workflows/tests.yml | 30 +- benchmarks/ReadBench.php | 1 - composer.json | 2 +- config/settings.php | 60 +- database/factories/SettingCategoryFactory.php | 15 +- .../factories/SettingDefinitionFactory.php | 2 +- database/factories/SettingFactory.php | 23 +- .../create_laranail_settings_tables.php | 694 +++++++++--------- src/Actions/Approvals/ApproveChange.php | 32 +- src/Actions/Approvals/CancelChange.php | 13 +- src/Actions/Approvals/ProposeChange.php | 10 +- src/Actions/Approvals/PruneChanges.php | 23 +- src/Actions/Approvals/QueryChanges.php | 14 +- src/Actions/Approvals/RejectChange.php | 13 +- src/Actions/Categories/CategoryGuard.php | 5 +- src/Actions/Categories/CreateCategory.php | 21 +- src/Actions/Categories/DeleteCategory.php | 12 +- src/Actions/Categories/ListCategories.php | 6 +- src/Actions/Categories/MoveCategory.php | 16 +- src/Actions/Categories/RenameCategory.php | 12 +- .../Configuration/DeleteDefinition.php | 14 +- src/Actions/Configuration/SaveDefinition.php | 30 +- src/Actions/DiagnoseSettings.php | 160 +--- src/Actions/DiffHistory.php | 8 +- src/Actions/MakeStore.php | 11 +- src/Actions/PruneAudit.php | 8 +- src/Actions/PruneHistory.php | 39 +- src/Actions/QueryAudit.php | 21 +- src/Actions/QueryHistory.php | 16 +- src/Actions/ReencryptSettings.php | 100 ++- src/Actions/RescopeOwners.php | 39 +- src/Actions/RollbackSetting.php | 8 +- src/Actions/SyncDefinitions.php | 48 +- src/Actions/Transfer/ImportStore.php | 16 +- src/Actions/WriteGuard.php | 2 +- src/Audit/DatabaseAuditSink.php | 15 +- src/Categories/CategoryManager.php | 25 +- src/Database/SchemaShape.php | 366 --------- src/Database/StoreSchema.php | 162 ---- src/Drivers/DatabaseDriver.php | 186 ++--- src/Enums/IdType.php | 8 +- src/Enums/IdentityMode.php | 38 - src/Enums/OwnerKeyType.php | 24 - src/Enums/TenancyMode.php | 12 + src/Enums/TranslationsMode.php | 24 - src/History/HistoryQuery.php | 13 +- src/Models/Concerns/BelongsToTenant.php | 28 + src/Models/Concerns/UsesSettingsSchema.php | 64 -- src/Models/ModelContext.php | 70 +- src/Models/Scopes/TenantScope.php | 34 + src/Models/Setting.php | 52 +- src/Models/SettingAuditEntry.php | 156 +++- src/Models/SettingCategory.php | 134 +++- src/Models/SettingChangeRequest.php | 221 ++++++ src/Models/SettingDefinition.php | 102 ++- src/Models/SettingHistory.php | 206 ++++++ src/Models/SettingsModel.php | 61 ++ src/Providers/SettingsServiceProvider.php | 28 +- .../Configuration/PersistedConfiguration.php | 18 +- src/Services/Database/AuditRepository.php | 174 ----- src/Services/Database/CategoryRepository.php | 261 ------- .../Database/ChangeRequestRepository.php | 323 -------- .../Database/DefinitionsRepository.php | 176 ----- src/Services/Database/HistoryRepository.php | 300 -------- .../Database/SchemaShapeRepository.php | 149 ---- .../Definitions/DatabaseDefinitions.php | 60 +- .../Definitions/DefinitionRegistry.php | 5 +- src/Services/Drivers/DriverFactory.php | 31 +- src/Services/Stores/SettingWriter.php | 40 +- src/Services/Stores/StoreRegistry.php | 84 ++- src/Services/Transfer/StoreSnapshots.php | 17 +- src/Stores/Store.php | 16 +- src/Support/Translations.php | 68 +- tests/Arch/ArchitectureTest.php | 5 +- tests/Arch/LayeringTest.php | 2 +- tests/Arch/ServicesTest.php | 16 +- tests/Feature/Database/ApprovalsTest.php | 8 +- tests/Feature/Database/CommandsTest.php | 16 +- tests/Feature/Database/DatabaseLayerTest.php | 15 +- tests/Feature/Database/DebuggingAidsTest.php | 3 +- .../Feature/Database/DefinitionsTableTest.php | 40 +- tests/Feature/Database/FixedSchemaTest.php | 169 +++++ .../Feature/Database/GovernanceEventsTest.php | 2 +- tests/Feature/Database/HistoryTest.php | 12 +- tests/Feature/Database/MaintenanceTest.php | 10 +- tests/Feature/Database/MigrationTest.php | 6 +- .../Database/ModelsAndFactoriesTest.php | 43 +- .../Database/PersistedConfigurationTest.php | 6 +- tests/Feature/Database/RestApiTest.php | 2 +- tests/Feature/Database/SchemaMatrixTest.php | 160 ---- tests/Feature/Database/SchemaShapeTest.php | 165 ----- tests/Feature/Database/SchemaSwitchesTest.php | 167 ----- tests/Feature/Database/SoftDeletesTest.php | 11 +- tests/Feature/Database/TenancyTest.php | 4 +- tests/Feature/PackageLayoutTest.php | 2 +- tests/Feature/ReferenceDocsTest.php | 4 +- tests/Pest.php | 2 +- tests/Support/Pairwise.php | 108 --- tests/TestCase.php | 2 - tests/Unit/DocsConformanceTest.php | 4 +- tests/Unit/SchemaShapeTest.php | 126 ---- tests/Unit/SupportTest.php | 28 +- 103 files changed, 2358 insertions(+), 4065 deletions(-) delete mode 100644 src/Database/SchemaShape.php delete mode 100644 src/Database/StoreSchema.php delete mode 100644 src/Enums/IdentityMode.php delete mode 100644 src/Enums/OwnerKeyType.php delete mode 100644 src/Enums/TranslationsMode.php create mode 100644 src/Models/Concerns/BelongsToTenant.php delete mode 100644 src/Models/Concerns/UsesSettingsSchema.php create mode 100644 src/Models/Scopes/TenantScope.php create mode 100644 src/Models/SettingChangeRequest.php create mode 100644 src/Models/SettingHistory.php create mode 100644 src/Models/SettingsModel.php delete mode 100644 src/Services/Database/AuditRepository.php delete mode 100644 src/Services/Database/CategoryRepository.php delete mode 100644 src/Services/Database/ChangeRequestRepository.php delete mode 100644 src/Services/Database/DefinitionsRepository.php delete mode 100644 src/Services/Database/HistoryRepository.php delete mode 100644 src/Services/Database/SchemaShapeRepository.php create mode 100644 tests/Feature/Database/FixedSchemaTest.php delete mode 100644 tests/Feature/Database/SchemaMatrixTest.php delete mode 100644 tests/Feature/Database/SchemaShapeTest.php delete mode 100644 tests/Feature/Database/SchemaSwitchesTest.php delete mode 100644 tests/Support/Pairwise.php delete mode 100644 tests/Unit/SchemaShapeTest.php diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml index e208e49..5b5b609 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -117,12 +117,10 @@ jobs: - name: Mutation testing (minimum score 70) # Pest's own mutator, not Infection: Infection has no Pest adapter, reads Pest's # version as PHPUnit's, writes a config PHPUnit 12 rejects, and cannot map Pest's - # generated test classes to its JUnit report. The schema matrix (group `matrix`) - # covers almost every line, so it is left out, and group `shared-app` writes into the - # testbench application every process shares; the Tests workflow runs both. Both carry - # group `mutation-excluded`, which is what is excluded: under --parallel Pest honours - # only the first --exclude-group, and a comma-separated list excludes nothing, so - # `--exclude-group=matrix,shared-app` ran every test and raced on the shared config file. + # generated test classes to its JUnit report. Group `shared-app` writes into the + # testbench application every process shares, so it is left out; the Tests workflow + # runs it. It also carries group `mutation-excluded`, which is what is excluded: under + # --parallel Pest honours only the first --exclude-group. env: MUTATE_PATHS: ${{ steps.scope.outputs.paths }} run: | diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 6aadcc0..bce3778 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -25,7 +25,8 @@ jobs: test-command: 'vendor/bin/pest' # The shared workflow runs on SQLite only, so the `database` test group runs again here on - # MySQL and Postgres service containers. Their passwords are throwaway literals: GitHub starts + # MySQL and Postgres service containers. That group includes the tenancy matrix (group + # `tenancy`: `tenancy.mode` none and column, end to end). Their passwords are throwaway literals: GitHub starts # services before any step, so they cannot come from a generator. databases: name: Database group · ${{ matrix.database }} @@ -78,30 +79,3 @@ jobs: - name: Run the database group run: vendor/bin/pest --group=database - - # §13: the full product of the schema switches (1,152 shapes, tenancy included) on SQLite, weekly and on demand. - # Pull requests run the pairwise set (10 shapes) inside the jobs above. - matrix-full: - name: Schema switches · full product - if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' - runs-on: ubuntu-latest - timeout-minutes: 40 - env: - LARANAIL_SETTINGS_MATRIX: full - COMPOSER_AUTH: '{"github-oauth": {"github.com": "${{ secrets.GITHUB_TOKEN }}"}}' - steps: - - uses: actions/checkout@v7 - - - name: Setup PHP 8.4 - uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 - with: - php-version: '8.4' - extensions: dom, curl, libxml, mbstring, zip, fileinfo, pdo, sqlite3, pdo_sqlite - coverage: none - tools: composer:v2 - - - name: Install dependencies - run: composer update --prefer-dist --no-interaction --no-progress - - - name: Run the full switch matrix - run: vendor/bin/pest --group=matrix diff --git a/benchmarks/ReadBench.php b/benchmarks/ReadBench.php index 6b88f52..b1ad4b9 100644 --- a/benchmarks/ReadBench.php +++ b/benchmarks/ReadBench.php @@ -113,7 +113,6 @@ private function boot(array $cache): void $config->set('database.default', 'bench'); $config->set('database.connections.bench', ['driver' => 'sqlite', 'database' => $directory . '/database.sqlite', 'prefix' => '', 'foreign_key_constraints' => true]); $config->set('cache.stores.file.path', $directory . '/cache'); - $config->set('laranail.settings.schema.path', $directory . '/settings-schema.php'); $config->set('laranail.settings.layers.shipped.path', $directory . '/none.php'); $config->set('laranail.settings.stores.settings.layers', ['database']); $config->set('laranail.settings.stores.settings.owners', ['owner', 'team']); diff --git a/composer.json b/composer.json index 2b6d968..c55dc47 100644 --- a/composer.json +++ b/composer.json @@ -79,7 +79,7 @@ "test": "vendor/bin/pest --colors=always", "test-coverage": "@test --coverage --min=90", "test-dirty": "@test --dirty --compact", - "mutate": "vendor/bin/pest --mutate --everything --exclude-group=matrix --min=70", + "mutate": "vendor/bin/pest --mutate --everything --exclude-group=mutation-excluded --min=70", "bench": [ "@composer --working-dir=tools/phpbench update --no-interaction --no-progress --quiet", "tools/phpbench/vendor/bin/phpbench run --config=phpbench.json --report=settings" diff --git a/config/settings.php b/config/settings.php index dc2b16c..71eef98 100644 --- a/config/settings.php +++ b/config/settings.php @@ -37,7 +37,7 @@ | bootstrap: skip the database layer while the application installs. | table: the values table name (default: the store name). | mode: `polymorphic` or `dedicated` (one owner alias, with a - | foreign key to `owner.table`). Recorded at migration time. + | foreign key to `owner.table`; read when migrating). | soft_deletes: keep forgotten rows trashed and restore them on write. | | 'user_settings' => [ @@ -82,51 +82,12 @@ 'stores' => 'settings_stores', ], - /* - |-------------------------------------------------------------------------- - | Schema switches - |-------------------------------------------------------------------------- - | - | Read by `install` and `make-store`, which record the resulting shape in - | the schema file (`schema.path`, default database/settings-schema.php). - | The package reads that file at runtime, so changing a switch after - | migrating has no effect until a migration applies it; `doctor` reports - | the drift. - | - | identity.mode: `slug_uid`, `slug_per_row` or `uid_only`. - | ids.type: `bigint`, `uuid`, `ulid`, or null to follow - | laranail.db-tools.id_type. - | ids.owner_key: `string` (settable_id as string(36)) or `typed`. - | translations.mode: `lang` (plain text) or `json` (per-locale maps). - | categories.soft_deletes: trash categories and restore them on re-create. - */ - 'schema' => [ - 'path' => env('LARANAIL_SETTINGS_SCHEMA_PATH'), - ], - - 'identity' => [ - 'mode' => 'slug_uid', - ], - - 'ids' => [ - 'type' => null, - 'owner_key' => 'string', - ], - - 'translations' => [ - 'mode' => 'lang', - ], - - 'categories' => [ - 'soft_deletes' => false, - ], - /* |-------------------------------------------------------------------------- | Tenancy |-------------------------------------------------------------------------- | - | mode (recorded at migration time): + | mode (read when migrating, and on every query): | `none` one set of settings for the application. | `column` a `tenant` column on every table, filled and filtered with | the current tenant ('' is the central partition). @@ -227,13 +188,13 @@ | Setting definitions are registered in code with DefinitionRegistry::define() | or kept in the definitions table. | - | table: create the settings_definitions table (migration time). | sources: where definitions come from, merged in order, later wins. + | Add `database` to read rows edited at runtime from the + | definitions table (one query per store per request). | allowed_rules: the validation rules a database definition may use. */ 'definitions' => [ - 'table' => false, - 'sources' => ['code', 'config', 'database'], + 'sources' => ['code', 'config'], 'allowed_rules' => ['required', 'nullable', 'string', 'integer', 'numeric', 'boolean', 'array', 'email', 'url', 'in', 'not_in', 'min', 'max', 'between', 'size', 'regex', 'date', 'alpha', 'alpha_dash', 'alpha_num'], ], @@ -327,13 +288,12 @@ | History |-------------------------------------------------------------------------- | - | enabled: create the settings_history table (migration time) and - | record every value change in it. + | Every value change is recorded in the history table. + | | keep_days: retention applied by prune-history; null to disable. | keep_versions: versions kept per setting; null to disable. */ 'history' => [ - 'enabled' => env('LARANAIL_SETTINGS_HISTORY', true), 'keep_days' => 365, 'keep_versions' => null, ], @@ -389,14 +349,12 @@ | Writes to definitions marked requiresApproval(), or to keys matched by | `stores..approvals.keys`, become change requests. | - | table: create settings_change_requests (migration time). | min_approvals: approvals needed to apply a change. | allow_self: let the requester approve their own request. | expire_after: days before an open request expires. | keep_days: days decided requests are kept by prune-changes. */ 'approvals' => [ - 'table' => true, 'min_approvals' => 1, 'allow_self' => false, 'expire_after' => 7, @@ -408,8 +366,8 @@ | Persisted configuration |-------------------------------------------------------------------------- | - | persisted: create settings_stores (migration time) to hold stores and - | layers saved through the API. + | persisted: read and write the stores and layers saved through the API + | (the settings_stores table). | sources: merge order, later wins: `config`, `database`, `runtime`. */ 'configuration' => [ diff --git a/database/factories/SettingCategoryFactory.php b/database/factories/SettingCategoryFactory.php index 5d7a847..87dd2f9 100644 --- a/database/factories/SettingCategoryFactory.php +++ b/database/factories/SettingCategoryFactory.php @@ -11,8 +11,7 @@ use Simtabi\Laranail\Settings\Models\SettingCategory; /** - * Categories for tests and seeding. Titles follow `translations.mode` (plain text, or a JSON map - * of locale to text). No Faker: slugs and titles are generated, so host applications need not + * Categories for tests and seeding. Titles are JSON maps of locale to text. No Faker: slugs and titles are generated, so host applications need not * install it. * * SettingCategory::factory()->forStore('user_settings')->system()->create(['slug' => 'mail']); @@ -24,10 +23,14 @@ final class SettingCategoryFactory extends Factory { protected $model = SettingCategory::class; - /** Text as `translations.mode` stores it: as is, or `{"": text}` (the text for any locale), as the engine writes it. */ - public static function text(string $text): string + /** + * Text as the engine stores it: `['' => text]`, the text for any locale. + * + * @return array + */ + public static function text(string $text): array { - return new Translations(ModelContext::shape()->translations)->store($text); + return Translations::of($text); } /** @return array */ @@ -64,7 +67,7 @@ public function parent(SettingCategory $parent): static return $this->state(['parent_id' => $parent->getKey(), 'store' => $parent->store]); } - /** A title (and optionally a description) as the shape stores them. */ + /** A title, and optionally a description. */ public function titled(string $title, ?string $description = null): static { return $this->state(['title' => self::text($title), 'description' => $description === null ? null : self::text($description)]); diff --git a/database/factories/SettingDefinitionFactory.php b/database/factories/SettingDefinitionFactory.php index 99776d5..0e3ae43 100644 --- a/database/factories/SettingDefinitionFactory.php +++ b/database/factories/SettingDefinitionFactory.php @@ -10,7 +10,7 @@ use Simtabi\Laranail\Settings\Models\SettingDefinition; /** - * Rows of the definitions table (`definitions.table`). `default` holds the encoded default, as + * Rows of the definitions table. `default` holds the encoded default, as * the definitions sync writes it. * * @extends Factory diff --git a/database/factories/SettingFactory.php b/database/factories/SettingFactory.php index 9b10395..a15870d 100644 --- a/database/factories/SettingFactory.php +++ b/database/factories/SettingFactory.php @@ -6,8 +6,6 @@ use Illuminate\Support\Str; use Simtabi\Laranail\Settings\Models\Setting; -use Simtabi\Laranail\Settings\Enums\IdentityMode; -use Simtabi\Laranail\Settings\Models\ModelContext; use Illuminate\Database\Eloquent\Factories\Factory; use Simtabi\Laranail\Settings\Models\SettingCategory; @@ -31,7 +29,7 @@ public function definition(): array { $key = 'test.' . Str::lower(Str::random(12)); - return $this->identity($key) + [ + return [ 'scope' => 'global', 'key' => $key, 'group' => 'test', @@ -51,7 +49,7 @@ public function forStore(string $store): static public function key(string $key): static { - return $this->state(fn (): array => ['key' => $key, 'group' => explode('.', $key, 2)[0]] + $this->identity($key)); + return $this->state(['key' => $key, 'group' => explode('.', $key, 2)[0]]); } /** The value, encoded as the pipeline encodes an unencrypted value. */ @@ -80,21 +78,4 @@ public function inCategory(SettingCategory $category): static { return $this->state(['category_id' => $category->getKey(), 'category_store' => $category->store]); } - - /** @return array the slug and uid columns the identity mode has */ - private function identity(string $key): array - { - $mode = ModelContext::shape()->identity; - $columns = []; - - if ($mode->hasSlug()) { - $columns['slug'] = $mode === IdentityMode::SlugPerRow ? sha1('global|' . $key . '|') : str_replace('.', '-', $key); - } - - if ($mode->hasUid()) { - $columns['uid'] = (string) Str::ulid(); - } - - return $columns; - } } diff --git a/database/migrations/create_laranail_settings_tables.php b/database/migrations/create_laranail_settings_tables.php index 2b7493b..7d81f90 100644 --- a/database/migrations/create_laranail_settings_tables.php +++ b/database/migrations/create_laranail_settings_tables.php @@ -5,112 +5,264 @@ use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; -use Simtabi\Laranail\Settings\Enums\IdType; use Illuminate\Database\Migrations\Migration; use Simtabi\Laranail\Settings\Data\StoreName; use Illuminate\Database\Schema\ColumnDefinition; -use Simtabi\Laranail\Settings\Enums\TenancyMode; -use Simtabi\Laranail\Settings\Enums\IdentityMode; -use Simtabi\Laranail\Settings\Enums\OwnerKeyType; -use Simtabi\Laranail\Settings\Database\SchemaShape; -use Simtabi\Laranail\Settings\Database\StoreSchema; -use Simtabi\Laranail\Settings\Enums\TranslationsMode; -use Simtabi\Laranail\Settings\Services\Database\SchemaShapeRepository; +use Simtabi\Laranail\Settings\Database\SchemaNames; /* * Every table laranail/settings uses, in dependency order: * * categories shared by the stores on a connection, nested by parent_id - * definitions optional (definitions.table), on the default store's connection + * definitions on the default store's connection * one values table per database store * audit actions and denials, never values - * history every value by version (history.enabled) - * change requests pending approvals (approvals.table) - * stores persisted store and layer configuration (configuration.persisted) + * history every value by version + * change requests writes waiting for approval + * stores stores and layers saved through the API, on the default store's connection * - * The shape (key types, identity mode, owner keys, soft deletes, translations, tenancy, table - * names and connections) comes from the recorded schema file, database/settings-schema.php, or - * from configuration when nothing is recorded. + * The shape is fixed. The one switch is `tenancy.mode`: in `column` mode every tenant-owned table + * gets a `tenant` column, and the tenant leads its unique and lookup indexes. * * `laranail::settings.make-store` copies this file for one store by rewriting the $only line * (and, with --connection, the $pinnedConnection line). Keep both lines exactly as they are. */ return new class extends Migration { - /** null: every recorded store plus the shared tables; a store name: that store only. */ + /** null: every configured store plus the shared tables; a store name: that store only. */ private ?string $only = null; private ?string $pinnedConnection = null; public function getConnection(): ?string { - return $this->pinnedConnection ?? $this->shape()->store($this->primaryStore())->connection; + return $this->pinnedConnection ?? $this->store($this->primaryStore())['connection']; } public function up(): void { - $shape = $this->shape(); - $names = $shape->names; + $names = $this->names(); foreach ($this->plan() as $connection => $tables) { + $schema = Schema::connection($connection); + $tenant = $this->tenantColumn(); + $binary = $this->binaryCollation($connection); + if ($tables['shared'] && $this->missing($connection, $names->categories())) { - $this->createCategories($connection, $shape); + $schema->create($names->categories(), function (Blueprint $table) use ($names, $tenant): void { + $name = $names->categories(); + + $table->ulid('id')->primary(); + + if ($tenant) { + $table->string('tenant', 64)->default(''); + } + + $table->string('store', 64); + $table->ulid('parent_id')->nullable(); + $table->json('title'); + $table->string('slug', 128); + $table->json('description')->nullable(); + $table->string('icon')->nullable(); + $table->unsignedInteger('sort_order')->default(0); + $table->boolean('is_system')->default(false); + $table->json('meta')->nullable(); + $table->timestamps(); + + $table->unique($this->withTenant(['store', 'slug']), $name . '_store_slug_unique'); + $table->unique(['id', 'store'], $name . '_id_store_unique'); + $table->index('parent_id', $name . '_parent_index'); + $table->foreign('parent_id', $name . '_parent_foreign')->references('id')->on($name)->nullOnDelete(); + }); } - if ($tables['definitions']) { - $this->createDefinitions($connection, $shape); + if ($tables['definitions'] && $this->missing($connection, $names->definitions())) { + $schema->create($names->definitions(), function (Blueprint $table) use ($names): void { + $name = $names->definitions(); + + $table->ulid('id')->primary(); + $table->string('store', 64); + $table->string('slug', 191); + $table->string('key', 191); + $table->string('group', 64); + $table->ulid('category_id')->nullable(); + $table->string('type', 64)->nullable(); + $table->longText('default')->nullable(); + $table->json('label')->nullable(); + $table->json('description')->nullable(); + $table->json('rules')->nullable(); + $table->boolean('is_encrypted')->default(false); + $table->boolean('is_public')->default(false); + $table->boolean('is_locked')->default(false); + $table->boolean('autoload')->default(true); + $table->boolean('inherits')->nullable(); + $table->json('overridable_by')->nullable(); + $table->boolean('is_system')->default(false); + $table->json('meta')->nullable(); + $table->timestamps(); + + $table->unique(['store', 'key'], $name . '_store_key_unique'); + $table->unique(['store', 'slug'], $name . '_store_slug_unique'); + $table->index('category_id', $name . '_category_index'); + $table->foreign('category_id', $name . '_category_foreign')->references('id')->on($names->categories())->nullOnDelete(); + }); } foreach ($tables['stores'] as $store) { - if ($this->missing($connection, $names->store($store->name, $store->table))) { - $this->createValues($connection, $shape, $store); + if ($this->missing($connection, $store['table'])) { + $schema->create($store['table'], function (Blueprint $table) use ($binary, $names, $store, $tenant): void { + $this->valuesTable($table, $store, $names, $tenant, $binary); + }); } } if ($tables['shared'] && $this->missing($connection, $names->audit())) { - $this->createAudit($connection, $shape); + $schema->create($names->audit(), function (Blueprint $table) use ($names, $tenant): void { + $name = $names->audit(); + + $table->ulid('id')->primary(); + + if ($tenant) { + $table->string('tenant', 64)->default(''); + } + + $table->timestamp('occurred_at'); + $table->string('action', 32); + $table->string('outcome', 16); + $table->string('store', 64)->nullable(); + $table->string('scope', 128)->nullable(); + $table->string('key', 191)->nullable(); + $table->string('locale', 16)->nullable(); + $table->unsignedInteger('version_from')->nullable(); + $table->unsignedInteger('version_to')->nullable(); + $table->char('change_request', 26)->nullable(); + $table->string('actor_type', 16); + $table->string('actor_alias', 64)->nullable(); + $table->string('actor_id', 64)->nullable(); + $table->string('channel', 16); + $table->string('ip', 45)->nullable(); + $table->string('user_agent')->nullable(); + $table->string('request_id')->nullable(); + $table->text('reason')->nullable(); + $table->json('meta')->nullable(); + + $table->index('occurred_at', $name . '_occurred_index'); + $table->index($this->withTenant(['store', 'scope', 'key']), $name . '_subject_index'); + $table->index(['actor_alias', 'actor_id'], $name . '_actor_index'); + }); } - if ($tables['shared'] && $shape->historyTable && $this->missing($connection, $names->history())) { - $this->createHistory($connection, $shape); + // One row per version of a setting, with the payload before and after exactly as the + // values table stores it. `setting_ref` is the values row's `uid`. + if ($tables['shared'] && $this->missing($connection, $names->history())) { + $schema->create($names->history(), function (Blueprint $table) use ($binary, $names, $tenant): void { + $name = $names->history(); + + $table->ulid('id')->primary(); + + if ($tenant) { + $this->collate($table->string('tenant', 64)->default(''), $binary); + } + + $table->string('store', 64); + $table->string('setting_ref', 36)->nullable(); + $this->collate($table->string('scope', 128), $binary); + $this->collate($table->string('key', 191), $binary); + $this->collate($table->string('locale', 16)->default(''), $binary); + $table->string('operation', 16); + $table->longText('old_value')->nullable(); + $table->longText('new_value')->nullable(); + $table->string('old_type', 64)->nullable(); + $table->string('new_type', 64)->nullable(); + $table->boolean('old_encrypted')->default(false); + $table->boolean('new_encrypted')->default(false); + $table->unsignedInteger('version'); + $table->string('causer_type', 16); + $table->string('causer_alias', 64)->nullable(); + $table->string('causer_id', 64)->nullable(); + $table->text('reason')->nullable(); + $table->timestamp('created_at'); + + $table->index($this->withTenant(['store', 'scope', 'key', 'locale', 'version']), $name . '_subject_index'); + $table->index('created_at', $name . '_created_index'); + }); } - if ($tables['shared'] && $shape->changeRequestsTable && $this->missing($connection, $names->changeRequests())) { - $this->createChangeRequests($connection, $shape); + // Writes waiting for approval. `payload` is stored as the values table would store it, + // and `base_version` lets a request whose setting has since changed become `stale`. + if ($tables['shared'] && $this->missing($connection, $names->changeRequests())) { + $schema->create($names->changeRequests(), function (Blueprint $table) use ($binary, $names, $tenant): void { + $name = $names->changeRequests(); + + $table->ulid('id')->primary(); + + if ($tenant) { + $this->collate($table->string('tenant', 64)->default(''), $binary); + } + + $table->string('store', 64); + $this->collate($table->string('scope', 128), $binary); + $this->collate($table->string('key', 191), $binary); + $this->collate($table->string('locale', 16)->default(''), $binary); + $table->string('operation', 16); + $table->longText('payload')->nullable(); + $table->string('type', 64)->nullable(); + $table->boolean('is_encrypted')->default(false); + $table->unsignedInteger('base_version')->default(0); + $table->string('status', 16); + $table->string('requested_by_type', 16); + $table->string('requested_by_alias', 64)->nullable(); + $table->string('requested_by_id', 64)->nullable(); + $table->json('approvals')->nullable(); + $table->string('decided_by_type', 16)->nullable(); + $table->string('decided_by_alias', 64)->nullable(); + $table->string('decided_by_id', 64)->nullable(); + $table->timestamp('decided_at')->nullable(); + $table->text('reason')->nullable(); + $table->text('decision_reason')->nullable(); + $table->timestamp('expires_at')->nullable(); + $table->timestamps(); + + $table->index($this->withTenant(['status', 'store']), $name . '_status_index'); + $table->index($this->withTenant(['store', 'scope', 'key', 'locale']), $name . '_subject_index'); + $table->index('expires_at', $name . '_expires_index'); + }); } - if ($tables['definitions'] && $shape->storesTable) { - $this->createStores($connection, $shape); + // Store and layer entries saved through the API; `config` holds the entry as JSON. + if ($tables['definitions'] && $this->missing($connection, $names->stores())) { + $schema->create($names->stores(), function (Blueprint $table) use ($names): void { + $table->ulid('id')->primary(); + $table->string('kind', 16); + $table->string('name', 64); + $table->json('config'); + $table->timestamps(); + + $table->unique(['kind', 'name'], $names->stores() . '_kind_name_unique'); + }); } } } public function down(): void { - $shape = $this->shape(); - $names = $shape->names; + $names = $this->names(); foreach (array_reverse($this->plan(), true) as $connection => $tables) { $schema = Schema::connection($connection); - if ($tables['definitions'] && $shape->storesTable) { + if ($tables['definitions']) { $schema->dropIfExists($names->stores()); } - if ($tables['shared'] && $shape->changeRequestsTable) { + if ($tables['shared']) { $schema->dropIfExists($names->changeRequests()); - } - - if ($tables['shared'] && $shape->historyTable) { $schema->dropIfExists($names->history()); - } - - if ($tables['shared']) { $schema->dropIfExists($names->audit()); } foreach (array_reverse($tables['stores']) as $store) { - $schema->dropIfExists($names->store($store->name, $store->table)); + $schema->dropIfExists($store['table']); } if ($tables['definitions']) { @@ -123,322 +275,162 @@ public function down(): void } } - private function createCategories(string $connection, SchemaShape $shape): void - { - $name = $shape->names->categories(); - - Schema::connection($connection)->create($name, function (Blueprint $table) use ($name, $shape): void { - $this->key($table, 'id', $shape->ids, primary: true); - $this->tenant($table, $shape); - $table->string('store', 64); - $this->key($table, 'parent_id', $shape->ids)->nullable(); - $this->translatable($table, 'title', $shape, nullable: false); - $table->string('slug', 128); - $this->translatable($table, 'description', $shape); - $table->string('icon')->nullable(); - $table->unsignedInteger('sort_order')->default(0); - $table->boolean('is_system')->default(false); - $table->json('meta')->nullable(); - $table->timestamps(); - - if ($shape->categoriesSoftDeletes) { - $table->timestamp('deleted_at')->nullable(); - } - - $table->unique([...$this->tenantColumns($shape), 'store', 'slug'], $name . '_store_slug_unique'); - $table->unique(['id', 'store'], $name . '_id_store_unique'); - $table->index('parent_id', $name . '_parent_index'); - $table->foreign('parent_id', $name . '_parent_foreign')->references('id')->on($name)->nullOnDelete(); - }); - } - - private function createDefinitions(string $connection, SchemaShape $shape): void - { - $name = $shape->names->definitions(); - $categories = $shape->names->categories(); - - Schema::connection($connection)->create($name, function (Blueprint $table) use ($categories, $name, $shape): void { - $this->key($table, 'id', $shape->ids, primary: true); - $table->string('store', 64); - $table->string('slug', 191); - $table->string('key', 191); - $table->string('group', 64); - $this->key($table, 'category_id', $shape->ids)->nullable(); - $table->string('type', 64)->nullable(); - $table->longText('default')->nullable(); - $this->translatable($table, 'label', $shape); - $this->translatable($table, 'description', $shape); - $table->json('rules')->nullable(); - $table->boolean('is_encrypted')->default(false); - $table->boolean('is_public')->default(false); - $table->boolean('is_locked')->default(false); - $table->boolean('autoload')->default(true); - $table->boolean('inherits')->nullable(); - $table->json('overridable_by')->nullable(); - $table->boolean('is_system')->default(false); - $table->json('meta')->nullable(); - $table->timestamps(); - - $table->unique(['store', 'key'], $name . '_store_key_unique'); - $table->unique(['store', 'slug'], $name . '_store_slug_unique'); - $table->index('category_id', $name . '_category_index'); - $table->foreign('category_id', $name . '_category_foreign')->references('id')->on($categories)->nullOnDelete(); - }); - } - /** * One store's values. The identity columns are binary-collated, so `Theme` and `theme` stay - * two rows on MySQL as they do elsewhere. + * two rows on MySQL as they do elsewhere. A dedicated store keeps an `owner_id` foreign key to + * its owner table instead of the polymorphic `settable_type` and `settable_id`. + * + * @param array{table: string, connection: ?string, owner: ?array{table: string, key: string, type: string}} $store */ - private function createValues(string $connection, SchemaShape $shape, StoreSchema $store): void - { - $name = $shape->names->store($store->name, $store->table); - $index = substr($name, 0, 40); - $binary = $this->binaryCollation($connection); - - Schema::connection($connection)->create($name, function (Blueprint $table) use ($binary, $index, $shape, $store): void { - $this->key($table, 'id', $shape->ids, primary: true); - - if ($shape->tenancy === TenancyMode::Column) { - $this->collate($table->string('tenant', 64)->default(''), $binary); - } - - if ($store->isDedicated()) { - $this->key($table, 'owner_id', $store->ownerKeyType); - } else { - $table->string('settable_type', 64)->nullable(); - $shape->ownerKey === OwnerKeyType::Typed - ? $this->key($table, 'settable_id', $shape->ownerKeyType)->nullable() - : $table->string('settable_id', 36)->nullable(); - } - - $this->collate($table->string('scope', 128), $binary); - $this->key($table, 'category_id', $shape->ids)->nullable(); - $table->string('category_store', 64)->nullable(); - $table->string('group', 64); - $this->collate($table->string('key', 191), $binary); - - if ($shape->identity->hasSlug()) { - $this->collate($table->string('slug', $shape->identity === IdentityMode::SlugPerRow ? 40 : 191)->nullable(), $binary); - } - - if ($shape->identity->hasUid()) { - $table->char('uid', 26)->nullable(); - } - - $this->collate($table->string('locale', 16)->default(''), $binary); - $table->longText('value')->nullable(); - $table->string('type', 64)->nullable(); - $this->translatable($table, 'label', $shape); - $this->translatable($table, 'description', $shape); - $table->boolean('is_encrypted')->default(false); - $table->boolean('is_locked')->default(false); - $table->boolean('is_public')->default(false); - $table->boolean('autoload')->default(true); - $table->unsignedInteger('sort_order')->default(0); - $table->json('meta')->nullable(); - $table->unsignedInteger('version')->default(1); - $table->timestamps(); - - if ($store->softDeletes) { - $table->timestamp('deleted_at')->nullable(); - } - - $this->indexValues($table, $index, $shape, $store); - }); - } - - private function indexValues(Blueprint $table, string $index, SchemaShape $shape, StoreSchema $store): void + private function valuesTable(Blueprint $table, array $store, SchemaNames $names, bool $tenant, ?string $binary): void { - $tenant = $this->tenantColumns($shape); + $index = substr($store['table'], 0, 40); + $owner = $store['owner']; - $table->unique([...$tenant, 'scope', 'key', 'locale'], $index . '_identity_unique'); + $table->ulid('id')->primary(); - if ($shape->identity->hasUid()) { - $table->unique('uid', $index . '_uid_unique'); + if ($tenant) { + $this->collate($table->string('tenant', 64)->default(''), $binary); } - match ($shape->identity) { - IdentityMode::SlugPerRow => $table->unique([...$tenant, 'slug'], $index . '_slug_unique'), - IdentityMode::SlugUid => $table->index('slug', $index . '_slug_index'), - IdentityMode::UidOnly => null, - }; - - if ($store->isDedicated()) { - $table->index('owner_id', $index . '_owner_index'); - $table->foreign('owner_id', $index . '_owner_foreign') - ->references($store->ownerKey)->on((string) $store->ownerTable)->cascadeOnDelete(); + if ($owner === null) { + $table->string('settable_type', 64)->nullable(); + $table->string('settable_id', 36)->nullable(); } else { + match ($owner['type']) { + 'uuid' => $table->char('owner_id', 36), + 'ulid' => $table->char('owner_id', 26), + default => $table->unsignedBigInteger('owner_id'), + }; + } + + $this->collate($table->string('scope', 128), $binary); + $table->ulid('category_id')->nullable(); + $table->string('category_store', 64)->nullable(); + $table->string('group', 64); + $this->collate($table->string('key', 191), $binary); + $table->ulid('uid'); + $this->collate($table->string('locale', 16)->default(''), $binary); + $table->longText('value')->nullable(); + $table->string('type', 64)->nullable(); + $table->json('label')->nullable(); + $table->json('description')->nullable(); + $table->boolean('is_encrypted')->default(false); + $table->boolean('is_locked')->default(false); + $table->boolean('is_public')->default(false); + $table->boolean('autoload')->default(true); + $table->unsignedInteger('sort_order')->default(0); + $table->json('meta')->nullable(); + $table->unsignedInteger('version')->default(1); + $table->timestamps(); + $table->timestamp('deleted_at')->nullable(); + + $table->unique($this->withTenant(['scope', 'key', 'locale']), $index . '_identity_unique'); + $table->unique('uid', $index . '_uid_unique'); + + if ($owner === null) { $table->index(['settable_type', 'settable_id'], $index . '_settable_index'); + } else { + $table->index('owner_id', $index . '_owner_index'); + $table->foreign('owner_id', $index . '_owner_foreign')->references($owner['key'])->on($owner['table'])->cascadeOnDelete(); } $table->index('category_id', $index . '_category_index'); $table->index(['autoload', 'scope'], $index . '_autoload_index'); $table->foreign(['category_id', 'category_store'], $index . '_category_foreign') - ->references(['id', 'store'])->on($shape->names->categories())->nullOnDelete(); - } - - /** Who did what, when and through which channel. There is no value column. */ - private function createAudit(string $connection, SchemaShape $shape): void - { - $name = $shape->names->audit(); - - Schema::connection($connection)->create($name, function (Blueprint $table) use ($name, $shape): void { - $table->char('id', 26)->primary(); - $this->tenant($table, $shape); - $table->timestamp('occurred_at'); - $table->string('action', 32); - $table->string('outcome', 16); - $table->string('store', 64)->nullable(); - $table->string('scope', 128)->nullable(); - $table->string('key', 191)->nullable(); - $table->string('locale', 16)->nullable(); - $table->unsignedInteger('version_from')->nullable(); - $table->unsignedInteger('version_to')->nullable(); - $table->char('change_request', 26)->nullable(); - $table->string('actor_type', 16); - $table->string('actor_alias', 64)->nullable(); - $table->string('actor_id', 64)->nullable(); - $table->string('channel', 16); - $table->string('ip', 45)->nullable(); - $table->string('user_agent')->nullable(); - $table->string('request_id')->nullable(); - $table->text('reason')->nullable(); - $table->json('meta')->nullable(); - - $table->index('occurred_at', $name . '_occurred_index'); - $table->index([...$this->tenantColumns($shape), 'store', 'scope', 'key'], $name . '_subject_index'); - $table->index(['actor_alias', 'actor_id'], $name . '_actor_index'); - }); + ->references(['id', 'store'])->on($names->categories())->nullOnDelete(); } /** - * One row per version of a setting, with the payload before and after exactly as the values - * table stores it. `setting_ref` is a string so the table never depends on `ids.type`. + * What to create on each connection, the default store's connection first. + * + * @return array}> */ - private function createHistory(string $connection, SchemaShape $shape): void + private function plan(): array { - $name = $shape->names->history(); - $binary = $this->binaryCollation($connection); + if ($this->only !== null) { + $store = $this->store(new StoreName($this->only)); + $connection = $this->pinnedConnection ?? $this->connectionName($store['connection']); - Schema::connection($connection)->create($name, function (Blueprint $table) use ($binary, $name, $shape): void { - $table->char('id', 26)->primary(); + return [$connection => ['shared' => $this->pinnedConnection !== null, 'definitions' => false, 'stores' => [$store]]]; + } - if ($shape->tenancy === TenancyMode::Column) { - $this->collate($table->string('tenant', 64)->default(''), $binary); - } + $main = $this->connectionName($this->store($this->primaryStore())['connection']); + $plan = [$main => ['shared' => true, 'definitions' => true, 'stores' => []]]; - $table->string('store', 64); - $table->string('setting_ref', 36)->nullable(); - $this->collate($table->string('scope', 128), $binary); - $this->collate($table->string('key', 191), $binary); - $this->collate($table->string('locale', 16)->default(''), $binary); - $table->string('operation', 16); - $table->longText('old_value')->nullable(); - $table->longText('new_value')->nullable(); - $table->string('old_type', 64)->nullable(); - $table->string('new_type', 64)->nullable(); - $table->boolean('old_encrypted')->default(false); - $table->boolean('new_encrypted')->default(false); - $table->unsignedInteger('version'); - $table->string('causer_type', 16); - $table->string('causer_alias', 64)->nullable(); - $table->string('causer_id', 64)->nullable(); - $table->text('reason')->nullable(); - $table->timestamp('created_at'); - - $table->index([...$this->tenantColumns($shape), 'store', 'scope', 'key', 'locale', 'version'], $name . '_subject_index'); - $table->index('created_at', $name . '_created_index'); - }); + foreach ($this->databaseStores() as $name) { + $store = $this->store(new StoreName($name)); + $connection = $this->connectionName($store['connection']); + $plan[$connection] ??= ['shared' => true, 'definitions' => false, 'stores' => []]; + $plan[$connection]['stores'][] = $store; + } + + return $plan; } - /** - * Writes waiting for approval. `payload` is stored as the values table would store it, and - * `base_version` lets a request whose setting has since changed become `stale`. - */ - private function createChangeRequests(string $connection, SchemaShape $shape): void + /** @return list the configured stores with a database layer */ + private function databaseStores(): array { - $name = $shape->names->changeRequests(); - $binary = $this->binaryCollation($connection); - - Schema::connection($connection)->create($name, function (Blueprint $table) use ($binary, $name, $shape): void { - $table->char('id', 26)->primary(); + $stores = []; - if ($shape->tenancy === TenancyMode::Column) { - $this->collate($table->string('tenant', 64)->default(''), $binary); + foreach ((array) config('laranail.settings.stores', []) as $name => $store) { + if (is_array($store) && $this->databaseLayer($store) !== null) { + $stores[] = (string) $name; } + } - $table->string('store', 64); - $this->collate($table->string('scope', 128), $binary); - $this->collate($table->string('key', 191), $binary); - $this->collate($table->string('locale', 16)->default(''), $binary); - $table->string('operation', 16); - $table->longText('payload')->nullable(); - $table->string('type', 64)->nullable(); - $table->boolean('is_encrypted')->default(false); - $table->unsignedInteger('base_version')->default(0); - $table->string('status', 16); - $table->string('requested_by_type', 16); - $table->string('requested_by_alias', 64)->nullable(); - $table->string('requested_by_id', 64)->nullable(); - $table->json('approvals')->nullable(); - $table->string('decided_by_type', 16)->nullable(); - $table->string('decided_by_alias', 64)->nullable(); - $table->string('decided_by_id', 64)->nullable(); - $table->timestamp('decided_at')->nullable(); - $table->text('reason')->nullable(); - $table->text('decision_reason')->nullable(); - $table->timestamp('expires_at')->nullable(); - $table->timestamps(); - - $table->index([...$this->tenantColumns($shape), 'status', 'store'], $name . '_status_index'); - $table->index([...$this->tenantColumns($shape), 'store', 'scope', 'key', 'locale'], $name . '_subject_index'); - $table->index('expires_at', $name . '_expires_index'); - }); + return $stores; } - /** Store and layer entries edited through the API; `config` holds the entry as JSON. */ - private function createStores(string $connection, SchemaShape $shape): void + /** + * A store's table, connection and, for a dedicated store, its owner table. + * + * @return array{table: string, connection: ?string, owner: ?array{table: string, key: string, type: string}} + */ + private function store(StoreName $name): array { - $name = $shape->names->stores(); - - Schema::connection($connection)->create($name, function (Blueprint $table) use ($name): void { - $table->char('id', 26)->primary(); - $table->string('kind', 16); - $table->string('name', 64); - $table->json('config'); - $table->timestamps(); + $store = config('laranail.settings.stores.' . $name->value); + $store = is_array($store) ? $store : []; + $table = $store['table'] ?? null; + $layer = $this->databaseLayer($store); + $connection = $this->pinnedConnection ?? ($layer['connection'] ?? null); + $owner = null; + + if (($store['mode'] ?? 'polymorphic') === 'dedicated' && is_array($store['owner'] ?? null) && is_string($store['owner']['table'] ?? null)) { + $type = $store['owner']['type'] ?? config('laranail.db-tools.id_type') ?? 'bigint'; + + $owner = [ + 'table' => $store['owner']['table'], + 'key' => is_string($store['owner']['key'] ?? null) ? $store['owner']['key'] : 'id', + 'type' => is_string($type) ? strtolower($type) : 'bigint', + ]; + } - $table->unique(['kind', 'name'], $name . '_kind_name_unique'); - }); + return [ + 'table' => $this->names()->store($name, is_string($table) ? $table : null), + 'connection' => is_string($connection) ? $connection : null, + 'owner' => $owner, + ]; } /** - * What to create on each connection, the default store's connection first. + * The store's first database layer, or null. + * + * @param array $store * - * @return array}> + * @return array|null */ - private function plan(): array + private function databaseLayer(array $store): ?array { - $shape = $this->shape(); - $main = $this->connectionOf($shape->store($this->primaryStore())); - - if ($this->only !== null) { - $store = $shape->store(new StoreName($this->only)); - $connection = $this->pinnedConnection ?? $this->connectionOf($store); - - return [$connection => ['shared' => $this->pinnedConnection !== null, 'definitions' => false, 'stores' => [$store]]]; - } - - $plan = [$main => ['shared' => true, 'definitions' => $shape->definitionsTable, 'stores' => []]]; + foreach ((array) ($store['layers'] ?? []) as $layer) { + $config = is_string($layer) ? config('laranail.settings.layers.' . $layer) : null; - foreach ($shape->stores as $store) { - $connection = $this->connectionOf($store); - $plan[$connection] ??= ['shared' => true, 'definitions' => false, 'stores' => []]; - $plan[$connection]['stores'][] = $store; + if (is_array($config) && ($config['driver'] ?? null) === 'database') { + return $config; + } } - return $plan; + return null; } /** @@ -450,41 +442,6 @@ private function missing(string $connection, string $table): bool return $this->only === null || ! Schema::connection($connection)->hasTable($table); } - /** - * A key column typed per `ids.type`. The primary key is an explicit command rather than the - * fluent ->primary(), so PostgreSQL sees it before a self-referencing foreign key. - */ - private function key(Blueprint $table, string $column, IdType $type, bool $primary = false): ColumnDefinition - { - if ($primary && $type === IdType::Bigint) { - return $table->bigIncrements($column); - } - - $definition = match ($type) { - IdType::Bigint => $table->unsignedBigInteger($column), - IdType::Uuid => $table->char($column, 36), - IdType::Ulid => $table->char($column, 26), - }; - - if ($primary) { - $table->primary($column); - } - - return $definition; - } - - /** A title, label or description: text, or a JSON map of locale to text. */ - private function translatable(Blueprint $table, string $column, SchemaShape $shape, bool $nullable = true): void - { - $definition = $shape->translations === TranslationsMode::Json - ? $table->json($column) - : ($column === 'title' ? $table->string($column) : $table->text($column)); - - if ($nullable) { - $definition->nullable(); - } - } - private function collate(ColumnDefinition $column, ?string $binary): ColumnDefinition { return $binary === null ? $column : $column->collation($binary); @@ -500,18 +457,28 @@ private function binaryCollation(string $connection): ?string }; } - /** The tenant column of column-mode tenancy: '' is the central partition. */ - private function tenant(Blueprint $table, SchemaShape $shape): void + /** + * Index columns, led by `tenant` in column-mode tenancy. + * + * @param list $columns + * + * @return list + */ + private function withTenant(array $columns): array { - if ($shape->tenancy === TenancyMode::Column) { - $table->string('tenant', 64)->default(''); - } + return $this->tenantColumn() ? ['tenant', ...$columns] : $columns; } - /** @return list */ - private function tenantColumns(SchemaShape $shape): array + private function tenantColumn(): bool { - return $shape->tenancy === TenancyMode::Column ? ['tenant'] : []; + return config('laranail.settings.tenancy.mode', 'none') === 'column'; + } + + private function names(): SchemaNames + { + $tables = config('laranail.settings.tables', []); + + return SchemaNames::fromConfig(is_array($tables) ? $tables : []); } private function primaryStore(): StoreName @@ -525,13 +492,8 @@ private function primaryStore(): StoreName return new StoreName(is_string($default) ? $default : 'settings'); } - private function connectionOf(StoreSchema $store): string - { - return $store->connection ?? DB::getDefaultConnection(); - } - - private function shape(): SchemaShape + private function connectionName(?string $connection): string { - return app(SchemaShapeRepository::class)->current(); + return $connection ?? DB::getDefaultConnection(); } }; diff --git a/src/Actions/Approvals/ApproveChange.php b/src/Actions/Approvals/ApproveChange.php index a908c10..ce380ff 100644 --- a/src/Actions/Approvals/ApproveChange.php +++ b/src/Actions/Approvals/ApproveChange.php @@ -14,6 +14,7 @@ use Simtabi\Laranail\Settings\Data\Subject; use Simtabi\Laranail\Settings\Stores\Store; use Simtabi\Laranail\Settings\Enums\Ability; +use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Data\Definition; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Data\ChangeRequest; @@ -25,14 +26,15 @@ use Simtabi\Laranail\Settings\Events\ChangeApplied; use Simtabi\Laranail\Settings\Enums\ChangeOperation; use Simtabi\Laranail\Settings\Events\ChangeApproved; +use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Exceptions\AccessDenied; +use Simtabi\Laranail\Settings\Models\SettingChangeRequest; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Services\Stores\SettingWriter; use Simtabi\Laranail\Settings\Services\Values\ValuePipeline; use Simtabi\Laranail\Settings\Exceptions\ChangeRequestClosed; use Simtabi\Laranail\Settings\Services\Definitions\Definitions; use Simtabi\Laranail\Settings\Exceptions\ConcurrentModification; -use Simtabi\Laranail\Settings\Services\Database\ChangeRequestRepository; /** * Approve a change request; needs `approve` on its setting. With enough approvals the change is @@ -57,15 +59,15 @@ public function __construct( public function handle(ChangeDecision $decision, ?Actor $actor = null): ChangeRequest { $store = $decision->store; - $repository = ChangeRequestRepository::of($store); - $request = $repository->get($store->name, $decision->id); + $database = $store->changeRequestsDatabase(); + $request = $database->attempt($store->name, static fn (): ChangeRequest => SettingChangeRequest::get($database->connectionName(), $store->name, $decision->id)); $key = new Key($request->key); $definition = $this->definitions->find($store, $key); $subject = Subject::of($store->name, $key, new Locale($request->locale), $request->owner(), $definition); $now = CarbonImmutable::now(); $this->access->authorize($actor, Ability::Approve, $subject); - $this->assertOpen($repository, $request, $now); + $this->assertOpen($database, $request, $now); if ($actor instanceof Actor && ! $this->policy->allowSelf && $request->isRequestedBy($actor)) { $this->access->auditor()->record(AuditAction::Approve, AuditOutcome::Denied, $subject, $actor, $decision->reason, meta: ['change_request' => $request->id, 'refusal' => 'self_approval']); @@ -77,12 +79,12 @@ public function handle(ChangeDecision $decision, ?Actor $actor = null): ChangeRe $remaining = max(0, $this->policy->minApprovals - count($approvals)); if ($remaining > 0) { - return $this->record($repository, $request, $subject, $actor, $decision->reason, $approvals, $remaining, $now); + return $this->record($database, $request, $subject, $actor, $decision->reason, $approvals, $remaining, $now); } try { - $version = $store->transaction(function () use ($repository, $request, $store, $key, $definition, $subject, $actor, $decision, $approvals, $now): int { - if (! $repository->transition($request, [ChangeStatus::Pending, ChangeStatus::Approved], ChangeStatus::Applied, $actor ?? Actor::system(), $decision->reason, $now, $approvals)) { + $version = $store->transaction(function () use ($database, $request, $store, $key, $definition, $subject, $actor, $decision, $approvals, $now): int { + if (! $database->attempt(new StoreName($request->store), static fn (): bool => SettingChangeRequest::transition($database->connectionName(), $request, [ChangeStatus::Pending, ChangeStatus::Approved], ChangeStatus::Applied, $actor ?? Actor::system(), $decision->reason, $now, $approvals))) { throw new ChangeRequestClosed(sprintf('Change request [%s] was decided by somebody else first.', $request->id)); } @@ -97,36 +99,36 @@ public function handle(ChangeDecision $decision, ?Actor $actor = null): ChangeRe }); } catch (ConcurrentModification) { // The setting moved on since the request was opened: never overwrite it. - $repository->transition($request, [ChangeStatus::Pending, ChangeStatus::Approved], ChangeStatus::Stale, $actor ?? Actor::system(), $decision->reason, $now, $approvals); + $database->attempt(new StoreName($request->store), static fn (): bool => SettingChangeRequest::transition($database->connectionName(), $request, [ChangeStatus::Pending, ChangeStatus::Approved], ChangeStatus::Stale, $actor ?? Actor::system(), $decision->reason, $now, $approvals)); $this->access->auditor()->record(AuditAction::Approve, AuditOutcome::Failed, $subject, $actor, $decision->reason, meta: ['change_request' => $request->id, 'refusal' => 'stale']); $this->events->dispatch(new ChangeStale($request->id, $request->store, $request->scope, $request->key, $request->locale, $request->operation->value)); - return $repository->get($store->name, $request->id); + return $database->attempt($store->name, static fn (): ChangeRequest => SettingChangeRequest::get($database->connectionName(), $store->name, $request->id)); } $this->events->dispatch(new ChangeApproved($request->id, $request->store, $request->scope, $request->key, $request->locale, $request->operation->value)); $this->events->dispatch(new ChangeApplied($request->id, $request->store, $request->scope, $request->key, $request->locale, $request->operation->value, $version)); - return $repository->get($store->name, $request->id); + return $database->attempt($store->name, static fn (): ChangeRequest => SettingChangeRequest::get($database->connectionName(), $store->name, $request->id)); } /** @param list $approvals */ - private function record(ChangeRequestRepository $repository, ChangeRequest $request, Subject $subject, ?Actor $actor, ?string $reason, array $approvals, int $remaining, CarbonImmutable $now): ChangeRequest + private function record(DatabaseDriver $database, ChangeRequest $request, Subject $subject, ?Actor $actor, ?string $reason, array $approvals, int $remaining, CarbonImmutable $now): ChangeRequest { - if (! $repository->transition($request, [ChangeStatus::Pending, ChangeStatus::Approved], ChangeStatus::Approved, null, null, $now, $approvals)) { + if (! $database->attempt(new StoreName($request->store), static fn (): bool => SettingChangeRequest::transition($database->connectionName(), $request, [ChangeStatus::Pending, ChangeStatus::Approved], ChangeStatus::Approved, null, null, $now, $approvals))) { throw new ChangeRequestClosed(sprintf('Change request [%s] was decided by somebody else first.', $request->id)); } $this->access->auditor()->record(AuditAction::Approve, AuditOutcome::Pending, $subject, $actor, $reason, meta: ['change_request' => $request->id, 'remaining' => $remaining]); $this->events->dispatch(new ChangeApproved($request->id, $request->store, $request->scope, $request->key, $request->locale, $request->operation->value, $remaining)); - return $repository->get($subject->store, $request->id); + return $database->attempt($subject->store, static fn (): ChangeRequest => SettingChangeRequest::get($database->connectionName(), $subject->store, $request->id)); } - private function assertOpen(ChangeRequestRepository $repository, ChangeRequest $request, CarbonImmutable $now): void + private function assertOpen(DatabaseDriver $database, ChangeRequest $request, CarbonImmutable $now): void { if ($request->status->isOpen() && $request->isExpired($now)) { - $repository->transition($request, [ChangeStatus::Pending, ChangeStatus::Approved], ChangeStatus::Expired, null, null, $now); + $database->attempt(new StoreName($request->store), static fn (): bool => SettingChangeRequest::transition($database->connectionName(), $request, [ChangeStatus::Pending, ChangeStatus::Approved], ChangeStatus::Expired, null, null, $now)); throw new ChangeRequestClosed(sprintf('Change request [%s] expired at %s.', $request->id, $request->expiresAt?->toIso8601String())); } diff --git a/src/Actions/Approvals/CancelChange.php b/src/Actions/Approvals/CancelChange.php index 940fe33..e3643fb 100644 --- a/src/Actions/Approvals/CancelChange.php +++ b/src/Actions/Approvals/CancelChange.php @@ -11,6 +11,7 @@ use Illuminate\Contracts\Events\Dispatcher; use Simtabi\Laranail\Settings\Data\Subject; use Simtabi\Laranail\Settings\Enums\Ability; +use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Data\ChangeRequest; use Simtabi\Laranail\Settings\Enums\AuditOutcome; @@ -18,9 +19,9 @@ use Simtabi\Laranail\Settings\Data\ChangeDecision; use Simtabi\Laranail\Settings\Events\ChangeCancelled; use Simtabi\Laranail\Settings\Exceptions\AccessDenied; +use Simtabi\Laranail\Settings\Models\SettingChangeRequest; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Exceptions\ChangeRequestClosed; -use Simtabi\Laranail\Settings\Services\Database\ChangeRequestRepository; /** Withdraw a change request; only its requester or trusted code may. */ final readonly class CancelChange @@ -37,8 +38,8 @@ public function __construct( public function handle(ChangeDecision $decision, ?Actor $actor = null): ChangeRequest { $store = $decision->store; - $repository = ChangeRequestRepository::of($store); - $request = $repository->get($store->name, $decision->id); + $database = $store->changeRequestsDatabase(); + $request = $database->attempt($store->name, static fn (): ChangeRequest => SettingChangeRequest::get($database->connectionName(), $store->name, $decision->id)); $subject = new Subject($store->name, new Key($request->key), $request->owner(), new Locale($request->locale)); if ($actor instanceof Actor && ! $actor->isSystem() && ! $request->isRequestedBy($actor)) { @@ -51,8 +52,8 @@ public function handle(ChangeDecision $decision, ?Actor $actor = null): ChangeRe $this->access->assertActorNotRequired(Ability::Update, $subject); } - $store->transaction(function () use ($repository, $request, $actor, $decision, $subject): void { - if (! $repository->transition($request, [ChangeStatus::Pending, ChangeStatus::Approved], ChangeStatus::Cancelled, $actor ?? Actor::system(), $decision->reason, CarbonImmutable::now())) { + $store->transaction(function () use ($database, $request, $actor, $decision, $subject): void { + if (! $database->attempt(new StoreName($request->store), static fn (): bool => SettingChangeRequest::transition($database->connectionName(), $request, [ChangeStatus::Pending, ChangeStatus::Approved], ChangeStatus::Cancelled, $actor ?? Actor::system(), $decision->reason, CarbonImmutable::now()))) { throw new ChangeRequestClosed(sprintf('Change request [%s] is %s and can no longer be cancelled.', $request->id, $request->status->value)); } @@ -61,6 +62,6 @@ public function handle(ChangeDecision $decision, ?Actor $actor = null): ChangeRe $this->events->dispatch(new ChangeCancelled($request->id, $request->store, $request->scope, $request->key, $request->locale, $request->operation->value)); - return $repository->get($store->name, $request->id); + return $database->attempt($store->name, static fn (): ChangeRequest => SettingChangeRequest::get($database->connectionName(), $store->name, $request->id)); } } diff --git a/src/Actions/Approvals/ProposeChange.php b/src/Actions/Approvals/ProposeChange.php index fb4fdef..434d849 100644 --- a/src/Actions/Approvals/ProposeChange.php +++ b/src/Actions/Approvals/ProposeChange.php @@ -18,11 +18,11 @@ use Simtabi\Laranail\Settings\Events\ChangeRequested; use Simtabi\Laranail\Settings\Exceptions\UnknownSetting; use Simtabi\Laranail\Settings\Exceptions\OwnerNotAllowed; +use Simtabi\Laranail\Settings\Models\SettingChangeRequest; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Services\Values\ValuePipeline; use Simtabi\Laranail\Settings\Exceptions\ApprovalUnavailable; use Simtabi\Laranail\Settings\Exceptions\InvalidSettingValue; -use Simtabi\Laranail\Settings\Services\Database\ChangeRequestRepository; /** * Open a change request; needs the ability of the write it proposes. The value is validated and @@ -48,7 +48,7 @@ public function handle(ChangeProposal $proposal, ?Actor $actor = null): ChangeRe $subject = $target->subject(); $this->access->authorize($actor, $proposal->operation->ability(), $subject); - $repository = ChangeRequestRepository::of($store); + $database = $store->changeRequestsDatabase(); if (! $target->definition instanceof Definition && $store->strict) { throw new UnknownSetting(sprintf('Store [%s] is strict and has no definition for [%s].', $store->name, $target->key)); @@ -64,8 +64,8 @@ public function handle(ChangeProposal $proposal, ?Actor $actor = null): ChangeRe $now = CarbonImmutable::now(); $requester = $actor ?? Actor::system($target->reason); - $request = $store->transaction(function () use ($repository, $store, $scope, $target, $proposal, $payload, $base, $now, $requester, $subject, $actor): ChangeRequest { - $request = $repository->create([ + $request = $store->transaction(function () use ($database, $store, $scope, $target, $proposal, $payload, $base, $now, $requester, $subject, $actor): ChangeRequest { + $request = $database->attempt($store->name, fn (): ChangeRequest => SettingChangeRequest::open($database->connectionName(), [ 'store' => $store->name->value, 'scope' => $scope->value, 'key' => $target->key->value, @@ -77,7 +77,7 @@ public function handle(ChangeProposal $proposal, ?Actor $actor = null): ChangeRe 'base_version' => $base, 'reason' => $target->reason, 'expires_at' => $this->policy->expireAfterDays === null ? null : $now->addDays($this->policy->expireAfterDays), - ], $requester, $now); + ], $requester, $now)); $this->access->auditor()->record(AuditAction::Propose, AuditOutcome::Pending, $subject, $actor, $target->reason, versionFrom: $base > 0 ? $base : null, meta: [ 'change_request' => $request->id, diff --git a/src/Actions/Approvals/PruneChanges.php b/src/Actions/Approvals/PruneChanges.php index 0c99bd7..f01105a 100644 --- a/src/Actions/Approvals/PruneChanges.php +++ b/src/Actions/Approvals/PruneChanges.php @@ -10,11 +10,12 @@ use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Enums\AuditOutcome; +use Simtabi\Laranail\Settings\Enums\ChangeStatus; use Simtabi\Laranail\Settings\Data\ApprovalPolicy; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; +use Simtabi\Laranail\Settings\Models\SettingChangeRequest; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; -use Simtabi\Laranail\Settings\Services\Database\ChangeRequestRepository; /** * Expire overdue open change requests and delete decided ones older than `approvals.keep_days`, @@ -42,14 +43,26 @@ public function handle(?Actor $actor = null): array foreach ($this->stores->all() as $store) { $database = $store->database(); - if (! $database instanceof DatabaseDriver || ! $database->shape()->changeRequestsTable || isset($seen[$database->connectionName()])) { + if (! $database instanceof DatabaseDriver || isset($seen[$database->connectionName()])) { continue; } $seen[$database->connectionName()] = true; - [$expired, $deleted] = new ChangeRequestRepository($database)->sweep($now, $cutoff, $store->name); - $totals['expired'] += $expired; - $totals['deleted'] += $deleted; + $connection = $database->connectionName(); + + // Every tenant's requests: expire the overdue ones, then delete decided ones past the cutoff. + $totals['expired'] += $database->attempt($store->name, static fn (): int => SettingChangeRequest::on($connection) + ->allTenants() + ->overdue($now) + ->update(['status' => ChangeStatus::Expired->value, 'updated_at' => $now])); + + if ($cutoff instanceof CarbonImmutable) { + $totals['deleted'] += $database->attempt($store->name, static fn (): int => SettingChangeRequest::on($connection) + ->allTenants() + ->whereNotIn('status', [ChangeStatus::Pending->value, ChangeStatus::Approved->value]) + ->where('updated_at', '<', $cutoff) + ->toBase()->delete()); + } } $this->access->auditor()->record(AuditAction::Prune, AuditOutcome::Allowed, $subject, $actor, meta: ['target' => 'change_requests'] + $totals); diff --git a/src/Actions/Approvals/QueryChanges.php b/src/Actions/Approvals/QueryChanges.php index 97f5f02..6707ffb 100644 --- a/src/Actions/Approvals/QueryChanges.php +++ b/src/Actions/Approvals/QueryChanges.php @@ -4,14 +4,15 @@ namespace Simtabi\Laranail\Settings\Actions\Approvals; +use Illuminate\Database\Eloquent\Builder; use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Data\Subject; use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Data\ChangeFilter; use Simtabi\Laranail\Settings\Data\ChangeRequest; +use Simtabi\Laranail\Settings\Models\SettingChangeRequest; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; -use Simtabi\Laranail\Settings\Services\Database\ChangeRequestRepository; /** * List a store's change requests, newest first. An actor without `approve` sees only their own. @@ -33,7 +34,16 @@ public function handle(ChangeFilter $filter, ?Actor $actor = null, int $limit = $this->access->assertActorNotRequired(Ability::Approve, $subject); } - $requests = ChangeRequestRepository::of($store)->list($filter, $limit, $after); + $database = $store->changeRequestsDatabase(); + $requests = $database->attempt($store->name, static fn (): array => SettingChangeRequest::on($database->connectionName()) + ->matching($filter) + ->when($after !== null, static fn (Builder $query): Builder => $query->where('id', '<', $after)) + ->limit($limit) + ->get() + ->map(static fn (SettingChangeRequest $request): ChangeRequest => $request->toRequest()) + ->values() + ->all()); + $requests = array_values($requests); if (! $actor instanceof Actor || $actor->isSystem() || $this->access->allows($actor, Ability::Approve, $subject)) { return $requests; diff --git a/src/Actions/Approvals/RejectChange.php b/src/Actions/Approvals/RejectChange.php index 7a05d3c..2d23b32 100644 --- a/src/Actions/Approvals/RejectChange.php +++ b/src/Actions/Approvals/RejectChange.php @@ -11,16 +11,17 @@ use Illuminate\Contracts\Events\Dispatcher; use Simtabi\Laranail\Settings\Data\Subject; use Simtabi\Laranail\Settings\Enums\Ability; +use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Data\ChangeRequest; use Simtabi\Laranail\Settings\Enums\AuditOutcome; use Simtabi\Laranail\Settings\Enums\ChangeStatus; use Simtabi\Laranail\Settings\Data\ChangeDecision; use Simtabi\Laranail\Settings\Events\ChangeRejected; +use Simtabi\Laranail\Settings\Models\SettingChangeRequest; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Exceptions\ChangeRequestClosed; use Simtabi\Laranail\Settings\Services\Definitions\Definitions; -use Simtabi\Laranail\Settings\Services\Database\ChangeRequestRepository; /** Reject a change request; needs `approve` on its setting. */ final readonly class RejectChange @@ -35,15 +36,15 @@ public function __construct( public function handle(ChangeDecision $decision, ?Actor $actor = null): ChangeRequest { $store = $decision->store; - $repository = ChangeRequestRepository::of($store); - $request = $repository->get($store->name, $decision->id); + $database = $store->changeRequestsDatabase(); + $request = $database->attempt($store->name, static fn (): ChangeRequest => SettingChangeRequest::get($database->connectionName(), $store->name, $decision->id)); $key = new Key($request->key); $subject = Subject::of($store->name, $key, new Locale($request->locale), $request->owner(), $this->definitions->find($store, $key)); $this->access->authorize($actor, Ability::Approve, $subject); - $store->transaction(function () use ($repository, $request, $actor, $decision, $subject): void { - if (! $repository->transition($request, [ChangeStatus::Pending, ChangeStatus::Approved], ChangeStatus::Rejected, $actor ?? Actor::system(), $decision->reason, CarbonImmutable::now())) { + $store->transaction(function () use ($database, $request, $actor, $decision, $subject): void { + if (! $database->attempt(new StoreName($request->store), static fn (): bool => SettingChangeRequest::transition($database->connectionName(), $request, [ChangeStatus::Pending, ChangeStatus::Approved], ChangeStatus::Rejected, $actor ?? Actor::system(), $decision->reason, CarbonImmutable::now()))) { throw new ChangeRequestClosed(sprintf('Change request [%s] is %s and can no longer be decided.', $request->id, $request->status->value)); } @@ -52,6 +53,6 @@ public function handle(ChangeDecision $decision, ?Actor $actor = null): ChangeRe $this->events->dispatch(new ChangeRejected($request->id, $request->store, $request->scope, $request->key, $request->locale, $request->operation->value)); - return $repository->get($store->name, $request->id); + return $database->attempt($store->name, static fn (): ChangeRequest => SettingChangeRequest::get($database->connectionName(), $store->name, $request->id)); } } diff --git a/src/Actions/Categories/CategoryGuard.php b/src/Actions/Categories/CategoryGuard.php index 24949d1..a90de81 100644 --- a/src/Actions/Categories/CategoryGuard.php +++ b/src/Actions/Categories/CategoryGuard.php @@ -15,7 +15,6 @@ use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Support\AuditedTransaction; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; -use Simtabi\Laranail\Settings\Services\Database\CategoryRepository; /** * Authorizes `manage_categories` and runs a category change, its events and its audit entry in @@ -31,7 +30,7 @@ public function __construct( /** * @template T * - * @param Closure(CategoryRepository, DatabaseDriver): T $work + * @param Closure(DatabaseDriver): T $work * @param list $also more events dispatched after `$after` * * @return T @@ -53,7 +52,7 @@ public function run(Store $store, CategorySlug $slug, ?Actor $actor, string $ope function () use ($store, $database, $work, $before): mixed { $this->events->dispatch($before); - return $work(new CategoryRepository($database, $store->name), $database); + return $database->attempt($store->name, static fn (): mixed => $work($database)); }, then: function () use ($after, $also): void { $this->events->dispatch($after); diff --git a/src/Actions/Categories/CreateCategory.php b/src/Actions/Categories/CreateCategory.php index 0380a69..6ceb87c 100644 --- a/src/Actions/Categories/CreateCategory.php +++ b/src/Actions/Categories/CreateCategory.php @@ -8,9 +8,12 @@ use Simtabi\Laranail\Settings\Stores\Store; use Simtabi\Laranail\Settings\Data\Category; use Simtabi\Laranail\Settings\Data\NewCategory; +use Simtabi\Laranail\Settings\Data\CategorySlug; use Simtabi\Laranail\Settings\Events\CategorySaved; +use Simtabi\Laranail\Settings\Support\Translations; use Simtabi\Laranail\Settings\Events\CategorySaving; -use Simtabi\Laranail\Settings\Services\Database\CategoryRepository; +use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; +use Simtabi\Laranail\Settings\Models\SettingCategory; /** Create a category, optionally under a parent in the same store. */ final readonly class CreateCategory @@ -23,6 +26,20 @@ public function handle(Store $store, NewCategory $category, ?Actor $actor = null { $events = [new CategorySaving($store->name->value, $category->slug->value), new CategorySaved($store->name->value, $category->slug->value)]; - return $this->guard->run($store, $category->slug, $actor, 'create', $events[0], $events[1], static fn (CategoryRepository $categories): Category => $categories->create($category)); + return $this->guard->run($store, $category->slug, $actor, 'create', $events[0], $events[1], static function (DatabaseDriver $database) use ($store, $category): Category { + $connection = $database->connectionName(); + $parent = $category->parent instanceof CategorySlug ? SettingCategory::idOf($connection, $store->name, $category->parent) : null; + + return SettingCategory::on($connection)->create([ + 'store' => $store->name->value, + 'slug' => $category->slug->value, + 'parent_id' => $parent, + 'title' => Translations::of($category->title, $category->translations), + 'description' => Translations::ofNullable($category->description), + 'icon' => $category->icon, + 'sort_order' => $category->sortOrder, + 'is_system' => $category->system, + ])->toCategory($category->parent); + }); } } diff --git a/src/Actions/Categories/DeleteCategory.php b/src/Actions/Categories/DeleteCategory.php index 7ec82df..7b9025a 100644 --- a/src/Actions/Categories/DeleteCategory.php +++ b/src/Actions/Categories/DeleteCategory.php @@ -9,8 +9,8 @@ use Simtabi\Laranail\Settings\Data\CategorySlug; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Events\CategoryDeleted; +use Simtabi\Laranail\Settings\Models\SettingCategory; use Simtabi\Laranail\Settings\Events\CategoryDeleting; -use Simtabi\Laranail\Settings\Services\Database\CategoryRepository; /** Delete a category; its children move to the top level and its settings keep their values. */ final readonly class DeleteCategory @@ -24,8 +24,14 @@ public function handle(Store $store, string $slug, ?Actor $actor = null): void $category = new CategorySlug($slug); $events = [new CategoryDeleting($store->name->value, $slug), new CategoryDeleted($store->name->value, $slug)]; - $this->guard->run($store, $category, $actor, 'delete', $events[0], $events[1], static function (CategoryRepository $categories, DatabaseDriver $database) use ($category, $store): void { - $categories->delete($category, $database->tableFor($store->name)); + $this->guard->run($store, $category, $actor, 'delete', $events[0], $events[1], static function (DatabaseDriver $database) use ($category, $store): void { + $connection = $database->connectionName(); + $id = SettingCategory::idOf($connection, $store->name, $category); + + // Unlinked here as well as by the foreign keys, which SQLite may not enforce. + SettingCategory::on($connection)->where('parent_id', $id)->update(['parent_id' => null]); + $database->unlinkCategory($store->name, $id); + SettingCategory::on($connection)->whereKey($id)->delete(); }); } } diff --git a/src/Actions/Categories/ListCategories.php b/src/Actions/Categories/ListCategories.php index db5ee0a..16fc523 100644 --- a/src/Actions/Categories/ListCategories.php +++ b/src/Actions/Categories/ListCategories.php @@ -9,8 +9,8 @@ use Simtabi\Laranail\Settings\Stores\Store; use Simtabi\Laranail\Settings\Data\Category; use Simtabi\Laranail\Settings\Enums\Ability; +use Simtabi\Laranail\Settings\Models\SettingCategory; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; -use Simtabi\Laranail\Settings\Services\Database\CategoryRepository; /** List a store's categories by sort order, then slug. */ final readonly class ListCategories @@ -24,6 +24,8 @@ public function handle(Store $store, ?Actor $actor = null): array { $this->access->authorize($actor, Ability::View, new Subject($store->name)); - return CategoryRepository::of($store)->all(); + $database = $store->requireDatabase('; categories are kept in the database.'); + + return $database->attempt($store->name, static fn (): array => SettingCategory::listFor($database->connectionName(), $store->name)); } } diff --git a/src/Actions/Categories/MoveCategory.php b/src/Actions/Categories/MoveCategory.php index 44610b9..9dd3a8b 100644 --- a/src/Actions/Categories/MoveCategory.php +++ b/src/Actions/Categories/MoveCategory.php @@ -10,7 +10,9 @@ use Simtabi\Laranail\Settings\Events\CategoryMoved; use Simtabi\Laranail\Settings\Events\CategorySaved; use Simtabi\Laranail\Settings\Events\CategorySaving; -use Simtabi\Laranail\Settings\Services\Database\CategoryRepository; +use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; +use Simtabi\Laranail\Settings\Models\SettingCategory; +use Simtabi\Laranail\Settings\Exceptions\CategoryCycle; /** Move a category under another in the same store, or to the top level with a null parent. */ final readonly class MoveCategory @@ -25,8 +27,16 @@ public function handle(Store $store, string $slug, ?string $parent, ?Actor $acto $under = $parent === null ? null : new CategorySlug($parent); $events = [new CategorySaving($store->name->value, $slug), new CategorySaved($store->name->value, $slug)]; - $this->guard->run($store, $category, $actor, 'move', $events[0], $events[1], static function (CategoryRepository $categories) use ($category, $under): void { - $categories->move($category, $under); + $this->guard->run($store, $category, $actor, 'move', $events[0], $events[1], static function (DatabaseDriver $database) use ($store, $category, $under): void { + $connection = $database->connectionName(); + $id = SettingCategory::idOf($connection, $store->name, $category); + $parent = $under instanceof CategorySlug ? SettingCategory::idOf($connection, $store->name, $under) : null; + + if ($parent !== null && in_array($id, [$parent, ...SettingCategory::ancestorsOf($connection, $parent)], true)) { + throw new CategoryCycle(sprintf('Category [%s] in store [%s] cannot move under [%s]: that is itself or one of its descendants.', $category, $store->name, $under)); + } + + SettingCategory::on($connection)->whereKey($id)->update(['parent_id' => $parent]); }, [new CategoryMoved($store->name->value, $slug, $parent)]); } } diff --git a/src/Actions/Categories/RenameCategory.php b/src/Actions/Categories/RenameCategory.php index c8f743c..ec7348e 100644 --- a/src/Actions/Categories/RenameCategory.php +++ b/src/Actions/Categories/RenameCategory.php @@ -8,9 +8,11 @@ use Simtabi\Laranail\Settings\Stores\Store; use Simtabi\Laranail\Settings\Data\NewCategory; use Simtabi\Laranail\Settings\Events\CategorySaved; +use Simtabi\Laranail\Settings\Support\Translations; use Simtabi\Laranail\Settings\Events\CategorySaving; +use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Events\CategoryRenamed; -use Simtabi\Laranail\Settings\Services\Database\CategoryRepository; +use Simtabi\Laranail\Settings\Models\SettingCategory; /** Give a category a new title; its slug stays. */ final readonly class RenameCategory @@ -24,8 +26,12 @@ public function handle(Store $store, string $slug, string $title, ?Actor $actor $input = new NewCategory($slug, $title); $events = [new CategorySaving($store->name->value, $slug), new CategorySaved($store->name->value, $slug)]; - $this->guard->run($store, $input->slug, $actor, 'rename', $events[0], $events[1], static function (CategoryRepository $categories) use ($input): void { - $categories->rename($input->slug, $input->title); + $this->guard->run($store, $input->slug, $actor, 'rename', $events[0], $events[1], static function (DatabaseDriver $database) use ($store, $input): void { + $connection = $database->connectionName(); + $category = SettingCategory::on($connection)->findOrFail(SettingCategory::idOf($connection, $store->name, $input->slug)); + + // The new title replaces the one for any locale; the other locales keep theirs. + $category->update(['title' => Translations::of($input->title, Translations::texts($category->title))]); }, [new CategoryRenamed($store->name->value, $slug)]); } } diff --git a/src/Actions/Configuration/DeleteDefinition.php b/src/Actions/Configuration/DeleteDefinition.php index f06ebe7..5ddaadc 100644 --- a/src/Actions/Configuration/DeleteDefinition.php +++ b/src/Actions/Configuration/DeleteDefinition.php @@ -11,11 +11,10 @@ use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Enums\AuditOutcome; -use Simtabi\Laranail\Settings\Support\ValueEncoder; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; +use Simtabi\Laranail\Settings\Models\SettingDefinition; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; -use Simtabi\Laranail\Settings\Services\Database\DefinitionsRepository; use Simtabi\Laranail\Settings\Services\Definitions\DatabaseDefinitions; /** Delete a definition saved through the API; returns whether one existed. */ @@ -23,7 +22,6 @@ { public function __construct( private DatabaseDefinitions $definitions, - private ValueEncoder $encoder, private AccessGuard $access, ) {} @@ -35,11 +33,15 @@ public function handle(Store $store, string $key, ?Actor $actor = null): bool $database = $store->database(); - if (! $database instanceof DatabaseDriver || ! $database->shape()->definitionsTable) { - throw new InvalidConfiguration(sprintf('Store [%s] has no definitions table.', $store->name)); + if (! $database instanceof DatabaseDriver) { + throw new InvalidConfiguration(sprintf('Store [%s] has no database layer, so it has no definitions table.', $store->name)); } - $deleted = new DefinitionsRepository($database, $this->encoder)->delete($store->name, $settingKey); + $deleted = $database->attempt($store->name, static fn (): int => SettingDefinition::on($database->connectionName()) + ->forStore($store->name) + ->runtime() + ->where('key', $settingKey->value) + ->toBase()->delete()) > 0; $this->definitions->forget($store); $this->access->auditor()->record(AuditAction::ManageDefinitions, AuditOutcome::Allowed, $subject, $actor, meta: ['operation' => 'delete', 'existed' => $deleted]); diff --git a/src/Actions/Configuration/SaveDefinition.php b/src/Actions/Configuration/SaveDefinition.php index c0d433f..400a82a 100644 --- a/src/Actions/Configuration/SaveDefinition.php +++ b/src/Actions/Configuration/SaveDefinition.php @@ -14,10 +14,10 @@ use Simtabi\Laranail\Settings\Enums\AuditOutcome; use Simtabi\Laranail\Settings\Support\ValueEncoder; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; +use Simtabi\Laranail\Settings\Models\SettingDefinition; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Exceptions\InvalidDefinition; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; -use Simtabi\Laranail\Settings\Services\Database\DefinitionsRepository; use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; use Simtabi\Laranail\Settings\Services\Definitions\DatabaseDefinitions; @@ -51,7 +51,7 @@ public function handle(Store $store, string $key, array $attributes, ?Actor $act } $definition = $this->registry->fromAttributes($key, $attributes, $store->name); - $this->repository($store)->save($store->name, $definition); + $this->save($store, $definition); $this->definitions->forget($store); $this->access->auditor()->record(AuditAction::ManageDefinitions, AuditOutcome::Allowed, $subject, $actor, meta: ['operation' => 'save']); @@ -59,15 +59,31 @@ public function handle(Store $store, string $key, array $attributes, ?Actor $act return $definition; } - /** @throws InvalidConfiguration */ - private function repository(Store $store): DefinitionsRepository + /** + * Save the definition as a runtime row. + * + * @throws InvalidConfiguration when the store has no database layer + * @throws InvalidDefinition when a system row already defines the key + */ + private function save(Store $store, Definition $definition): void { $database = $store->database(); - if (! $database instanceof DatabaseDriver || ! $database->shape()->definitionsTable) { - throw new InvalidConfiguration(sprintf('Store [%s] has no definitions table: turn on laranail.settings.definitions.table and migrate.', $store->name)); + if (! $database instanceof DatabaseDriver) { + throw new InvalidConfiguration(sprintf('Store [%s] has no database layer, so it has no definitions table.', $store->name)); } - return new DefinitionsRepository($database, $this->encoder); + $default = $definition->hasDefault ? $this->encoder->encode($definition->key, $definition->default) : null; + + $database->attempt($store->name, static function () use ($database, $store, $definition, $default): void { + $row = SettingDefinition::on($database->connectionName())->forStore($store->name)->where('key', $definition->key->value)->first(); + + if ($row?->is_system === true) { + throw new InvalidDefinition(sprintf('Setting [%s] in store [%s] is defined in code or configuration; change it there.', $definition->key, $store->name)); + } + + $row ??= SettingDefinition::on($database->connectionName())->make(['store' => $store->name->value, 'key' => $definition->key->value, 'is_system' => false]); + $row->fillFromDefinition($definition, $default)->save(); + }); } } diff --git a/src/Actions/DiagnoseSettings.php b/src/Actions/DiagnoseSettings.php index af51863..09b611a 100644 --- a/src/Actions/DiagnoseSettings.php +++ b/src/Actions/DiagnoseSettings.php @@ -6,36 +6,33 @@ use Carbon\CarbonImmutable; use Simtabi\Laranail\Settings\Data\Scope; -use Simtabi\Laranail\Settings\Enums\IdType; use Simtabi\Laranail\Settings\Stores\Store; use Simtabi\Laranail\Settings\Diagnostics\Finding; -use Simtabi\Laranail\Settings\Database\SchemaShape; +use Simtabi\Laranail\Settings\Models\ModelContext; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Contracts\DatabaseBacked; +use Simtabi\Laranail\Settings\Models\SettingChangeRequest; use Simtabi\Laranail\Settings\Exceptions\SettingsException; use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Support\LaravelValueEncrypter; use Simtabi\Laranail\Package\Tools\Services\Doctor\DoctorResult; use Simtabi\Laranail\Settings\Services\Database\SchemaInspector; -use Simtabi\Laranail\Settings\Services\Database\SchemaShapeRepository; use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; -use Simtabi\Laranail\Settings\Services\Database\ChangeRequestRepository; use Simtabi\Laranail\Settings\Services\Configuration\PersistedConfiguration; /** * The findings of `laranail::settings.doctor`. Read-only. * - * Per store with a database layer: readiness, schema drift, scopes that name a class or an alias - * the store does not list, category links to another store, keys outside their category, + * Per store with a database layer: readiness, missing columns, scopes that name a class or an + * alias the store does not list, category links to another store, keys outside their category, * encrypted values no key can read, and overdue change requests. Then: every code or config * definition whose key sits outside its category, and persisted configuration entries skipped as - * invalid. Schema drift compares the schema file with configuration, its shape version with this - * release's, and the live tables with the recorded shape. + * invalid. */ final readonly class DiagnoseSettings { - /** The values-table columns every shape has; the rest depend on the switches. */ - private const array VALUES_COLUMNS = ['id', 'scope', 'category_id', 'category_store', 'group', 'key', 'locale', 'value', 'type', 'label', 'description', 'is_encrypted', 'is_locked', 'is_public', 'autoload', 'sort_order', 'meta', 'version', 'created_at', 'updated_at']; + /** The values-table columns every store has; owner columns depend on the store's mode. */ + private const array VALUES_COLUMNS = ['id', 'uid', 'scope', 'category_id', 'category_store', 'group', 'key', 'locale', 'value', 'type', 'label', 'description', 'is_encrypted', 'is_locked', 'is_public', 'autoload', 'sort_order', 'meta', 'version', 'created_at', 'updated_at', 'deleted_at']; private const array CATEGORY_COLUMNS = ['id', 'store', 'parent_id', 'title', 'slug', 'description', 'icon', 'sort_order', 'is_system', 'meta', 'created_at', 'updated_at']; @@ -51,7 +48,6 @@ public function __construct( private StoreRegistry $stores, - private SchemaShapeRepository $shapes, private LaravelValueEncrypter $encrypter, private PersistedConfiguration $persisted, private DefinitionRegistry $definitions, @@ -60,7 +56,7 @@ public function __construct( /** @return list */ public function handle(): array { - $findings = $this->schemaFile($this->shapes); + $findings = []; foreach ($this->stores->all() as $name => $store) { $database = $this->databaseOf($store); @@ -80,16 +76,13 @@ public function handle(): array } $findings[] = new Finding("{$name}: readiness", 'The database layer answers and its table exists', DoctorResult::pass(sprintf('Table [%s] on [%s] is ready.', $database->tableFor($store->name), $database->connectionName()))); - $findings[] = $this->drift($store, $database); + $findings[] = $this->columns($store, $database); $findings[] = $this->scopes($store, $database); $findings[] = $this->categories($store, $database); $findings[] = $this->categoryKeys($store, $database); $findings[] = $this->encryption($store, $database, $this->encrypter); - - if ($database->shape()->changeRequestsTable) { - $findings[] = $this->changeRequests($store, $database); - } + $findings[] = $this->changeRequests($store, $database); } $findings[] = $this->definitionCategories(); @@ -113,132 +106,37 @@ private function databaseOf(Store $store): ?DatabaseDriver return null; } - /** - * The schema file against the configuration and against this release. - * - * @return list - */ - private function schemaFile(SchemaShapeRepository $shapes): array - { - $name = 'schema file'; - $description = 'The recorded schema matches the configuration and this release'; - - try { - $recorded = $shapes->recorded(); - $configured = $shapes->configured(); - } catch (SettingsException $exception) { - return [new Finding($name, $description, DoctorResult::fail($exception->getMessage()))]; - } - - if (! $recorded instanceof SchemaShape) { - return [new Finding($name, $description, DoctorResult::warn(sprintf('No schema file at [%s]; the shape is read from configuration. Run laranail::settings.install to record it.', $shapes->path())))]; - } - - $findings = []; - - if ($recorded->version < SchemaShape::VERSION) { - $findings[] = new Finding('schema version', 'The schema is at this release\'s shape version', DoctorResult::fail(sprintf('The schema file is at shape version %d; this release needs %d. Publish and run the upgrade migrations, then record the new version.', $recorded->version, SchemaShape::VERSION))); - } - - foreach ($this->stores->all() as $storeName => $store) { - if ($store->hasDatabaseLayer() && ! $recorded->hasStore($store->name)) { - $findings[] = new Finding("{$storeName}: recorded", 'The store is in the schema file', DoctorResult::fail(sprintf('Store [%s] has a database layer but no entry in the schema file: run laranail::settings.make-store %s.', $storeName, $storeName))); - } - } - - $differences = array_values(array_filter( - $configured->differencesFrom($recorded), - static fn (string $line): bool => ! str_starts_with($line, 'stores.') || array_any(array_keys($recorded->stores), static fn (string $store): bool => str_starts_with($line, "stores.{$store}.")), - )); - - $findings[] = new Finding($name, $description, $differences === [] - ? DoctorResult::pass('The configuration matches the recorded schema.') - : DoctorResult::warn('The configuration differs from the recorded schema (the recorded one is in force; a migration is needed to change it): ' . implode('; ', $differences), ['differences' => $differences])); - - return $findings; - } - - private function drift(Store $store, DatabaseDriver $database): Finding + /** Every column the package uses exists on the store's tables. */ + private function columns(Store $store, DatabaseDriver $database): Finding { - $shape = $database->shape(); - $schema = $shape->store($store->name); - $missing = []; - $unexpected = []; - $tenant = $shape->tenancy->hasColumn() ? ['tenant'] : []; + $names = ModelContext::names(); + $tenant = $database->hasTenantColumn() ? ['tenant'] : []; + $owner = $store->isDedicated() ? ['owner_id'] : ['settable_type', 'settable_id']; $expected = [ - $database->tableFor($store->name) => [...self::VALUES_COLUMNS, ...$tenant, ...$this->switchColumns($shape, $schema->isDedicated(), $schema->softDeletes)], - $shape->names->categories() => [...self::CATEGORY_COLUMNS, ...$tenant, ...($shape->categoriesSoftDeletes ? ['deleted_at'] : [])], - $shape->names->audit() => [...self::AUDIT_COLUMNS, ...$tenant], + $database->tableFor($store->name) => [...self::VALUES_COLUMNS, ...$owner, ...$tenant], + $names->categories() => [...self::CATEGORY_COLUMNS, ...$tenant], + $names->audit() => [...self::AUDIT_COLUMNS, ...$tenant], + $names->history() => [...self::HISTORY_COLUMNS, ...$tenant], + $names->changeRequests() => [...self::CHANGE_REQUEST_COLUMNS, ...$tenant], ]; - if ($shape->definitionsTable) { - $expected[$shape->names->definitions()] = self::DEFINITION_COLUMNS; - } - - if ($shape->historyTable) { - $expected[$shape->names->history()] = [...self::HISTORY_COLUMNS, ...$tenant]; - } - - if ($shape->changeRequestsTable) { - $expected[$shape->names->changeRequests()] = [...self::CHANGE_REQUEST_COLUMNS, ...$tenant]; - } - - if ($shape->storesTable && $database->connectionName() === $this->stores->default()->database()?->connectionName()) { - $expected[$shape->names->stores()] = self::STORES_COLUMNS; + if ($database->connectionName() === $this->stores->default()->database()?->connectionName()) { + $expected[$names->definitions()] = self::DEFINITION_COLUMNS; + $expected[$names->stores()] = self::STORES_COLUMNS; } $inspector = new SchemaInspector($database); + $missing = []; foreach ($expected as $table => $columns) { - $present = $inspector->columns($table) ?? []; - - foreach (array_diff($columns, $present) as $column) { + foreach (array_diff($columns, $inspector->columns($table) ?? []) as $column) { $missing[] = $table . '.' . $column; } - - foreach (array_diff(array_intersect($present, ['deleted_at', 'slug', 'uid', 'settable_type', 'settable_id', 'owner_id', 'tenant']), $columns) as $column) { - $unexpected[] = $table . '.' . $column; - } - } - - $idType = $this->idTypeDrift($inspector, $database->tableFor($store->name), $shape->ids); - - if ($missing !== []) { - return new Finding("{$store->name}: schema", 'The tables have every column the recorded schema uses', DoctorResult::fail('Missing columns (publish and run the latest migrations): ' . implode(', ', $missing), ['missing' => $missing])); } - if ($idType !== null) { - return new Finding("{$store->name}: schema", 'The tables have every column the recorded schema uses', DoctorResult::fail($idType)); - } - - return new Finding("{$store->name}: schema", 'The tables have every column the recorded schema uses', $unexpected === [] - ? DoctorResult::pass('No schema drift.') - : DoctorResult::warn('Columns the recorded schema does not have (a switch changed without a migration?): ' . implode(', ', $unexpected), ['unexpected' => $unexpected])); - } - - /** @return list the values-table columns the switches add */ - private function switchColumns(SchemaShape $shape, bool $dedicated, bool $softDeletes): array - { - return [ - ...($dedicated ? ['owner_id'] : ['settable_type', 'settable_id']), - ...($shape->identity->hasSlug() ? ['slug'] : []), - ...($shape->identity->hasUid() ? ['uid'] : []), - ...($softDeletes ? ['deleted_at'] : []), - ]; - } - - /** A message when the table's `id` column is not of the recorded key type, else null. */ - private function idTypeDrift(SchemaInspector $inspector, string $table, IdType $type): ?string - { - $typeName = $inspector->idType($table); - - if ($typeName === null) { - return null; - } - - $integer = str_contains(strtolower($typeName), 'int'); - - return $integer === ($type === IdType::Bigint) ? null : sprintf('Table [%s] has an id of type [%s], but the recorded key type is [%s].', $table, $typeName, $type->value); + return new Finding("{$store->name}: schema", 'The tables have every column the package uses', $missing === [] + ? DoctorResult::pass('Every column is present.') + : DoctorResult::fail('Missing columns (publish and run the latest migrations): ' . implode(', ', $missing), ['missing' => $missing])); } private function scopes(Store $store, DatabaseDriver $database): Finding @@ -306,7 +204,7 @@ private function encryption(Store $store, DatabaseDriver $database, LaravelValue /** Open change requests past their expiry: prune-changes has not run. */ private function changeRequests(Store $store, DatabaseDriver $database): Finding { - $overdue = new ChangeRequestRepository($database)->overdue(CarbonImmutable::now(), $store->name); + $overdue = $database->attempt($store->name, static fn (): int => SettingChangeRequest::on($database->connectionName())->overdue(CarbonImmutable::now())->count()); return new Finding("{$store->name}: change requests", 'No open change request is past its expiry', $overdue === 0 ? DoctorResult::pass('No overdue change requests.') diff --git a/src/Actions/DiffHistory.php b/src/Actions/DiffHistory.php index 6352d46..88fb88b 100644 --- a/src/Actions/DiffHistory.php +++ b/src/Actions/DiffHistory.php @@ -10,11 +10,11 @@ use Simtabi\Laranail\Settings\Data\HistoryDiff; use Simtabi\Laranail\Settings\Data\HistoryEntry; use Simtabi\Laranail\Settings\Data\SettingTarget; +use Simtabi\Laranail\Settings\Models\SettingHistory; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Exceptions\HistoryUnavailable; use Simtabi\Laranail\Settings\Services\Values\ValuePipeline; -use Simtabi\Laranail\Settings\Services\Database\HistoryRepository; /** * Compare one setting at two versions. Sensitive values are decrypted only for an actor with @@ -36,16 +36,14 @@ public function handle(SettingTarget $target, int $from, int $to, ?Actor $actor $store = $target->store; $scope = $subject->scope(); $database = $store->database(); - $history = $database instanceof DatabaseDriver && $database->shape()->historyTable ? new HistoryRepository($database) : null; - - if (! $history instanceof HistoryRepository) { + if (! $database instanceof DatabaseDriver) { throw new HistoryUnavailable(sprintf('Store [%s] keeps no history.', $store->name)); } $entries = []; foreach ([$from, $to] as $version) { - $entries[] = $history->find($store->name, $scope, $target->key, $target->locale, $version) + $entries[] = $database->attempt($store->name, static fn (): ?HistoryEntry => SettingHistory::entryAt($database->connectionName(), $store->name, $scope, $target->key, $target->locale, $version)) ?? throw new HistoryUnavailable(sprintf('Setting [%s] in store [%s] for scope [%s] has no version %d in its history.', $target->key, $store->name, $scope, $version)); } diff --git a/src/Actions/MakeStore.php b/src/Actions/MakeStore.php index 018c333..5ded678 100644 --- a/src/Actions/MakeStore.php +++ b/src/Actions/MakeStore.php @@ -9,14 +9,12 @@ use Simtabi\Laranail\Settings\Data\OwnerRef; use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Data\GeneratedStore; -use Simtabi\Laranail\Settings\Database\StoreSchema; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; -use Simtabi\Laranail\Settings\Services\Database\SchemaShapeRepository; /** * Generate the migration for a new database store: a copy of the package migration with its - * `$only` (and optionally `$pinnedConnection`) line rewritten, and record the store's shape. - * Returns the file written and the configuration entry to add. + * `$only` (and optionally `$pinnedConnection`) line rewritten. Returns the file written and the + * configuration entry to add. */ final readonly class MakeStore { @@ -35,7 +33,6 @@ public function __construct( private Filesystem $files, private string $migration, private string $migrations, - private ?SchemaShapeRepository $shapes = null, ) {} /** @@ -64,10 +61,6 @@ public function handle(StoreName $store, ?string $connection = null, array $owne self::CONNECTION_LINE => $connection === null ? self::CONNECTION_LINE : sprintf("private ?string \$pinnedConnection = '%s';", $connection), ])]; - if ($this->shapes instanceof SchemaShapeRepository) { - $this->shapes->recordStore($this->shapes->configured()->stores[$store->value] ?? new StoreSchema($store, connection: $connection)); - } - return new GeneratedStore($store, $written, $this->config($store, $connection, $owners)); } diff --git a/src/Actions/PruneAudit.php b/src/Actions/PruneAudit.php index 785452c..9458656 100644 --- a/src/Actions/PruneAudit.php +++ b/src/Actions/PruneAudit.php @@ -13,10 +13,10 @@ use Simtabi\Laranail\Settings\Enums\AuditOutcome; use Simtabi\Laranail\Settings\Events\AuditPruned; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; +use Simtabi\Laranail\Settings\Models\SettingAuditEntry; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; -use Simtabi\Laranail\Settings\Services\Database\AuditRepository; /** Delete audit rows older than `audit.keep_days` on every connection; returns the number removed. */ final readonly class PruneAudit @@ -49,7 +49,11 @@ public function handle(int $keepDays, ?Actor $actor = null): int $seen[$database->connectionName()] = true; - $removed += new AuditRepository($database)->prune($cutoff, $store->name); + // Every tenant's rows. + $removed += $database->attempt($store->name, static fn (): int => SettingAuditEntry::on($database->connectionName()) + ->allTenants() + ->where('occurred_at', '<', $cutoff) + ->toBase()->delete()); } $this->access->auditor()->record(AuditAction::Prune, AuditOutcome::Allowed, $subject, $actor, meta: ['target' => 'audit', 'keep_days' => $keepDays, 'removed' => $removed]); diff --git a/src/Actions/PruneHistory.php b/src/Actions/PruneHistory.php index a75b704..696f116 100644 --- a/src/Actions/PruneHistory.php +++ b/src/Actions/PruneHistory.php @@ -11,12 +11,13 @@ use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Enums\AuditOutcome; +use Simtabi\Laranail\Settings\Models\ModelContext; use Simtabi\Laranail\Settings\Events\HistoryPruned; +use Simtabi\Laranail\Settings\Models\SettingHistory; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; -use Simtabi\Laranail\Settings\Services\Database\HistoryRepository; /** * Delete history entries older than `history.keep_days` or more than `history.keep_versions` @@ -52,12 +53,12 @@ public function handle(?int $keepDays, ?int $keepVersions, ?Actor $actor = null) foreach ($this->stores->all() as $store) { $database = $store->database(); - if (! $database instanceof DatabaseDriver || ! $database->shape()->historyTable || isset($seen[$database->connectionName()])) { + if (! $database instanceof DatabaseDriver || isset($seen[$database->connectionName()])) { continue; } $seen[$database->connectionName()] = true; - $removed += new HistoryRepository($database)->prune($cutoff, $keepVersions, $store->name); + $removed += $database->attempt($store->name, fn (): int => $this->prune($database->connectionName(), $cutoff, $keepVersions)); } $this->access->auditor()->record(AuditAction::Prune, AuditOutcome::Allowed, $subject, $actor, meta: ['target' => 'history', 'keep_days' => $keepDays, 'keep_versions' => $keepVersions, 'removed' => $removed]); @@ -65,4 +66,36 @@ public function handle(?int $keepDays, ?int $keepVersions, ?Actor $actor = null) return $removed; } + + /** Delete every tenant's entries older than `$cutoff` or more than `$keepVersions` behind, and return how many. */ + private function prune(string $connection, ?CarbonImmutable $cutoff, ?int $keepVersions): int + { + $removed = $cutoff instanceof CarbonImmutable ? SettingHistory::on($connection)->allTenants()->where('created_at', '<', $cutoff)->toBase()->delete() : 0; + + if ($keepVersions === null) { + return $removed; + } + + $columns = [...(ModelContext::hasTenantColumn() ? ['tenant'] : []), 'store', 'scope', 'key', 'locale']; + $settings = SettingHistory::on($connection)->allTenants()->select($columns)->selectRaw('max(version) as newest')->groupBy($columns)->toBase()->get(); + + foreach ($settings as $setting) { + $setting = (array) $setting; + $newest = is_numeric($setting['newest'] ?? null) ? (int) $setting['newest'] : 0; + + if ($newest - $keepVersions < 1) { + continue; + } + + $query = SettingHistory::on($connection)->allTenants()->where('version', '<=', $newest - $keepVersions); + + foreach ($columns as $column) { + $query->where($column, $setting[$column] ?? null); + } + + $removed += $query->toBase()->delete(); + } + + return $removed; + } } diff --git a/src/Actions/QueryAudit.php b/src/Actions/QueryAudit.php index 1d0a8b2..d88c613 100644 --- a/src/Actions/QueryAudit.php +++ b/src/Actions/QueryAudit.php @@ -5,8 +5,8 @@ namespace Simtabi\Laranail\Settings\Actions; use Illuminate\Pagination\Cursor; -use Illuminate\Database\Query\Builder; use Illuminate\Support\LazyCollection; +use Illuminate\Database\Eloquent\Builder; use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Data\Subject; use Simtabi\Laranail\Settings\Enums\Ability; @@ -14,10 +14,10 @@ use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Data\AuditEntry; use Simtabi\Laranail\Settings\Data\AuditFilter; +use Simtabi\Laranail\Settings\Models\SettingAuditEntry; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Exceptions\DriverUnavailable; use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; -use Simtabi\Laranail\Settings\Services\Database\AuditRepository; /** Read the audit trail of the filtered store, or the default store, newest first. */ final readonly class QueryAudit @@ -36,13 +36,13 @@ public function get(AuditFilter $filter, ?Actor $actor = null, ?int $limit = nul $query->limit(max(1, $limit)); } - return array_values(array_map(fn (object $row): AuditEntry => $this->entry((array) $row), $query->get()->all())); + return array_values(array_map(static fn (SettingAuditEntry $row): AuditEntry => $row->toEntry(), $query->get()->all())); } /** @return LazyCollection streamed in chunks, for large trails */ public function cursor(AuditFilter $filter, ?Actor $actor = null): LazyCollection { - return $this->query($filter, $actor)->cursor()->map(fn (object $row): AuditEntry => $this->entry((array) $row)); + return $this->query($filter, $actor)->cursor()->map(static fn (SettingAuditEntry $row): AuditEntry => $row->toEntry()); } /** One page; pass its `nextCursor` back for the next. */ @@ -51,13 +51,14 @@ public function paginate(AuditFilter $filter, ?Actor $actor = null, int $perPage $page = $this->query($filter, $actor)->cursorPaginate(max(1, $perPage), ['*'], 'cursor', $cursor === null ? null : Cursor::fromEncoded($cursor)); return new AuditPage( - array_values(array_map(fn (mixed $row): AuditEntry => $this->entry(is_object($row) ? (array) $row : []), $page->items())), + array_values(array_map(static fn (SettingAuditEntry $row): AuditEntry => $row->toEntry(), $page->items())), max(1, $perPage), $page->nextCursor()?->encode(), $page->previousCursor()?->encode(), ); } + /** @return Builder */ private function query(AuditFilter $filter, ?Actor $actor): Builder { $store = $filter->store instanceof StoreName ? $this->stores->get($filter->store) : $this->stores->default(); @@ -68,15 +69,9 @@ private function query(AuditFilter $filter, ?Actor $actor): Builder owner: $filter->scope?->owner(), )); - $audit = AuditRepository::locate($this->stores, $store->name) + $database = $this->stores->auditDatabase($store->name) ?? throw new DriverUnavailable(sprintf('Store [%s] has no active database layer, so its audit trail went to the log and cannot be queried.', $store->name)); - return $audit->query($filter); - } - - /** @param array $row */ - private function entry(array $row): AuditEntry - { - return AuditRepository::entry($row); + return SettingAuditEntry::on($database->connectionName())->matching($filter); } } diff --git a/src/Actions/QueryHistory.php b/src/Actions/QueryHistory.php index 9795991..948a03a 100644 --- a/src/Actions/QueryHistory.php +++ b/src/Actions/QueryHistory.php @@ -4,16 +4,16 @@ namespace Simtabi\Laranail\Settings\Actions; -use Illuminate\Database\Query\Builder; +use Illuminate\Database\Eloquent\Builder; use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Data\Subject; use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Data\HistoryFilter; +use Simtabi\Laranail\Settings\Models\SettingHistory; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Exceptions\HistoryUnavailable; use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; -use Simtabi\Laranail\Settings\Services\Database\HistoryRepository; /** Build the value history query for the filtered store, or the default store. */ final readonly class QueryHistory @@ -23,7 +23,11 @@ public function __construct( private AccessGuard $access, ) {} - /** @throws HistoryUnavailable */ + /** + * @return Builder + * + * @throws HistoryUnavailable + */ public function handle(HistoryFilter $filter, ?Actor $actor = null): Builder { $store = $filter->store instanceof StoreName ? $this->stores->get($filter->store) : $this->stores->default(); @@ -34,9 +38,9 @@ public function handle(HistoryFilter $filter, ?Actor $actor = null): Builder owner: $filter->scope?->owner(), )); - $history = HistoryRepository::locate($this->stores, $store->name) - ?? throw new HistoryUnavailable(sprintf('Store [%s] keeps no history: it has no active database layer, or its schema was recorded without the history table.', $store->name)); + $database = $store->database() + ?? throw new HistoryUnavailable(sprintf('Store [%s] keeps no history: it has no active database layer.', $store->name)); - return $history->query($filter->with(store: $store->name)); + return SettingHistory::on($database->connectionName())->matching($filter->with(store: $store->name)); } } diff --git a/src/Actions/ReencryptSettings.php b/src/Actions/ReencryptSettings.php index fd06c3c..93a1bec 100644 --- a/src/Actions/ReencryptSettings.php +++ b/src/Actions/ReencryptSettings.php @@ -4,18 +4,21 @@ namespace Simtabi\Laranail\Settings\Actions; +use Closure; +use Illuminate\Database\Eloquent\Builder; use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Data\Subject; +use Illuminate\Database\Eloquent\Collection; use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Enums\AuditOutcome; +use Simtabi\Laranail\Settings\Models\SettingHistory; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; +use Simtabi\Laranail\Settings\Models\SettingChangeRequest; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Exceptions\SettingsException; use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Support\LaravelValueEncrypter; -use Simtabi\Laranail\Settings\Services\Database\HistoryRepository; -use Simtabi\Laranail\Settings\Services\Database\ChangeRequestRepository; /** * Re-encrypt every encrypted value, history payload and pending change request under the current @@ -65,21 +68,94 @@ public function handle(?Actor $actor = null): array $connections[$database->connectionName()] = true; - if ($database->shape()->historyTable) { - [$rewritten, $failed] = new HistoryRepository($database)->rewriteEncrypted($store->name, $rewrite); - $totals['history'] += $rewritten; - $totals['failed'] += $failed; - } + [$rewritten, $failed] = $database->attempt($store->name, fn (): array => $this->rewriteHistory($database->connectionName(), $rewrite)); + $totals['history'] += $rewritten; + $totals['failed'] += $failed; - if ($database->shape()->changeRequestsTable) { - [$rewritten, $failed] = new ChangeRequestRepository($database)->rewriteEncrypted($store->name, $rewrite); - $totals['changes'] += $rewritten; - $totals['failed'] += $failed; - } + [$rewritten, $failed] = $database->attempt($store->name, fn (): array => $this->rewriteChangeRequests($database->connectionName(), $rewrite)); + $totals['changes'] += $rewritten; + $totals['failed'] += $failed; } $this->access->auditor()->record(AuditAction::Reencrypt, $totals['failed'] === 0 ? AuditOutcome::Allowed : AuditOutcome::Failed, $subject, $actor, meta: $totals); return $totals; } + + /** + * Rewrite every tenant's encrypted old and new history payloads. + * + * @param Closure(string): ?string $rewrite returns null when it cannot read a payload + * + * @return array{int, int} rewritten and failed counts + */ + private function rewriteHistory(string $connection, Closure $rewrite): array + { + $rewritten = 0; + $failed = 0; + + SettingHistory::on($connection) + ->allTenants() + ->where(static fn (Builder $query): Builder => $query->where('old_encrypted', true)->orWhere('new_encrypted', true)) + ->chunkById(500, static function (Collection $entries) use ($rewrite, &$rewritten, &$failed): void { + foreach ($entries as $entry) { + $columns = []; + + foreach (['old', 'new'] as $side) { + $payload = $entry->getAttribute($side . '_value'); + + if ($entry->getAttribute($side . '_encrypted') !== true || ! is_string($payload)) { + continue; + } + + $new = $rewrite($payload); + $new === null ? $failed++ : $columns[$side . '_value'] = $new; + } + + if ($columns !== []) { + $entry->update($columns); + $rewritten++; + } + } + }); + + return [$rewritten, $failed]; + } + + /** + * Rewrite every tenant's encrypted proposed payloads. A request's `updated_at` stays, since + * pruning reads it. + * + * @param Closure(string): ?string $rewrite returns null when it cannot read a payload + * + * @return array{int, int} rewritten and failed counts + */ + private function rewriteChangeRequests(string $connection, Closure $rewrite): array + { + $rewritten = 0; + $failed = 0; + + SettingChangeRequest::on($connection) + ->allTenants() + ->where('is_encrypted', true) + ->whereNotNull('payload') + ->chunkById(500, static function (Collection $requests) use ($rewrite, &$rewritten, &$failed): void { + foreach ($requests as $request) { + $payload = $request->getAttribute('payload'); + $new = is_string($payload) ? $rewrite($payload) : null; + + if ($new === null) { + $failed++; + + continue; + } + + $request->timestamps = false; + $request->update(['payload' => $new]); + $rewritten++; + } + }); + + return [$rewritten, $failed]; + } } diff --git a/src/Actions/RescopeOwners.php b/src/Actions/RescopeOwners.php index c9de0d9..d33edf2 100644 --- a/src/Actions/RescopeOwners.php +++ b/src/Actions/RescopeOwners.php @@ -4,19 +4,21 @@ namespace Simtabi\Laranail\Settings\Actions; +use Illuminate\Database\Eloquent\Builder; use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Data\Scope; use Simtabi\Laranail\Settings\Data\Subject; +use Illuminate\Database\Eloquent\Collection; use Simtabi\Laranail\Settings\Data\OwnerRef; use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Enums\AuditOutcome; +use Simtabi\Laranail\Settings\Models\SettingHistory; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; +use Simtabi\Laranail\Settings\Models\SettingChangeRequest; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Exceptions\InvalidIdentifier; use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; -use Simtabi\Laranail\Settings\Services\Database\HistoryRepository; -use Simtabi\Laranail\Settings\Services\Database\ChangeRequestRepository; /** * Rename an owner alias in stored values, history and change requests after the application @@ -56,10 +58,7 @@ public function handle(string $from, string $to, ?Actor $actor = null): array $store->transaction(function () use ($database, $store, $from, $to, &$totals): void { $totals['values'] += $database->rescope($store->name, $from, $to); - - if ($database->shape()->historyTable) { - $totals['history'] += new HistoryRepository($database)->rescope($store->name, $from, $to); - } + $totals['history'] += $database->attempt($store->name, fn (): int => $this->rescope(SettingHistory::on($database->connectionName())->allTenants()->where('store', $store->name->value), $from, $to)); }); $store->forgetCachedStore(); @@ -70,9 +69,9 @@ public function handle(string $from, string $to, ?Actor $actor = null): array foreach ($this->stores->all() as $store) { $database = $store->database(); - if ($database instanceof DatabaseDriver && $database->shape()->changeRequestsTable && ! isset($seen[$database->connectionName()])) { + if ($database instanceof DatabaseDriver && ! isset($seen[$database->connectionName()])) { $seen[$database->connectionName()] = true; - $totals['changes'] += new ChangeRequestRepository($database)->rescope($store->name, $from, $to); + $totals['changes'] += $database->attempt($store->name, fn (): int => $this->rescope(SettingChangeRequest::on($database->connectionName())->allTenants(), $from, $to)); } } @@ -80,4 +79,28 @@ public function handle(string $from, string $to, ?Actor $actor = null): array return $totals; } + + /** + * Rename an owner alias in the scopes these rows hold, and return how many changed. Their + * timestamps stay as they are. + * + * @param Builder|Builder $rows + */ + private function rescope(Builder $rows, string $from, string $to): int + { + $changed = 0; + + $rows->where('scope', '>=', $from . ':') + ->where('scope', '<', $from . ';') + ->chunkById(500, static function (Collection $models) use ($from, $to, &$changed): void { + foreach ($models as $model) { + $scope = $model->getAttribute('scope'); + $model->timestamps = false; + $model->update(['scope' => $to . substr(is_string($scope) ? $scope : '', strlen($from))]); + $changed++; + } + }); + + return $changed; + } } diff --git a/src/Actions/RollbackSetting.php b/src/Actions/RollbackSetting.php index a6cf09c..67d2ee2 100644 --- a/src/Actions/RollbackSetting.php +++ b/src/Actions/RollbackSetting.php @@ -10,12 +10,12 @@ use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Data\HistoryEntry; use Simtabi\Laranail\Settings\Data\SettingTarget; +use Simtabi\Laranail\Settings\Models\SettingHistory; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Events\SettingRolledBack; use Simtabi\Laranail\Settings\Exceptions\HistoryUnavailable; use Simtabi\Laranail\Settings\Services\Stores\SettingWriter; use Simtabi\Laranail\Settings\Services\Values\ValuePipeline; -use Simtabi\Laranail\Settings\Services\Database\HistoryRepository; /** * Write a setting's value from an earlier version as a new version, through the normal write @@ -39,13 +39,11 @@ public function handle(SettingTarget $target, int $toVersion, ?Actor $actor = nu $store = $target->store; $scope = $target->subject()->scope(); $database = $store->database(); - $history = $database instanceof DatabaseDriver && $database->shape()->historyTable ? new HistoryRepository($database) : null; - - if (! $history instanceof HistoryRepository) { + if (! $database instanceof DatabaseDriver) { throw new HistoryUnavailable(sprintf('Store [%s] keeps no history, so [%s] cannot be rolled back.', $store->name, $target->key)); } - $entry = $history->find($store->name, $scope, $target->key, $target->locale, $toVersion); + $entry = $database->attempt($store->name, static fn (): ?HistoryEntry => SettingHistory::entryAt($database->connectionName(), $store->name, $scope, $target->key, $target->locale, $toVersion)); if (! $entry instanceof HistoryEntry || $entry->newValue === null) { throw new HistoryUnavailable(sprintf('Setting [%s] in store [%s] for scope [%s] has no value at version %d in its history.', $target->key, $store->name, $scope, $toVersion)); diff --git a/src/Actions/SyncDefinitions.php b/src/Actions/SyncDefinitions.php index bebb751..cb317e5 100644 --- a/src/Actions/SyncDefinitions.php +++ b/src/Actions/SyncDefinitions.php @@ -8,14 +8,16 @@ use Illuminate\Contracts\Events\Dispatcher; use Simtabi\Laranail\Settings\Data\Subject; use Simtabi\Laranail\Settings\Enums\Ability; +use Simtabi\Laranail\Settings\Data\StoreName; +use Simtabi\Laranail\Settings\Data\Definition; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Enums\AuditOutcome; use Simtabi\Laranail\Settings\Support\ValueEncoder; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Events\DefinitionsSynced; +use Simtabi\Laranail\Settings\Models\SettingDefinition; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; -use Simtabi\Laranail\Settings\Services\Database\DefinitionsRepository; use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; /** @@ -51,14 +53,13 @@ public function handle(?Actor $actor = null): array foreach ($this->stores->all() as $name => $store) { $database = $store->database(); - if (! $database instanceof DatabaseDriver || ! $database->shape()->definitionsTable) { + if (! $database instanceof DatabaseDriver) { $report['skipped'][] = $name; continue; } - $repository = new DefinitionsRepository($database, $this->encoder); - $result = $database->attempt($store->name, fn (): array => $database->transaction(fn (): array => $repository->sync($store->name, $byStore[$name] ?? []), $store->name)); + $result = $database->attempt($store->name, fn (): array => $database->transaction(fn (): array => $this->sync($database, $store->name, $byStore[$name] ?? []), $store->name)); $report['synced'] += $result['synced']; $report['removed'] += $result['removed']; $report['conflicts'] = [...$report['conflicts'], ...$result['conflicts']]; @@ -74,4 +75,43 @@ public function handle(?Actor $actor = null): array return $report; } + + /** + * Sync a store's code and config definitions as system rows, leaving runtime rows alone. + * + * @param list $definitions + * + * @return array{synced: int, removed: int, conflicts: list} + */ + private function sync(DatabaseDriver $database, StoreName $store, array $definitions): array + { + $connection = $database->connectionName(); + $synced = 0; + $conflicts = []; + $keys = []; + + foreach ($definitions as $definition) { + $keys[] = $definition->key->value; + $row = SettingDefinition::on($connection)->forStore($store)->where('key', $definition->key->value)->first(); + + if ($row !== null && ! $row->is_system) { + $conflicts[] = $store->value . '.' . $definition->key->value; + + continue; + } + + $row ??= SettingDefinition::on($connection)->make(['store' => $store->value, 'key' => $definition->key->value, 'is_system' => true]); + $row->fillFromDefinition($definition, $this->encodedDefault($definition))->save(); + $synced++; + } + + $removed = SettingDefinition::on($connection)->forStore($store)->where('is_system', true)->whereNotIn('key', $keys === [] ? [''] : $keys)->toBase()->delete(); + + return ['synced' => $synced, 'removed' => $removed, 'conflicts' => $conflicts]; + } + + private function encodedDefault(Definition $definition): ?string + { + return $definition->hasDefault ? $this->encoder->encode($definition->key, $definition->default) : null; + } } diff --git a/src/Actions/Transfer/ImportStore.php b/src/Actions/Transfer/ImportStore.php index a350dd0..743ee6c 100644 --- a/src/Actions/Transfer/ImportStore.php +++ b/src/Actions/Transfer/ImportStore.php @@ -21,6 +21,7 @@ use Simtabi\Laranail\Settings\Enums\AuditOutcome; use Simtabi\Laranail\Settings\Actions\LockSetting; use Simtabi\Laranail\Settings\Support\ValueEncoder; +use Simtabi\Laranail\Settings\Models\SettingCategory; use Simtabi\Laranail\Settings\Data\Transfer\ImportReport; use Simtabi\Laranail\Settings\Data\Transfer\ImportRequest; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; @@ -31,7 +32,6 @@ use Simtabi\Laranail\Settings\Services\Definitions\Definitions; use Simtabi\Laranail\Settings\Services\Transfer\StoreSnapshots; use Simtabi\Laranail\Settings\Actions\Categories\CreateCategory; -use Simtabi\Laranail\Settings\Services\Database\CategoryRepository; /** * Import an export or importer document in one transaction, as a dry run unless the request @@ -58,7 +58,7 @@ public function handle(ImportRequest $request, ?Actor $actor = null): ImportRepo $this->access->authorize($actor, Ability::Import, $subject); $current = $this->snapshots->export($store, ExportMode::Ciphertext)->settingsByIdentity(); - $existingCategories = array_map(static fn (Category $category): string => $category->slug->value, CategoryRepository::of($store)->all()); + $existingCategories = array_map(static fn (Category $category): string => $category->slug->value, $this->categories($store)); $plan = $this->plan($request, $current); $categories = $this->categoriesToCreate($request->document->categories, $existingCategories); @@ -191,4 +191,16 @@ private function target(Store $store, ExportedSetting $setting, ?string $reason) return new SettingTarget($store, $setting->key, $setting->locale, $setting->scope->owner(), $definition, $reason); } + + /** + * The store's categories, from its database layer. + * + * @return list + */ + private function categories(Store $store): array + { + $database = $store->requireDatabase('; categories are kept in the database.'); + + return $database->attempt($store->name, static fn (): array => SettingCategory::listFor($database->connectionName(), $store->name)); + } } diff --git a/src/Actions/WriteGuard.php b/src/Actions/WriteGuard.php index b4e7284..5e8cb12 100644 --- a/src/Actions/WriteGuard.php +++ b/src/Actions/WriteGuard.php @@ -52,7 +52,7 @@ public function run(Ability $ability, SettingTarget $target, ?Actor $actor, bool $this->access->auditor()->record($action, AuditOutcome::Failed, $subject, $actor, $target->reason, meta: ['refusal' => 'approval_unavailable']); throw new ApprovalUnavailable($proposal instanceof ChangeProposal - ? sprintf('Setting [%s] in store [%s] requires approval, and the store cannot hold change requests (it needs an active database layer and the change requests table).', $target->key, $target->store->name) + ? sprintf('Setting [%s] in store [%s] requires approval, and the store cannot hold change requests (it needs an active database layer).', $target->key, $target->store->name) : sprintf('Setting [%s] in store [%s] requires approval; propose the change instead of making it directly.', $target->key, $target->store->name)); } diff --git a/src/Audit/DatabaseAuditSink.php b/src/Audit/DatabaseAuditSink.php index f179ade..8ce0919 100644 --- a/src/Audit/DatabaseAuditSink.php +++ b/src/Audit/DatabaseAuditSink.php @@ -8,9 +8,10 @@ use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Data\AuditEntry; use Simtabi\Laranail\Settings\Contracts\AuditSink; +use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Exceptions\DriverFailure; +use Simtabi\Laranail\Settings\Models\SettingAuditEntry; use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; -use Simtabi\Laranail\Settings\Services\Database\AuditRepository; /** * Writes audit entries to the audit table on the connection of the entry's store (or the default @@ -26,17 +27,19 @@ public function __construct( /** Whether there is an active database layer to write this entry to. */ public function accepts(AuditEntry $entry): bool { - return $this->target($entry) instanceof AuditRepository; + return $this->target($entry) instanceof DatabaseDriver; } public function record(AuditEntry $entry): void { - ($this->target($entry) ?? throw new DriverFailure(sprintf('The database audit sink has no active database layer for store [%s].', $entry->store ?? 'default'))) - ->insert($entry); + $database = $this->target($entry) ?? throw new DriverFailure(sprintf('The database audit sink has no active database layer for store [%s].', $entry->store ?? 'default')); + + $database->attempt(new StoreName($entry->store ?? 'audit'), static fn (): SettingAuditEntry => SettingAuditEntry::on($database->connectionName()) + ->create(SettingAuditEntry::attributesOf($entry))); } - private function target(AuditEntry $entry): ?AuditRepository + private function target(AuditEntry $entry): ?DatabaseDriver { - return AuditRepository::locate(($this->stores)(), $entry->store === null ? null : new StoreName($entry->store)); + return ($this->stores)()->auditDatabase($entry->store === null ? null : new StoreName($entry->store)); } } diff --git a/src/Categories/CategoryManager.php b/src/Categories/CategoryManager.php index 7653d29..55050ed 100644 --- a/src/Categories/CategoryManager.php +++ b/src/Categories/CategoryManager.php @@ -11,6 +11,7 @@ use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Data\NewCategory; use Simtabi\Laranail\Settings\Data\CategorySlug; +use Simtabi\Laranail\Settings\Models\SettingCategory; use Simtabi\Laranail\Settings\Exceptions\CategoryCycle; use Simtabi\Laranail\Settings\Exceptions\UnknownCategory; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; @@ -20,7 +21,6 @@ use Simtabi\Laranail\Settings\Actions\Categories\CreateCategory; use Simtabi\Laranail\Settings\Actions\Categories\DeleteCategory; use Simtabi\Laranail\Settings\Actions\Categories\RenameCategory; -use Simtabi\Laranail\Settings\Services\Database\CategoryRepository; /** * The categories of one store, as the handle's actor. Reads need `view`; changes need @@ -79,20 +79,35 @@ public function get(string $slug): Category { $category = new CategorySlug($slug); - return $this->repository($category->value)->get($category); + foreach ($this->list($category->value) as $candidate) { + if ($candidate->slug->value === $category->value) { + return $candidate; + } + } + + $database = $this->store()->requireDatabase('; categories are kept in the database.'); + + // Not in this store: name the store that has it, or report it unknown. + $database->attempt($this->store()->name, fn (): string => SettingCategory::idOf($database->connectionName(), $this->store()->name, $category)); + + throw new UnknownCategory(sprintf('Store [%s] has no category [%s].', $this->store()->name, $category)); } /** @return list */ public function all(): array { - return $this->repository(null)->all(); + return $this->list(null); } - private function repository(?string $category): CategoryRepository + /** @return list */ + private function list(?string $category): array { $this->access->authorize($this->actor, Ability::View, new Subject($this->store()->name, category: $category)); - return CategoryRepository::of($this->store()); + $store = $this->store(); + $database = $store->requireDatabase('; categories are kept in the database.'); + + return $database->attempt($store->name, static fn (): array => SettingCategory::listFor($database->connectionName(), $store->name)); } private function store(): Store diff --git a/src/Database/SchemaShape.php b/src/Database/SchemaShape.php deleted file mode 100644 index 867cf7b..0000000 --- a/src/Database/SchemaShape.php +++ /dev/null @@ -1,366 +0,0 @@ - $stores database stores, by name */ - public function __construct( - public int $version = self::VERSION, - public IdentityMode $identity = IdentityMode::SlugUid, - public IdType $ids = IdType::Bigint, - public OwnerKeyType $ownerKey = OwnerKeyType::String, - public IdType $ownerKeyType = IdType::Bigint, - public TranslationsMode $translations = TranslationsMode::Lang, - public bool $categoriesSoftDeletes = false, - public bool $definitionsTable = false, - public SchemaNames $names = new SchemaNames, - public array $stores = [], - public TenancyMode $tenancy = TenancyMode::None, - public bool $historyTable = false, - public bool $changeRequestsTable = false, - public bool $storesTable = false, - ) {} - - /** - * The shape the current configuration describes. - * - * @param array $settings `laranail.settings` - * @param mixed $dbToolsIdType `laranail.db-tools.id_type`, which `ids.type` follows unless set - */ - public static function fromConfig(array $settings, mixed $dbToolsIdType = null): self - { - $ids = self::section($settings, 'ids'); - $followed = is_string($dbToolsIdType) ? IdType::parse($dbToolsIdType) : null; - $type = $ids['type'] ?? null; - $idType = $type === null ? ($followed ?? IdType::Bigint) : (is_string($type) ? IdType::parse($type) : null); - - if (! $idType instanceof IdType) { - throw new InvalidConfiguration('laranail.settings.ids.type: use bigint, uuid or ulid (or leave it null to follow laranail.db-tools.id_type).'); - } - - $ownerKey = self::enum($ids, 'owner_key', OwnerKeyType::String, OwnerKeyType::tryFrom(...), 'laranail.settings.ids.owner_key: use [string] or [typed].'); - $identity = self::enum(self::section($settings, 'identity'), 'mode', IdentityMode::SlugUid, IdentityMode::tryFrom(...), 'laranail.settings.identity.mode: use slug_uid, slug_per_row or uid_only.'); - $translations = self::enum(self::section($settings, 'translations'), 'mode', TranslationsMode::Lang, TranslationsMode::tryFrom(...), 'laranail.settings.translations.mode: use [lang] or [json].'); - $tenancy = self::enum(self::section($settings, 'tenancy'), 'mode', TenancyMode::None, TenancyMode::tryFrom(...), 'laranail.settings.tenancy.mode: use none, column or database.'); - $categories = self::section($settings, 'categories'); - $definitions = $settings['definitions'] ?? []; - - if (! is_bool($categories['soft_deletes'] ?? false)) { - throw new InvalidConfiguration('laranail.settings.categories.soft_deletes: true or false.'); - } - - $definitionsTable = is_array($definitions) ? ($definitions['table'] ?? false) : false; - - if (! is_bool($definitionsTable)) { - throw new InvalidConfiguration('laranail.settings.definitions.table: true or false.'); - } - - $history = self::section($settings, 'history')['enabled'] ?? true; - - if (! is_bool($history)) { - throw new InvalidConfiguration('laranail.settings.history.enabled: true or false.'); - } - - $approvals = self::section($settings, 'approvals')['table'] ?? true; - - if (! is_bool($approvals)) { - throw new InvalidConfiguration('laranail.settings.approvals.table: true or false.'); - } - - $persisted = self::section($settings, 'configuration')['persisted'] ?? false; - - if (! is_bool($persisted)) { - throw new InvalidConfiguration('laranail.settings.configuration.persisted: true or false.'); - } - - $default = $settings['default'] ?? 'settings'; - $default = new StoreName(is_string($default) ? $default : 'settings'); - - return new self( - self::VERSION, - $identity, - $idType, - $ownerKey, - $followed ?? IdType::Bigint, - $translations, - $categories['soft_deletes'] ?? false, - $definitionsTable, - SchemaNames::fromConfig(self::section($settings, 'tables')), - self::storesFromConfig($settings, $followed ?? IdType::Bigint, $default), - $tenancy, - $history, - $approvals, - $persisted, - ); - } - - /** - * Read a recorded schema file. - * - * @param array $data what the file returns - */ - public static function fromArray(array $data): self - { - $version = $data['shape_version'] ?? null; - - if (! is_int($version) || $version < 1) { - throw new InvalidConfiguration('Schema file: `shape_version` must be a positive integer.'); - } - - $switches = self::section($data, 'switches'); - $tables = self::section($data, 'tables'); - $stores = []; - - foreach (self::section($data, 'stores') as $name => $entry) { - if (! is_array($entry)) { - throw new InvalidConfiguration(sprintf('Schema file: store [%s] must be an array.', $name)); - } - - $stores[(string) $name] = StoreSchema::fromArray(new StoreName((string) $name), $entry); - } - - $invalid = static fn (string $switch): InvalidConfiguration => new InvalidConfiguration(sprintf('Schema file: switch [%s] has an unknown value.', $switch)); - - return new self( - $version, - IdentityMode::tryFrom(self::text($switches, 'identity', 'slug_uid')) ?? throw $invalid('identity'), - IdType::parse(self::text($switches, 'ids', 'bigint')) ?? throw $invalid('ids'), - OwnerKeyType::tryFrom(self::text($switches, 'owner_key', 'string')) ?? throw $invalid('owner_key'), - IdType::parse(self::text($switches, 'owner_key_type', 'bigint')) ?? throw $invalid('owner_key_type'), - TranslationsMode::tryFrom(self::text($switches, 'translations', 'lang')) ?? throw $invalid('translations'), - ($switches['categories_soft_deletes'] ?? false) === true, - ($switches['definitions_table'] ?? false) === true, - SchemaNames::fromConfig($tables), - $stores, - TenancyMode::tryFrom(self::text($switches, 'tenancy', 'none')) ?? throw $invalid('tenancy'), - // A file recorded before the history table existed describes a schema without it. - ($switches['history_table'] ?? false) === true, - // Likewise for the change requests and persisted configuration tables. - ($switches['change_requests_table'] ?? false) === true, - ($switches['stores_table'] ?? false) === true, - ); - } - - /** @return array what the schema file returns */ - public function toArray(): array - { - $stores = []; - - foreach ($this->stores as $name => $store) { - $stores[$name] = $store->toArray(); - } - - ksort($stores); - - return [ - 'shape_version' => $this->version, - 'switches' => [ - 'identity' => $this->identity->value, - 'ids' => $this->ids->value, - 'owner_key' => $this->ownerKey->value, - 'owner_key_type' => $this->ownerKeyType->value, - 'translations' => $this->translations->value, - 'categories_soft_deletes' => $this->categoriesSoftDeletes, - 'definitions_table' => $this->definitionsTable, - 'tenancy' => $this->tenancy->value, - 'history_table' => $this->historyTable, - 'change_requests_table' => $this->changeRequestsTable, - 'stores_table' => $this->storesTable, - ], - 'tables' => $this->names->toArray(), - 'stores' => $stores, - ]; - } - - /** The recorded entry of a store, or the default shape for a store not recorded. */ - public function store(StoreName $name): StoreSchema - { - return $this->stores[$name->value] ?? new StoreSchema($name); - } - - public function hasStore(StoreName $name): bool - { - return isset($this->stores[$name->value]); - } - - /** A copy with one more store; an existing entry is kept, since its table already exists. */ - public function withStore(StoreSchema $store): self - { - if ($this->hasStore($store->name)) { - return $this; - } - - return new self($this->version, $this->identity, $this->ids, $this->ownerKey, $this->ownerKeyType, $this->translations, $this->categoriesSoftDeletes, $this->definitionsTable, $this->names, [...$this->stores, $store->name->value => $store], $this->tenancy, $this->historyTable, $this->changeRequestsTable, $this->storesTable); - } - - /** - * Every difference from another shape, one line each. - * - * @return list - */ - public function differencesFrom(self $other): array - { - $differences = []; - $mine = self::flatten($this->toArray()); - $theirs = self::flatten($other->toArray()); - - foreach (array_unique([...array_keys($theirs), ...array_keys($mine)]) as $path) { - if ($path === 'shape_version') { - continue; - } - - $from = $theirs[$path] ?? null; - $to = $mine[$path] ?? null; - - if ($from !== $to) { - $differences[] = sprintf('%s: %s → %s', $path, $this->show($from), $this->show($to)); - } - } - - return $differences; - } - - /** - * @param array $settings - * - * @return array the stores with a database layer - */ - private static function storesFromConfig(array $settings, IdType $ownerKeyType, StoreName $default): array - { - $layers = self::section($settings, 'layers'); - $stores = []; - - foreach (self::section($settings, 'stores') as $name => $config) { - if (! is_array($config)) { - continue; - } - - $database = null; - - foreach ((array) ($config['layers'] ?? []) as $layer) { - $layerConfig = is_string($layer) ? ($layers[$layer] ?? null) : null; - - if (is_array($layerConfig) && ($layerConfig['driver'] ?? null) === 'database') { - $database = $layerConfig; - - break; - } - } - - if ($database === null) { - continue; - } - - try { - $storeName = new StoreName((string) $name); - } catch (InvalidIdentifier $exception) { - throw new InvalidConfiguration(sprintf('laranail.settings.stores.%s: %s', $name, $exception->getMessage()), 0, $exception); - } - - $connection = $database['connection'] ?? null; - $stores[$storeName->value] = StoreSchema::fromConfig($storeName, $config, is_string($connection) ? $connection : null, $ownerKeyType, $default); - } - - foreach ($stores as $store) { - if ($store->fallback instanceof StoreName && ($stores[$store->fallback->value] ?? null)?->mode === StoreMode::Dedicated) { - throw new InvalidConfiguration(sprintf('laranail.settings.stores.%s.fallback: [%s] is dedicated too, so it has no global rows either.', $store->name, $store->fallback)); - } - } - - return $stores; - } - - /** - * @template T of \BackedEnum - * - * @param array $section - * @param T $default - * @param callable(string): (T|null) $parse - * - * @return T - */ - private static function enum(array $section, string $key, BackedEnum $default, callable $parse, string $message): BackedEnum - { - $value = $section[$key] ?? null; - - if ($value === null) { - return $default; - } - - return (is_string($value) ? $parse($value) : null) ?? throw new InvalidConfiguration($message); - } - - /** - * @param array $data - * - * @return array - */ - private static function section(array $data, string $key): array - { - $value = $data[$key] ?? []; - - return is_array($value) ? $value : throw new InvalidConfiguration(sprintf('laranail.settings.%s: an array is required.', $key)); - } - - /** @param array $data */ - private static function text(array $data, string $key, string $default): string - { - $value = $data[$key] ?? $default; - - return is_string($value) ? $value : $default; - } - - /** - * @param array $data - * - * @return array - */ - private static function flatten(array $data, string $prefix = ''): array - { - $flat = []; - - foreach ($data as $key => $value) { - $path = $prefix === '' ? (string) $key : $prefix . '.' . $key; - - if (is_array($value)) { - $flat += self::flatten($value, $path); - } else { - $flat[$path] = $value; - } - } - - return $flat; - } - - private function show(mixed $value): string - { - return match (true) { - $value === null => 'none', - is_bool($value) => $value ? 'true' : 'false', - is_scalar($value) => (string) $value, - default => get_debug_type($value), - }; - } -} diff --git a/src/Database/StoreSchema.php b/src/Database/StoreSchema.php deleted file mode 100644 index 9c5bfb5..0000000 --- a/src/Database/StoreSchema.php +++ /dev/null @@ -1,162 +0,0 @@ -` entry. - * - * @param array $config - */ - public static function fromConfig(StoreName $name, array $config, ?string $connection, IdType $ownerKeyType, StoreName $default): self - { - $path = 'laranail.settings.stores.' . $name->value; - $mode = $config['mode'] ?? StoreMode::Polymorphic->value; - $mode = is_string($mode) ? StoreMode::tryFrom($mode) : null; - - if (! $mode instanceof StoreMode) { - throw new InvalidConfiguration($path . '.mode: use [polymorphic] or [dedicated].'); - } - - $softDeletes = $config['soft_deletes'] ?? false; - - if (! is_bool($softDeletes)) { - throw new InvalidConfiguration($path . '.soft_deletes: true or false.'); - } - - $table = $config['table'] ?? null; - - if ($table !== null && ! is_string($table)) { - throw new InvalidConfiguration($path . '.table: a table name is required.'); - } - - if ($mode === StoreMode::Polymorphic) { - return new self($name, $mode, $softDeletes, $table, $connection); - } - - $owners = $config['owners'] ?? []; - - if (! is_array($owners) || count($owners) !== 1 || ! is_string($owners[array_key_first($owners)])) { - throw new InvalidConfiguration($path . '.owners: a dedicated store holds exactly one owner alias.'); - } - - $owner = $config['owner'] ?? []; - - if (! is_array($owner) || ! is_string($owner['table'] ?? null)) { - throw new InvalidConfiguration($path . '.owner.table: a dedicated store names the table its owners live in.'); - } - - $key = $owner['key'] ?? 'id'; - $type = $owner['type'] ?? null; - $parsedType = is_string($type) ? IdType::parse($type) : $ownerKeyType; - - if (! is_string($key) || ! $parsedType instanceof IdType) { - throw new InvalidConfiguration($path . '.owner: `key` is a column name and `type` one of bigint, uuid, ulid.'); - } - - $fallback = $config['fallback'] ?? $default->value; - - try { - $fallbackName = new StoreName(is_string($fallback) ? $fallback : ''); - } catch (InvalidIdentifier $exception) { - throw new InvalidConfiguration($path . '.fallback: ' . $exception->getMessage(), 0, $exception); - } - - if ($fallbackName->value === $name->value) { - throw new InvalidConfiguration($path . '.fallback: a dedicated store has no global rows, so its fallback must be another store.'); - } - - return new self($name, $mode, $softDeletes, $table, $connection, $owners[array_key_first($owners)], $owner['table'], $key, $parsedType, $fallbackName); - } - - /** @param array $entry one entry of the schema file's `stores` */ - public static function fromArray(StoreName $name, array $entry): self - { - $mode = StoreMode::tryFrom(self::text($entry, 'mode') ?? 'polymorphic') - ?? throw new InvalidConfiguration(sprintf('Schema file: store [%s] has an unknown mode.', $name)); - $fallback = self::text($entry, 'fallback'); - - return new self( - $name, - $mode, - ($entry['soft_deletes'] ?? false) === true, - self::text($entry, 'table'), - self::text($entry, 'connection'), - self::text($entry, 'owner_alias'), - self::text($entry, 'owner_table'), - self::text($entry, 'owner_key') ?? 'id', - IdType::parse(self::text($entry, 'owner_key_type') ?? 'bigint') ?? IdType::Bigint, - $fallback === null ? null : new StoreName($fallback), - ); - } - - /** @return array the entry written to the schema file */ - public function toArray(): array - { - return [ - 'mode' => $this->mode->value, - 'soft_deletes' => $this->softDeletes, - 'table' => $this->table, - 'connection' => $this->connection, - 'owner_alias' => $this->ownerAlias, - 'owner_table' => $this->ownerTable, - 'owner_key' => $this->mode === StoreMode::Dedicated ? $this->ownerKey : null, - 'owner_key_type' => $this->mode === StoreMode::Dedicated ? $this->ownerKeyType->value : null, - 'fallback' => $this->fallback?->value, - ]; - } - - public function isDedicated(): bool - { - return $this->mode === StoreMode::Dedicated; - } - - /** @param array $entry */ - private static function text(array $entry, string $key): ?string - { - $value = $entry[$key] ?? null; - - return is_string($value) && $value !== '' ? $value : null; - } -} diff --git a/src/Drivers/DatabaseDriver.php b/src/Drivers/DatabaseDriver.php index 010665c..d6acae1 100644 --- a/src/Drivers/DatabaseDriver.php +++ b/src/Drivers/DatabaseDriver.php @@ -19,12 +19,11 @@ use Simtabi\Laranail\Settings\Data\OwnerRef; use Simtabi\Laranail\Settings\Data\RecordSet; use Simtabi\Laranail\Settings\Data\StoreName; -use Simtabi\Laranail\Settings\Enums\IdentityMode; -use Simtabi\Laranail\Settings\Enums\OwnerKeyType; +use Simtabi\Laranail\Settings\Models\Setting; +use Simtabi\Laranail\Settings\Models\ModelContext; use Simtabi\Laranail\Settings\Database\SchemaNames; -use Simtabi\Laranail\Settings\Database\SchemaShape; -use Simtabi\Laranail\Settings\Database\StoreSchema; use Illuminate\Database\ConnectionResolverInterface; +use Simtabi\Laranail\Settings\Models\SettingCategory; use Simtabi\Laranail\Settings\Support\DatabaseValues; use Simtabi\Laranail\Settings\Contracts\DatabaseBacked; use Simtabi\Laranail\Settings\Exceptions\DriverFailure; @@ -43,7 +42,8 @@ * * Writes are version-checked and raise {@see ConcurrentModification} on a conflict. Database * errors surface as {@see DriverUnavailable} or {@see DriverFailure}, never as PDO exceptions. - * The table's shape comes from the recorded {@see SchemaShape}, not from live configuration. + * Each instance serves one store: its table, soft deletes and dedicated owner come from that + * store's configuration. */ final readonly class DatabaseDriver implements DatabaseBacked { @@ -52,48 +52,25 @@ /** * @param ?string $table the store's configured table (`stores..table`); null uses the store name * @param Closure(): SchemaReadinessInterface $probe db-tools' schema readiness, resolved only after a database error - * @param (Closure(): SchemaShape)|null $shape the recorded schema shape; null is the default shape over $names - * @param (Closure(): ?string)|null $tenant the current tenant (column-mode tenancy); null is no tenant + * @param bool $tenantColumn whether the tables carry a tenant column (`tenancy.mode` = column) + * @param (Closure(): ?string)|null $tenant the current tenant; null is no tenant + * @param ?string $ownerAlias the one owner alias of a dedicated store; null for a polymorphic store + * @param ?string $fallback the store a dedicated store's global values live in */ public function __construct( private ConnectionResolverInterface $db, private ?string $connection, - private SchemaNames $names, private ?string $table, private bool $writable, private Closure $probe, - private ?Closure $shape = null, + private bool $tenantColumn = false, private ?Closure $tenant = null, + private bool $softDeletes = false, + private ?string $ownerAlias = null, + private IdType $ownerKeyType = IdType::Bigint, + private ?string $fallback = null, ) {} - /** - * A new primary key for this key type; empty for bigint, which the database assigns. - * - * @return array{id?: string} - */ - public static function newId(IdType $type): array - { - return match ($type) { - IdType::Bigint => [], - IdType::Uuid => ['id' => (string) Str::orderedUuid()], - IdType::Ulid => ['id' => (string) Str::ulid()], - }; - } - - /** The recorded schema shape the table was created with. */ - public function shape(): SchemaShape - { - $shape = $this->shape instanceof Closure ? ($this->shape)() : null; - - return $shape instanceof SchemaShape ? $shape : new SchemaShape(names: $this->names); - } - - /** The recorded schema of one store. */ - public function schemaOf(StoreName $store): StoreSchema - { - return $this->shape()->store($store); - } - public function database(): self { return $this; @@ -117,15 +94,13 @@ public function connectionName(): string public function tableFor(StoreName $store): string { - $shape = $this->shape(); - - return $shape->names->store($store, $shape->hasStore($store) ? $shape->store($store)->table : $this->table); + return Setting::tableFor($store, $this->table); } /** The current tenant in column-mode tenancy; '' for central rows and in other modes. */ public function tenant(): string { - if (! $this->shape()->tenancy->hasColumn() || ! $this->tenant instanceof Closure) { + if (! $this->tenantColumn || ! $this->tenant instanceof Closure) { return ''; } @@ -134,21 +109,15 @@ public function tenant(): string return is_string($tenant) ? $tenant : ''; } - /** Limit a query to the current tenant in column-mode tenancy. */ - public function scoped(Builder $query): Builder - { - return $this->shape()->tenancy->hasColumn() ? $query->where('tenant', $this->tenant()) : $query; - } - - /** @return array{tenant?: string} the tenant column a new row carries */ - public function tenantColumns(): array + /** Whether the tables carry a tenant column (`tenancy.mode` = column). */ + public function hasTenantColumn(): bool { - return $this->shape()->tenancy->hasColumn() ? ['tenant' => $this->tenant()] : []; + return $this->tenantColumn; } public function names(): SchemaNames { - return $this->shape()->names; + return ModelContext::names(); } public function connection(): Connection @@ -206,7 +175,7 @@ public function put(StoreName $store, Record $record): void $now = $record->writtenAt ?? CarbonImmutable::now(); $columns = $this->columns($store, $record) + ['version' => $record->version, 'updated_at' => $now]; $expected = $record->version - 1; - $softDeletes = $this->schemaOf($store)->softDeletes; + $softDeletes = $this->softDeletes; // Versions start at 1, so a first write (expected 0) has no row to update. if ($expected > 0 && $this->live($store)->where('scope', $record->scope->value)->where('key', $record->key->value)->where('locale', $record->locale->value)->where('version', $expected)->update($columns) > 0) { @@ -227,7 +196,9 @@ public function put(StoreName $store, Record $record): void try { // A savepoint: on Postgres a unique violation would abort the whole transaction. - $this->connection()->transaction(fn (): bool => $this->table($store)->insert($columns + $this->identityColumns($record) + $this->tenantColumns() + [ + $this->connection()->transaction(fn (): bool => $this->table($store)->insert($columns + $this->tenantColumns() + [ + 'id' => (string) Str::ulid(), + 'uid' => (string) Str::ulid(), 'scope' => $record->scope->value, 'key' => $record->key->value, 'locale' => $record->locale->value, @@ -245,7 +216,7 @@ public function put(StoreName $store, Record $record): void /** The version of this identity's trashed row, or 0 when there is none. */ public function trashedVersion(StoreName $store, Scope $scope, Key $key, Locale $locale): int { - if (! $this->schemaOf($store)->softDeletes) { + if (! $this->softDeletes) { return 0; } @@ -268,21 +239,19 @@ public function lockedFind(StoreName $store, Scope $scope, Key $key, Locale $loc }); } - /** The row's `uid`, or its primary key, as the history table references it. */ + /** The row's `uid`, as the history table references it. */ public function reference(StoreName $store, Scope $scope, Key $key, Locale $locale): ?string { - $column = $this->shape()->identity->hasUid() ? 'uid' : 'id'; + $reference = $this->attempt($store, fn (): mixed => $this->identity($this->table($store), $scope, $key, $locale)->value('uid')); - $reference = $this->attempt($store, fn (): mixed => $this->identity($this->table($store), $scope, $key, $locale)->value($column)); - - return is_int($reference) || is_string($reference) ? (string) $reference : null; + return is_string($reference) ? $reference : null; } public function forget(StoreName $store, Scope $scope, Key $key, Locale $locale): void { $this->assertWritable($store); - $this->attempt($store, fn (): int => $this->schemaOf($store)->softDeletes + $this->attempt($store, fn (): int => $this->softDeletes ? $this->identity($this->live($store), $scope, $key, $locale)->update(['deleted_at' => CarbonImmutable::now()]) : $this->identity($this->table($store), $scope, $key, $locale)->delete()); } @@ -292,11 +261,20 @@ public function flushScope(StoreName $store, Scope $scope): int { $this->assertWritable($store); - return $this->attempt($store, fn (): int => $this->schemaOf($store)->softDeletes + return $this->attempt($store, fn (): int => $this->softDeletes ? $this->live($store)->where('scope', $scope->value)->update(['deleted_at' => CarbonImmutable::now()]) : $this->table($store)->where('scope', $scope->value)->delete()); } + /** Unlink every row of the store, in every tenant and trashed or not, from a category. */ + public function unlinkCategory(StoreName $store, string $category): int + { + return $this->attempt($store, fn (): int => $this->connection()->table($this->tableFor($store)) + ->where('category_id', $category) + ->where('category_store', $store->value) + ->update(['category_id' => null, 'category_store' => null])); + } + /** * Every distinct live owner scope of one alias. * @@ -376,26 +354,16 @@ public function rescope(StoreName $store, string $from, string $to): int return $this->attempt($store, function () use ($store, $from, $to): int { $changed = 0; - $polymorphic = ! $this->schemaOf($store)->isDedicated(); - $perRow = $this->shape()->identity === IdentityMode::SlugPerRow; $this->connection()->table($this->tableFor($store)) ->where('scope', '>=', $from . ':') ->where('scope', '<', $from . ';') - ->select(['id', 'scope', 'key', 'locale']) - ->chunkById(500, function ($rows) use ($store, $from, $to, $polymorphic, $perRow, &$changed): void { + ->select(['id', 'scope']) + ->chunkById(500, function ($rows) use ($store, $from, $to, &$changed): void { foreach ($rows as $row) { $row = (array) $row; $scope = $to . substr(is_string($row['scope'] ?? null) ? $row['scope'] : '', strlen($from)); - $columns = ['scope' => $scope]; - - if ($polymorphic) { - $columns['settable_type'] = $to; - } - - if ($perRow) { - $columns['slug'] = sha1($scope . '|' . (is_string($row['key'] ?? null) ? $row['key'] : '') . '|' . (is_string($row['locale'] ?? null) ? $row['locale'] : '')); - } + $columns = $this->ownerAlias === null ? ['scope' => $scope, 'settable_type' => $to] : ['scope' => $scope]; $changed += $this->connection()->table($this->tableFor($store))->where('id', $row['id'])->update($columns); } @@ -498,7 +466,7 @@ private function live(StoreName $store): Builder { $query = $this->table($store); - return $this->schemaOf($store)->softDeletes ? $query->whereNull('deleted_at') : $query; + return $this->softDeletes ? $query->whereNull('deleted_at') : $query; } private function trashed(StoreName $store): Builder @@ -506,6 +474,18 @@ private function trashed(StoreName $store): Builder return $this->table($store)->whereNotNull('deleted_at'); } + /** Limit a query to the current tenant in column-mode tenancy. */ + private function scoped(Builder $query): Builder + { + return $this->tenantColumn ? $query->where('tenant', $this->tenant()) : $query; + } + + /** @return array{tenant?: string} the tenant column a new row carries */ + private function tenantColumns(): array + { + return $this->tenantColumn ? ['tenant' => $this->tenant()] : []; + } + private function identity(Builder $query, Scope $scope, Key $key, Locale $locale): Builder { return $query->where('scope', $scope->value)->where('key', $key->value)->where('locale', $locale->value); @@ -535,7 +515,7 @@ private function columns(StoreName $store, Record $record): array } /** - * The owner columns of a row for the store's mode. + * The owner columns of a row: `settable_type` and `settable_id`, or a dedicated store's `owner_id`. * * @return array * @@ -543,55 +523,26 @@ private function columns(StoreName $store, Record $record): array */ private function ownerColumns(StoreName $store, Scope $scope): array { - $schema = $this->schemaOf($store); $owner = $scope->owner(); [$alias, $id] = $owner instanceof OwnerRef ? [$owner->alias, $owner->id] : [null, null]; - if (! $schema->isDedicated()) { - $shape = $this->shape(); - - return [ - 'settable_type' => $alias, - 'settable_id' => $id === null || $shape->ownerKey === OwnerKeyType::String ? $id : $this->typedKey($store, $id, $shape->ownerKeyType), - ]; + if ($this->ownerAlias === null) { + return ['settable_type' => $alias, 'settable_id' => $id]; } if ($alias === null || $id === null) { - throw new OwnerNotAllowed(sprintf('Store [%s] is dedicated to owner [%s] and holds no global values; write those to store [%s].', $store, $schema->ownerAlias, $schema->fallback)); + throw new OwnerNotAllowed(sprintf('Store [%s] is dedicated to owner [%s] and holds no global values; write those to store [%s].', $store, $this->ownerAlias, $this->fallback)); } - if ($alias !== $schema->ownerAlias) { - throw new OwnerNotAllowed(sprintf('Store [%s] is dedicated to owner [%s], not [%s].', $store, $schema->ownerAlias, $alias)); + if ($alias !== $this->ownerAlias) { + throw new OwnerNotAllowed(sprintf('Store [%s] is dedicated to owner [%s], not [%s].', $store, $this->ownerAlias, $alias)); } - return ['owner_id' => $this->typedKey($store, $id, $schema->ownerKeyType)]; - } - - /** An owner id cast to the column's type. */ - private function typedKey(StoreName $store, string $id, IdType $type): int|string - { - return match ($type) { + return ['owner_id' => match ($this->ownerKeyType) { IdType::Bigint => ctype_digit($id) ? (int) $id : throw new OwnerNotAllowed(sprintf('Store [%s] types owner keys as bigint; [%s] is not one.', $store, $id)), IdType::Uuid => strlen($id) === 36 ? $id : throw new OwnerNotAllowed(sprintf('Store [%s] types owner keys as uuid; [%s] is not one.', $store, $id)), IdType::Ulid => strlen($id) === 26 ? $id : throw new OwnerNotAllowed(sprintf('Store [%s] types owner keys as ulid; [%s] is not one.', $store, $id)), - }; - } - - /** - * The columns only an insert sets: a generated key and the identity columns. - * - * @return array - */ - private function identityColumns(Record $record): array - { - $shape = $this->shape(); - $columns = self::newId($shape->ids); - - return $columns + match ($shape->identity) { - IdentityMode::SlugUid => ['slug' => $record->key->slug(), 'uid' => (string) Str::ulid()], - IdentityMode::SlugPerRow => ['slug' => sha1($record->scope->value . '|' . $record->key->value . '|' . $record->locale->value)], - IdentityMode::UidOnly => ['uid' => (string) Str::ulid()], - }; + }]; } /** @@ -599,21 +550,16 @@ private function identityColumns(Record $record): array * * @throws CategoryStoreMismatch when the slug belongs to another store only */ - private function categoryId(StoreName $store, Record $record): int|string|null + private function categoryId(StoreName $store, Record $record): ?string { if ($record->category === null) { return null; } - $categories = $this->scoped($this->connection()->table($this->names()->categories()))->where('slug', $record->category); - - if ($this->shape()->categoriesSoftDeletes) { - $categories->whereNull('deleted_at'); - } - + $categories = $this->scoped($this->connection()->table(new SettingCategory()->getTable()))->where('slug', $record->category); $id = (clone $categories)->where('store', $store->value)->value('id'); - if (is_int($id) || is_string($id)) { + if (is_string($id)) { return $id; } diff --git a/src/Enums/IdType.php b/src/Enums/IdType.php index adafdba..8414568 100644 --- a/src/Enums/IdType.php +++ b/src/Enums/IdType.php @@ -9,21 +9,21 @@ use Simtabi\Laranail\Enumerator\Attributes\Description; use Simtabi\Laranail\Enumerator\Concerns\HasEnumeratorBehavior; -/** The key type of the package's tables (`ids.type`); unset, it follows `laranail.db-tools.id_type`. */ +/** The key type of a dedicated store's owner table (`stores..owner.type`); unset, it follows `laranail.db-tools.id_type`. */ enum IdType: string implements Enumerator { use HasEnumeratorBehavior; #[Label('Big integer')] - #[Description('An auto-incrementing unsigned big integer. The default.')] + #[Description('An unsigned big integer. The default.')] case Bigint = 'bigint'; #[Label('UUID')] - #[Description('A time-ordered UUID generated by the package (36 characters).')] + #[Description('A UUID (36 characters).')] case Uuid = 'uuid'; #[Label('ULID')] - #[Description('A ULID generated by the package (26 characters).')] + #[Description('A ULID (26 characters).')] case Ulid = 'ulid'; /** Read a configured value, accepting db-tools' upper-case names too. */ diff --git a/src/Enums/IdentityMode.php b/src/Enums/IdentityMode.php deleted file mode 100644 index d0d8a68..0000000 --- a/src/Enums/IdentityMode.php +++ /dev/null @@ -1,38 +0,0 @@ -limit(max(1, $limit)); } - return array_values(array_map(fn (object $row): HistoryEntry => $this->entry((array) $row), $query->get()->all())); + return array_values(array_map($this->entry(...), $query->get()->all())); } /** @return LazyCollection streamed in chunks, for long trails */ public function cursor(): LazyCollection { - return $this->action->handle($this->filter, $this->actor)->cursor()->map(fn (object $row): HistoryEntry => $this->entry((array) $row)); + return $this->action->handle($this->filter, $this->actor)->cursor()->map($this->entry(...)); } /** One page; pass its `nextCursor` back for the next. */ @@ -111,17 +111,16 @@ public function paginate(int $perPage = 50, ?string $cursor = null): HistoryPage $page = $this->action->handle($this->filter, $this->actor)->cursorPaginate(max(1, $perPage), ['*'], 'cursor', $cursor === null ? null : Cursor::fromEncoded($cursor)); return new HistoryPage( - array_values(array_map(fn (mixed $row): HistoryEntry => $this->entry(is_object($row) ? (array) $row : []), $page->items())), + array_values(array_map($this->entry(...), $page->items())), max(1, $perPage), $page->nextCursor()?->encode(), $page->previousCursor()?->encode(), ); } - /** @param array $row */ - private function entry(array $row): HistoryEntry + private function entry(SettingHistory $row): HistoryEntry { - $entry = HistoryRepository::entry($row); + $entry = $row->toEntry(); return $this->mayView instanceof Closure && ! ($this->mayView)($entry) ? $entry->redacted() : $entry; } diff --git a/src/Models/Concerns/BelongsToTenant.php b/src/Models/Concerns/BelongsToTenant.php new file mode 100644 index 0000000..2276f6d --- /dev/null +++ b/src/Models/Concerns/BelongsToTenant.php @@ -0,0 +1,28 @@ +usesTenantColumn() && ModelContext::hasTenantColumn() && $model->getAttribute('tenant') === null) { + $model->setAttribute('tenant', ModelContext::tenant()); + } + }); + } +} diff --git a/src/Models/Concerns/UsesSettingsSchema.php b/src/Models/Concerns/UsesSettingsSchema.php deleted file mode 100644 index dbfa3bf..0000000 --- a/src/Models/Concerns/UsesSettingsSchema.php +++ /dev/null @@ -1,64 +0,0 @@ -getModel(); - - if (ModelContext::hasTenantColumn() && method_exists($model, 'usesTenantColumn') && $model->usesTenantColumn()) { - $query->where($query->qualifyColumn('tenant'), ModelContext::tenant()); - } - }); - - static::creating(static function (self $model): void { - if (ModelContext::hasTenantColumn() && $model->usesTenantColumn() && $model->getAttribute('tenant') === null) { - $model->setAttribute('tenant', ModelContext::tenant()); - } - - if ($model->getKey() === null) { - foreach (DatabaseDriver::newId($model->idType()) as $column => $id) { - $model->setAttribute($column, $id); - } - } - }); - } - - public function getIncrementing(): bool - { - return $this->idType() === IdType::Bigint; - } - - public function getKeyType(): string - { - return $this->idType() === IdType::Bigint ? 'int' : 'string'; - } - - /** Whether this table carries the tenant column in column-mode tenancy. */ - public function usesTenantColumn(): bool - { - return true; - } - - protected function idType(): IdType - { - return ModelContext::shape()->ids; - } -} diff --git a/src/Models/ModelContext.php b/src/Models/ModelContext.php index 09d9080..0fe4f00 100644 --- a/src/Models/ModelContext.php +++ b/src/Models/ModelContext.php @@ -5,44 +5,46 @@ namespace Simtabi\Laranail\Settings\Models; use Closure; +use Illuminate\Contracts\Config\Repository; use Simtabi\Laranail\Settings\Data\StoreName; -use Simtabi\Laranail\Settings\Database\SchemaShape; +use Simtabi\Laranail\Settings\Enums\TenancyMode; +use Simtabi\Laranail\Settings\Database\SchemaNames; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; /** - * The schema shape, current tenant and default store the Eloquent models read. + * The configuration and current tenant the Eloquent models read. * * Eloquent builds models with `new static`, so nothing can be injected. The provider sets closures - * here that resolve the scoped services on each call, so no request or tenant state is held. + * here that resolve the services on each call, so no request or tenant state is held. */ final class ModelContext { - /** @var (Closure(): SchemaShape)|null */ - private static ?Closure $shape = null; + /** @var (Closure(): Repository)|null */ + private static ?Closure $config = null; /** @var (Closure(): ?string)|null */ private static ?Closure $tenant = null; - /** @var (Closure(): string)|null */ - private static ?Closure $defaultStore = null; - /** - * @param Closure(): SchemaShape $shape + * @param Closure(): Repository $config * @param Closure(): ?string $tenant - * @param Closure(): string $defaultStore */ - public static function use(Closure $shape, Closure $tenant, Closure $defaultStore): void + public static function use(Closure $config, Closure $tenant): void { - self::$shape = $shape; + self::$config = $config; self::$tenant = $tenant; - self::$defaultStore = $defaultStore; } - public static function shape(): SchemaShape + /** The package's table names, from `tables`. */ + public static function names(): SchemaNames { - return self::$shape instanceof Closure - ? (self::$shape)() - : throw new InvalidConfiguration('The settings models are used before SettingsServiceProvider registered them.'); + return SchemaNames::fromConfig(self::config()->array('laranail.settings.tables', [])); + } + + /** Whether the tables carry a tenant column (`tenancy.mode` = column). */ + public static function hasTenantColumn(): bool + { + return TenancyMode::fromConfig(self::config()->get('laranail.settings.tenancy.mode'))->hasColumn(); } /** The tenant column value; '' outside a tenant or when tenancy is not column mode. */ @@ -51,19 +53,41 @@ public static function tenant(): string return self::hasTenantColumn() && self::$tenant instanceof Closure ? ((self::$tenant)() ?? '') : ''; } - public static function hasTenantColumn(): bool + public static function defaultStore(): StoreName { - return self::shape()->tenancy->hasColumn(); + return new StoreName(self::config()->string('laranail.settings.default', 'settings')); } - public static function defaultStore(): StoreName + /** + * A store's configuration entry; empty when the store is not configured. + * + * @return array + */ + public static function store(StoreName $store): array { - return new StoreName(self::$defaultStore instanceof Closure ? (self::$defaultStore)() : 'settings'); + $config = self::config()->get('laranail.settings.stores.' . $store->value); + + return is_array($config) ? $config : []; } - /** The connection a store's tables live on; null is the default connection. */ + /** The connection of a store's first database layer; null is the default connection. */ public static function connectionOf(StoreName $store): ?string { - return self::shape()->store($store)->connection; + foreach ((array) (self::store($store)['layers'] ?? []) as $layer) { + $config = is_string($layer) ? self::config()->get('laranail.settings.layers.' . $layer) : null; + + if (is_array($config) && ($config['driver'] ?? null) === 'database') { + return is_string($config['connection'] ?? null) ? $config['connection'] : null; + } + } + + return null; + } + + private static function config(): Repository + { + return self::$config instanceof Closure + ? (self::$config)() + : throw new InvalidConfiguration('The settings models are used before SettingsServiceProvider registered them.'); } } diff --git a/src/Models/Scopes/TenantScope.php b/src/Models/Scopes/TenantScope.php new file mode 100644 index 0000000..d287247 --- /dev/null +++ b/src/Models/Scopes/TenantScope.php @@ -0,0 +1,34 @@ + + */ +final class TenantScope implements Scope +{ + /** + * @param Builder $builder + * @param TModel $model + */ + public function apply(Builder $builder, Model $model): void + { + if ($model instanceof SettingsModel && $model->usesTenantColumn() && ModelContext::hasTenantColumn()) { + $builder->where($model->qualifyColumn('tenant'), ModelContext::tenant()); + } + } +} diff --git a/src/Models/Setting.php b/src/Models/Setting.php index 77d57e0..0e8f923 100644 --- a/src/Models/Setting.php +++ b/src/Models/Setting.php @@ -5,38 +5,42 @@ namespace Simtabi\Laranail\Settings\Models; use Override; -use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Builder; use Simtabi\Laranail\Settings\Data\StoreName; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Factories\HasFactory; use Simtabi\Laranail\Settings\Database\Factories\SettingFactory; -use Simtabi\Laranail\Settings\Models\Concerns\UsesSettingsSchema; /** * A row of a store's values table, for factories, admin screens and tests. Belongs to the default * store unless {@see inStore()} or {@see forStore()} names another. * * `value` is the encoded payload. Writing it here bypasses validation, encryption, locks, - * authorization and audit; application code uses `Settings::set()`. + * authorization and audit; application code uses `Settings::set()`. The engine reads and writes + * this table through the query builder, using {@see tableFor()} for its name. * - * @property int|string $id + * @property string $id + * @property string $uid * @property string $scope * @property string $key * @property string $locale * @property ?string $value * @property int $version */ -final class Setting extends Model +final class Setting extends SettingsModel { /** @use HasFactory */ use HasFactory; - use UsesSettingsSchema; + private ?string $store = null; - protected $guarded = []; + /** A store's values table: `tables.prefix` plus `stores..table`, else the store name. */ + public static function tableFor(StoreName $store, ?string $table = null): string + { + $configured = ModelContext::store($store)['table'] ?? null; - private ?string $store = null; + return ModelContext::names()->store($store, $table ?? (is_string($configured) ? $configured : null)); + } /** @return Builder */ public static function forStore(string $store): Builder @@ -48,7 +52,7 @@ public static function forStore(string $store): Builder public function inStore(string $store): static { $this->store = new StoreName($store)->value; - $this->setTable($this->storeTable()); + $this->setTable(self::tableFor($this->storeName())); $this->setConnection(ModelContext::connectionOf($this->storeName())); return $this; @@ -62,13 +66,18 @@ public function storeName(): StoreName #[Override] public function getTable(): string { - return $this->table ?? $this->storeTable(); + return $this->table ?? self::tableFor($this->storeName()); } + /** + * Both keys are ULIDs. + * + * @return list + */ #[Override] - public function getConnectionName(): ?string + public function uniqueIds(): array { - return parent::getConnectionName() ?? ModelContext::connectionOf($this->storeName()); + return ['id', 'uid']; } /** @@ -94,10 +103,11 @@ public function category(): BelongsTo #[Override] protected static function booted(): void { + // Trashed rows are hidden in stores that keep forgotten rows (`stores..soft_deletes`). self::addGlobalScope('laranail-settings.live', static function (Builder $query): void { $model = $query->getModel(); - if ($model instanceof self && ModelContext::shape()->store($model->storeName())->softDeletes) { + if ($model instanceof self && (ModelContext::store($model->storeName())['soft_deletes'] ?? false) === true) { $query->whereNull($query->qualifyColumn('deleted_at')); } }); @@ -108,11 +118,19 @@ protected static function newFactory(): SettingFactory return SettingFactory::new(); } + #[Override] + protected function defaultConnectionName(): ?string + { + return ModelContext::connectionOf($this->storeName()); + } + /** @return array */ #[Override] protected function casts(): array { return [ + 'label' => 'array', + 'description' => 'array', 'is_encrypted' => 'boolean', 'is_locked' => 'boolean', 'is_public' => 'boolean', @@ -122,12 +140,4 @@ protected function casts(): array 'meta' => 'array', ]; } - - private function storeTable(): string - { - $shape = ModelContext::shape(); - $store = $this->storeName(); - - return $shape->names->store($store, $shape->store($store)->table); - } } diff --git a/src/Models/SettingAuditEntry.php b/src/Models/SettingAuditEntry.php index a81a6ab..cb9b778 100644 --- a/src/Models/SettingAuditEntry.php +++ b/src/Models/SettingAuditEntry.php @@ -5,51 +5,149 @@ namespace Simtabi\Laranail\Settings\Models; use Override; -use Illuminate\Database\Eloquent\Model; -use Simtabi\Laranail\Settings\Enums\IdType; +use JsonException; +use Carbon\CarbonImmutable; +use Illuminate\Database\Eloquent\Builder; +use Simtabi\Laranail\Settings\Enums\Channel; +use Simtabi\Laranail\Settings\Data\StoreName; +use Simtabi\Laranail\Settings\Data\AuditEntry; +use Simtabi\Laranail\Settings\Enums\ActorType; +use Simtabi\Laranail\Settings\Data\AuditFilter; +use Simtabi\Laranail\Settings\Enums\AuditAction; +use Simtabi\Laranail\Settings\Enums\AuditOutcome; use Illuminate\Database\Eloquent\Factories\HasFactory; -use Simtabi\Laranail\Settings\Models\Concerns\UsesSettingsSchema; +use Simtabi\Laranail\Settings\Exceptions\DriverFailure; use Simtabi\Laranail\Settings\Database\Factories\SettingAuditEntryFactory; /** - * A row of the append-only audit table, for factories and tests. Never holds a value. + * A row of the append-only audit table: who did what, when and through which channel. Never holds + * a value. * * @property string $id * @property string $action * @property string $outcome */ -final class SettingAuditEntry extends Model +final class SettingAuditEntry extends SettingsModel { /** @use HasFactory */ use HasFactory; - use UsesSettingsSchema; - public $timestamps = false; - protected $guarded = []; + /** + * The attributes of a row for an entry. + * + * @return array + */ + public static function attributesOf(AuditEntry $entry): array + { + return [ + 'id' => $entry->id, + 'occurred_at' => $entry->occurredAt, + 'action' => $entry->action->value, + 'outcome' => $entry->outcome->value, + 'store' => $entry->store, + 'scope' => $entry->scope, + 'key' => $entry->key, + 'locale' => $entry->locale, + 'version_from' => $entry->versionFrom, + 'version_to' => $entry->versionTo, + 'change_request' => is_string($entry->meta['change_request'] ?? null) ? $entry->meta['change_request'] : null, + 'actor_type' => $entry->actorType->value, + 'actor_alias' => $entry->actorAlias, + 'actor_id' => $entry->actorId, + 'channel' => $entry->channel->value, + 'ip' => $entry->ip, + 'user_agent' => $entry->userAgent, + 'request_id' => $entry->requestId, + 'reason' => $entry->reason, + 'meta' => $entry->meta === [] ? null : $entry->meta, + ]; + } #[Override] public function getTable(): string { - return ModelContext::shape()->names->audit(); + return $this->table ?? ModelContext::names()->audit(); } - #[Override] - public function getConnectionName(): ?string + /** + * This row as an entry. + * + * @throws DriverFailure when the row is malformed + */ + public function toEntry(): AuditEntry { - return parent::getConnectionName() ?? ModelContext::connectionOf(ModelContext::defaultStore()); + $row = $this->getAttributes(); + $text = static fn (string $column): ?string => is_string($row[$column] ?? null) ? $row[$column] : null; + $number = static fn (string $column): ?int => is_numeric($row[$column] ?? null) ? (int) $row[$column] : null; + $id = $text('id'); + $occurred = $text('occurred_at'); + $action = AuditAction::tryFrom($text('action') ?? ''); + $outcome = AuditOutcome::tryFrom($text('outcome') ?? ''); + $actorType = ActorType::tryFrom($text('actor_type') ?? ''); + $channel = Channel::tryFrom($text('channel') ?? ''); + + if ($id === null || $occurred === null || ! $action instanceof AuditAction || ! $outcome instanceof AuditOutcome || ! $actorType instanceof ActorType || ! $channel instanceof Channel) { + throw new DriverFailure(sprintf('Audit row [%s] is malformed.', $id ?? '?')); + } + + return new AuditEntry( + id: $id, + occurredAt: CarbonImmutable::parse($occurred), + action: $action, + outcome: $outcome, + store: $text('store'), + scope: $text('scope'), + key: $text('key'), + locale: $text('locale'), + versionFrom: $number('version_from'), + versionTo: $number('version_to'), + actorType: $actorType, + actorAlias: $text('actor_alias'), + actorId: $text('actor_id'), + channel: $channel, + ip: $text('ip'), + userAgent: $text('user_agent'), + requestId: $text('request_id'), + reason: $text('reason'), + meta: $this->meta($text('meta')), + ); } - protected static function newFactory(): SettingAuditEntryFactory + /** + * The rows matching a filter, newest first. + * + * @param Builder $query + * + * @return Builder + */ + public function scopeMatching(Builder $query, AuditFilter $filter): Builder { - return SettingAuditEntryFactory::new(); + if ($filter->store instanceof StoreName) { + $query->where('store', $filter->store->value); + } + + foreach (['scope' => $filter->scope?->value, 'key' => $filter->key?->value, 'action' => $filter->action?->value, 'outcome' => $filter->outcome?->value] as $column => $value) { + if ($value !== null) { + $query->where($column, $value); + } + } + + if ($filter->since instanceof CarbonImmutable) { + $query->where('occurred_at', '>=', $filter->since); + } + + if ($filter->until instanceof CarbonImmutable) { + $query->where('occurred_at', '<=', $filter->until); + } + + return $query->orderByDesc('occurred_at')->orderByDesc('id'); } - /** Always a ULID, whatever `ids.type` says. */ - protected function idType(): IdType + protected static function newFactory(): SettingAuditEntryFactory { - return IdType::Ulid; + return SettingAuditEntryFactory::new(); } /** @return array */ @@ -58,4 +156,28 @@ protected function casts(): array { return ['occurred_at' => 'immutable_datetime', 'meta' => 'array', 'version_from' => 'integer', 'version_to' => 'integer']; } + + /** @return array the scalar entries of the stored meta */ + private function meta(?string $json): array + { + if ($json === null) { + return []; + } + + try { + $decoded = json_decode($json, true, 4, JSON_THROW_ON_ERROR); + } catch (JsonException) { + return []; + } + + $meta = []; + + foreach (is_array($decoded) ? $decoded : [] as $key => $value) { + if (is_scalar($value) || $value === null) { + $meta[(string) $key] = $value; + } + } + + return $meta; + } } diff --git a/src/Models/SettingCategory.php b/src/Models/SettingCategory.php index b2457fb..8974da3 100644 --- a/src/Models/SettingCategory.php +++ b/src/Models/SettingCategory.php @@ -5,48 +5,101 @@ namespace Simtabi\Laranail\Settings\Models; use Override; -use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Builder; +use Simtabi\Laranail\Settings\Data\Category; +use Simtabi\Laranail\Settings\Data\StoreName; +use Simtabi\Laranail\Settings\Data\CategorySlug; use Illuminate\Database\Eloquent\Relations\HasMany; +use Simtabi\Laranail\Settings\Support\Translations; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Factories\HasFactory; -use Simtabi\Laranail\Settings\Models\Concerns\UsesSettingsSchema; +use Simtabi\Laranail\Settings\Exceptions\CategoryCycle; +use Simtabi\Laranail\Settings\Models\Scopes\TenantScope; +use Simtabi\Laranail\Settings\Exceptions\UnknownCategory; +use Simtabi\Laranail\Settings\Exceptions\CategoryStoreMismatch; use Simtabi\Laranail\Settings\Database\Factories\SettingCategoryFactory; /** - * A row of the categories table, for factories, seeders and admin screens. Changes made here skip - * authorization and audit; application code uses `Settings::categories()`. + * A row of the categories table. Categories belong to one store and nest by `parent_id`; titles and + * descriptions are JSON maps of locale to text. Changes made directly here skip authorization and + * audit; application code uses `Settings::categories()`. * - * @property int|string $id + * @property string $id * @property string $store - * @property int|string|null $parent_id - * @property string $title + * @property ?string $parent_id + * @property array $title * @property string $slug - * @property ?string $description + * @property ?array $description * @property ?string $icon * @property int $sort_order * @property bool $is_system * @property ?array $meta */ -final class SettingCategory extends Model +final class SettingCategory extends SettingsModel { /** @use HasFactory */ use HasFactory; - use UsesSettingsSchema; + /** + * A store's categories as data, by sort order then slug. + * + * @return list + */ + public static function listFor(?string $connection, StoreName $store): array + { + $rows = self::on($connection)->forStore($store)->orderBy('sort_order')->orderBy('slug')->get(); + $slugs = $rows->pluck('slug', 'id')->all(); - protected $guarded = []; + return array_values($rows->map(static fn (self $row): Category => $row->toCategory( + $row->parent_id !== null && is_string($slugs[$row->parent_id] ?? null) ? new CategorySlug($slugs[$row->parent_id]) : null, + ))->all()); + } - #[Override] - public function getTable(): string + /** + * The id of a store's category. + * + * @throws CategoryStoreMismatch when the slug belongs to another store only + * @throws UnknownCategory + */ + public static function idOf(?string $connection, StoreName $store, CategorySlug $slug): string { - return ModelContext::shape()->names->categories(); + $id = self::on($connection)->forStore($store)->where('slug', $slug->value)->value('id'); + + if (is_string($id)) { + return $id; + } + + $elsewhere = self::on($connection)->where('slug', $slug->value)->value('store'); + + throw is_string($elsewhere) + ? new CategoryStoreMismatch(sprintf('Category [%s] belongs to store [%s], not [%s].', $slug, $elsewhere, $store)) + : new UnknownCategory(sprintf('Store [%s] has no category [%s].', $store, $slug)); } - #[Override] - public function getConnectionName(): ?string + /** + * The ids above a category, nearest first. + * + * @return list + * + * @throws CategoryCycle when the data already holds a cycle + */ + public static function ancestorsOf(?string $connection, string $id): array { - return parent::getConnectionName() ?? ModelContext::connectionOf(ModelContext::defaultStore()); + $ancestors = []; + + // Bounded, so a cycle already in the data cannot loop forever. + for ($guard = 0; $guard < 10_000; $guard++) { + $parent = self::on($connection)->whereKey($id)->value('parent_id'); + + if (! is_string($parent)) { + return $ancestors; + } + + $ancestors[] = $parent; + $id = $parent; + } + + throw new CategoryCycle('The categories already contain a cycle; repair them in the database.'); } /** @return BelongsTo */ @@ -61,24 +114,51 @@ public function children(): HasMany return $this->hasMany(self::class, 'parent_id'); } + #[Override] + public function getTable(): string + { + return $this->table ?? ModelContext::names()->categories(); + } + + /** This row as data, with its parent's slug. */ + public function toCategory(?CategorySlug $parent = null): Category + { + return new Category( + id: $this->id, + store: new StoreName($this->store), + slug: new CategorySlug($this->slug), + title: Translations::text($this->title) ?? '', + parent: $parent, + description: Translations::text($this->description), + icon: $this->icon, + sortOrder: $this->sort_order, + system: $this->is_system, + titles: Translations::texts($this->title), + ); + } + /** * @param Builder $query * * @return Builder */ - public function scopeForStore(Builder $query, string $store): Builder + public function scopeForStore(Builder $query, StoreName|string $store): Builder { - return $query->where('store', $store); + return $query->where('store', $store instanceof StoreName ? $store->value : $store); } - #[Override] - protected static function booted(): void + /** + * The central categories ('' in column-mode tenancy), which every tenant's definitions use. + * + * @param Builder $query + * + * @return Builder + */ + public function scopeCentral(Builder $query): Builder { - self::addGlobalScope('laranail-settings.live', static function (Builder $query): void { - if (ModelContext::shape()->categoriesSoftDeletes) { - $query->whereNull($query->qualifyColumn('deleted_at')); - } - }); + $query->withoutGlobalScope(TenantScope::class); + + return ModelContext::hasTenantColumn() ? $query->where('tenant', '') : $query; } protected static function newFactory(): SettingCategoryFactory @@ -90,6 +170,6 @@ protected static function newFactory(): SettingCategoryFactory #[Override] protected function casts(): array { - return ['is_system' => 'boolean', 'sort_order' => 'integer', 'meta' => 'array']; + return ['title' => 'array', 'description' => 'array', 'is_system' => 'boolean', 'sort_order' => 'integer', 'meta' => 'array']; } } diff --git a/src/Models/SettingChangeRequest.php b/src/Models/SettingChangeRequest.php new file mode 100644 index 0000000..b977e1c --- /dev/null +++ b/src/Models/SettingChangeRequest.php @@ -0,0 +1,221 @@ +create([ + 'store' => $request['store'], + 'scope' => $request['scope'], + 'key' => $request['key'], + 'locale' => $request['locale'], + 'operation' => $request['operation']->value, + 'payload' => $request['payload'], + 'type' => $request['type'], + 'is_encrypted' => $request['encrypted'], + 'base_version' => $request['base_version'], + 'status' => ChangeStatus::Pending->value, + 'requested_by_type' => $requester->type->value, + 'requested_by_alias' => $requester->alias, + 'requested_by_id' => $requester->id, + 'reason' => $request['reason'], + 'expires_at' => $request['expires_at'], + 'created_at' => $now, + 'updated_at' => $now, + ])->refresh()->toRequest(); + } + + /** @throws UnknownChangeRequest */ + public static function get(?string $connection, StoreName $store, string $id): ChangeRequest + { + return self::on($connection)->find($id)?->toRequest() + ?? throw new UnknownChangeRequest(sprintf('Store [%s] has no change request [%s].', $store, $id)); + } + + /** + * Move a request from one of `$from` to a new status; false when someone else decided it first. + * + * @param list $from + * @param list|null $approvals the approvals so far, when they change + */ + public static function transition(?string $connection, ChangeRequest $request, array $from, ChangeStatus $to, ?Actor $decidedBy, ?string $reason, CarbonImmutable $now, ?array $approvals = null): bool + { + $columns = ['status' => $to->value, 'updated_at' => $now]; + + if ($approvals !== null) { + $columns['approvals'] = json_encode($approvals, JSON_THROW_ON_ERROR); + } + + if ($decidedBy instanceof Actor) { + $columns += [ + 'decided_by_type' => $decidedBy->type->value, + 'decided_by_alias' => $decidedBy->alias, + 'decided_by_id' => $decidedBy->id, + 'decided_at' => $now, + 'decision_reason' => $reason, + ]; + } + + $statuses = array_map(static fn (ChangeStatus $status): string => $status->value, $from); + $updated = self::on($connection)->whereKey($request->id)->whereIn('status', $statuses)->toBase()->update($columns); + + if ($updated > 0) { + return true; + } + + // MySQL counts changed rows, so an identical update reports 0; that only means a lost race + // when the target status is not one of the allowed ones. + if (! in_array($to->value, $statuses, true)) { + return false; + } + + return self::on($connection)->whereKey($request->id)->where('status', $to->value)->exists(); + } + + #[Override] + public function getTable(): string + { + return $this->table ?? ModelContext::names()->changeRequests(); + } + + /** + * This row as a request. + * + * @throws DriverFailure when the row is malformed + */ + public function toRequest(): ChangeRequest + { + $row = $this->getAttributes(); + $text = static fn (string $column): ?string => is_string($row[$column] ?? null) ? $row[$column] : null; + $time = static fn (string $column): ?CarbonImmutable => $text($column) === null ? null : CarbonImmutable::parse($text($column)); + $id = $text('id'); + $operation = ChangeOperation::tryFrom($text('operation') ?? ''); + $status = ChangeStatus::tryFrom($text('status') ?? ''); + $requester = ActorType::tryFrom($text('requested_by_type') ?? ''); + $base = $row['base_version'] ?? null; + $store = $text('store'); + $scope = $text('scope'); + $key = $text('key'); + + if ($id === null || $store === null || $scope === null || $key === null || ! $operation instanceof ChangeOperation || ! $status instanceof ChangeStatus || ! $requester instanceof ActorType || ! is_numeric($base)) { + throw new DriverFailure(sprintf('Change request row [%s] is malformed.', $id ?? '?')); + } + + $approvals = $text('approvals') === null ? [] : json_decode($text('approvals'), true); + + return new ChangeRequest( + id: $id, + store: $store, + scope: $scope, + key: $key, + locale: $text('locale') ?? '', + operation: $operation, + payload: $text('payload'), + type: $text('type'), + encrypted: DatabaseValues::boolean($row['is_encrypted'] ?? false), + baseVersion: (int) $base, + status: $status, + requestedByType: $requester, + requestedByAlias: $text('requested_by_alias'), + requestedById: $text('requested_by_id'), + approvals: is_array($approvals) ? array_values(array_filter($approvals, is_string(...))) : [], + decidedByType: ActorType::tryFrom($text('decided_by_type') ?? ''), + decidedByAlias: $text('decided_by_alias'), + decidedById: $text('decided_by_id'), + decidedAt: $time('decided_at'), + reason: $text('reason'), + decisionReason: $text('decision_reason'), + expiresAt: $time('expires_at'), + createdAt: $time('created_at'), + ); + } + + /** + * The requests of a filter, newest first. + * + * @param Builder $query + * + * @return Builder + */ + public function scopeMatching(Builder $query, ChangeFilter $filter): Builder + { + $query->where('store', $filter->store->value); + + foreach (['id' => $filter->id, 'status' => $filter->status?->value, 'scope' => $filter->scope?->value, 'key' => $filter->key?->value] as $column => $value) { + if ($value !== null) { + $query->where($column, $value); + } + } + + return $query->orderByDesc('id'); + } + + /** + * Pending and approved requests: those still waiting to be applied. + * + * @param Builder $query + * + * @return Builder + */ + public function scopeOpen(Builder $query): Builder + { + return $query->whereIn('status', [ChangeStatus::Pending->value, ChangeStatus::Approved->value]); + } + + /** + * Open requests past their expiry. + * + * @param Builder $query + * + * @return Builder + */ + public function scopeOverdue(Builder $query, CarbonImmutable $now): Builder + { + return $query->open()->whereNotNull('expires_at')->where('expires_at', '<=', $now); + } + + /** @return array */ + #[Override] + protected function casts(): array + { + return [ + 'approvals' => 'array', + 'is_encrypted' => 'boolean', + 'base_version' => 'integer', + 'decided_at' => 'immutable_datetime', + 'expires_at' => 'immutable_datetime', + ]; + } +} diff --git a/src/Models/SettingDefinition.php b/src/Models/SettingDefinition.php index 2effb9d..64a5ce5 100644 --- a/src/Models/SettingDefinition.php +++ b/src/Models/SettingDefinition.php @@ -5,52 +5,114 @@ namespace Simtabi\Laranail\Settings\Models; use Override; -use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Builder; +use Simtabi\Laranail\Settings\Data\StoreName; +use Simtabi\Laranail\Settings\Data\Definition; +use Simtabi\Laranail\Settings\Support\Translations; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Factories\HasFactory; -use Simtabi\Laranail\Settings\Models\Concerns\UsesSettingsSchema; +use Simtabi\Laranail\Settings\Models\Scopes\TenantScope; use Simtabi\Laranail\Settings\Database\Factories\SettingDefinitionFactory; /** - * A row of the optional definitions table. Shared by every tenant, so it has no tenant column. - * `is_system` rows are synced from code and config. + * A row of the definitions table, on the default store's connection. Shared by every tenant, so it + * has no tenant column. `is_system` rows are synced from code and config; the others are edited at + * runtime. * - * @property int|string $id + * @property string $id * @property string $store * @property string $key * @property string $slug + * @property string $group + * @property ?string $category_id + * @property ?string $type + * @property ?string $default + * @property ?array $label + * @property ?array $description + * @property ?list $rules + * @property ?list $overridable_by + * @property ?bool $inherits + * @property bool $is_encrypted + * @property bool $is_public + * @property bool $is_locked * @property bool $is_system + * @property-read ?SettingCategory $category */ -final class SettingDefinition extends Model +final class SettingDefinition extends SettingsModel { /** @use HasFactory */ use HasFactory; - use UsesSettingsSchema; - - protected $guarded = []; - #[Override] public function getTable(): string { - return ModelContext::shape()->names->definitions(); + return $this->table ?? ModelContext::names()->definitions(); } - #[Override] - public function getConnectionName(): ?string + /** @return BelongsTo */ + public function category(): BelongsTo { - return parent::getConnectionName() ?? ModelContext::connectionOf(ModelContext::defaultStore()); + return $this->belongsTo(SettingCategory::class, 'category_id')->withoutGlobalScope(TenantScope::class); } - public function usesTenantColumn(): bool + /** + * Fill the columns a definition describes. A category links to the store's central category + * of that slug, since definitions are shared by every tenant. + * + * @param ?string $default the encoded default; an encrypted definition's default is never stored + */ + public function fillFromDefinition(Definition $definition, ?string $default): static { - return false; + $category = $definition->category === null ? null : SettingCategory::on($this->getConnectionName()) + ->central() + ->forStore($this->store) + ->where('slug', $definition->category) + ->value('id'); + + return $this->fill([ + 'slug' => $definition->key->slug(), + 'group' => $definition->group(), + 'category_id' => is_string($category) ? $category : null, + 'type' => $definition->type, + 'default' => $definition->encrypted ? null : $default, + 'label' => Translations::ofNullable($definition->label), + 'description' => Translations::ofNullable($definition->description), + 'rules' => $definition->rules, + 'is_encrypted' => $definition->encrypted, + 'is_public' => $definition->public, + 'is_locked' => $definition->locked, + 'inherits' => $definition->inherits, + 'overridable_by' => $definition->overridableBy, + ]); } - /** @return BelongsTo */ - public function category(): BelongsTo + /** + * @param Builder $query + * + * @return Builder + */ + public function scopeForStore(Builder $query, StoreName|string $store): Builder { - return $this->belongsTo(SettingCategory::class, 'category_id'); + return $query->where('store', $store instanceof StoreName ? $store->value : $store); + } + + /** + * Rows edited at runtime, not synced from code or config. + * + * @param Builder $query + * + * @return Builder + */ + public function scopeRuntime(Builder $query): Builder + { + return $query->where('is_system', false); + } + + /** Definitions are shared by every tenant, so the table has no tenant column. */ + #[Override] + public function usesTenantColumn(): bool + { + return false; } protected static function newFactory(): SettingDefinitionFactory @@ -63,6 +125,8 @@ protected static function newFactory(): SettingDefinitionFactory protected function casts(): array { return [ + 'label' => 'array', + 'description' => 'array', 'rules' => 'array', 'overridable_by' => 'array', 'meta' => 'array', diff --git a/src/Models/SettingHistory.php b/src/Models/SettingHistory.php new file mode 100644 index 0000000..15208c4 --- /dev/null +++ b/src/Models/SettingHistory.php @@ -0,0 +1,206 @@ +create([ + 'store' => $store->value, + 'setting_ref' => $reference, + 'scope' => $subject->scope->value, + 'key' => $subject->key->value, + 'locale' => $subject->locale->value, + 'operation' => $operation->value, + 'old_value' => $before?->payload, + 'new_value' => $after?->payload, + 'old_type' => $before?->type, + 'new_type' => $after?->type, + 'old_encrypted' => $before instanceof Record && $before->encrypted, + 'new_encrypted' => $after instanceof Record && $after->encrypted, + 'version' => ($after ?? $before)->version, + 'causer_type' => $causer->type->value, + 'causer_alias' => $causer->alias, + 'causer_id' => $causer->id, + 'reason' => $reason ?? $causer->context->reason, + 'created_at' => $at, + ]); + } + + /** The highest version in a setting's history, or 0. */ + public static function latestVersion(?string $connection, StoreName $store, Scope $scope, Key $key, Locale $locale): int + { + $version = self::on($connection)->forSetting($store, $scope, $key, $locale)->max('version'); + + return is_numeric($version) ? (int) $version : 0; + } + + /** The entry that produced this version of a setting's value, or null. */ + public static function entryAt(?string $connection, StoreName $store, Scope $scope, Key $key, Locale $locale, int $version): ?HistoryEntry + { + return self::on($connection) + ->forSetting($store, $scope, $key, $locale) + ->where('version', $version) + ->where('operation', '!=', HistoryOperation::Forget->value) + ->orderByDesc('id') + ->first() + ?->toEntry(); + } + + #[Override] + public function getTable(): string + { + return $this->table ?? ModelContext::names()->history(); + } + + /** + * This row as an entry. + * + * @throws DriverFailure when the row is malformed + */ + public function toEntry(): HistoryEntry + { + $row = $this->getAttributes(); + $text = static fn (string $column): ?string => is_string($row[$column] ?? null) ? $row[$column] : null; + $id = $text('id'); + $store = $text('store'); + $scope = $text('scope'); + $key = $text('key'); + $created = $text('created_at'); + $operation = HistoryOperation::tryFrom($text('operation') ?? ''); + $causer = ActorType::tryFrom($text('causer_type') ?? ''); + $version = $row['version'] ?? null; + + if ($id === null || $store === null || $scope === null || $key === null || $created === null || ! $operation instanceof HistoryOperation || ! $causer instanceof ActorType || ! is_numeric($version)) { + throw new DriverFailure(sprintf('History row [%s] is malformed.', $id ?? '?')); + } + + return new HistoryEntry( + id: $id, + store: $store, + settingRef: $text('setting_ref'), + scope: $scope, + key: $key, + locale: $text('locale') ?? '', + operation: $operation, + oldValue: $text('old_value'), + newValue: $text('new_value'), + oldType: $text('old_type'), + newType: $text('new_type'), + oldEncrypted: DatabaseValues::boolean($row['old_encrypted'] ?? false), + newEncrypted: DatabaseValues::boolean($row['new_encrypted'] ?? false), + version: (int) $version, + causerType: $causer, + causerAlias: $text('causer_alias'), + causerId: $text('causer_id'), + reason: $text('reason'), + createdAt: CarbonImmutable::parse($created), + ); + } + + /** + * One setting's trail. + * + * @param Builder $query + * + * @return Builder + */ + public function scopeForSetting(Builder $query, StoreName $store, Scope $scope, Key $key, Locale $locale): Builder + { + return $query->where('store', $store->value) + ->where('scope', $scope->value) + ->where('key', $key->value) + ->where('locale', $locale->value); + } + + /** + * The entries matching a filter, newest version first. + * + * @param Builder $query + * + * @return Builder + */ + public function scopeMatching(Builder $query, HistoryFilter $filter): Builder + { + foreach (['store' => $filter->store?->value, 'scope' => $filter->scope?->value, 'key' => $filter->key?->value, 'locale' => $filter->locale?->value] as $column => $value) { + if ($value !== null) { + $query->where($column, $value); + } + } + + if ($filter->since instanceof CarbonImmutable) { + $query->where('created_at', '>=', $filter->since); + } + + if ($filter->until instanceof CarbonImmutable) { + $query->where('created_at', '<=', $filter->until); + } + + if ($filter->fromVersion !== null) { + $query->where('version', '>=', $filter->fromVersion); + } + + if ($filter->toVersion !== null) { + $query->where('version', '<=', $filter->toVersion); + } + + return $query->orderByDesc('version')->orderByDesc('id'); + } + + /** @return array */ + #[Override] + protected function casts(): array + { + return ['old_encrypted' => 'boolean', 'new_encrypted' => 'boolean', 'version' => 'integer', 'created_at' => 'immutable_datetime']; + } +} diff --git a/src/Models/SettingsModel.php b/src/Models/SettingsModel.php new file mode 100644 index 0000000..00cb7a3 --- /dev/null +++ b/src/Models/SettingsModel.php @@ -0,0 +1,61 @@ +defaultConnectionName(); + } + + /** + * Every tenant's rows, for maintenance that works across tenants. + * + * @param Builder $query + * + * @return Builder + */ + public function scopeAllTenants(Builder $query): Builder + { + return $query->withoutGlobalScope(TenantScope::class); + } + + /** Whether this table has the tenant column in column-mode tenancy. */ + public function usesTenantColumn(): bool + { + return true; + } + + /** JSON columns keep Unicode and slashes readable, as the engine writes them. */ + #[Override] + protected function asJson($value, $flags = 0) + { + return parent::asJson($value, $flags | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + } + + /** The connection used when no query named one: the default store's. */ + protected function defaultConnectionName(): ?string + { + return ModelContext::connectionOf(ModelContext::defaultStore()); + } +} diff --git a/src/Providers/SettingsServiceProvider.php b/src/Providers/SettingsServiceProvider.php index 375f387..0424f1a 100644 --- a/src/Providers/SettingsServiceProvider.php +++ b/src/Providers/SettingsServiceProvider.php @@ -49,8 +49,6 @@ use Simtabi\Laranail\Settings\Typed\TypedSettings; use Illuminate\Cache\Repository as CacheRepository; use Simtabi\Laranail\Settings\Contracts\Authorizer; -use Simtabi\Laranail\Settings\Database\SchemaNames; -use Simtabi\Laranail\Settings\Database\SchemaShape; use Simtabi\Laranail\Settings\Support\ValueEncoder; use Illuminate\Contracts\Encryption\StringEncrypter; use Illuminate\Database\ConnectionResolverInterface; @@ -108,7 +106,6 @@ use Illuminate\Contracts\Notifications\Dispatcher as Notifications; use Simtabi\Laranail\Package\Tools\Providers\PackageServiceProvider; use Simtabi\Laranail\Settings\Services\Tenancy\TenantDiscriminators; -use Simtabi\Laranail\Settings\Services\Database\SchemaShapeRepository; use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; use Simtabi\Laranail\DbTools\Schema\Contracts\SchemaReadinessInterface; use Simtabi\Laranail\Settings\Database\Seeders\DefaultCategoriesSeeder; @@ -172,7 +169,6 @@ public function configurePackage(Package $package): void $command ->startWith(static function (InstallCommand $command): void { self::refuseForeignTables($command); - self::recordSchema($command); }) ->publishConfigFile() ->publishMigrations() @@ -230,14 +226,6 @@ private static function refuseForeignTables(InstallCommand $command): void } } - /** Record the schema the published migrations will produce; an existing record only gains new stores. */ - private static function recordSchema(InstallCommand $command): void - { - $shapes = $command->getLaravel()->make(SchemaShapeRepository::class); - $shapes->record(); - $command->info('Recorded the settings schema in ' . $shapes->path()); - } - /** Copy code and config definitions into the definitions table, when it exists already. */ private static function syncDefinitions(InstallCommand $command): void { @@ -302,7 +290,7 @@ private static function configurationSources(Repository $config): array */ private static function definitionSources(Repository $config): array { - $sources = $config->get('laranail.settings.definitions.sources', ['code', 'config', 'database']); + $sources = $config->get('laranail.settings.definitions.sources', ['code', 'config']); $names = is_array($sources) ? array_values(array_filter($sources, is_string(...))) : null; if ($names === null || count($names) !== count($sources) || array_diff($names, ['code', 'config', 'database']) !== []) { @@ -376,13 +364,12 @@ private function registerTenancy(): void $app = $this->app; ModelContext::use( - static fn (): SchemaShape => $app->make(SchemaShapeRepository::class)->current(), + static fn (): Repository => $app->make(Repository::class), static fn (): ?string => $app->make(TenantDiscriminator::class)->current(), - static fn (): string => $app->make(Repository::class)->string('laranail.settings.default', 'settings'), ); } - /** The driver factory, the recorded schema, installation evidence and the value encrypter. */ + /** The driver factory, installation evidence and the value encrypter. */ private function registerDrivers(): void { // A singleton, so a driver registered with extend() lasts; the scoped services it hands @@ -394,18 +381,10 @@ private function registerDrivers(): void $app->make(RecordSerializer::class), $app->basePath(), $app->make(ConnectionResolverInterface::class), - SchemaNames::fromConfig($app->make(Repository::class)->array('laranail.settings.tables', [])), static fn (): SchemaReadinessInterface => $app->make(SchemaReadinessInterface::class), - static fn (): SchemaShape => $app->make(SchemaShapeRepository::class)->current(), static fn (): ?string => $app->make(TenantDiscriminator::class)->current(), )); - $this->app->scoped(SchemaShapeRepository::class, static function (Application $app): SchemaShapeRepository { - $path = $app->make(Repository::class)->get('laranail.settings.schema.path'); - - return new SchemaShapeRepository($app->make(Filesystem::class), is_string($path) && $path !== '' ? $path : $app->databasePath('settings-schema.php'), $app->make(Repository::class)); - }); - // The operator's flag, or laranail/installer-headless (suggested) reporting an install. $this->app->scoped(InstallationEvidence::class, static function (Application $app): InstallationEvidence { $installer = 'Simtabi\\Laranail\\Installer\\Headless\\Support\\InstallationState'; @@ -460,7 +439,6 @@ static function (string $change) use ($app): void { $app->make(Filesystem::class), dirname(__DIR__, 2) . '/database/migrations/' . MakeStore::MIGRATION . '.php', $app->databasePath('migrations'), - $app->make(SchemaShapeRepository::class), )); } diff --git a/src/Services/Configuration/PersistedConfiguration.php b/src/Services/Configuration/PersistedConfiguration.php index 4ce8884..0d1bf10 100644 --- a/src/Services/Configuration/PersistedConfiguration.php +++ b/src/Services/Configuration/PersistedConfiguration.php @@ -14,7 +14,7 @@ use Simtabi\Laranail\Settings\Support\Json; use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Logging\LogContext; -use Simtabi\Laranail\Settings\Database\SchemaShape; +use Simtabi\Laranail\Settings\Database\SchemaNames; use Illuminate\Database\ConnectionResolverInterface; use Simtabi\Laranail\Settings\Exceptions\DriverFailure; use Simtabi\Laranail\Settings\Logging\OperationalLogger; @@ -23,7 +23,6 @@ use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Services\Drivers\DriverFactory; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; -use Simtabi\Laranail\Settings\Services\Database\SchemaShapeRepository; /** * Store and layer configuration saved in the `settings_stores` table. @@ -47,10 +46,10 @@ final class PersistedConfiguration * @param mixed $enabled `configuration.persisted` * @param array $configStores `laranail.settings.stores` * @param array $configLayers `laranail.settings.layers` + * @param array $tables `laranail.settings.tables` */ public function __construct( private readonly ConnectionResolverInterface $db, - private readonly SchemaShapeRepository $shapes, private readonly DriverFactory $drivers, private readonly OperationalLogger $log, #[Config('laranail.settings.configuration.persisted', false)] @@ -61,11 +60,13 @@ public function __construct( private readonly array $configLayers = [], #[Config('laranail.settings.default', 'settings')] private readonly string $default = 'settings', + #[Config('laranail.settings.tables', [])] + private readonly array $tables = [], ) {} public function isEnabled(): bool { - return filter_var($this->enabled, FILTER_VALIDATE_BOOL) && $this->shape()->storesTable; + return filter_var($this->enabled, FILTER_VALIDATE_BOOL); } /** Changes whenever an entry is saved or deleted so registries rebuild. */ @@ -249,7 +250,7 @@ private function changed(): void private function assertEnabled(): void { if (! $this->isEnabled()) { - throw new InvalidConfiguration('laranail.settings.configuration.persisted: persisted configuration is off (or its table was never migrated); turn it on and run the migration first.'); + throw new InvalidConfiguration('laranail.settings.configuration.persisted: persisted configuration is off; turn it on first.'); } } @@ -261,12 +262,7 @@ private function table(): Builder throw new DriverFailure('The persisted configuration connection is unavailable.', 0, $exception); } - return $connection->table($this->shape()->names->stores()); - } - - private function shape(): SchemaShape - { - return $this->shapes->current(); + return $connection->table(SchemaNames::fromConfig($this->tables)->stores()); } /** The connection of the default store's first database layer. */ diff --git a/src/Services/Database/AuditRepository.php b/src/Services/Database/AuditRepository.php deleted file mode 100644 index 121bd59..0000000 --- a/src/Services/Database/AuditRepository.php +++ /dev/null @@ -1,174 +0,0 @@ -get($store) : $stores->default())->database() ?? $stores->default()->database(); - - return $database instanceof DatabaseDriver ? new self($database) : null; - } - - /** - * Build an entry from one row; a malformed row raises DriverFailure. - * - * @param array $row - */ - public static function entry(array $row): AuditEntry - { - $text = static fn (string $column): ?string => is_string($row[$column] ?? null) ? $row[$column] : null; - $number = static fn (string $column): ?int => is_numeric($row[$column] ?? null) ? (int) $row[$column] : null; - $id = $text('id'); - $occurred = $text('occurred_at'); - $action = AuditAction::tryFrom($text('action') ?? ''); - $outcome = AuditOutcome::tryFrom($text('outcome') ?? ''); - $actorType = ActorType::tryFrom($text('actor_type') ?? ''); - $channel = Channel::tryFrom($text('channel') ?? ''); - - if ($id === null || $occurred === null || ! $action instanceof AuditAction || ! $outcome instanceof AuditOutcome || ! $actorType instanceof ActorType || ! $channel instanceof Channel) { - throw new DriverFailure(sprintf('Audit row [%s] is malformed.', $id ?? '?')); - } - - return new AuditEntry( - id: $id, - occurredAt: CarbonImmutable::parse($occurred), - action: $action, - outcome: $outcome, - store: $text('store'), - scope: $text('scope'), - key: $text('key'), - locale: $text('locale'), - versionFrom: $number('version_from'), - versionTo: $number('version_to'), - actorType: $actorType, - actorAlias: $text('actor_alias'), - actorId: $text('actor_id'), - channel: $channel, - ip: $text('ip'), - userAgent: $text('user_agent'), - requestId: $text('request_id'), - reason: $text('reason'), - meta: self::meta($text('meta')), - ); - } - - public function database(): DatabaseDriver - { - return $this->database; - } - - /** Write one entry. */ - public function insert(AuditEntry $entry): void - { - $this->database->attempt(new StoreName($entry->store ?? 'audit'), fn (): bool => $this->table()->insert([ - 'id' => $entry->id, - 'occurred_at' => $entry->occurredAt, - 'action' => $entry->action->value, - 'outcome' => $entry->outcome->value, - 'store' => $entry->store, - 'scope' => $entry->scope, - 'key' => $entry->key, - 'locale' => $entry->locale, - 'version_from' => $entry->versionFrom, - 'version_to' => $entry->versionTo, - 'change_request' => is_string($entry->meta['change_request'] ?? null) ? $entry->meta['change_request'] : null, - 'actor_type' => $entry->actorType->value, - 'actor_alias' => $entry->actorAlias, - 'actor_id' => $entry->actorId, - 'channel' => $entry->channel->value, - 'ip' => $entry->ip, - 'user_agent' => $entry->userAgent, - 'request_id' => $entry->requestId, - 'reason' => $entry->reason, - 'meta' => $entry->meta === [] ? null : Json::encode($entry->meta, 'An audit entry\'s meta'), - ] + $this->database->tenantColumns())); - } - - /** The current tenant's rows matching a filter, newest first. */ - public function query(AuditFilter $filter): Builder - { - $query = $this->database->scoped($this->table()); - - if ($filter->store instanceof StoreName) { - $query->where('store', $filter->store->value); - } - - foreach (['scope' => $filter->scope?->value, 'key' => $filter->key?->value, 'action' => $filter->action?->value, 'outcome' => $filter->outcome?->value] as $column => $value) { - if ($value !== null) { - $query->where($column, $value); - } - } - - if ($filter->since instanceof CarbonImmutable) { - $query->where('occurred_at', '>=', $filter->since); - } - - if ($filter->until instanceof CarbonImmutable) { - $query->where('occurred_at', '<=', $filter->until); - } - - return $query->orderByDesc('occurred_at')->orderByDesc('id'); - } - - /** Delete every tenant's rows older than the cutoff. */ - public function prune(CarbonImmutable $cutoff, StoreName $store): int - { - return $this->database->attempt($store, fn (): int => $this->table()->where('occurred_at', '<', $cutoff)->delete()); - } - - /** @return array */ - private static function meta(?string $json): array - { - if ($json === null) { - return []; - } - - try { - $decoded = json_decode($json, true, 4, JSON_THROW_ON_ERROR); - } catch (JsonException) { - return []; - } - - $meta = []; - - foreach (is_array($decoded) ? $decoded : [] as $key => $value) { - if (is_scalar($value) || $value === null) { - $meta[(string) $key] = $value; - } - } - - return $meta; - } - - private function table(): Builder - { - return $this->database->connection()->table($this->database->names()->audit()); - } -} diff --git a/src/Services/Database/CategoryRepository.php b/src/Services/Database/CategoryRepository.php deleted file mode 100644 index 58c353d..0000000 --- a/src/Services/Database/CategoryRepository.php +++ /dev/null @@ -1,261 +0,0 @@ -requireDatabase('; categories are kept in the database.'), $store->name); - } - - /** @throws UnknownCategory */ - public function get(CategorySlug $slug): Category - { - foreach ($this->all() as $category) { - if ($category->slug->value === $slug->value) { - return $category; - } - } - - throw $this->unknown($slug); - } - - /** @return list the store's categories, by sort order then slug */ - public function all(): array - { - $rows = $this->database->attempt($this->store, fn (): array => $this->query() - ->orderBy('sort_order') - ->orderBy('slug') - ->get(['id', 'parent_id', 'slug', 'title', 'description', 'icon', 'sort_order', 'is_system']) - ->map(static fn (object $row): array => (array) $row) - ->all()); - - $slugs = []; - - foreach ($rows as $row) { - $slugs[$this->id($row['id'] ?? null)] = $this->string($row['slug'] ?? null); - } - - return array_values(array_map(fn (array $row): Category => new Category( - id: $this->id($row['id'] ?? null), - store: $this->store, - slug: new CategorySlug($this->string($row['slug'] ?? null)), - title: $this->translations()->text($this->string($row['title'] ?? null)), - parent: isset($row['parent_id'], $slugs[$this->id($row['parent_id'])]) ? new CategorySlug($slugs[$this->id($row['parent_id'])]) : null, - description: is_string($row['description'] ?? null) ? $this->translations()->text($row['description']) : null, - icon: is_string($row['icon'] ?? null) ? $row['icon'] : null, - sortOrder: is_numeric($row['sort_order'] ?? null) ? (int) $row['sort_order'] : 0, - system: DatabaseValues::boolean($row['is_system'] ?? false), - titles: $this->translations()->texts($this->string($row['title'] ?? null)), - ), $rows)); - } - - /** - * @throws CategoryStoreMismatch when the parent belongs to another store - * @throws UnknownCategory when the parent does not exist - */ - public function create(NewCategory $category): Category - { - $parent = $category->parent instanceof CategorySlug ? $this->idOf($category->parent) : null; - $now = CarbonImmutable::now(); - $columns = [ - 'parent_id' => $parent, - 'title' => $this->translations()->store($category->title, $category->translations), - 'description' => $this->translations()->storeNullable($category->description), - 'icon' => $category->icon, - 'sort_order' => $category->sortOrder, - 'is_system' => $category->system, - 'updated_at' => $now, - ]; - - // A trashed category of the same slug is restored, not duplicated. - if ($this->softDeletes() && $this->database->attempt($this->store, fn (): int => $this->table() - ->where('store', $this->store->value) - ->where('slug', $category->slug->value) - ->whereNotNull('deleted_at') - ->update($columns + ['deleted_at' => null, 'meta' => null])) > 0) { - return $this->get($category->slug); - } - - $this->database->attempt($this->store, fn (): bool => $this->table()->insert($columns + DatabaseDriver::newId($this->database->shape()->ids) + $this->database->tenantColumns() + [ - 'store' => $this->store->value, - 'slug' => $category->slug->value, - 'created_at' => $now, - ])); - - return $this->get($category->slug); - } - - /** @throws UnknownCategory */ - public function rename(CategorySlug $slug, string $title): void - { - $this->update($slug, ['title' => $this->translations()->store($title, $this->get($slug)->titles)]); - } - - /** - * Move a category under another, or to the top level with null. - * - * @throws CategoryCycle - * @throws CategoryStoreMismatch - * @throws UnknownCategory - */ - public function move(CategorySlug $slug, ?CategorySlug $parent): void - { - $id = $this->idOf($slug); - $parentId = $parent instanceof CategorySlug ? $this->idOf($parent) : null; - - if ($parentId !== null && in_array((string) $id, array_map(strval(...), [$parentId, ...$this->ancestors($parentId)]), true)) { - throw new CategoryCycle(sprintf('Category [%s] in store [%s] cannot move under [%s]: that is itself or one of its descendants.', $slug, $this->store, $parent)); - } - - $this->update($slug, ['parent_id' => $parentId]); - } - - /** - * Delete a category, moving its children to the top level and unlinking its settings. - * - * Unlinks explicitly because SQLite may not enforce the foreign keys. - * - * @throws UnknownCategory - */ - public function delete(CategorySlug $slug, string $valuesTable): void - { - $id = $this->idOf($slug); - - $this->database->attempt($this->store, function () use ($id, $valuesTable): void { - $this->query()->where('parent_id', $id)->update(['parent_id' => null]); - $this->database->connection()->table($valuesTable) - ->where('category_id', $id) - ->where('category_store', $this->store->value) - ->update(['category_id' => null, 'category_store' => null]); - $this->softDeletes() - ? $this->query()->where('id', $id)->update(['deleted_at' => CarbonImmutable::now(), 'parent_id' => null]) - : $this->query()->where('id', $id)->delete(); - }); - } - - private function id(mixed $value): int|string - { - return is_int($value) || is_string($value) ? $value : throw new DriverFailure('A category row has no usable id.'); - } - - private function string(mixed $value): string - { - return is_string($value) ? $value : throw new DriverFailure('A category row is malformed.'); - } - - /** @param array $columns */ - private function update(CategorySlug $slug, array $columns): void - { - $this->idOf($slug); - - $this->database->attempt($this->store, fn (): int => $this->query() - ->where('slug', $slug->value) - ->update($columns + ['updated_at' => CarbonImmutable::now()])); - } - - /** @return list the ids above this one, nearest first */ - private function ancestors(int|string $id): array - { - $ancestors = []; - $current = $id; - - // Bounded, so a cycle already in the data cannot loop forever. - for ($guard = 0; $guard < 10_000; $guard++) { - $parent = $this->database->attempt($this->store, fn (): mixed => $this->query()->where('id', $current)->value('parent_id')); - - if (! is_int($parent) && ! is_string($parent)) { - return $ancestors; - } - - $ancestors[] = $parent; - $current = $parent; - } - - throw new CategoryCycle(sprintf('The categories of store [%s] already contain a cycle; repair them in the database.', $this->store)); - } - - /** - * @throws CategoryStoreMismatch - * @throws UnknownCategory - */ - private function idOf(CategorySlug $slug): int|string - { - $id = $this->database->attempt($this->store, fn (): mixed => $this->query()->where('slug', $slug->value)->value('id')); - - if (is_int($id) || is_string($id)) { - return $id; - } - - throw $this->unknown($slug); - } - - private function unknown(CategorySlug $slug): UnknownCategory|CategoryStoreMismatch - { - $elsewhere = $this->database->attempt($this->store, fn (): mixed => $this->live($this->table())->where('slug', $slug->value)->value('store')); - - return is_string($elsewhere) - ? new CategoryStoreMismatch(sprintf('Category [%s] belongs to store [%s], not [%s].', $slug, $elsewhere, $this->store)) - : new UnknownCategory(sprintf('Store [%s] has no category [%s].', $this->store, $slug)); - } - - /** This store's live (not trashed) categories. */ - private function query(): Builder - { - return $this->live($this->table()->where('store', $this->store->value)); - } - - private function live(Builder $query): Builder - { - return $this->softDeletes() ? $query->whereNull('deleted_at') : $query; - } - - private function softDeletes(): bool - { - return $this->database->shape()->categoriesSoftDeletes; - } - - /** Titles and descriptions as `translations.mode` stores them. */ - private function translations(): Translations - { - return new Translations($this->database->shape()->translations); - } - - /** The categories table, limited to the current tenant. */ - private function table(): Builder - { - return $this->database->scoped($this->database->connection()->table($this->database->names()->categories())); - } -} diff --git a/src/Services/Database/ChangeRequestRepository.php b/src/Services/Database/ChangeRequestRepository.php deleted file mode 100644 index 2ac0dfa..0000000 --- a/src/Services/Database/ChangeRequestRepository.php +++ /dev/null @@ -1,323 +0,0 @@ -database(); - - if (! $database instanceof DatabaseDriver || ! $database->shape()->changeRequestsTable) { - throw new ApprovalUnavailable(sprintf('Store [%s] cannot hold change requests: it needs an active database layer and the change requests table (approvals.table).', $store->name)); - } - - return new self($database); - } - - /** - * Build a request from one row; a malformed row raises DriverFailure. - * - * @param array $row - */ - public static function request(array $row): ChangeRequest - { - $text = static fn (string $column): ?string => is_string($row[$column] ?? null) ? $row[$column] : null; - $time = static fn (string $column): ?CarbonImmutable => $text($column) === null ? null : CarbonImmutable::parse($text($column)); - $id = $text('id'); - $operation = ChangeOperation::tryFrom($text('operation') ?? ''); - $status = ChangeStatus::tryFrom($text('status') ?? ''); - $requester = ActorType::tryFrom($text('requested_by_type') ?? ''); - $base = $row['base_version'] ?? null; - $store = $text('store'); - $scope = $text('scope'); - $key = $text('key'); - - if ($id === null || $store === null || $scope === null || $key === null || ! $operation instanceof ChangeOperation || ! $status instanceof ChangeStatus || ! $requester instanceof ActorType || ! is_numeric($base)) { - throw new DriverFailure(sprintf('Change request row [%s] is malformed.', $id ?? '?')); - } - - $approvals = $text('approvals') === null ? [] : json_decode($text('approvals'), true); - - return new ChangeRequest( - id: $id, - store: $store, - scope: $scope, - key: $key, - locale: $text('locale') ?? '', - operation: $operation, - payload: $text('payload'), - type: $text('type'), - encrypted: DatabaseValues::boolean($row['is_encrypted'] ?? false), - baseVersion: (int) $base, - status: $status, - requestedByType: $requester, - requestedByAlias: $text('requested_by_alias'), - requestedById: $text('requested_by_id'), - approvals: is_array($approvals) ? array_values(array_filter($approvals, is_string(...))) : [], - decidedByType: ActorType::tryFrom($text('decided_by_type') ?? ''), - decidedByAlias: $text('decided_by_alias'), - decidedById: $text('decided_by_id'), - decidedAt: $time('decided_at'), - reason: $text('reason'), - decisionReason: $text('decision_reason'), - expiresAt: $time('expires_at'), - createdAt: $time('created_at'), - ); - } - - /** @throws UnknownChangeRequest */ - public function get(StoreName $store, string $id): ChangeRequest - { - return $this->find($store, $id) ?? throw new UnknownChangeRequest(sprintf('Store [%s] has no change request [%s].', $store, $id)); - } - - public function database(): DatabaseDriver - { - return $this->database; - } - - /** - * Open a request and return it. - * - * @param array{store: string, scope: string, key: string, locale: string, operation: ChangeOperation, payload: ?string, type: ?string, encrypted: bool, base_version: int, reason: ?string, expires_at: ?CarbonImmutable} $request - */ - public function create(array $request, Actor $requester, CarbonImmutable $now): ChangeRequest - { - $id = (string) Str::ulid(); - $store = new StoreName($request['store']); - - $this->database->attempt($store, fn (): bool => $this->table()->insert([ - 'id' => $id, - 'store' => $request['store'], - 'scope' => $request['scope'], - 'key' => $request['key'], - 'locale' => $request['locale'], - 'operation' => $request['operation']->value, - 'payload' => $request['payload'], - 'type' => $request['type'], - 'is_encrypted' => $request['encrypted'], - 'base_version' => $request['base_version'], - 'status' => ChangeStatus::Pending->value, - 'requested_by_type' => $requester->type->value, - 'requested_by_alias' => $requester->alias, - 'requested_by_id' => $requester->id, - 'approvals' => null, - 'reason' => $request['reason'], - 'expires_at' => $request['expires_at'], - 'created_at' => $now, - 'updated_at' => $now, - ] + $this->database->tenantColumns())); - - return $this->find($store, $id) ?? throw new DriverFailure(sprintf('Change request [%s] was not stored.', $id)); - } - - /** The current tenant's request with this id, or null. */ - public function find(StoreName $store, string $id): ?ChangeRequest - { - $row = $this->database->attempt($store, fn (): ?object => $this->database->scoped($this->table())->where('id', $id)->first()); - - return $row === null ? null : self::request((array) $row); - } - - /** - * The current tenant's requests of a filter, newest first. - * - * @return list - */ - public function list(ChangeFilter $filter, int $limit = 100, ?string $after = null): array - { - return $this->database->attempt($filter->store, function () use ($filter, $limit, $after): array { - $query = $this->query($filter); - - if ($after !== null) { - $query->where('id', '<', $after); - } - - return array_values(array_map(static fn (object $row): ChangeRequest => self::request((array) $row), $query->limit($limit)->get()->all())); - }); - } - - /** - * Move a request from one of `$from` to a new status; false when someone else decided it first. - * - * @param list $from - * @param list|null $approvals the approvals so far, when they change - */ - public function transition(ChangeRequest $request, array $from, ChangeStatus $to, ?Actor $decidedBy, ?string $reason, CarbonImmutable $now, ?array $approvals = null): bool - { - $columns = ['status' => $to->value, 'updated_at' => $now]; - - if ($approvals !== null) { - $columns['approvals'] = Json::encode($approvals, 'A change request\'s approvals'); - } - - if ($decidedBy instanceof Actor) { - $columns += [ - 'decided_by_type' => $decidedBy->type->value, - 'decided_by_alias' => $decidedBy->alias, - 'decided_by_id' => $decidedBy->id, - 'decided_at' => $now, - 'decision_reason' => $reason, - ]; - } - - $statuses = array_map(static fn (ChangeStatus $status): string => $status->value, $from); - - return $this->database->attempt(new StoreName($request->store), function () use ($request, $statuses, $columns): bool { - $updated = $this->database->scoped($this->table()) - ->where('id', $request->id) - ->whereIn('status', $statuses) - ->update($columns); - - if ($updated > 0) { - return true; - } - - // MySQL counts changed rows, so an identical update reports 0; that only means a lost - // race when the target status is not one of the allowed ones. - if (! in_array($columns['status'], $statuses, true)) { - return false; - } - - return $this->database->scoped($this->table()) - ->where('id', $request->id) - ->where('status', $columns['status']) - ->exists(); - }); - } - - /** - * Rewrite every tenant's encrypted proposed payloads. - * - * @param Closure(string): ?string $rewrite returns null when it cannot read a payload - * - * @return array{int, int} rewritten and failed counts - */ - public function rewriteEncrypted(StoreName $store, Closure $rewrite): array - { - return $this->database->attempt($store, function () use ($rewrite): array { - $rewritten = 0; - $failed = 0; - - $this->table()->where('is_encrypted', true)->whereNotNull('payload')->select(['id', 'payload'])->chunkById(500, function ($rows) use ($rewrite, &$rewritten, &$failed): void { - foreach ($rows as $row) { - $row = (array) $row; - $new = is_string($row['payload'] ?? null) ? $rewrite($row['payload']) : null; - - if ($new === null) { - $failed++; - - continue; - } - - $rewritten += $this->table()->where('id', $row['id'])->update(['payload' => $new]); - } - }); - - return [$rewritten, $failed]; - }); - } - - /** Rename an owner alias in every tenant's requests. */ - public function rescope(StoreName $store, string $from, string $to): int - { - return $this->database->attempt($store, function () use ($from, $to): int { - $changed = 0; - - foreach ($this->table()->where('scope', '>=', $from . ':')->where('scope', '<', $from . ';')->get(['id', 'scope']) as $row) { - $row = (array) $row; - $scope = is_string($row['scope'] ?? null) ? $row['scope'] : ''; - $changed += $this->table()->where('id', $row['id'])->update(['scope' => $to . substr($scope, strlen($from))]); - } - - return $changed; - }); - } - - /** - * Expire overdue open requests and delete decided ones older than `$cutoff`, for every tenant. - * - * @return array{int, int} expired and deleted counts - */ - public function sweep(CarbonImmutable $now, ?CarbonImmutable $cutoff, StoreName $store): array - { - return $this->database->attempt($store, function () use ($now, $cutoff): array { - $expired = $this->table() - ->whereIn('status', [ChangeStatus::Pending->value, ChangeStatus::Approved->value]) - ->whereNotNull('expires_at') - ->where('expires_at', '<=', $now) - ->update(['status' => ChangeStatus::Expired->value, 'updated_at' => $now]); - - $deleted = $cutoff instanceof CarbonImmutable - ? $this->table() - ->whereNotIn('status', [ChangeStatus::Pending->value, ChangeStatus::Approved->value]) - ->where('updated_at', '<', $cutoff) - ->delete() - : 0; - - return [$expired, $deleted]; - }); - } - - /** How many of the current tenant's open requests are past their expiry. */ - public function overdue(CarbonImmutable $now, StoreName $store): int - { - return $this->database->attempt($store, fn (): int => $this->database->scoped($this->table()) - ->whereIn('status', [ChangeStatus::Pending->value, ChangeStatus::Approved->value]) - ->whereNotNull('expires_at') - ->where('expires_at', '<=', $now) - ->count()); - } - - private function query(ChangeFilter $filter): Builder - { - $query = $this->database->scoped($this->table())->where('store', $filter->store->value); - - foreach (['id' => $filter->id, 'status' => $filter->status?->value, 'scope' => $filter->scope?->value, 'key' => $filter->key?->value] as $column => $value) { - if ($value !== null) { - $query->where($column, $value); - } - } - - return $query->orderByDesc('id'); - } - - private function table(): Builder - { - return $this->database->connection()->table($this->database->names()->changeRequests()); - } -} diff --git a/src/Services/Database/DefinitionsRepository.php b/src/Services/Database/DefinitionsRepository.php deleted file mode 100644 index e3b525c..0000000 --- a/src/Services/Database/DefinitionsRepository.php +++ /dev/null @@ -1,176 +0,0 @@ -> - */ - public function runtimeRows(StoreName $store): array - { - $database = $this->database; - $names = $database->names(); - - return array_values($database->attempt($store, static fn (): array => $database->connection() - ->table($names->definitions() . ' as d') - ->leftJoin($names->categories() . ' as c', 'c.id', '=', 'd.category_id') - ->where('d.store', $store->value) - ->where('d.is_system', false) - ->get(['d.*', 'c.slug as category_slug']) - ->map(static fn (object $row): array => (array) $row) - ->all())); - } - - /** - * Sync a store's code and config definitions as system rows, leaving runtime rows alone. - * - * @param list $definitions - * - * @return array{synced: int, removed: int, conflicts: list} - */ - public function sync(StoreName $store, array $definitions): array - { - $database = $this->database; - $table = static fn () => $database->connection()->table($database->names()->definitions())->where('store', $store->value); - $now = CarbonImmutable::now(); - $translations = new Translations($this->database->shape()->translations); - $synced = 0; - $conflicts = []; - $keys = []; - - foreach ($definitions as $definition) { - $keys[] = $definition->key->value; - $row = $table()->where('key', $definition->key->value)->first(['is_system']); - - if ($row !== null && ! DatabaseValues::boolean($row->is_system ?? false)) { - $conflicts[] = $store->value . '.' . $definition->key->value; - - continue; - } - - $columns = $this->columns($store, $definition, $translations) + ['updated_at' => $now]; - - if ($row === null) { - $table()->insert($columns + DatabaseDriver::newId($this->database->shape()->ids) + [ - 'store' => $store->value, - 'key' => $definition->key->value, - 'is_system' => true, - 'created_at' => $now, - ]); - } else { - $table()->where('key', $definition->key->value)->update($columns); - } - - $synced++; - } - - $removed = $table()->where('is_system', true)->whereNotIn('key', $keys === [] ? [''] : $keys)->delete(); - - return ['synced' => $synced, 'removed' => $removed, 'conflicts' => $conflicts]; - } - - /** - * Save a definition edited through the API as a runtime row. - * - * @throws InvalidDefinition when a system row already defines the key - */ - public function save(StoreName $store, Definition $definition): void - { - $database = $this->database; - $table = static fn () => $database->connection()->table($database->names()->definitions())->where('store', $store->value); - $now = CarbonImmutable::now(); - - $database->attempt($store, function () use ($table, $store, $definition, $now): void { - $row = $table()->where('key', $definition->key->value)->first(['is_system']); - - if ($row !== null && DatabaseValues::boolean($row->is_system ?? false)) { - throw new InvalidDefinition(sprintf('Setting [%s] in store [%s] is defined in code or configuration; change it there.', $definition->key, $store)); - } - - $columns = $this->columns($store, $definition, new Translations($this->database->shape()->translations)) + ['updated_at' => $now]; - - if ($row === null) { - $table()->insert($columns + DatabaseDriver::newId($this->database->shape()->ids) + [ - 'store' => $store->value, - 'key' => $definition->key->value, - 'is_system' => false, - 'created_at' => $now, - ]); - - return; - } - - $table()->where('key', $definition->key->value)->update($columns); - }); - } - - /** Delete a runtime definition row and return whether one was there. */ - public function delete(StoreName $store, Key $key): bool - { - $database = $this->database; - - return $database->attempt($store, static fn (): int => $database->connection()->table($database->names()->definitions()) - ->where('store', $store->value) - ->where('key', $key->value) - ->where('is_system', false) - ->delete()) > 0; - } - - /** @return array */ - private function columns(StoreName $store, Definition $definition, Translations $translations): array - { - $category = null; - - if ($definition->category !== null) { - $categories = $this->database->connection()->table($this->database->names()->categories()); - - // Definitions are shared by every tenant, so they link to the central categories (''). - if ($this->database->shape()->tenancy->hasColumn()) { - $categories->where('tenant', ''); - } - - $category = $categories->where('store', $store->value)->where('slug', $definition->category)->value('id'); - } - - return [ - 'slug' => $definition->key->slug(), - 'group' => $definition->group(), - 'category_id' => is_int($category) || is_string($category) ? $category : null, - 'type' => $definition->type, - // An encrypted setting's default stays in code: the table must not hold a readable copy. - 'default' => $definition->hasDefault && ! $definition->encrypted ? $this->encoder->encode($definition->key, $definition->default) : null, - 'label' => $translations->storeNullable($definition->label), - 'description' => $translations->storeNullable($definition->description), - 'rules' => Json::encode($definition->rules, 'A definition'), - 'is_encrypted' => $definition->encrypted, - 'is_public' => $definition->public, - 'is_locked' => $definition->locked, - 'inherits' => $definition->inherits, - 'overridable_by' => Json::encode($definition->overridableBy, 'A definition'), - ]; - } -} diff --git a/src/Services/Database/HistoryRepository.php b/src/Services/Database/HistoryRepository.php deleted file mode 100644 index a982a5b..0000000 --- a/src/Services/Database/HistoryRepository.php +++ /dev/null @@ -1,300 +0,0 @@ -get($store)->database(); - - return $database instanceof DatabaseDriver && $database->shape()->historyTable ? new self($database) : null; - } - - /** - * Build an entry from one row; a malformed row raises DriverFailure. - * - * @param array $row - */ - public static function entry(array $row): HistoryEntry - { - $text = static fn (string $column): ?string => is_string($row[$column] ?? null) ? $row[$column] : null; - $id = $text('id'); - $store = $text('store'); - $scope = $text('scope'); - $key = $text('key'); - $created = $text('created_at'); - $operation = HistoryOperation::tryFrom($text('operation') ?? ''); - $causer = ActorType::tryFrom($text('causer_type') ?? ''); - $version = $row['version'] ?? null; - - if ($id === null || $store === null || $scope === null || $key === null || $created === null || ! $operation instanceof HistoryOperation || ! $causer instanceof ActorType || ! is_numeric($version)) { - throw new DriverFailure(sprintf('History row [%s] is malformed.', $id ?? '?')); - } - - return new HistoryEntry( - id: $id, - store: $store, - settingRef: $text('setting_ref'), - scope: $scope, - key: $key, - locale: $text('locale') ?? '', - operation: $operation, - oldValue: $text('old_value'), - newValue: $text('new_value'), - oldType: $text('old_type'), - newType: $text('new_type'), - oldEncrypted: DatabaseValues::boolean($row['old_encrypted'] ?? false), - newEncrypted: DatabaseValues::boolean($row['new_encrypted'] ?? false), - version: (int) $version, - causerType: $causer, - causerAlias: $text('causer_alias'), - causerId: $text('causer_id'), - reason: $text('reason'), - createdAt: CarbonImmutable::parse($created), - ); - } - - public function database(): DatabaseDriver - { - return $this->database; - } - - /** Append one entry in the caller's transaction; `$before` is null for a first write, `$after` for a forget. */ - public function record( - StoreName $store, - HistoryOperation $operation, - ?Record $before, - ?Record $after, - int $version, - ?string $reference, - ?Actor $causer, - ?string $reason, - CarbonImmutable $at, - ): void { - $subject = $after ?? $before ?? throw new DriverFailure('A history entry needs the row before or after the change.'); - $causer ??= Actor::system(); - - $this->database->attempt($store, fn (): bool => $this->table()->insert([ - 'id' => (string) Str::ulid(), - 'store' => $store->value, - 'setting_ref' => $reference, - 'scope' => $subject->scope->value, - 'key' => $subject->key->value, - 'locale' => $subject->locale->value, - 'operation' => $operation->value, - 'old_value' => $before?->payload, - 'new_value' => $after?->payload, - 'old_type' => $before?->type, - 'new_type' => $after?->type, - 'old_encrypted' => $before instanceof Record && $before->encrypted, - 'new_encrypted' => $after instanceof Record && $after->encrypted, - 'version' => $version, - 'causer_type' => $causer->type->value, - 'causer_alias' => $causer->alias, - 'causer_id' => $causer->id, - 'reason' => $reason ?? $causer->context->reason, - 'created_at' => $at, - ] + $this->database->tenantColumns())); - } - - /** The highest version in this identity's history, or 0. */ - public function latestVersion(StoreName $store, Scope $scope, Key $key, Locale $locale): int - { - $version = $this->database->attempt($store, fn (): mixed => $this->identity($store, $scope, $key, $locale)->max('version')); - - return is_numeric($version) ? (int) $version : 0; - } - - /** The entry that produced this version of the value, or null. */ - public function find(StoreName $store, Scope $scope, Key $key, Locale $locale, int $version): ?HistoryEntry - { - $row = $this->database->attempt($store, fn (): ?object => $this->identity($store, $scope, $key, $locale) - ->where('version', $version) - ->where('operation', '!=', HistoryOperation::Forget->value) - ->orderByDesc('id') - ->first()); - - return $row === null ? null : self::entry((array) $row); - } - - /** The current tenant's entries matching a filter, newest version first. */ - public function query(HistoryFilter $filter): Builder - { - $query = $this->database->scoped($this->table()); - - foreach (['store' => $filter->store?->value, 'scope' => $filter->scope?->value, 'key' => $filter->key?->value, 'locale' => $filter->locale?->value] as $column => $value) { - if ($value !== null) { - $query->where($column, $value); - } - } - - if ($filter->since instanceof CarbonImmutable) { - $query->where('created_at', '>=', $filter->since); - } - - if ($filter->until instanceof CarbonImmutable) { - $query->where('created_at', '<=', $filter->until); - } - - if ($filter->fromVersion !== null) { - $query->where('version', '>=', $filter->fromVersion); - } - - if ($filter->toVersion !== null) { - $query->where('version', '<=', $filter->toVersion); - } - - return $query->orderByDesc('version')->orderByDesc('id'); - } - - /** Delete entries older than `$cutoff` or more than `$keepVersions` behind, and return how many. */ - public function prune(?CarbonImmutable $cutoff, ?int $keepVersions, StoreName $store): int - { - return $this->database->attempt($store, function () use ($cutoff, $keepVersions): int { - $removed = $cutoff instanceof CarbonImmutable ? $this->table()->where('created_at', '<', $cutoff)->delete() : 0; - - if ($keepVersions === null) { - return $removed; - } - - $tenant = $this->database->shape()->tenancy->hasColumn() ? ['tenant'] : []; - $groups = $this->table() - ->select([...$tenant, 'store', 'scope', 'key', 'locale']) - ->selectRaw('max(version) as newest') - ->groupBy([...$tenant, 'store', 'scope', 'key', 'locale']) - ->get(); - - foreach ($groups as $group) { - $group = (array) $group; - $newest = is_numeric($group['newest'] ?? null) ? (int) $group['newest'] : 0; - - if ($newest - $keepVersions < 1) { - continue; - } - - $query = $this->table()->where('version', '<=', $newest - $keepVersions); - - foreach ([...$tenant, 'store', 'scope', 'key', 'locale'] as $column) { - $query->where($column, $group[$column] ?? null); - } - - $removed += $query->delete(); - } - - return $removed; - }); - } - - /** - * Rewrite every encrypted old and new payload in the history, for every tenant. - * - * @param Closure(string): ?string $rewrite returns null when it cannot read a payload - * - * @return array{int, int} rewritten and failed counts - */ - public function rewriteEncrypted(StoreName $store, Closure $rewrite): array - { - return $this->database->attempt($store, function () use ($rewrite): array { - $rewritten = 0; - $failed = 0; - - $this->table() - ->where(static fn (Builder $query): Builder => $query->where('old_encrypted', true)->orWhere('new_encrypted', true)) - ->select(['id', 'old_value', 'new_value', 'old_encrypted', 'new_encrypted']) - ->chunkById(500, function ($rows) use ($rewrite, &$rewritten, &$failed): void { - foreach ($rows as $row) { - $row = (array) $row; - $columns = []; - - foreach (['old', 'new'] as $side) { - $payload = $row[$side . '_value'] ?? null; - - if (! DatabaseValues::boolean($row[$side . '_encrypted'] ?? false) || ! is_string($payload)) { - continue; - } - - $new = $rewrite($payload); - $new === null ? $failed++ : $columns[$side . '_value'] = $new; - } - - if ($columns !== []) { - $this->table()->where('id', $row['id'])->update($columns); - $rewritten++; - } - } - }); - - return [$rewritten, $failed]; - }); - } - - /** Rename an owner alias in every tenant's history and return how many entries changed. */ - public function rescope(StoreName $store, string $from, string $to): int - { - return $this->database->attempt($store, function () use ($store, $from, $to): int { - $changed = 0; - - $this->table() - ->where('store', $store->value) - ->where('scope', '>=', $from . ':') - ->where('scope', '<', $from . ';') - ->select(['id', 'scope']) - ->chunkById(500, function ($rows) use ($from, $to, &$changed): void { - foreach ($rows as $row) { - $row = (array) $row; - $scope = is_string($row['scope'] ?? null) ? $row['scope'] : ''; - $changed += $this->table()->where('id', $row['id'])->update(['scope' => $to . substr($scope, strlen($from))]); - } - }); - - return $changed; - }); - } - - private function identity(StoreName $store, Scope $scope, Key $key, Locale $locale): Builder - { - return $this->database->scoped($this->table()) - ->where('store', $store->value) - ->where('scope', $scope->value) - ->where('key', $key->value) - ->where('locale', $locale->value); - } - - private function table(): Builder - { - return $this->database->connection()->table($this->database->names()->history()); - } -} diff --git a/src/Services/Database/SchemaShapeRepository.php b/src/Services/Database/SchemaShapeRepository.php deleted file mode 100644 index 856964f..0000000 --- a/src/Services/Database/SchemaShapeRepository.php +++ /dev/null @@ -1,149 +0,0 @@ -path; - } - - public function exists(): bool - { - return $this->files->isFile($this->path); - } - - /** - * The recorded shape, or null when nothing is recorded yet. - * - * @throws InvalidConfiguration when the file does not return a valid shape - */ - public function recorded(): ?SchemaShape - { - if (! $this->exists()) { - return null; - } - - try { - $data = $this->files->getRequire($this->path); - } catch (Throwable $exception) { - throw new InvalidConfiguration(sprintf('The schema file [%s] could not be read: %s', $this->path, $exception->getMessage()), 0, $exception); - } - - return is_array($data) - ? SchemaShape::fromArray($data) - : throw new InvalidConfiguration(sprintf('The schema file [%s] must return an array.', $this->path)); - } - - /** The shape the current configuration describes. */ - public function configured(): SchemaShape - { - $settings = $this->config->get('laranail.settings'); - - return SchemaShape::fromConfig(is_array($settings) ? $settings : [], $this->config->get('laranail.db-tools.id_type')); - } - - /** The recorded shape, else the configured one. */ - public function current(): SchemaShape - { - return $this->current ??= $this->recorded() ?? $this->configured(); - } - - /** - * Record the configured shape, keeping anything already recorded. - * - * Recorded entries describe tables that may already exist, so only new stores are added. - */ - public function record(): SchemaShape - { - $recorded = $this->recorded(); - $configured = $this->configured(); - $shape = $recorded ?? $configured; - - foreach ($configured->stores as $store) { - $shape = $shape->withStore($store); - } - - $this->write($shape); - - return $shape; - } - - /** Record one more store, keeping the rest of the file. */ - public function recordStore(StoreSchema $store): SchemaShape - { - $shape = ($this->recorded() ?? $this->configured())->withStore($store); - $this->write($shape); - - return $shape; - } - - public function write(SchemaShape $shape): void - { - $this->files->ensureDirectoryExists(dirname($this->path)); - $this->files->put($this->path, $this->render($shape)); - $this->current = $shape; - } - - private function render(SchemaShape $shape): string - { - return <<export($shape->toArray(), 0)}; - - PHP; - } - - /** var_export with short arrays and stable indentation. */ - private function export(mixed $value, int $depth): string - { - if (! is_array($value)) { - return var_export($value, true); - } - - if ($value === []) { - return '[]'; - } - - $indent = str_repeat(' ', $depth + 1); - $lines = []; - - foreach ($value as $key => $item) { - $lines[] = $indent . var_export($key, true) . ' => ' . $this->export($item, $depth + 1) . ','; - } - - return "[\n" . implode("\n", $lines) . "\n" . str_repeat(' ', $depth) . ']'; - } -} diff --git a/src/Services/Definitions/DatabaseDefinitions.php b/src/Services/Definitions/DatabaseDefinitions.php index baf8e71..7c81281 100644 --- a/src/Services/Definitions/DatabaseDefinitions.php +++ b/src/Services/Definitions/DatabaseDefinitions.php @@ -6,15 +6,13 @@ use Simtabi\Laranail\Settings\Data\Key; use Simtabi\Laranail\Settings\Stores\Store; -use Simtabi\Laranail\Settings\Support\Json; use Simtabi\Laranail\Settings\Data\Definition; use Simtabi\Laranail\Settings\Support\Translations; use Simtabi\Laranail\Settings\Support\ValueEncoder; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; -use Simtabi\Laranail\Settings\Support\DatabaseValues; +use Simtabi\Laranail\Settings\Models\SettingDefinition; use Simtabi\Laranail\Settings\Exceptions\InvalidDefinition; use Simtabi\Laranail\Settings\Services\Casting\CasterRegistry; -use Simtabi\Laranail\Settings\Services\Database\DefinitionsRepository; /** * The `database` definition source: runtime rows of the definitions table. @@ -46,7 +44,7 @@ public function all(Store $store): array { $database = $store->database(); - if (! $this->enabled || ! $database instanceof DatabaseDriver || ! $database->shape()->definitionsTable) { + if (! $this->enabled || ! $database instanceof DatabaseDriver) { return []; } @@ -61,7 +59,7 @@ public function find(Store $store, Key $key): ?Definition $database = $store->database(); - if (! $database instanceof DatabaseDriver || ! $database->shape()->definitionsTable) { + if (! $database instanceof DatabaseDriver) { return null; } @@ -71,32 +69,32 @@ public function find(Store $store, Key $key): ?Definition /** @return array */ private function load(Store $store, DatabaseDriver $database): array { - $rows = new DefinitionsRepository($database, $this->encoder)->runtimeRows($store->name); - $translations = new Translations($database->shape()->translations); + $rows = $database->attempt($store->name, static fn (): array => SettingDefinition::on($database->connectionName()) + ->with('category') + ->forStore($store->name) + ->runtime() + ->get() + ->all()); $definitions = []; foreach ($rows as $row) { - $definition = $this->definition($store, $row, $translations); + $definition = $this->definition($store, $row); $definitions[$definition->key->value] = $definition; } return $definitions; } - /** @param array $row */ - private function definition(Store $store, array $row, Translations $translations): Definition + private function definition(Store $store, SettingDefinition $row): Definition { - $text = static fn (string $column): ?string => is_string($row[$column] ?? null) && $row[$column] !== '' ? $row[$column] : null; - $flag = static fn (string $column): bool => DatabaseValues::boolean($row[$column] ?? false); - $key = new Key($text('key') ?? throw new InvalidDefinition('A definitions row has no key.')); - $type = $text('type'); + $key = new Key($row->key); + $type = $row->type === '' ? null : $row->type; if ($type !== null && ! $this->casters->has($type)) { throw new InvalidDefinition(sprintf('Definitions table: setting [%s] uses unknown type [%s]; register a caster for it.', $key, $type)); } - $default = $text('default'); - $inherits = $row['inherits'] ?? null; + $default = $row->default === '' ? null : $row->default; return new Definition( store: $store->name, @@ -104,24 +102,28 @@ private function definition(Store $store, array $row, Translations $translations type: $type, default: $default === null ? null : $this->encoder->decode($key, $default), hasDefault: $default !== null, - rules: $this->rules($text('rules')), - encrypted: $flag('is_encrypted'), - public: $flag('is_public'), - locked: $flag('is_locked'), - inherits: $inherits === null ? null : DatabaseValues::boolean($inherits), - overridableBy: Json::strings($text('overridable_by')), - label: $translations->nullableText($text('label')), - description: $translations->nullableText($text('description')), - category: $text('category_slug'), - group: $text('group'), + rules: $this->rules($row->rules ?? []), + encrypted: $row->is_encrypted, + public: $row->is_public, + locked: $row->is_locked, + inherits: $row->inherits, + overridableBy: array_values(array_filter($row->overridable_by ?? [], is_string(...))), + label: Translations::text($row->label), + description: Translations::text($row->description), + category: $row->category?->slug, + group: $row->group === '' ? null : $row->group, ); } - /** @return list the stored rules whose name is allowed */ - private function rules(?string $json): array + /** + * @param array $rules + * + * @return list the stored rules whose name is allowed + */ + private function rules(array $rules): array { return array_values(array_filter( - Json::strings($json), + array_values(array_filter($rules, is_string(...))), fn (string $rule): bool => in_array(explode(':', $rule, 2)[0], $this->allowedRules, true), )); } diff --git a/src/Services/Definitions/DefinitionRegistry.php b/src/Services/Definitions/DefinitionRegistry.php index 9ee1757..bac2dd0 100644 --- a/src/Services/Definitions/DefinitionRegistry.php +++ b/src/Services/Definitions/DefinitionRegistry.php @@ -17,7 +17,10 @@ */ final class DefinitionRegistry { - /** Names under `laranail.settings.definitions` that are options, not setting keys. */ + /** + * Names under `laranail.settings.definitions` that are options, not setting keys. `table` is + * no longer an option; it stays so an older config file never defines a setting named `table`. + */ public const array OPTIONS = ['table', 'sources', 'allowed_rules']; /** @var array */ diff --git a/src/Services/Drivers/DriverFactory.php b/src/Services/Drivers/DriverFactory.php index 10b96dc..1763304 100644 --- a/src/Services/Drivers/DriverFactory.php +++ b/src/Services/Drivers/DriverFactory.php @@ -6,14 +6,15 @@ use Closure; use Illuminate\Contracts\Config\Repository; +use Simtabi\Laranail\Settings\Enums\IdType; use Simtabi\Laranail\Settings\Contracts\Driver; use Simtabi\Laranail\Settings\Data\LayerConfig; use Simtabi\Laranail\Settings\Enums\DriverType; use Simtabi\Laranail\Settings\Drivers\PhpDriver; +use Simtabi\Laranail\Settings\Enums\TenancyMode; use Simtabi\Laranail\Settings\Drivers\JsonDriver; use Simtabi\Laranail\Settings\Drivers\ArrayDriver; use Simtabi\Laranail\Settings\Database\SchemaNames; -use Simtabi\Laranail\Settings\Database\SchemaShape; use Simtabi\Laranail\Settings\Drivers\ConfigDriver; use Illuminate\Database\ConnectionResolverInterface; use Illuminate\Contracts\Filesystem\Factory as Disks; @@ -38,9 +39,7 @@ public function __construct( private readonly RecordSerializer $serializer, private readonly string $basePath, private readonly ?ConnectionResolverInterface $db = null, - private readonly SchemaNames $names = new SchemaNames, private readonly ?Closure $probe = null, - private readonly ?Closure $shape = null, private readonly ?Closure $tenant = null, ) {} @@ -116,13 +115,31 @@ private function database(LayerConfig $layer): DatabaseDriver /** @var Closure(): SchemaReadinessInterface $probe */ $probe = $this->probe; - /** @var (Closure(): SchemaShape)|null $shape */ - $shape = $this->shape; - /** @var (Closure(): ?string)|null $tenant */ $tenant = $this->tenant; + $owner = $layer->option('owner'); + + return new DatabaseDriver( + db: $this->db, + connection: $connection, + table: $table, + writable: $layer->writable, + probe: $probe, + tenantColumn: TenancyMode::fromConfig($this->config->get('laranail.settings.tenancy.mode'))->hasColumn(), + tenant: $tenant, + softDeletes: $layer->option('soft_deletes') === true, + ownerAlias: is_array($owner) && is_string($owner['alias'] ?? null) ? $owner['alias'] : null, + ownerKeyType: is_array($owner) ? $this->ownerKeyType($owner['type'] ?? null) : IdType::Bigint, + fallback: is_array($owner) && is_string($owner['fallback'] ?? null) ? $owner['fallback'] : null, + ); + } + + /** A dedicated store's owner key type; unset, it follows `laranail.db-tools.id_type`. */ + private function ownerKeyType(mixed $type): IdType + { + $type ??= $this->config->get('laranail.db-tools.id_type'); - return new DatabaseDriver($this->db, $connection, $this->names, $table, $layer->writable, $probe, $shape, $tenant); + return (is_string($type) ? IdType::parse($type) : null) ?? IdType::Bigint; } private function json(LayerConfig $layer): JsonDriver diff --git a/src/Services/Stores/SettingWriter.php b/src/Services/Stores/SettingWriter.php index 3979e2f..8a0fb14 100644 --- a/src/Services/Stores/SettingWriter.php +++ b/src/Services/Stores/SettingWriter.php @@ -20,6 +20,7 @@ use Simtabi\Laranail\Settings\Events\SettingSaved; use Simtabi\Laranail\Settings\Events\SettingLocked; use Simtabi\Laranail\Settings\Events\SettingSaving; +use Simtabi\Laranail\Settings\Models\SettingHistory; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Enums\HistoryOperation; use Simtabi\Laranail\Settings\Events\SettingUnlocked; @@ -33,7 +34,6 @@ use Simtabi\Laranail\Settings\Services\Values\ValuePipeline; use Simtabi\Laranail\Settings\Exceptions\InvalidSettingValue; use Simtabi\Laranail\Settings\Exceptions\ConcurrentModification; -use Simtabi\Laranail\Settings\Services\Database\HistoryRepository; /** * Every write path: set, forget, lock and unlock. @@ -194,36 +194,36 @@ private function baseVersion(Layer $layer, Store $store, Scope $scope, Key $key, return $existing->version; } - $trashed = $this->database($layer)?->trashedVersion($store->name, $scope, $key, $locale) ?? 0; + $database = $this->database($layer); + + if (! $database instanceof DatabaseDriver) { + return 0; + } - return max($trashed, $this->history($layer)?->latestVersion($store->name, $scope, $key, $locale) ?? 0); + $trashed = $database->trashedVersion($store->name, $scope, $key, $locale); + $history = $database->attempt($store->name, static fn (): int => SettingHistory::latestVersion($database->connectionName(), $store->name, $scope, $key, $locale)); + + return max($trashed, $history); } /** Store a record and its history entry in one transaction. */ private function persist(Store $store, Layer $layer, HistoryOperation $operation, ?Record $before, Record $after): void { - $history = $this->history($layer); + $database = $this->database($layer); - if (! $history instanceof HistoryRepository) { + if (! $database instanceof DatabaseDriver) { $layer->driver->put($store->name, $after); return; } - $history->database()->transaction(function () use ($store, $layer, $history, $operation, $before, $after): void { + $database->transaction(function () use ($store, $layer, $database, $operation, $before, $after): void { $layer->driver->put($store->name, $after); - $history->record($store->name, $operation, $before, $after, $after->version, $history->database()->reference($store->name, $after->scope, $after->key, $after->locale), $this->causer, $this->reason, $this->clock->now()); + $reference = $database->reference($store->name, $after->scope, $after->key, $after->locale); + $database->attempt($store->name, fn (): SettingHistory => SettingHistory::record($database->connectionName(), $store->name, $operation, $before, $after, $reference, $this->causer, $this->reason, $this->clock->now())); }, $store->name); } - /** The history table of the layer's database, when the recorded schema has one. */ - private function history(Layer $layer): ?HistoryRepository - { - $database = $this->database($layer); - - return $database instanceof DatabaseDriver && $database->shape()->historyTable ? new HistoryRepository($database) : null; - } - private function database(Layer $layer): ?DatabaseDriver { return $layer->driver instanceof DatabaseBacked && $layer->driver->isActive() ? $layer->driver->database() : null; @@ -242,14 +242,14 @@ private function remove(Store $store, Key $key, Locale $locale, ?OwnerRef $owner } $this->events->dispatch(new SettingForgetting($store->name->value, $scope->value, $key->value, $locale->value, $existing->version)); - $history = $this->history($layer); + $database = $this->database($layer); - if ($history instanceof HistoryRepository) { + if ($database instanceof DatabaseDriver) { // A tombstone: the version that was removed, no new value. The next write continues after it. - $history->database()->transaction(function () use ($store, $layer, $history, $scope, $key, $locale, $existing): void { - $reference = $history->database()->reference($store->name, $scope, $key, $locale); + $database->transaction(function () use ($store, $layer, $database, $scope, $key, $locale, $existing): void { + $reference = $database->reference($store->name, $scope, $key, $locale); $layer->driver->forget($store->name, $scope, $key, $locale); - $history->record($store->name, HistoryOperation::Forget, $existing, null, $existing->version, $reference, $this->causer, $this->reason, $this->clock->now()); + $database->attempt($store->name, fn (): SettingHistory => SettingHistory::record($database->connectionName(), $store->name, HistoryOperation::Forget, $existing, null, $reference, $this->causer, $this->reason, $this->clock->now())); }, $store->name); } else { $layer->driver->forget($store->name, $scope, $key, $locale); diff --git a/src/Services/Stores/StoreRegistry.php b/src/Services/Stores/StoreRegistry.php index f982c71..5db0eb8 100644 --- a/src/Services/Stores/StoreRegistry.php +++ b/src/Services/Stores/StoreRegistry.php @@ -10,12 +10,12 @@ use Simtabi\Laranail\Settings\Stores\Layer; use Simtabi\Laranail\Settings\Stores\Store; use Simtabi\Laranail\Settings\Data\StoreName; +use Simtabi\Laranail\Settings\Enums\StoreMode; use Simtabi\Laranail\Settings\Contracts\Driver; use Simtabi\Laranail\Settings\Data\LayerConfig; use Simtabi\Laranail\Settings\Enums\DriverType; use Simtabi\Laranail\Settings\Events\LayerSkipped; use Simtabi\Laranail\Settings\Database\SchemaNames; -use Simtabi\Laranail\Settings\Database\StoreSchema; use Simtabi\Laranail\Settings\Drivers\CachingDriver; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Exceptions\UnknownStore; @@ -93,6 +93,12 @@ public function globalOf(Store $store): Store return $store->fallback instanceof StoreName ? $this->get($store->fallback) : $store; } + /** The database layer holding a store's audit trail: its own, else the default store's, else null. */ + public function auditDatabase(?StoreName $store): ?DatabaseDriver + { + return ($store instanceof StoreName ? $this->get($store) : $this->default())->database() ?? $this->default()->database(); + } + /** The one store whose owners include this alias. */ public function forOwner(string $alias): Store { @@ -164,20 +170,28 @@ private function build(): array } $bootstrap = ($config['bootstrap'] ?? false) === true; - $schema = StoreSchema::fromConfig($storeName, $config, null, IdType::Bigint, new StoreName($this->default)); + $softDeletes = $config['soft_deletes'] ?? false; + + if (! is_bool($softDeletes)) { + throw new InvalidConfiguration($path . '.soft_deletes: true or false.'); + } + + $owner = $this->dedicatedOwner($config, $storeName, $path); + $options = ['table' => $table, 'soft_deletes' => $softDeletes, 'owner' => $owner]; $built[$storeName->value] = new Store( name: $storeName, - layers: array_map(fn (string $layer): Layer => $this->storeLayer($layer, $path, $storeName, $table, $bootstrap), $layerNames), + layers: array_map(fn (string $layer): Layer => $this->storeLayer($layer, $path, $storeName, $options, $bootstrap), $layerNames), owners: $owners, strict: ($config['strict'] ?? false) === true, inherits: ($config['inherits'] ?? false) === true, locksOverridable: $this->locksOverridable($config['locks'] ?? [], $path . '.locks'), bootstrap: $bootstrap, table: $table, - mode: $schema->mode, - fallback: $schema->fallback, + mode: $owner === null ? StoreMode::Polymorphic : StoreMode::Dedicated, + fallback: $owner === null ? null : new StoreName($owner['fallback']), approvalKeys: $this->approvalKeys($config['approvals'] ?? [], $path . '.approvals'), + softDeletes: $softDeletes, ); } @@ -199,9 +213,10 @@ private function build(): array * * The cache wraps the gate, so a skipped layer is never cached. */ - private function storeLayer(string $name, string $storePath, StoreName $store, ?string $table, bool $bootstrap): Layer + /** @param array $options the store's table, soft deletes and dedicated owner, for a database layer */ + private function storeLayer(string $name, string $storePath, StoreName $store, array $options, bool $bootstrap): Layer { - $layer = $this->gatedLayer($this->layer($name, $storePath, $table === null ? [] : ['table' => $table]), $store, $bootstrap); + $layer = $this->gatedLayer($this->layer($name, $storePath, array_filter($options, static fn (mixed $value): bool => $value !== null)), $store, $bootstrap); return $this->cache instanceof SettingsCache && $layer->driver instanceof DatabaseBacked ? new Layer($layer->name, new CachingDriver($layer->driver, $this->cache), $layer->type) @@ -280,6 +295,61 @@ private function driverFactory(): DriverFactory return $this->runtime instanceof RuntimeConfiguration ? $this->drivers->withExtensions($this->runtime->drivers()) : $this->drivers; } + /** + * The owner of a dedicated store, or null for a polymorphic one. + * + * @param array $config + * + * @return array{alias: string, table: string, key: string, type: ?string, fallback: string}|null + */ + private function dedicatedOwner(array $config, StoreName $store, string $path): ?array + { + $mode = $config['mode'] ?? StoreMode::Polymorphic->value; + $mode = is_string($mode) ? StoreMode::tryFrom($mode) : null; + + if (! $mode instanceof StoreMode) { + throw new InvalidConfiguration($path . '.mode: use [polymorphic] or [dedicated].'); + } + + if ($mode === StoreMode::Polymorphic) { + return null; + } + + $owners = $config['owners'] ?? []; + + if (! is_array($owners) || count($owners) !== 1 || ! is_string($owners[array_key_first($owners)])) { + throw new InvalidConfiguration($path . '.owners: a dedicated store holds exactly one owner alias.'); + } + + $owner = $config['owner'] ?? []; + + if (! is_array($owner) || ! is_string($owner['table'] ?? null)) { + throw new InvalidConfiguration($path . '.owner.table: a dedicated store names the table its owners live in.'); + } + + SchemaNames::assertTable($owner['table'], $path . '.owner.table'); + $key = $owner['key'] ?? 'id'; + $type = $owner['type'] ?? null; + + if (! is_string($key) || preg_match('/^[a-z_][a-z0-9_]{0,63}$/', $key) !== 1 || ($type !== null && (! is_string($type) || ! IdType::parse($type) instanceof IdType))) { + throw new InvalidConfiguration($path . '.owner: `key` is a column name and `type` one of bigint, uuid, ulid.'); + } + + $fallback = $config['fallback'] ?? $this->default; + + try { + $fallback = new StoreName(is_string($fallback) ? $fallback : ''); + } catch (InvalidIdentifier $exception) { + throw new InvalidConfiguration($path . '.fallback: ' . $exception->getMessage(), 0, $exception); + } + + if ($fallback->value === $store->value) { + throw new InvalidConfiguration($path . '.fallback: a dedicated store has no global rows, so its fallback must be another store.'); + } + + return ['alias' => $owners[array_key_first($owners)], 'table' => $owner['table'], 'key' => $key, 'type' => $type, 'fallback' => $fallback->value]; + } + private function locksOverridable(mixed $locks, string $path): bool { if (! is_array($locks)) { diff --git a/src/Services/Transfer/StoreSnapshots.php b/src/Services/Transfer/StoreSnapshots.php index 18424e8..90d0918 100644 --- a/src/Services/Transfer/StoreSnapshots.php +++ b/src/Services/Transfer/StoreSnapshots.php @@ -8,15 +8,16 @@ use Simtabi\Laranail\Settings\Data\Scope; use Simtabi\Laranail\Settings\Data\Record; use Simtabi\Laranail\Settings\Stores\Store; +use Simtabi\Laranail\Settings\Data\Category; use Simtabi\Laranail\Settings\Enums\ExportMode; use Simtabi\Laranail\Settings\Support\ValueEncoder; +use Simtabi\Laranail\Settings\Models\SettingCategory; use Simtabi\Laranail\Settings\Data\Transfer\StoreDiff; use Simtabi\Laranail\Settings\Exceptions\StoreNotWritable; use Simtabi\Laranail\Settings\Data\Transfer\ExportDocument; use Simtabi\Laranail\Settings\Data\Transfer\ExportedSetting; use Simtabi\Laranail\Settings\Support\LaravelValueEncrypter; use Simtabi\Laranail\Settings\Data\Transfer\ExportedCategory; -use Simtabi\Laranail\Settings\Services\Database\CategoryRepository; /** * Exports a store's current-tenant rows to an {@see ExportDocument} and compares a store with one. @@ -56,7 +57,7 @@ public function export(Store $store, ExportMode $mode): ExportDocument return new ExportDocument( $store->name->value, - array_map(ExportedCategory::of(...), CategoryRepository::of($store)->all()), + array_map(ExportedCategory::of(...), $this->categories($store)), $settings, $mode, CarbonImmutable::now()->toIso8601String(), @@ -123,4 +124,16 @@ private function setting(Record $record, ExportMode $mode): ExportedSetting ExportMode::Plaintext => $make($this->encoder->decode($record->key, $this->encrypter->decrypt($record->payload))), }; } + + /** + * The store's categories, from its database layer. + * + * @return list + */ + private function categories(Store $store): array + { + $database = $store->requireDatabase('; categories are kept in the database.'); + + return $database->attempt($store->name, static fn (): array => SettingCategory::listFor($database->connectionName(), $store->name)); + } } diff --git a/src/Stores/Store.php b/src/Stores/Store.php index 4d1b259..e33b814 100644 --- a/src/Stores/Store.php +++ b/src/Stores/Store.php @@ -14,6 +14,7 @@ use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Contracts\DatabaseBacked; use Simtabi\Laranail\Settings\Exceptions\StoreNotWritable; +use Simtabi\Laranail\Settings\Exceptions\ApprovalUnavailable; /** * A configured store: its layers in read order, the owner aliases it accepts, and its policies. @@ -37,6 +38,7 @@ public function __construct( public StoreMode $mode = StoreMode::Polymorphic, public ?StoreName $fallback = null, public array $approvalKeys = [], + public bool $softDeletes = false, ) {} /** Whether a write of this key becomes a change request. */ @@ -45,10 +47,20 @@ public function requiresApproval(Key $key): bool return array_any($this->approvalKeys, static fn (string $glob): bool => fnmatch($glob, $key->value, FNM_NOESCAPE)); } - /** Whether this store has an active database layer with a change requests table. */ + /** Whether this store has an active database layer, which holds its change requests. */ public function acceptsChangeRequests(): bool { - return $this->database()?->shape()->changeRequestsTable ?? false; + return $this->database() instanceof DatabaseDriver; + } + + /** + * The database layer that holds this store's change requests. + * + * @throws ApprovalUnavailable when the store has no active database layer + */ + public function changeRequestsDatabase(): DatabaseDriver + { + return $this->database() ?? throw new ApprovalUnavailable(sprintf('Store [%s] cannot hold change requests: it needs an active database layer.', $this->name)); } public function isDedicated(): bool diff --git a/src/Support/Translations.php b/src/Support/Translations.php index 7e32380..289d7e8 100644 --- a/src/Support/Translations.php +++ b/src/Support/Translations.php @@ -4,81 +4,61 @@ namespace Simtabi\Laranail\Settings\Support; -use Simtabi\Laranail\Settings\Enums\TranslationsMode; - /** - * Reads and writes titles, labels and descriptions per `translations.mode`: plain text, or a JSON - * map of locale to text where `''` applies to any locale. + * Titles, labels and descriptions are stored as JSON maps of locale to text, where `''` is the + * text for any locale. */ final readonly class Translations { - public function __construct( - private TranslationsMode $mode, - ) {} - - public function isJson(): bool - { - return $this->mode === TranslationsMode::Json; - } - /** - * The text as the column holds it. + * The map to store for a text and its translations. * - * @param array $translations locale => text, used in json mode + * @param array $translations locale => text + * + * @return array */ - public function store(string $text, array $translations = []): string + public static function of(string $text, array $translations = []): array { - return $this->isJson() ? Json::encode(['' => $text] + $translations, 'A title or description') : $text; + return ['' => $text] + $translations; } - /** {@see store()} for a nullable column: null stays null. */ - public function storeNullable(?string $text): ?string + /** + * {@see of()} for a nullable column: null stays null. + * + * @return array|null + */ + public static function ofNullable(?string $text): ?array { - return $text === null ? null : $this->store($text); + return $text === null ? null : self::of($text); } - /** The text for any locale: the `''` entry, else the first text, else the stored value as is. */ - public function text(string $stored): string + /** The text for any locale: the `''` entry, else the first text; null when there is none. */ + public static function text(mixed $stored): ?string { - $texts = $this->texts($stored); - - if (isset($texts[''])) { - return $texts['']; - } - - foreach ($texts as $text) { - return $text; - } - - return $stored; - } + $texts = self::texts($stored); - /** {@see text()} for a nullable column: null stays null. */ - public function nullableText(?string $stored): ?string - { - return $stored === null ? null : $this->text($stored); + return $texts[''] ?? ($texts === [] ? null : reset($texts)); } /** - * Every text by locale; `['' => stored]` when the value is not a JSON map of texts. + * Every text by locale. A plain string reads as the text for any locale. * * @return array */ - public function texts(string $stored): array + public static function texts(mixed $stored): array { - if (! $this->isJson()) { + if (is_string($stored)) { return ['' => $stored]; } - $decoded = json_decode($stored, true); $texts = []; - foreach (is_array($decoded) ? $decoded : [] as $locale => $text) { + foreach (is_array($stored) ? $stored : [] as $locale => $text) { if (is_string($text)) { $texts[(string) $locale] = $text; } } - return $texts === [] ? ['' => $stored] : $texts; + return $texts; } } diff --git a/tests/Arch/ArchitectureTest.php b/tests/Arch/ArchitectureTest.php index 2962bc0..c2dda8d 100644 --- a/tests/Arch/ArchitectureTest.php +++ b/tests/Arch/ArchitectureTest.php @@ -7,6 +7,7 @@ use Simtabi\Laranail\Settings\Actions\SetSetting; use Simtabi\Laranail\Settings\Actions\LockSetting; use Simtabi\Laranail\Settings\Typed\TypedSettings; +use Simtabi\Laranail\Settings\Models\SettingsModel; use Simtabi\Laranail\Settings\Actions\ForgetSetting; use Simtabi\Laranail\Settings\Actions\UnlockSetting; use Simtabi\Laranail\Settings\Typed\SettingsMigration; @@ -31,6 +32,8 @@ // Bases applications extend: a typed settings class, a settings migration. TypedSettings::class, SettingsMigration::class, + // The models' shared base. + SettingsModel::class, ]); arch('nothing outside Providers and Facades reaches into the container') @@ -94,7 +97,7 @@ }; // A scan that inspects nothing has broken, not found a clean tree. - expect($inspected)->toBeGreaterThanOrEqual(355) + expect($inspected)->toBeGreaterThanOrEqual(354) ->and($offending)->toBe([]) ->and($files($root . '/resources/views'))->toBe(['mail/alert.blade.php']) ->and($files($root . '/resources/assets'))->toBe(['.gitkeep']); diff --git a/tests/Arch/LayeringTest.php b/tests/Arch/LayeringTest.php index c30c4e5..f5886f5 100644 --- a/tests/Arch/LayeringTest.php +++ b/tests/Arch/LayeringTest.php @@ -92,7 +92,7 @@ function classOf(string $path): string } } - expect(count($files))->toBeGreaterThanOrEqual(355) + expect(count($files))->toBeGreaterThanOrEqual(354) ->and($offenders)->toBe([]); }); diff --git a/tests/Arch/ServicesTest.php b/tests/Arch/ServicesTest.php index 2c693cc..1a50b18 100644 --- a/tests/Arch/ServicesTest.php +++ b/tests/Arch/ServicesTest.php @@ -21,13 +21,9 @@ TenantDiscriminator::class, Importer::class, ]; -/** The 19 classes moved into Services\ in 0.1, whose old names were removed: old name => new name. */ +/** The 15 classes moved into Services\ in 0.1 that still exist, whose old names were removed: old name => new name. */ const MOVED_SERVICES = [ - 'Database\\AuditRepository' => 'Services\\Database\\AuditRepository', - 'Database\\CategoryRepository' => 'Services\\Database\\CategoryRepository', - 'Database\\DefinitionsRepository' => 'Services\\Database\\DefinitionsRepository', 'Database\\SchemaInspector' => 'Services\\Database\\SchemaInspector', - 'Database\\SchemaShapeRepository' => 'Services\\Database\\SchemaShapeRepository', 'Stores\\SettingWriter' => 'Services\\Stores\\SettingWriter', 'Stores\\StoreRegistry' => 'Services\\Stores\\StoreRegistry', 'Resolution\\Resolver' => 'Services\\Resolution\\Resolver', @@ -75,11 +71,11 @@ function servicesSources(): array } } - expect(count($services))->toBeGreaterThanOrEqual(25) + expect(count($services))->toBeGreaterThanOrEqual(21) ->and($offenders)->toBe([]); }); -it('files every repository and registry under Services', function (): void { +it('files every registry under Services', function (): void { $files = servicesSources(); $offenders = array_keys(array_filter( $files, @@ -93,8 +89,8 @@ function servicesSources(): array )); // The positive control: the scan does find the repositories and registries that exist. - expect(count($files))->toBeGreaterThanOrEqual(355) - ->and(count($found))->toBeGreaterThanOrEqual(9) + expect(count($files))->toBeGreaterThanOrEqual(354) + ->and(count($found))->toBeGreaterThanOrEqual(3) ->and($offenders)->toBe([]); }); @@ -102,7 +98,7 @@ function servicesSources(): array $base = 'Simtabi\\Laranail\\Settings\\'; $root = dirname(__DIR__, 2); - expect(count(MOVED_SERVICES))->toBe(19) + expect(count(MOVED_SERVICES))->toBe(15) ->and(is_file($root . '/src/deprecated-aliases.php'))->toBeFalse() ->and(array_keys(array_filter(MOVED_SERVICES, static fn (string $new, string $old): bool => class_exists($base . $old), ARRAY_FILTER_USE_BOTH)))->toBe([]) ->and(array_values(array_filter(MOVED_SERVICES, static fn (string $new): bool => ! class_exists($base . $new))))->toBe([]); diff --git a/tests/Feature/Database/ApprovalsTest.php b/tests/Feature/Database/ApprovalsTest.php index abf91ac..a21709b 100644 --- a/tests/Feature/Database/ApprovalsTest.php +++ b/tests/Feature/Database/ApprovalsTest.php @@ -5,7 +5,6 @@ use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\Event; -use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Artisan; use Simtabi\Laranail\Settings\Data\OwnerRef; use Simtabi\Laranail\Settings\Enums\Ability; @@ -235,11 +234,12 @@ function needsApproval(string $key = 'mail.host'): void }); it('refuses approval where a store cannot hold change requests', function (): void { - useDatabase(['approvals.table' => false]); + // File layers only: no database layer to hold the request. + config()->set('laranail.settings.stores.settings.layers', ['runtime', 'shipped']); + app()->forgetScopedInstances(); needsApproval(); - expect(Schema::hasTable('settings_change_requests'))->toBeFalse() - ->and(fn () => settings()->set('mail.host', 'a.test'))->toThrow(ApprovalUnavailable::class, 'cannot hold change requests') + expect(fn () => settings()->set('mail.host', 'a.test'))->toThrow(ApprovalUnavailable::class, 'cannot hold change requests') ->and(fn (): ChangeRequest => settings()->propose('mail.host', 'a.test'))->toThrow(ApprovalUnavailable::class); }); diff --git a/tests/Feature/Database/CommandsTest.php b/tests/Feature/Database/CommandsTest.php index 144af2a..057e0ae 100644 --- a/tests/Feature/Database/CommandsTest.php +++ b/tests/Feature/Database/CommandsTest.php @@ -2,6 +2,7 @@ declare(strict_types=1); +use Illuminate\Support\Str; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Schema; @@ -11,7 +12,6 @@ use Simtabi\Laranail\Settings\Actions\MakeStore; use Simtabi\Laranail\Settings\Exceptions\InvalidIdentifier; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; -use Simtabi\Laranail\Settings\Services\Database\SchemaShapeRepository; // Writes into the testbench application shared by every process, so it cannot run in parallel. // It also carries `mutation-excluded`, because Pest's parallel runner honours one --exclude-group. @@ -33,7 +33,7 @@ function settingsMigrations(): array File::delete(config_path('laranail/settings.php')); }); -it('publishes the config and the one migration on install, and records the schema', function (): void { +it('publishes the config and the one migration on install', function (): void { config()->set('laranail.settings.stores.settings.layers', ['database', 'runtime', 'shipped']); $this->artisan('laranail::settings.install')->assertSuccessful(); @@ -41,8 +41,7 @@ function settingsMigrations(): array $names = array_map(static fn (string $path): string => preg_replace('/^\d{4}_\d{2}_\d{2}_\d{6}_/', '', basename($path)) ?? '', settingsMigrations()); sort($names); - expect($names)->toBe(['create_laranail_settings_tables.php']) - ->and(app(SchemaShapeRepository::class)->recorded()?->hasStore(new StoreName('settings')))->toBeTrue(); + expect($names)->toBe(['create_laranail_settings_tables.php']); }); it('refuses to install over a table of the same name that is not its own', function (): void { @@ -121,7 +120,7 @@ function settingsMigrations(): array ->and($schema->hasTable('settings_audit'))->toBeFalse(); }); -it('reports readiness, schema drift and rows the database cannot guard', function (): void { +it('reports readiness, missing columns and rows the database cannot guard', function (): void { useDatabase([ 'stores.settings.owners' => ['user'], 'stores.files' => ['layers' => ['runtime']], @@ -129,18 +128,19 @@ function settingsMigrations(): array $this->artisan('laranail::settings.doctor') ->expectsOutputToContain(sprintf('Table [settings] on [%s] is ready.', DB::getDefaultConnection())) - ->expectsOutputToContain('No schema drift.') + ->expectsOutputToContain('Every column is present.') ->expectsOutputToContain('Every scope uses a listed alias.') ->expectsOutputToContain('No database layer') ->assertSuccessful(); $now = now(); - $row = static fn (string $scope, string $uid, array $extra = []): array => $extra + ['scope' => $scope, 'key' => 'k', 'locale' => '', 'group' => 'k', 'uid' => $uid, 'value' => '1', 'version' => 1, 'created_at' => $now, 'updated_at' => $now]; + $row = static fn (string $scope, string $uid, array $extra = []): array => $extra + ['id' => (string) Str::ulid(), 'scope' => $scope, 'key' => 'k', 'locale' => '', 'group' => 'k', 'uid' => $uid, 'value' => '1', 'version' => 1, 'created_at' => $now, 'updated_at' => $now]; DB::table('settings')->insert($row('team:1', str_repeat('A', 26))); // A cross-store link only an import or manual SQL could make: the foreign key holds (the // category exists), but it belongs to another store. Disabling the key instead is not // portable: PostgreSQL only defers constraints declared deferrable. - $other = DB::table('settings_categories')->insertGetId(['store' => 'other', 'title' => 'Other', 'slug' => 'other', 'created_at' => $now, 'updated_at' => $now]); + $other = (string) Str::ulid(); + DB::table('settings_categories')->insert(['id' => $other, 'store' => 'other', 'title' => '{"":"Other"}', 'slug' => 'other', 'created_at' => $now, 'updated_at' => $now]); DB::table('settings')->insert($row('global', str_repeat('B', 26), ['key' => 'c', 'category_id' => $other, 'category_store' => 'other'])); $this->artisan('laranail::settings.doctor') diff --git a/tests/Feature/Database/DatabaseLayerTest.php b/tests/Feature/Database/DatabaseLayerTest.php index 006d685..35fa634 100644 --- a/tests/Feature/Database/DatabaseLayerTest.php +++ b/tests/Feature/Database/DatabaseLayerTest.php @@ -2,6 +2,7 @@ declare(strict_types=1); +use Illuminate\Support\Str; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; use Simtabi\Laranail\Settings\Data\Key; @@ -34,14 +35,13 @@ function databaseDriver(bool $writable = true): DatabaseDriver useDatabase(); }); -it('stores a value as a row with its slug, uid, group and version', function (): void { +it('stores a value as a row with its uid, group and version', function (): void { settings()->set('mail.from_address', 'ap@acme.test'); $row = DB::table('settings')->first(); expect(settings()->get('mail.from_address'))->toBe('ap@acme.test') ->and($row?->scope)->toBe('global') - ->and($row?->slug)->toBe('mail-from_address') ->and($row?->group)->toBe('mail') ->and(strlen((string) $row?->uid))->toBe(26) ->and((int) $row?->version)->toBe(1) @@ -71,7 +71,7 @@ function databaseDriver(bool $writable = true): DatabaseDriver it('keeps the identity index inside the utf8mb4 byte budget, tenant column included', function (): void { $migration = (string) file_get_contents(dirname(__DIR__, 3) . '/database/migrations/create_laranail_settings_tables.php'); - $values = substr($migration, (int) strpos($migration, 'private function createValues'), 4000); + $values = substr($migration, (int) strpos($migration, 'private function valuesTable'), 4000); preg_match_all("/string\\('(tenant|scope|key|locale)', (\\d+)\\)/", $values, $matches); $lengths = array_combine($matches[1], array_map(intval(...), $matches[2])); ksort($lengths); @@ -82,7 +82,7 @@ function databaseDriver(bool $writable = true): DatabaseDriver it('treats keys case-sensitively in the table and lower-cases them in the API', function (): void { $now = now(); - $row = static fn (string $key, string $uid): array => ['scope' => 'global', 'key' => $key, 'locale' => '', 'group' => 'x', 'uid' => $uid, 'value' => '1', 'version' => 1, 'created_at' => $now, 'updated_at' => $now]; + $row = static fn (string $key, string $uid): array => ['id' => (string) Str::ulid(), 'scope' => 'global', 'key' => $key, 'locale' => '', 'group' => 'x', 'uid' => $uid, 'value' => '1', 'version' => 1, 'created_at' => $now, 'updated_at' => $now]; DB::table('settings')->insert($row('Theme', str_repeat('A', 26))); DB::table('settings')->insert($row('theme', str_repeat('B', 26))); @@ -150,8 +150,9 @@ function databaseDriver(bool $writable = true): DatabaseDriver it('links a setting to its category in the same store and refuses one from another store', function (): void { $now = now(); - $id = DB::table('settings_categories')->insertGetId(['store' => 'settings', 'title' => 'Mail', 'slug' => 'mail', 'created_at' => $now, 'updated_at' => $now]); - DB::table('settings_categories')->insert(['store' => 'billing', 'title' => 'Tax', 'slug' => 'tax', 'created_at' => $now, 'updated_at' => $now]); + $id = (string) Str::ulid(); + DB::table('settings_categories')->insert(['id' => $id, 'store' => 'settings', 'title' => '{"":"Mail"}', 'slug' => 'mail', 'created_at' => $now, 'updated_at' => $now]); + DB::table('settings_categories')->insert(['id' => (string) Str::ulid(), 'store' => 'billing', 'title' => '{"":"Tax"}', 'slug' => 'tax', 'created_at' => $now, 'updated_at' => $now]); $registry = app(DefinitionRegistry::class); $registry->define('mail.from')->inCategory('mail')->register(); @@ -161,7 +162,7 @@ function databaseDriver(bool $writable = true): DatabaseDriver settings()->set('mail.from', 'ap@acme.test'); settings()->set('misc.flag', true); - expect((int) DB::table('settings')->where('key', 'mail.from')->value('category_id'))->toBe($id) + expect(DB::table('settings')->where('key', 'mail.from')->value('category_id'))->toBe($id) ->and(DB::table('settings')->where('key', 'mail.from')->value('category_store'))->toBe('settings') ->and(DB::table('settings')->where('key', 'misc.flag')->value('category_id'))->toBeNull() ->and(fn () => settings()->set('tax.rate', 16))->toThrow(CategoryStoreMismatch::class, 'belongs to store [billing]') diff --git a/tests/Feature/Database/DebuggingAidsTest.php b/tests/Feature/Database/DebuggingAidsTest.php index b60175a..dca2aac 100644 --- a/tests/Feature/Database/DebuggingAidsTest.php +++ b/tests/Feature/Database/DebuggingAidsTest.php @@ -2,6 +2,7 @@ declare(strict_types=1); +use Illuminate\Support\Str; use Psr\Log\AbstractLogger; use Illuminate\Support\Facades\DB; use Simtabi\Laranail\Settings\Data\Actor; @@ -91,7 +92,7 @@ public function log($level, string|Stringable $message, array $context = []): vo settings()->categories()->create(new NewCategory('mail', 'Mail')); $mail = DB::table('settings_categories')->where('slug', 'mail')->value('id'); $now = now(); - $row = static fn (string $key, string $uid): array => ['scope' => 'global', 'key' => $key, 'locale' => '', 'group' => 'x', 'uid' => $uid, 'value' => '1', 'version' => 1, 'category_id' => $mail, 'category_store' => 'settings', 'created_at' => $now, 'updated_at' => $now]; + $row = static fn (string $key, string $uid): array => ['id' => (string) Str::ulid(), 'scope' => 'global', 'key' => $key, 'locale' => '', 'group' => 'x', 'uid' => $uid, 'value' => '1', 'version' => 1, 'category_id' => $mail, 'category_store' => 'settings', 'created_at' => $now, 'updated_at' => $now]; DB::table('settings')->insert($row('mail.host', str_repeat('A', 26))); diff --git a/tests/Feature/Database/DefinitionsTableTest.php b/tests/Feature/Database/DefinitionsTableTest.php index b6927b6..086a805 100644 --- a/tests/Feature/Database/DefinitionsTableTest.php +++ b/tests/Feature/Database/DefinitionsTableTest.php @@ -2,6 +2,7 @@ declare(strict_types=1); +use Illuminate\Support\Str; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; use Simtabi\Laranail\Settings\Data\Actor; @@ -20,6 +21,7 @@ function runtimeDefinition(string $key, array $columns = []): void { DB::table('settings_definitions')->insert($columns + [ + 'id' => (string) Str::ulid(), 'store' => 'settings', 'slug' => str_replace('.', '-', $key), 'key' => $key, @@ -32,16 +34,16 @@ function runtimeDefinition(string $key, array $columns = []): void it('syncs code and config definitions in as system rows and removes stale ones', function (): void { config()->set('laranail.settings.definitions', ['site.name' => ['type' => 'string', 'default' => 'Acme', 'label' => 'Site name']] + config('laranail.settings.definitions')); - useDatabase(['definitions.table' => true]); + useDatabase(['definitions.sources' => ['code', 'config', 'database']]); settings()->categories()->create(new NewCategory('mail', 'Mail')); app(DefinitionRegistry::class)->define('mail.password')->ofType('string')->withDefault(TestCredentials::password())->encrypted()->inCategory('mail')->register(); - DB::table('settings_definitions')->insert(['store' => 'settings', 'slug' => 'gone', 'key' => 'gone', 'group' => 'gone', 'is_system' => true, 'created_at' => now(), 'updated_at' => now()]); + DB::table('settings_definitions')->insert(['id' => (string) Str::ulid(), 'store' => 'settings', 'slug' => 'gone', 'key' => 'gone', 'group' => 'gone', 'is_system' => true, 'created_at' => now(), 'updated_at' => now()]); $report = app(SyncDefinitions::class)->handle(); $password = DB::table('settings_definitions')->where('key', 'mail.password')->first(); expect($report)->toMatchArray(['synced' => 2, 'removed' => 1, 'conflicts' => []]) - ->and(DB::table('settings_definitions')->where('key', 'site.name')->value('label'))->toBe('Site name') + ->and(DB::table('settings_definitions')->where('key', 'site.name')->value('label'))->toBe('{"":"Site name"}') ->and(DB::table('settings_definitions')->where('key', 'site.name')->value('default'))->toBe('"Acme"') ->and((bool) $password?->is_system)->toBeTrue() ->and($password?->default)->toBeNull() @@ -52,18 +54,18 @@ function runtimeDefinition(string $key, array $columns = []): void }); it('reports a runtime row that shares a key with code, and leaves it alone', function (): void { - useDatabase(['definitions.table' => true]); + useDatabase(['definitions.sources' => ['code', 'config', 'database']]); app(DefinitionRegistry::class)->define('site.name')->ofType('string')->register(); - runtimeDefinition('site.name', ['label' => 'Edited']); + runtimeDefinition('site.name', ['label' => '{"":"Edited"}']); expect(app(SyncDefinitions::class)->handle()['conflicts'])->toBe(['settings.site.name']) - ->and(DB::table('settings_definitions')->value('label'))->toBe('Edited'); + ->and(DB::table('settings_definitions')->value('label'))->toBe('{"":"Edited"}'); }); it('answers for keys no code covers from runtime rows, never from system rows', function (): void { - useDatabase(['definitions.table' => true]); - runtimeDefinition('billing.currency', ['type' => 'string', 'default' => '"EUR"', 'rules' => '["required","in:EUR,USD","exists:currencies,code"]', 'label' => 'Currency']); - DB::table('settings_definitions')->insert(['store' => 'settings', 'slug' => 'site-name', 'key' => 'site.name', 'group' => 'site', 'default' => '"Stale"', 'is_system' => true, 'created_at' => now(), 'updated_at' => now()]); + useDatabase(['definitions.sources' => ['code', 'config', 'database']]); + runtimeDefinition('billing.currency', ['type' => 'string', 'default' => '"EUR"', 'rules' => '["required","in:EUR,USD","exists:currencies,code"]', 'label' => '{"":"Currency"}']); + DB::table('settings_definitions')->insert(['id' => (string) Str::ulid(), 'store' => 'settings', 'slug' => 'site-name', 'key' => 'site.name', 'group' => 'site', 'default' => '"Stale"', 'is_system' => true, 'created_at' => now(), 'updated_at' => now()]); expect(settings()->get('billing.currency'))->toBe('EUR') ->and(settings()->has('site.name'))->toBeFalse() @@ -76,7 +78,7 @@ function runtimeDefinition(string $key, array $columns = []): void }); it('never lets a table row loosen a coded definition', function (): void { - useDatabase(['definitions.table' => true]); + useDatabase(['definitions.sources' => ['code', 'config', 'database']]); app(DefinitionRegistry::class)->define('mail.password')->ofType('string')->encrypted()->register(); runtimeDefinition('mail.password', ['is_encrypted' => false, 'is_public' => true]); @@ -86,14 +88,14 @@ function runtimeDefinition(string $key, array $columns = []): void }); it('refuses a row whose type is not a registered caster', function (): void { - useDatabase(['definitions.table' => true]); + useDatabase(['definitions.sources' => ['code', 'config', 'database']]); runtimeDefinition('x.y', ['type' => 'App\\Evil']); expect(fn (): mixed => settings()->get('x.y'))->toThrow(InvalidDefinition::class, 'unknown type'); }); -it('reads JSON labels in json translations mode', function (): void { - useDatabase(['definitions.table' => true, 'translations.mode' => 'json']); +it('reads per-locale JSON labels', function (): void { + useDatabase(['definitions.sources' => ['code', 'config', 'database']]); app(DefinitionRegistry::class)->define('site.name')->labelled('Site name')->register(); runtimeDefinition('site.tagline', ['label' => '{"":"Tagline","fr":"Slogan"}', 'default' => '"Hi"']); @@ -104,7 +106,7 @@ function runtimeDefinition(string $key, array $columns = []): void }); it('reads no table definitions when `database` is not a source, and validates sources', function (): void { - useDatabase(['definitions.table' => true, 'definitions.sources' => ['code', 'config']]); + useDatabase(['definitions.sources' => ['code', 'config']]); runtimeDefinition('billing.currency', ['default' => '"EUR"']); expect(settings()->has('billing.currency'))->toBeFalse(); @@ -133,7 +135,7 @@ function runtimeDefinition(string $key, array $columns = []): void }); it('needs manage_definitions to sync with an actor, is audited, and runs from the command and doctor --fix', function (): void { - useDatabase(['definitions.table' => true]); + useDatabase(['definitions.sources' => ['code', 'config', 'database']]); $audit = auditInMemory(); expect(fn () => app(SyncDefinitions::class)->handle(Actor::user(user())))->toThrow(AccessDenied::class); @@ -147,14 +149,14 @@ function runtimeDefinition(string $key, array $columns = []): void $this->artisan('laranail::settings.doctor', ['--fix' => true])->expectsOutputToContain('Synced 0 definition(s)'); }); -it('skips stores without the table when syncing', function (): void { - useDatabase(); +it('skips stores without a database layer when syncing', function (): void { + useDatabase(['stores.files' => ['layers' => ['runtime']]]); - expect(app(SyncDefinitions::class)->handle()['skipped'])->toBe(['settings']); + expect(app(SyncDefinitions::class)->handle()['skipped'])->toBe(['files']); }); it('reports skipped stores and conflicts from the command, and fails when syncing fails', function (): void { - useDatabase(['definitions.table' => true, 'stores.files' => ['layers' => ['runtime']]]); + useDatabase(['stores.files' => ['layers' => ['runtime']]]); app(DefinitionRegistry::class)->define('site.name')->register(); runtimeDefinition('site.name'); diff --git a/tests/Feature/Database/FixedSchemaTest.php b/tests/Feature/Database/FixedSchemaTest.php new file mode 100644 index 0000000..b46de1a --- /dev/null +++ b/tests/Feature/Database/FixedSchemaTest.php @@ -0,0 +1,169 @@ + ['user']]); + + settings()->for(new OwnerRef('user', 42))->set('theme', 'dark'); + $row = DB::table('settings')->first(); + + expect(array_map(Schema::hasTable(...), ['settings_categories', 'settings_definitions', 'settings', 'settings_audit', 'settings_history', 'settings_change_requests', 'settings_stores'])) + ->each->toBeTrue() + ->and(strlen((string) $row->id))->toBe(26) + ->and(strlen((string) $row->uid))->toBe(26) + ->and($row->uid)->not->toBe($row->id) + ->and($row->settable_type)->toBe('user') + ->and($row->settable_id)->toBe('42') + ->and(Schema::hasColumn('settings', 'slug'))->toBeFalse() + ->and(Schema::hasColumn('settings', 'tenant'))->toBeFalse() + ->and(DB::table('settings_history')->value('setting_ref'))->toBe($row->uid); +}); + +it('stores titles as per-locale JSON', function (): void { + useDatabase(); + + $mail = settings()->categories()->create(new NewCategory('mail', 'Mail', translations: ['fr' => 'Courrier'])); + + expect(json_decode((string) DB::table('settings_categories')->value('title'), true))->toBe(['' => 'Mail', 'fr' => 'Courrier']) + ->and($mail->titleIn('fr_CA'))->toBe('Courrier') + ->and($mail->titleIn('de'))->toBe('Mail') + ->and(fn (): NewCategory => new NewCategory('x', 'X', translations: ['fr' => ' ']))->toThrow(InvalidIdentifier::class); +}); + +it('prefixes every table and honours each override, including the foreign-table check', function (): void { + useDatabase([ + 'tables.prefix' => 'app_', + 'tables.categories' => 'setting_groups', + 'tables.audit' => 'setting_log', + 'tables.definitions' => 'setting_defs', + 'stores.settings.table' => 'preferences', + ]); + + settings()->categories()->create(new NewCategory('mail', 'Mail')); + settings()->set('site.name', 'Acme'); + + expect(Schema::hasTable('app_preferences'))->toBeTrue() + ->and(Schema::hasTable('app_setting_groups'))->toBeTrue() + ->and(Schema::hasTable('app_setting_log'))->toBeTrue() + ->and(Schema::hasTable('app_setting_defs'))->toBeTrue() + ->and(Schema::hasTable('settings'))->toBeFalse() + ->and(DB::table('app_preferences')->value('key'))->toBe('site.name') + ->and(app(FindForeignTables::class)->handle())->toBe([]); + + // A foreign table under a prefixed name is still refused. + Schema::drop('app_setting_log'); + Schema::create('app_setting_log', static function (Blueprint $table): void { + $table->id(); + $table->string('message'); + }); + + expect(app(FindForeignTables::class)->handle())->toBe([DB::getDefaultConnection() . '.app_setting_log']); +}); + +it('has doctor fail on a missing column and pass on a complete schema', function (): void { + useDatabase(); + + expect(Artisan::call('laranail::settings.doctor'))->toBe(0) + ->and(Artisan::output())->toContain('Every column is present.'); + + Schema::table('settings_audit', static function (Blueprint $table): void { + $table->dropIndex('settings_audit_actor_index'); + $table->dropColumn('actor_alias'); + }); + + expect(Artisan::call('laranail::settings.doctor'))->toBe(1) + ->and(Artisan::output())->toContain('settings_audit.actor_alias'); +}); + +it('runs end to end under each tenancy mode', function (string $tenancy): void { + $column = $tenancy === 'column'; + + useDatabase([ + 'tenancy.mode' => $tenancy, + 'stores.settings.owners' => ['team'], + 'stores.settings.soft_deletes' => true, + 'stores.settings.inherits' => true, + 'stores.user_settings' => [ + 'layers' => ['database'], + 'owners' => ['user'], + 'mode' => 'dedicated', + 'owner' => ['table' => 'users', 'type' => 'bigint'], + 'inherits' => true, + ], + ], stores: ['user_settings'], ownerTables: ['users' => 'bigint']); + // Column-mode tenancy runs the whole scenario inside tenant `acme`. + app()->instance(TenantDiscriminator::class, new ClosureTenantDiscriminator(static fn (): ?string => $column ? 'acme' : null)); + DB::table('users')->insert(['id' => 1, 'name' => 'Ada']); + + $user = new OwnerRef('user', 1); + $team = new OwnerRef('team', 7); + + $categories = settings()->categories(); + $mail = $categories->create(new NewCategory('mail', 'Mail', translations: ['fr' => 'Courrier'])); + app(DefinitionRegistry::class)->define('mail.host')->inCategory('mail')->labelled('Host')->register(); + + settings()->set('mail.host', 'smtp.acme.test'); + settings()->set('site.name', 'Acme'); + settings()->for($user)->set('theme', 'dark'); + settings()->for($team)->set('theme', 'dark'); + settings()->for($team)->forget('theme'); + settings()->for($team)->set('theme', 'light'); + settings()->for($team)->lock('theme'); + settings()->for($team)->unlock('theme'); + + $synced = app(SyncDefinitions::class)->handle()['synced']; + $trail = settings()->for($team)->history()->key('theme')->get(); + $request = settings()->for($team)->propose('theme', 'dark'); + $exit = Artisan::call('laranail::settings.doctor', ['--json' => true]); + $report = Artisan::output(); + + expect(settings()->get('mail.host'))->toBe('smtp.acme.test') + ->and(settings()->for($team)->get('theme'))->toBe('light') + ->and(settings()->for($user)->get('theme'))->toBe('dark') + ->and(settings()->for($user)->get('site.name'))->toBe('Acme') + ->and($synced)->toBe(1) + ->and((int) DB::table('settings')->where('scope', 'team:7')->value('version'))->toBe(4) + ->and(DB::table('user_settings')->value('owner_id'))->toBe(1) + ->and(array_map(static fn (HistoryEntry $entry): string => $entry->operation->value . ':' . $entry->version, $trail))->toBe(['unlock:4', 'lock:3', 'set:2', 'forget:1', 'set:1']) + ->and($request->scope)->toBe('team:7') + ->and(DB::table('settings')->where('key', 'mail.host')->value('category_id'))->toBe($mail->id) + ->and(settings()->audit()->get())->not->toBeEmpty() + ->and(Schema::hasColumn('settings', 'tenant'))->toBe($column) + ->and(Schema::hasColumn('settings_definitions', 'tenant'))->toBeFalse() + ->and($column ? DB::table('settings_history')->distinct()->pluck('tenant')->all() : ['acme'])->toBe(['acme']) + ->and($report)->toContain('Every column is present.') + ->and($exit)->toBe(0); + + if (! $column) { + return; + } + + // Another tenant, in the next request, sees none of it. + app()->forgetScopedInstances(); + app()->instance(TenantDiscriminator::class, new ClosureTenantDiscriminator(static fn (): string => 'globex')); + + expect(settings()->get('mail.host'))->toBeNull() + ->and(settings()->categories()->all())->toBe([]) + ->and(settings()->audit()->get())->toBe([]); +})->with(['none', 'column'])->group('tenancy'); diff --git a/tests/Feature/Database/GovernanceEventsTest.php b/tests/Feature/Database/GovernanceEventsTest.php index edb102b..25cbbee 100644 --- a/tests/Feature/Database/GovernanceEventsTest.php +++ b/tests/Feature/Database/GovernanceEventsTest.php @@ -36,7 +36,7 @@ }); it('announces a definitions sync with its counts', function (): void { - useDatabase(['definitions.table' => true]); + useDatabase(['definitions.sources' => ['code', 'config', 'database']]); Event::fake([DefinitionsSynced::class]); app(DefinitionRegistry::class)->define('site.name')->register(); app(DefinitionRegistry::class)->define('site.url')->register(); diff --git a/tests/Feature/Database/HistoryTest.php b/tests/Feature/Database/HistoryTest.php index 758598c..376fed5 100644 --- a/tests/Feature/Database/HistoryTest.php +++ b/tests/Feature/Database/HistoryTest.php @@ -274,17 +274,13 @@ function trail(string $key, ?OwnerRef $owner = null): array ->and(settings()->history()->store('settings')->global()->key('site.name')->cursor()->count())->toBe(5); }); -it('keeps no history when the schema was recorded without the table', function (): void { - useDatabase(['history.enabled' => false]); +it('keeps no history for a store without a database layer', function (): void { + config()->set('laranail.settings.stores.settings.layers', ['runtime', 'shipped']); + app()->forgetScopedInstances(); settings()->set('site.name', 'Acme'); - settings()->set('site.name', 'Acme Ltd'); - settings()->forget('site.name'); - settings()->set('site.name', 'Again'); - expect(Schema::hasTable('settings_history'))->toBeFalse() - ->and((int) DB::table('settings')->where('key', 'site.name')->value('version'))->toBe(1) - ->and(fn (): array => settings()->history()->get())->toThrow(HistoryUnavailable::class, 'keeps no history') + expect(fn (): array => settings()->history()->get())->toThrow(HistoryUnavailable::class, 'keeps no history') ->and(fn (): int => settings()->rollback('site.name', 1))->toThrow(HistoryUnavailable::class, 'cannot be rolled back') ->and(fn (): HistoryDiff => settings()->historyDiff('site.name', 1, 1))->toThrow(HistoryUnavailable::class, 'keeps no history'); }); diff --git a/tests/Feature/Database/MaintenanceTest.php b/tests/Feature/Database/MaintenanceTest.php index f2bc4b4..401c2bc 100644 --- a/tests/Feature/Database/MaintenanceTest.php +++ b/tests/Feature/Database/MaintenanceTest.php @@ -2,6 +2,7 @@ declare(strict_types=1); +use Illuminate\Support\Str; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Artisan; use Simtabi\Laranail\Settings\Data\Actor; @@ -90,16 +91,15 @@ function rotateKey(bool $keepPrevious): void }); it('renames an owner alias in values, history and change requests, and doctor stops flagging it', function (): void { - useDatabase(['stores.settings.owners' => ['user', 'member'], 'identity.mode' => 'slug_per_row']); + useDatabase(['stores.settings.owners' => ['user', 'member']]); settings()->for(new OwnerRef('user', 4))->set('theme', 'dark'); settings()->for(new OwnerRef('user', 4))->propose('theme', 'light'); - DB::table('settings')->insert(['scope' => 'App\\Models\\Legacy:9', 'settable_type' => 'App\\Models\\Legacy', 'settable_id' => '9', 'key' => 'theme', 'group' => 'theme', 'locale' => '', 'value' => '"blue"', 'slug' => sha1('legacy'), 'created_at' => now(), 'updated_at' => now()]); + DB::table('settings')->insert(['id' => (string) Str::ulid(), 'uid' => (string) Str::ulid(), 'scope' => 'App\\Models\\Legacy:9', 'settable_type' => 'App\\Models\\Legacy', 'settable_id' => '9', 'key' => 'theme', 'group' => 'theme', 'locale' => '', 'value' => '"blue"', 'created_at' => now(), 'updated_at' => now()]); expect(Artisan::call('laranail::settings.rescope', ['from' => 'user', 'to' => 'member']))->toBe(0) ->and(Artisan::output())->toContain('in 1 value(s), 1 history entry and 1 change request(s)') ->and(settings()->for(new OwnerRef('member', 4))->get('theme'))->toBe('dark') ->and(DB::table('settings')->where('scope', 'member:4')->value('settable_type'))->toBe('member') - ->and(DB::table('settings')->where('scope', 'member:4')->value('slug'))->toBe(sha1('member:4|theme|')) ->and(DB::table('settings_history')->where('scope', 'member:4')->count())->toBe(1) ->and(DB::table('settings_change_requests')->where('scope', 'member:4')->count())->toBe(1); @@ -114,7 +114,7 @@ function rotateKey(bool $keepPrevious): void ->and(Artisan::call('laranail::settings.rescope', ['from' => 'user', 'to' => 'Bad Alias']))->toBe(1); }); -it('reports overdue change requests and schema drift on the governance tables', function (): void { +it('reports overdue change requests and missing columns on the governance tables', function (): void { app(DefinitionRegistry::class)->define('mail.host')->requiresApproval()->register(); settings()->set('mail.host', 'a.test'); $this->travel(8)->days(); @@ -128,6 +128,6 @@ function rotateKey(bool $keepPrevious): void Artisan::call('laranail::settings.doctor', ['--json' => true]); expect($report)->toContain('past their expiry') - ->and($report)->toContain('No schema drift.') + ->and($report)->toContain('Every column is present.') ->and(Artisan::output())->toContain('settings_change_requests.decision_reason'); }); diff --git a/tests/Feature/Database/MigrationTest.php b/tests/Feature/Database/MigrationTest.php index fa7d619..c33aec1 100644 --- a/tests/Feature/Database/MigrationTest.php +++ b/tests/Feature/Database/MigrationTest.php @@ -5,7 +5,6 @@ use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; use Illuminate\Database\Migrations\Migration; -use Simtabi\Laranail\Settings\Database\SchemaNames; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Services\Database\SchemaInspector; @@ -80,8 +79,8 @@ function packageMigration(): Migration expect(packageMigration()->getConnection())->toBe(DB::getDefaultConnection()); }); -it('creates the definitions table on the default store\'s connection when it is on, after categories', function (): void { - useDatabase(['definitions.table' => true]); +it('creates the definitions table on the default store\'s connection, after categories', function (): void { + useDatabase(['definitions.sources' => ['code', 'config', 'database']]); expect(Schema::hasTable('settings_definitions'))->toBeTrue() ->and(collect(Schema::getForeignKeys('settings_definitions'))->pluck('foreign_table')->all())->toBe(['settings_categories']); @@ -98,7 +97,6 @@ function packageMigration(): Migration $inspector = new SchemaInspector(new DatabaseDriver( app('db'), 'unreachable', - new SchemaNames, null, true, static fn (): SchemaReadinessInterface => app(SchemaReadinessInterface::class), diff --git a/tests/Feature/Database/ModelsAndFactoriesTest.php b/tests/Feature/Database/ModelsAndFactoriesTest.php index 2ab467c..d5bcad6 100644 --- a/tests/Feature/Database/ModelsAndFactoriesTest.php +++ b/tests/Feature/Database/ModelsAndFactoriesTest.php @@ -6,11 +6,9 @@ use Illuminate\Database\Eloquent\Builder; use Simtabi\Laranail\Settings\Data\OwnerRef; use Simtabi\Laranail\Settings\Models\Setting; -use Simtabi\Laranail\Settings\Data\NewCategory; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Enums\AuditOutcome; use Simtabi\Laranail\Settings\Models\ModelContext; -use Simtabi\Laranail\Settings\Database\SchemaShape; use Simtabi\Laranail\Settings\Models\SettingCategory; use Simtabi\Laranail\Settings\Models\SettingAuditEntry; use Simtabi\Laranail\Settings\Models\SettingDefinition; @@ -22,15 +20,15 @@ * The engine never reads through them, but what they write must be what the engine reads. */ -it('builds categories with store, system and parent states', function (string $ids): void { - useDatabase(['ids.type' => $ids, 'stores.billing' => ['layers' => ['database']]], stores: ['billing']); +it('builds categories with store, system and parent states', function (): void { + useDatabase(['stores.billing' => ['layers' => ['database']]], stores: ['billing']); $general = SettingCategory::factory()->system()->create(['slug' => 'general']); $mail = SettingCategory::factory()->parent($general)->titled('Mail', 'Outgoing mail')->create(['slug' => 'mail']); $billing = SettingCategory::factory()->forStore('billing')->create(); expect($general->is_system)->toBeTrue() - ->and($ids === 'bigint' ? is_int($general->getKey()) : strlen((string) $general->getKey()))->toBe($ids === 'bigint' ? true : ($ids === 'uuid' ? 36 : 26)) + ->and(strlen($general->getKey()))->toBe(26) ->and($mail->parent?->is($general))->toBeTrue() ->and($general->children()->pluck('slug')->all())->toBe(['mail']) ->and(SettingCategory::query()->forStore('billing')->sole()->is($billing))->toBeTrue() @@ -38,18 +36,18 @@ ->and(settings()->categories()->get('mail')->parent?->value)->toBe('general') ->and(settings()->categories()->get('mail')->title)->toBe('Mail') ->and(settings()->categories()->get('general')->system)->toBeTrue(); -})->with(['bigint', 'uuid', 'ulid']); +}); -it('writes JSON titles in json translations mode', function (): void { - useDatabase(['translations.mode' => 'json']); +it('writes JSON titles', function (): void { + useDatabase(); SettingCategory::factory()->titled('Mail')->create(['slug' => 'mail']); expect(settings()->categories()->get('mail')->title)->toBe('Mail'); }); -it('builds values rows the engine reads', function (string $identity): void { - useDatabase(['identity.mode' => $identity, 'stores.settings.owners' => ['user'], 'stores.billing' => ['layers' => ['database']]], stores: ['billing']); +it('builds values rows the engine reads', function (): void { + useDatabase(['stores.settings.owners' => ['user'], 'stores.billing' => ['layers' => ['database']]], stores: ['billing']); $category = SettingCategory::factory()->create(['slug' => 'site']); $row = Setting::factory()->key('site.name')->value('Acme')->inCategory($category)->create(); @@ -64,24 +62,21 @@ ->and(settings()->store('billing')->get('billing.currency'))->toBe('EUR') ->and(Setting::forStore('billing')->pluck('key')->all())->toBe(['billing.currency']) ->and(Setting::forStore('billing')->first()?->storeName()->value)->toBe('billing') - ->and(Setting::query()->count())->toBe(3); -})->with(['slug_uid', 'slug_per_row', 'uid_only']); + ->and(Setting::query()->count())->toBe(3) + ->and(strlen($row->uid))->toBe(26); +}); it('hides trashed rows, as the engine does', function (): void { - useDatabase(['stores.settings.soft_deletes' => true, 'categories.soft_deletes' => true]); + useDatabase(['stores.settings.soft_deletes' => true]); settings()->set('site.name', 'Acme'); settings()->forget('site.name'); - settings()->categories()->create(new NewCategory('mail', 'Mail')); - settings()->categories()->delete('mail'); expect(DB::table('settings')->count())->toBe(1) - ->and(Setting::query()->count())->toBe(0) - ->and(DB::table('settings_categories')->count())->toBe(1) - ->and(SettingCategory::query()->count())->toBe(0); + ->and(Setting::query()->count())->toBe(0); }); it('builds definition and audit rows', function (): void { - useDatabase(['definitions.table' => true]); + useDatabase(['definitions.sources' => ['code', 'config', 'database']]); $definition = SettingDefinition::factory()->key('mail.host')->system()->create(); $entry = SettingAuditEntry::factory()->action(AuditAction::Forget, AuditOutcome::Denied)->by('user', 3)->at(now()->subDay())->create(); @@ -103,13 +98,13 @@ }); it('says so when a model is used before the provider registered it', function (): void { - $shape = new ReflectionProperty(ModelContext::class, 'shape'); - $saved = $shape->getValue(); - $shape->setValue(null, null); + $config = new ReflectionProperty(ModelContext::class, 'config'); + $saved = $config->getValue(); + $config->setValue(null, null); try { - expect(fn (): SchemaShape => ModelContext::shape())->toThrow(InvalidConfiguration::class, 'before SettingsServiceProvider'); + expect(ModelContext::names(...))->toThrow(InvalidConfiguration::class, 'before SettingsServiceProvider'); } finally { - $shape->setValue(null, $saved); + $config->setValue(null, $saved); } }); diff --git a/tests/Feature/Database/PersistedConfigurationTest.php b/tests/Feature/Database/PersistedConfigurationTest.php index 5feccb5..cec7bd7 100644 --- a/tests/Feature/Database/PersistedConfigurationTest.php +++ b/tests/Feature/Database/PersistedConfigurationTest.php @@ -24,15 +24,15 @@ */ beforeEach(function (): void { - useDatabase(['configuration.persisted' => true, 'definitions.table' => true]); + useDatabase(['configuration.persisted' => true, 'definitions.sources' => ['code', 'config', 'database']]); }); -it('creates the persisted configuration table only when the switch is on', function (): void { +it('always creates the persisted configuration table, and saves to it only when the switch is on', function (): void { expect(Schema::hasTable('settings_stores'))->toBeTrue(); useDatabase(['configuration.persisted' => false]); - expect(Schema::hasTable('settings_stores'))->toBeFalse() + expect(Schema::hasTable('settings_stores'))->toBeTrue() ->and(fn () => settings()->persistedConfiguration()->saveStore('extra', ['layers' => ['runtime']]))->toThrow(InvalidConfiguration::class, 'persisted configuration is off'); }); diff --git a/tests/Feature/Database/RestApiTest.php b/tests/Feature/Database/RestApiTest.php index 07df693..f334bda 100644 --- a/tests/Feature/Database/RestApiTest.php +++ b/tests/Feature/Database/RestApiTest.php @@ -30,7 +30,7 @@ 'laranail.settings.http.enabled' => true, 'laranail.settings.http.middleware' => ['api', 'auth'], ]); - useDatabase(['stores.settings.owners' => ['user'], 'definitions.table' => true, 'configuration.persisted' => true, 'verification.driver' => 'none']); + useDatabase(['stores.settings.owners' => ['user'], 'definitions.sources' => ['code', 'config', 'database'], 'configuration.persisted' => true, 'verification.driver' => 'none']); Relation::morphMap(['user' => TestUser::class]); allowGates(...Ability::cases()); $this->actingAs(user(1)); diff --git a/tests/Feature/Database/SchemaMatrixTest.php b/tests/Feature/Database/SchemaMatrixTest.php deleted file mode 100644 index a026c60..0000000 --- a/tests/Feature/Database/SchemaMatrixTest.php +++ /dev/null @@ -1,160 +0,0 @@ -> */ -function switchFactors(): array -{ - return [ - 'identity' => ['slug_uid', 'slug_per_row', 'uid_only'], - 'ids' => ['bigint', 'uuid', 'ulid'], - 'owner_key' => ['string', 'typed'], - 'mode' => ['polymorphic', 'dedicated'], - 'soft_deletes' => [false, true], - 'translations' => ['lang', 'json'], - 'definitions_table' => [false, true], - 'categories_soft_deletes' => [false, true], - 'tenancy' => ['none', 'column'], - 'history' => [true, false], - 'approvals' => [true, false], - ]; -} - -/** @return list> */ -function switchShapes(): array -{ - return getenv('LARANAIL_SETTINGS_MATRIX') === 'full' ? Pairwise::product(switchFactors()) : Pairwise::rows(switchFactors()); -} - -it('covers every pair of switch values with a counted set of shapes', function (): void { - $shapes = switchShapes(); - $covered = []; - - foreach ($shapes as $shape) { - foreach (Pairwise::pairs($shape) as $pair) { - $covered[$pair] = true; - } - } - - $all = []; - - foreach (Pairwise::product(switchFactors()) as $row) { - foreach (Pairwise::pairs($row) as $pair) { - $all[$pair] = true; - } - } - - // 141 pairs among the first eight switches, plus 2 × 18 for tenancy, 2 × 20 for history and - // 2 × 22 for the change requests table = 261. The full product is 4,608 shapes; pairwise is 11. - expect(count($shapes))->toBe(getenv('LARANAIL_SETTINGS_MATRIX') === 'full' ? 4608 : 11) - ->and(count($all))->toBe(261) - ->and(array_diff_key($all, $covered))->toBe([]); -})->group('matrix', 'mutation-excluded'); - -it('runs every shape end to end and reports no drift', function (array $shape): void { - $dedicated = $shape['mode'] === 'dedicated'; - $ownerStore = $dedicated ? 'user_settings' : 'settings'; - - $config = [ - 'identity.mode' => $shape['identity'], - 'ids.type' => $shape['ids'], - 'ids.owner_key' => $shape['owner_key'], - 'translations.mode' => $shape['translations'], - 'definitions.table' => $shape['definitions_table'], - 'categories.soft_deletes' => $shape['categories_soft_deletes'], - 'tenancy.mode' => $shape['tenancy'], - 'history.enabled' => $shape['history'], - 'approvals.table' => $shape['approvals'], - 'stores.settings.owners' => $dedicated ? [] : ['user'], - 'stores.settings.soft_deletes' => $shape['soft_deletes'], - 'stores.settings.inherits' => true, - ]; - - if ($dedicated) { - $config['stores.user_settings'] = [ - 'layers' => ['database'], - 'owners' => ['user'], - 'mode' => 'dedicated', - 'owner' => ['table' => 'users', 'type' => 'bigint'], - 'soft_deletes' => $shape['soft_deletes'], - 'inherits' => true, - ]; - } - - useDatabase($config, stores: $dedicated ? ['user_settings'] : [], ownerTables: ['users' => 'bigint']); - // Column-mode tenancy runs the whole scenario inside tenant `acme`. - app()->instance(TenantDiscriminator::class, new ClosureTenantDiscriminator(static fn (): ?string => $shape['tenancy'] === 'column' ? 'acme' : null)); - app(SchemaShapeRepository::class)->record(); - DB::table('users')->insert(['id' => 1, 'name' => 'Ada']); - - $user = new OwnerRef('user', 1); - - // Categories: create with translations, delete, create again (restored when trashed). - $categories = settings()->categories(); - $mail = $categories->create(new NewCategory('mail', 'Mail', translations: ['fr' => 'Courrier'])); - $categories->delete('mail'); - $again = $categories->create(new NewCategory('mail', 'Email')); - app(DefinitionRegistry::class)->define('mail.host')->inCategory('mail')->labelled('Host')->register(); - - // Values: global, owner, category link, forget then set, lock and unlock. - settings()->set('mail.host', 'smtp.acme.test'); - settings()->set('site.name', 'Acme'); - settings()->for($user)->set('theme', 'dark'); - settings()->for($user)->forget('theme'); - settings()->for($user)->set('theme', 'light'); - settings()->for($user)->lock('theme'); - settings()->for($user)->unlock('theme'); - - if ($shape['definitions_table']) { - expect(app(SyncDefinitions::class)->handle()['synced'])->toBe(1); - } - - // History: the forget left a tombstone, so the row created again continued the trail. - $trail = $shape['history'] ? settings()->for($user)->history()->key('theme')->get() : []; - - $exit = Artisan::call('laranail::settings.doctor', ['--json' => true]); - $report = Artisan::output(); - - expect(settings()->get('mail.host'))->toBe('smtp.acme.test') - ->and(settings()->for($user)->get('theme'))->toBe('light') - ->and(settings()->for($user)->get('site.name'))->toBe('Acme') - ->and(DB::table($ownerStore)->where('scope', 'user:1')->count())->toBe(1) - ->and((int) DB::table($ownerStore)->where('scope', 'user:1')->value('version'))->toBe($shape['soft_deletes'] || $shape['history'] ? 4 : 3) - ->and(Schema::hasTable('settings_history'))->toBe($shape['history']) - ->and(Schema::hasTable('settings_change_requests'))->toBe($shape['approvals']) - ->and($shape['approvals'] ? settings()->for($user)->propose('theme', 'dark')->scope : 'user:1')->toBe('user:1') - ->and(array_map(static fn (HistoryEntry $entry): string => $entry->operation->value . ':' . $entry->version, $trail)) - ->toBe($shape['history'] ? ['unlock:4', 'lock:3', 'set:2', 'forget:1', 'set:1'] : []) - ->and($shape['history'] && $shape['tenancy'] === 'column' ? DB::table('settings_history')->distinct()->pluck('tenant')->all() : ['acme'])->toBe(['acme']) - ->and(DB::table('settings')->where('key', 'mail.host')->value('category_id'))->toBe($again->id) - ->and($again->id === $mail->id)->toBe($shape['categories_soft_deletes']) - ->and(DB::table('settings')->distinct()->pluck($shape['tenancy'] === 'column' ? 'tenant' : 'scope')->contains('acme'))->toBe($shape['tenancy'] === 'column') - ->and($report)->toContain('No schema drift.') - ->and($report)->toContain('The configuration matches the recorded schema.') - ->and($exit)->toBe(0); -})->with(fn (): array => array_map( - static fn (array $shape): array => [$shape], - array_combine(array_map(static fn (array $shape): string => implode(',', array_map(static fn (mixed $value): string => is_bool($value) ? ($value ? 'on' : 'off') : $value, $shape)), switchShapes()), switchShapes()), -))->group('matrix', 'mutation-excluded'); diff --git a/tests/Feature/Database/SchemaShapeTest.php b/tests/Feature/Database/SchemaShapeTest.php deleted file mode 100644 index d7151a2..0000000 --- a/tests/Feature/Database/SchemaShapeTest.php +++ /dev/null @@ -1,165 +0,0 @@ -group('shared-app', 'mutation-excluded'); - -function shapes(): SchemaShapeRepository -{ - return app(SchemaShapeRepository::class); -} - -/** The doctor's JSON report. */ -function doctorReport(): string -{ - Artisan::call('laranail::settings.doctor', ['--json' => true]); - - return Artisan::output(); -} - -it('records the configured shape in the schema file and reads it back', function (): void { - config()->set('laranail.settings.identity.mode', 'uid_only'); - config()->set('laranail.settings.stores.settings.layers', ['database']); - config()->set('laranail.settings.stores.settings.soft_deletes', true); - - $recorded = shapes()->record(); - app()->forgetScopedInstances(); - - expect(File::get(shapes()->path()))->toContain("'identity' => 'uid_only'") - ->and(shapes()->recorded()?->toArray())->toBe($recorded->toArray()) - ->and(shapes()->current()->store(new StoreName('settings'))->softDeletes)->toBeTrue(); -}); - -it('makes the runtime read the recorded shape, not config changed after migrating', function (): void { - useDatabase(); - shapes()->record(); - - config()->set('laranail.settings.identity.mode', 'uid_only'); - config()->set('laranail.settings.stores.settings.soft_deletes', true); - app()->forgetScopedInstances(); - - settings()->set('site.name', 'Acme'); - settings()->forget('site.name'); - - expect(DB::table('settings')->count())->toBe(0) - ->and(shapes()->current()->identity->value)->toBe('slug_uid'); -}); - -it('keeps recorded switches and stores and only adds new stores on record', function (): void { - config()->set('laranail.settings.stores.settings.layers', ['database']); - shapes()->record(); - - config()->set('laranail.settings.ids.type', 'uuid'); - config()->set('laranail.settings.stores.settings.soft_deletes', true); - config()->set('laranail.settings.stores.billing', ['layers' => ['database'], 'soft_deletes' => true]); - $shape = shapes()->record(); - - expect($shape->ids->value)->toBe('bigint') - ->and($shape->store(new StoreName('settings'))->softDeletes)->toBeFalse() - ->and($shape->store(new StoreName('billing'))->softDeletes)->toBeTrue(); -}); - -it('records the store make-store generates, from its configuration when it has one', function (): void { - config()->set('laranail.settings.stores.ledger', ['layers' => ['database'], 'soft_deletes' => true]); - - app(MakeStore::class)->handle(new StoreName('ledger')); - app(MakeStore::class)->handle(new StoreName('archive'), 'archive_db'); - - $recorded = shapes()->recorded(); - - expect($recorded?->store(new StoreName('ledger'))->softDeletes)->toBeTrue() - ->and($recorded?->store(new StoreName('archive'))->connection)->toBe('archive_db'); - - File::delete(glob(database_path('migrations') . '/*settings*.php') ?: []); -}); - -it('refuses a schema file that does not hold a shape', function (string $contents, string $message): void { - File::put(shapes()->path(), $contents); - - expect(fn (): ?SchemaShape => shapes()->recorded())->toThrow(InvalidConfiguration::class, $message); -})->with([ - 'not an array' => [' [' [" 1, 'switches' => ['identity' => 'nope']];", 'switch [identity]'], - 'unknown mode' => [" 1, 'stores' => ['settings' => ['mode' => 'nope']]];", 'unknown mode'], - 'store not array' => [" 1, 'stores' => ['settings' => 1]];", 'must be an array'], - 'broken PHP' => ['toContain('No schema file'); - - shapes()->record(); - - expect(doctorReport())->toContain('The configuration matches the recorded schema.'); -}); - -it('warns about configuration that drifted from the recorded schema', function (): void { - useDatabase(); - shapes()->record(); - config()->set('laranail.settings.translations.mode', 'json'); - config()->set('laranail.settings.stores.settings.soft_deletes', true); - app()->forgetScopedInstances(); - - $this->artisan('laranail::settings.doctor') - ->expectsOutputToContain('switches.translations: lang → json') - ->assertSuccessful(); - - expect(doctorReport())->toContain('stores.settings.soft_deletes: false'); -}); - -it('fails on an unrecorded database store, a missing column or a wrong id type', function (): void { - useDatabase(); - shapes()->write(new SchemaShape(stores: [])); - - expect(doctorReport())->toContain('has a database layer but no entry in the schema file'); - - $data = shapes()->configured()->toArray(); - $data['shape_version'] = 1; - File::put(shapes()->path(), ' 1] + $data, true) . ';'); - - expect(doctorReport())->not->toContain('no entry in the schema file'); - - // The recorded shape says soft deletes; the table has no deleted_at. - shapes()->write(shapes()->configured()->withStore(new StoreSchema(new StoreName('x')))); - $soft = shapes()->configured()->toArray(); - $soft['stores']['settings']['soft_deletes'] = true; - File::put(shapes()->path(), 'forgetScopedInstances(); - - expect(doctorReport())->toContain('settings.deleted_at'); - - // The recorded shape says ulid; the table has a bigint id. - $ulid = shapes()->configured()->toArray(); - $ulid['switches']['ids'] = 'ulid'; - File::put(shapes()->path(), 'forgetScopedInstances(); - - expect(doctorReport())->toContain('recorded key type is [ulid]'); -}); - -it('warns about columns the recorded shape does not have', function (): void { - useDatabase(['stores.settings.soft_deletes' => true]); - $plain = shapes()->configured()->toArray(); - $plain['stores']['settings']['soft_deletes'] = false; - File::put(shapes()->path(), 'forgetScopedInstances(); - - expect(Schema::hasColumn('settings', 'deleted_at'))->toBeTrue() - ->and(doctorReport())->toContain('Columns the recorded schema does not have'); -}); diff --git a/tests/Feature/Database/SchemaSwitchesTest.php b/tests/Feature/Database/SchemaSwitchesTest.php deleted file mode 100644 index 4de2a18..0000000 --- a/tests/Feature/Database/SchemaSwitchesTest.php +++ /dev/null @@ -1,167 +0,0 @@ - ['user']]); - - settings()->set('mail.from_address', 'a@acme.test'); - settings()->for(new OwnerRef('user', 1))->set('mail.from_address', 'b@acme.test'); - - $rows = DB::table('settings')->orderBy('scope')->get(); - - expect($rows->pluck('slug')->unique()->all())->toBe(['mail-from_address']) - ->and($rows->pluck('uid')->unique())->toHaveCount(2); -}); - -it('gives each row a unique sha1 slug and no uid in slug_per_row mode', function (): void { - useDatabase(['identity.mode' => 'slug_per_row', 'stores.settings.owners' => ['user']]); - - settings()->set('mail.from_address', 'a@acme.test'); - settings()->for(new OwnerRef('user', 1))->set('mail.from_address', 'b@acme.test'); - settings()->set('mail.from_address', 'c@acme.test'); - - expect(valueColumns())->not->toContain('uid') - ->and(DB::table('settings')->where('scope', 'global')->value('slug'))->toBe(sha1('global|mail.from_address|')) - ->and(DB::table('settings')->where('scope', 'user:1')->value('slug'))->toBe(sha1('user:1|mail.from_address|')) - ->and(settings()->get('mail.from_address'))->toBe('c@acme.test'); - - $unique = collect(Schema::getIndexes('settings'))->filter(static fn (array $index): bool => $index['unique'] && $index['columns'] === ['slug']); - - expect($unique)->toHaveCount(1); -}); - -it('keeps only a uid in uid_only mode', function (): void { - useDatabase(['identity.mode' => 'uid_only']); - - settings()->set('site.name', 'Acme'); - - expect(valueColumns())->not->toContain('slug') - ->and(strlen((string) DB::table('settings')->value('uid')))->toBe(26) - ->and(settings()->get('site.name'))->toBe('Acme'); -}); - -it('keys every package table by uuid or ulid, with matching category keys', function (string $type, int $length): void { - useDatabase(['ids.type' => $type, 'definitions.table' => true]); - - $category = settings()->categories()->create(new NewCategory('mail', 'Mail')); - settings()->configuration()->define('mail.host')->inCategory('mail')->register(); - settings()->set('mail.host', 'smtp.acme.test'); - - $row = DB::table('settings')->first(); - - expect(strlen((string) $category->id))->toBe($length) - ->and(strlen((string) $row?->id))->toBe($length) - ->and($row?->category_id)->toBe($category->id) - ->and(settings()->get('mail.host'))->toBe('smtp.acme.test'); -})->with([ - 'uuid' => ['uuid', 36], - 'ulid' => ['ulid', 26], -]); - -it('follows laranail.db-tools.id_type when ids.type is not set', function (): void { - config()->set('laranail.db-tools.id_type', 'ULID'); - useDatabase(); - - settings()->set('site.name', 'Acme'); - - expect(app(SchemaShapeRepository::class)->current()->ids->value)->toBe('ulid') - ->and(strlen((string) DB::table('settings')->value('id')))->toBe(26); -}); - -it('refuses an ids.type it does not know', function (): void { - config()->set('laranail.settings.ids.type', 'serial'); - - expect(fn () => app(SchemaShapeRepository::class)->configured())->toThrow(InvalidConfiguration::class, 'laranail.settings.ids.type'); -}); - -it('types settable_id like the owners\' keys when ids.owner_key is typed', function (): void { - useDatabase(['ids.owner_key' => 'typed', 'stores.settings.owners' => ['user']]); - - settings()->for(new OwnerRef('user', 42))->set('theme', 'dark'); - - expect((int) DB::table('settings')->value('settable_id'))->toBe(42) - ->and(settings()->for(new OwnerRef('user', 42))->get('theme'))->toBe('dark') - ->and(fn () => settings()->for(new OwnerRef('user', 'abc'))->set('theme', 'light'))->toThrow(OwnerNotAllowed::class, 'bigint'); -}); - -it('stores titles as per-locale JSON in json translations mode', function (): void { - useDatabase(['translations.mode' => 'json']); - - $categories = settings()->categories(); - $categories->create(new NewCategory('mail', 'Mail', description: 'Outgoing mail', translations: ['fr' => 'Courrier', 'pt-br' => 'Correio'])); - $categories->rename('mail', 'Email'); - $mail = $categories->get('mail'); - $stored = json_decode((string) DB::table('settings_categories')->value('title'), true); - - expect($mail->title)->toBe('Email') - ->and($mail->titleIn('fr_CA'))->toBe('Courrier') - ->and($mail->titleIn('pt_BR'))->toBe('Correio') - ->and($mail->titleIn('de'))->toBe('Email') - ->and($mail->description)->toBe('Outgoing mail') - ->and($stored)->toMatchArray(['' => 'Email', 'fr' => 'Courrier', 'pt_BR' => 'Correio']); -}); - -it('keeps plain titles in lang mode, where translations are not stored', function (): void { - useDatabase(); - - $mail = settings()->categories()->create(new NewCategory('mail', 'settings.categories.mail', translations: ['fr' => 'Courrier'])); - - expect(DB::table('settings_categories')->value('title'))->toBe('settings.categories.mail') - ->and($mail->titles)->toBe(['' => 'settings.categories.mail']) - ->and(fn (): NewCategory => new NewCategory('x', 'X', translations: ['fr' => ' ']))->toThrow(InvalidIdentifier::class); -}); - -it('prefixes every table and honours each override, including the foreign-table check', function (): void { - useDatabase([ - 'tables.prefix' => 'app_', - 'tables.categories' => 'setting_groups', - 'tables.audit' => 'setting_log', - 'tables.definitions' => 'setting_defs', - 'definitions.table' => true, - 'stores.settings.table' => 'preferences', - ]); - - settings()->categories()->create(new NewCategory('mail', 'Mail')); - settings()->set('site.name', 'Acme'); - - expect(Schema::hasTable('app_preferences'))->toBeTrue() - ->and(Schema::hasTable('app_setting_groups'))->toBeTrue() - ->and(Schema::hasTable('app_setting_log'))->toBeTrue() - ->and(Schema::hasTable('app_setting_defs'))->toBeTrue() - ->and(Schema::hasTable('settings'))->toBeFalse() - ->and(DB::table('app_preferences')->value('key'))->toBe('site.name') - ->and(app(FindForeignTables::class)->handle())->toBe([]); - - // A foreign table under a prefixed name is still refused. - Schema::drop('app_setting_log'); - Schema::create('app_setting_log', static function (Blueprint $table): void { - $table->id(); - $table->string('message'); - }); - - expect(app(FindForeignTables::class)->handle())->toBe([DB::getDefaultConnection() . '.app_setting_log']); -}); - -it('runs the definitions migration as a no-op while the table is off', function (): void { - useDatabase(); - - expect(Schema::hasTable('settings_definitions'))->toBeFalse(); -}); diff --git a/tests/Feature/Database/SoftDeletesTest.php b/tests/Feature/Database/SoftDeletesTest.php index dc8870e..56ea821 100644 --- a/tests/Feature/Database/SoftDeletesTest.php +++ b/tests/Feature/Database/SoftDeletesTest.php @@ -11,7 +11,7 @@ use Simtabi\Laranail\Settings\Exceptions\UnknownCategory; beforeEach(function (): void { - useDatabase(['stores.settings.soft_deletes' => true, 'stores.settings.owners' => ['user'], 'categories.soft_deletes' => true]); + useDatabase(['stores.settings.soft_deletes' => true, 'stores.settings.owners' => ['user']]); }); it('trashes a forgotten row instead of deleting it, and reads past it', function (): void { @@ -82,20 +82,19 @@ ->and(settings()->for($owner)->has('locale'))->toBeFalse(); }); -it('trashes a deleted category and restores it when its slug is created again', function (): void { +it('deletes a category for good, so creating its slug again makes a new one', function (): void { $categories = settings()->categories(); $first = $categories->create(new NewCategory('mail', 'Mail')); $categories->delete('mail'); expect(fn (): Category => $categories->get('mail'))->toThrow(UnknownCategory::class) - ->and(DB::table('settings_categories')->count())->toBe(1); + ->and(DB::table('settings_categories')->count())->toBe(0); $again = $categories->create(new NewCategory('mail', 'Email')); - expect($again->id)->toBe($first->id) + expect($again->id)->not->toBe($first->id) ->and($again->title)->toBe('Email') - ->and(DB::table('settings_categories')->count())->toBe(1) - ->and(DB::table('settings_categories')->value('deleted_at'))->toBeNull(); + ->and(DB::table('settings_categories')->count())->toBe(1); }); it('does not link a setting to a trashed category', function (): void { diff --git a/tests/Feature/Database/TenancyTest.php b/tests/Feature/Database/TenancyTest.php index 34f0aa5..5aaa26b 100644 --- a/tests/Feature/Database/TenancyTest.php +++ b/tests/Feature/Database/TenancyTest.php @@ -12,7 +12,6 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; use Simtabi\Laranail\Settings\Tenancy\NullTenantDiscriminator; use Simtabi\Laranail\Settings\Tenancy\ClosureTenantDiscriminator; -use Simtabi\Laranail\Settings\Services\Database\SchemaShapeRepository; /* * Column-mode tenancy. One database; every values, categories and audit row carries @@ -162,6 +161,5 @@ public function getKey(): int config()->set('laranail.settings.tenancy.mode', 'schema'); app()->forgetScopedInstances(); - expect(fn () => app(SchemaShapeRepository::class)->configured()) - ->toThrow(InvalidConfiguration::class, 'laranail.settings.tenancy.mode'); + expect(ModelContext::hasTenantColumn(...))->toThrow(InvalidConfiguration::class, 'laranail.settings.tenancy.mode'); }); diff --git a/tests/Feature/PackageLayoutTest.php b/tests/Feature/PackageLayoutTest.php index 6759b3f..3ffdc5e 100644 --- a/tests/Feature/PackageLayoutTest.php +++ b/tests/Feature/PackageLayoutTest.php @@ -105,7 +105,7 @@ function messageKeysUsedInSource(): array $keys = [...$keys, ...$matches[1]]; } - expect($files)->toBeGreaterThanOrEqual(355); + expect($files)->toBeGreaterThanOrEqual(354); $problems = (string) file_get_contents($root . '/Http/Support/Problems.php'); preg_match_all("/this->make\\(\\d+, '([a-z-]+)'/", $problems, $fixed); diff --git a/tests/Feature/ReferenceDocsTest.php b/tests/Feature/ReferenceDocsTest.php index df066a2..3379f60 100644 --- a/tests/Feature/ReferenceDocsTest.php +++ b/tests/Feature/ReferenceDocsTest.php @@ -133,9 +133,9 @@ function documentedConfigKeys(array $config, string $prefix = ''): array $keys = documentedConfigKeys($config); $rows = array_filter(explode("\n", referencePage('configuration.md')), static fn (string $line): bool => str_starts_with($line, '| `')); // A default that is resolved later, or that differs by store or layer, is documented in words. - $describedDefaults = ['schema.path', 'stores..layers', 'seed.categories', 'definitions.allowed_rules', 'readiness.flush_on', 'importers', 'authorization.permissions', 'definitions.sources', 'configuration.sources', 'audit.sinks', 'verification.abilities']; + $describedDefaults = ['stores..layers', 'seed.categories', 'definitions.allowed_rules', 'readiness.flush_on', 'importers', 'authorization.permissions', 'definitions.sources', 'configuration.sources', 'audit.sinks', 'verification.abilities']; - expect(count($keys))->toBeGreaterThanOrEqual(80); + expect(count($keys))->toBeGreaterThanOrEqual(74); foreach ($keys as $key => $default) { $row = array_values(array_filter($rows, static fn (string $line): bool => str_contains(explode('|', $line)[1] ?? '', '`' . $key . '`')))[0] ?? null; diff --git a/tests/Pest.php b/tests/Pest.php index b8db9d8..29dcb92 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -85,7 +85,7 @@ function useDatabase(array $config = [], array $stores = [], array $ownerTables // One directory per distinct set of files, reused: the migrator requires each file, and PHP // keeps every compiled file for the life of the process, so a fresh path per call would leak - // a migration's worth of memory per test (the full switch matrix runs thousands of them). + // a migration's worth of memory per test. $migration = (string) file_get_contents(__DIR__ . '/../database/migrations/create_laranail_settings_tables.php'); $directory = sys_get_temp_dir() . '/laranail-settings-migrations-' . sha1(serialize([$migration, $stores, $ownerTables])); diff --git a/tests/Support/Pairwise.php b/tests/Support/Pairwise.php deleted file mode 100644 index f11cc39..0000000 --- a/tests/Support/Pairwise.php +++ /dev/null @@ -1,108 +0,0 @@ -> $factors - * - * @return list> - */ - public static function rows(array $factors): array - { - $product = self::product($factors); - $uncovered = []; - - foreach ($product as $row) { - foreach (self::pairs($row) as $pair) { - $uncovered[$pair] = true; - } - } - - $rows = []; - - while ($uncovered !== []) { - $best = null; - $bestCount = 0; - - foreach ($product as $row) { - $count = count(array_intersect_key(array_flip(self::pairs($row)), $uncovered)); - - if ($count > $bestCount) { - [$best, $bestCount] = [$row, $count]; - } - } - - if ($best === null) { - break; - } - - $rows[] = $best; - - foreach (self::pairs($best) as $pair) { - unset($uncovered[$pair]); - } - } - - return $rows; - } - - /** - * @param array> $factors - * - * @return list> - */ - public static function product(array $factors): array - { - $rows = [[]]; - - foreach ($factors as $name => $values) { - $next = []; - - foreach ($rows as $row) { - foreach ($values as $value) { - $next[] = $row + [$name => $value]; - } - } - - $rows = $next; - } - - return $rows; - } - - /** - * Every pair of (factor = value) in one row, as stable strings. - * - * @param array $row - * - * @return list - */ - public static function pairs(array $row): array - { - $cells = []; - - foreach ($row as $name => $value) { - $cells[] = $name . '=' . var_export($value, true); - } - - $pairs = []; - - foreach ($cells as $i => $a) { - foreach (array_slice($cells, $i + 1) as $b) { - $pairs[] = $a . '&' . $b; - } - } - - return $pairs; - } -} diff --git a/tests/TestCase.php b/tests/TestCase.php index dd550bb..aeeaa96 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -93,8 +93,6 @@ private function configureSettings(): void Storage::fake('local'); // No shipped file unless a test ships one. config()->set('laranail.settings.layers.shipped.path', '/nonexistent/laranail-settings-defaults.php'); - // The schema-shape file goes to a path of this test's own, never the skeleton's database/. - config()->set('laranail.settings.schema.path', sys_get_temp_dir() . '/laranail-settings-schema-' . bin2hex(random_bytes(6)) . '.php'); // File layers only unless a test asks for the database (useDatabase() in tests/Pest.php). config()->set('laranail.settings.stores.settings.layers', ['runtime', 'shipped']); } diff --git a/tests/Unit/DocsConformanceTest.php b/tests/Unit/DocsConformanceTest.php index ad94ecc..1e0f7f6 100644 --- a/tests/Unit/DocsConformanceTest.php +++ b/tests/Unit/DocsConformanceTest.php @@ -6,10 +6,10 @@ uses(AssertsDocsConformance::class); -// Floor = the 50 pages shipped today (5 guides, 27 reference, 18 recipes; counted 2026-11-10). Raise it as pages +// Floor = the 49 pages shipped today (5 guides, 26 reference, 18 recipes; counted 2026-11-10, after schema-switches.md was folded into database.md). Raise it as pages // are added; a glob that suddenly matches fewer has broken rather than found a clean tree. it('conforms to the org docs standard', function (): void { - $this->assertDocsConformToStandard(dirname(__DIR__, 2), 50); + $this->assertDocsConformToStandard(dirname(__DIR__, 2), 49); expect(true)->toBeTrue(); }); diff --git a/tests/Unit/SchemaShapeTest.php b/tests/Unit/SchemaShapeTest.php deleted file mode 100644 index 80049bc..0000000 --- a/tests/Unit/SchemaShapeTest.php +++ /dev/null @@ -1,126 +0,0 @@ - $extra */ -function settingsConfig(array $extra = []): array -{ - return array_replace_recursive([ - 'default' => 'settings', - 'stores' => ['settings' => ['layers' => ['database', 'runtime']], 'files' => ['layers' => ['runtime']]], - 'layers' => ['database' => ['driver' => 'database', 'connection' => 'tenant'], 'runtime' => ['driver' => 'json']], - ], $extra); -} - -it('derives the default shape from default configuration, with database stores only', function (): void { - $shape = SchemaShape::fromConfig(settingsConfig()); - - expect($shape->identity)->toBe(IdentityMode::SlugUid) - ->and($shape->ids)->toBe(IdType::Bigint) - ->and(array_keys($shape->stores))->toBe(['settings']) - ->and($shape->store(new StoreName('settings'))->connection)->toBe('tenant') - ->and($shape->store(new StoreName('files'))->mode)->toBe(StoreMode::Polymorphic) - ->and($shape->hasStore(new StoreName('files')))->toBeFalse(); -}); - -it('follows db-tools\' upper-case id type unless ids.type is set', function (): void { - expect(SchemaShape::fromConfig(settingsConfig(), 'UUID')->ids)->toBe(IdType::Uuid) - ->and(SchemaShape::fromConfig(settingsConfig(), 'UUID')->ownerKeyType)->toBe(IdType::Uuid) - ->and(SchemaShape::fromConfig(settingsConfig(['ids' => ['type' => 'ULID']]), 'UUID')->ids)->toBe(IdType::Ulid) - ->and(SchemaShape::fromConfig(settingsConfig(), 'nonsense')->ids)->toBe(IdType::Bigint); -}); - -it('round-trips through the schema file format', function (): void { - $shape = SchemaShape::fromConfig(settingsConfig([ - 'identity' => ['mode' => 'slug_per_row'], - 'translations' => ['mode' => 'json'], - 'categories' => ['soft_deletes' => true], - 'definitions' => ['table' => true], - 'tables' => ['prefix' => 'app_'], - 'stores' => [ - 'settings' => ['soft_deletes' => true, 'owners' => ['team']], - 'users' => ['layers' => ['database'], 'owners' => ['user'], 'mode' => 'dedicated', 'owner' => ['table' => 'members', 'key' => 'uuid', 'type' => 'uuid']], - ], - ])); - - expect(SchemaShape::fromArray($shape->toArray())->toArray())->toBe($shape->toArray()) - ->and($shape->store(new StoreName('users'))->fallback?->value)->toBe('settings') - ->and($shape->store(new StoreName('users'))->ownerKey)->toBe('uuid') - ->and($shape->differencesFrom($shape))->toBe([]); -}); - -it('lists every difference between two shapes, one line each', function (): void { - $before = SchemaShape::fromConfig(settingsConfig()); - $after = SchemaShape::fromConfig(settingsConfig(['identity' => ['mode' => 'uid_only'], 'stores' => ['settings' => ['soft_deletes' => true]]])); - - expect($after->differencesFrom($before))->toBe([ - 'switches.identity: slug_uid → uid_only', - 'stores.settings.soft_deletes: false → true', - ]); -}); - -it('keeps an existing store entry when the same store is added again', function (): void { - $shape = SchemaShape::fromConfig(settingsConfig()); - $other = new StoreSchema(new StoreName('settings'), softDeletes: true); - - expect($shape->withStore($other)->store(new StoreName('settings'))->softDeletes)->toBeFalse() - ->and($shape->withStore(new StoreSchema(new StoreName('extra')))->hasStore(new StoreName('extra')))->toBeTrue(); -}); - -it('names the config path of every invalid switch', function (array $extra, string $message): void { - expect(fn (): SchemaShape => SchemaShape::fromConfig(settingsConfig($extra)))->toThrow(InvalidConfiguration::class, $message); -})->with([ - 'identity' => [['identity' => ['mode' => 'nope']], 'identity.mode'], - 'owner key' => [['ids' => ['owner_key' => 'int']], 'ids.owner_key'], - 'id type not text' => [['ids' => ['type' => 5]], 'ids.type'], - 'translations' => [['translations' => ['mode' => 'po']], 'translations.mode'], - 'categories' => [['categories' => ['soft_deletes' => 'yes']], 'categories.soft_deletes'], - 'definitions table' => [['definitions' => ['table' => 'yes']], 'definitions.table'], - 'soft deletes' => [['stores' => ['settings' => ['soft_deletes' => 1]]], 'soft_deletes'], - 'table' => [['stores' => ['settings' => ['table' => 5]]], '.table'], - 'bad store name' => [['stores' => ['Bad Name' => ['layers' => ['database']]]], 'stores.Bad Name'], - 'section' => [['identity' => 'slug_uid'], 'laranail.settings.identity'], - 'dedicated chain' => [['stores' => [ - 'a' => ['layers' => ['database'], 'owners' => ['x'], 'mode' => 'dedicated', 'owner' => ['table' => 'xs'], 'fallback' => 'b'], - 'b' => ['layers' => ['database'], 'owners' => ['y'], 'mode' => 'dedicated', 'owner' => ['table' => 'ys']], - ]], 'is dedicated too'], - 'bad fallback name' => [['stores' => ['a' => ['layers' => ['database'], 'owners' => ['x'], 'mode' => 'dedicated', 'owner' => ['table' => 'xs'], 'fallback' => 'Bad Name']]], '.fallback'], - 'owner key column' => [['stores' => ['a' => ['layers' => ['database'], 'owners' => ['x'], 'mode' => 'dedicated', 'owner' => ['table' => 'xs', 'key' => 'Bad Key']]]], 'owner.key'], -]); - -it('refuses a dedicated store schema built without an owner', function (): void { - expect(fn (): StoreSchema => new StoreSchema(new StoreName('a'), StoreMode::Dedicated))->toThrow(InvalidConfiguration::class, 'dedicated store needs') - ->and(fn (): StoreSchema => new StoreSchema(new StoreName('a'), ownerTable: 'Bad Table'))->toThrow(InvalidConfiguration::class, 'owner.table'); -}); - -it('parses id types loosely and knows which identity columns each mode has', function (): void { - expect(IdType::parse(' BIGINT '))->toBe(IdType::Bigint) - ->and(IdType::parse('serial'))->toBeNull() - ->and(IdentityMode::UidOnly->hasSlug())->toBeFalse() - ->and(IdentityMode::SlugPerRow->hasUid())->toBeFalse() - ->and(IdentityMode::SlugUid->hasSlug() && IdentityMode::SlugUid->hasUid())->toBeTrue(); -}); - -it('records the tenancy mode, and reads a file written before it existed as none', function (): void { - $shape = SchemaShape::fromConfig(settingsConfig(['tenancy' => ['mode' => 'column']])); - $written = $shape->toArray(); - $older = $written; - unset($older['switches']['tenancy']); - - expect($shape->tenancy)->toBe(TenancyMode::Column) - ->and($written['switches']['tenancy'])->toBe('column') - ->and(SchemaShape::fromArray($written)->tenancy)->toBe(TenancyMode::Column) - ->and(SchemaShape::fromArray($older)->tenancy)->toBe(TenancyMode::None) - ->and($shape->withStore(new StoreSchema(new StoreName('extra')))->tenancy)->toBe(TenancyMode::Column) - ->and(SchemaShape::fromConfig(settingsConfig())->differencesFrom($shape))->toContain('switches.tenancy: column → none') - ->and(fn (): SchemaShape => SchemaShape::fromArray(['switches' => ['tenancy' => 'schema']] + $written))->toThrow(InvalidConfiguration::class, 'tenancy'); -}); diff --git a/tests/Unit/SupportTest.php b/tests/Unit/SupportTest.php index 8b07fd5..a364562 100644 --- a/tests/Unit/SupportTest.php +++ b/tests/Unit/SupportTest.php @@ -6,27 +6,21 @@ use Simtabi\Laranail\Settings\Support\Json; use Simtabi\Laranail\Settings\Data\OwnerRef; use Simtabi\Laranail\Settings\Support\Translations; -use Simtabi\Laranail\Settings\Enums\TranslationsMode; use Simtabi\Laranail\Settings\Support\DatabaseValues; use Simtabi\Laranail\Settings\Exceptions\DriverFailure; use Simtabi\Laranail\Settings\Exceptions\InvalidIdentifier; -it('stores and reads titles in both translation modes', function (): void { - $lang = new Translations(TranslationsMode::Lang); - $json = new Translations(TranslationsMode::Json); - - expect($lang->store('Mail', ['fr' => 'Courrier']))->toBe('Mail') - ->and($lang->texts('Mail'))->toBe(['' => 'Mail']) - ->and($lang->isJson())->toBeFalse() - ->and($json->store('Mail/É', ['fr' => 'Courrier']))->toBe('{"":"Mail/É","fr":"Courrier"}') - ->and($json->text('{"":"Mail","fr":"Courrier"}'))->toBe('Mail') - ->and($json->text('{"fr":"Courrier","de":"Post"}'))->toBe('Courrier') - ->and($json->texts('{"":"Mail","fr":3}'))->toBe(['' => 'Mail']) - ->and($json->text('not json'))->toBe('not json') - ->and($json->text('{"fr":3}'))->toBe('{"fr":3}') - ->and($json->storeNullable(null))->toBeNull() - ->and($json->nullableText(null))->toBeNull() - ->and($json->nullableText('{"":"Mail"}'))->toBe('Mail'); +it('builds and reads per-locale title maps', function (): void { + expect(Translations::of('Mail/É', ['fr' => 'Courrier']))->toBe(['' => 'Mail/É', 'fr' => 'Courrier']) + ->and(Translations::ofNullable(null))->toBeNull() + ->and(Translations::ofNullable('Mail'))->toBe(['' => 'Mail']) + ->and(Translations::text(['' => 'Mail', 'fr' => 'Courrier']))->toBe('Mail') + ->and(Translations::text(['fr' => 'Courrier', 'de' => 'Post']))->toBe('Courrier') + ->and(Translations::texts(['' => 'Mail', 'fr' => 3]))->toBe(['' => 'Mail']) + ->and(Translations::text('Mail'))->toBe('Mail') + ->and(Translations::texts('Mail'))->toBe(['' => 'Mail']) + ->and(Translations::text(['fr' => 3]))->toBeNull() + ->and(Translations::text(null))->toBeNull(); }); it('encodes JSON with one set of flags and names what failed', function (): void { From 85d181831447452a4f286c02c2a5520e434afc5a Mon Sep 17 00:00:00 2001 From: Imani Manyara Date: Tue, 10 Nov 2026 15:30:18 -0500 Subject: [PATCH 2/4] Document the fixed schema and the model data layer --- CHANGELOG.md | 42 ++++++++ README.md | 1 - docs/architecture.md | 47 ++++---- docs/configuration.md | 23 ++-- docs/getting-started.md | 2 +- docs/installation.md | 12 +-- docs/recipes/setting-up-multi-tenancy.md | 2 +- docs/tools/approvals.md | 2 +- docs/tools/commands.md | 12 +-- docs/tools/database.md | 82 ++++++++++---- docs/tools/history.md | 9 +- docs/tools/models-and-factories.md | 26 +++-- docs/tools/persisted-configuration.md | 6 +- docs/tools/rest-api-reference.md | 2 +- docs/tools/schema-switches.md | 131 ----------------------- docs/tools/settings-api.md | 2 +- docs/tools/tenancy.md | 6 +- 17 files changed, 178 insertions(+), 229 deletions(-) delete mode 100644 docs/tools/schema-switches.md diff --git a/CHANGELOG.md b/CHANGELOG.md index f5cd9ac..127b3f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -209,6 +209,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- The table shape is fixed, with `tenancy.mode` as the one switch: every table is keyed by a ULID, + each values row has a unique `uid` (the history's `setting_ref`) and no `slug`, `settable_id` is + `string(36)`, and titles, labels and descriptions are JSON maps of locale to text. The migration + always creates the definitions, history, change requests and persisted configuration tables, and + every values table has `deleted_at`. In `column` mode each tenant-owned table gets `tenant` in its + unique and lookup keys. Dedicated stores keep their `owner_id` foreign key. +- History is always recorded for a store with a database layer, and change requests always have + their table. A store on file layers only still raises `HistoryUnavailable` and + `ApprovalUnavailable`. +- `definitions.sources` defaults to `['code', 'config']`: add `database` to read definitions saved at + runtime, which costs one query per store per request. +- `configuration.persisted` now only turns the persisted configuration on and off; its table always + exists. +- Deleting a category deletes the row; creating the slug again makes a new category. +- The Eloquent models are the data layer for categories, definitions, audit, history and change + requests: `SettingsModel` holds the ULID keys, the connection and the tenant scope + (`Models\Scopes\TenantScope`, lifted with `allTenants()`), and the new `SettingHistory` and + `SettingChangeRequest` join `Setting`, `SettingCategory`, `SettingDefinition` and + `SettingAuditEntry`. The database driver still reads and writes values through the query builder + and takes the table name from `Setting::tableFor()`. `ModelContext` now holds the configuration + and the current tenant only. +- `doctor` checks that every column the package uses exists, instead of comparing a recorded shape + with configuration and the database. +- `QueryHistory::handle()` returns an Eloquent builder of `SettingHistory`. + - Prepared for the public release. Source, config, migration, route, helper and test comments are rewritten as short plain docblocks, with no references to internal planning documents; the design rationale they carried is now in `docs/architecture.md`. Comment lines in `src/` went @@ -302,6 +327,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Removed +- Removed with the owner's approval (2026-11-10), before the first tag, with the fixed schema: + the config keys `schema.path`, `identity.mode`, `ids.type`, `ids.owner_key`, + `translations.mode`, `categories.soft_deletes`, `definitions.table`, `history.enabled` and + `approvals.table`; `Database\SchemaShape`, `Database\StoreSchema`, + `Services\Database\SchemaShapeRepository` and the `database/settings-schema.php` file that + `install` and `make-store` recorded; the `Enums\IdentityMode`, `Enums\OwnerKeyType` and + `Enums\TranslationsMode` enums; `DatabaseDriver::newId()`, `shape()` and `schemaOf()`; the + `doctor` checks against a recorded shape; the pairwise schema matrix + (`tests/Feature/Database/SchemaMatrixTest.php`, `tests/Support/Pairwise.php`, test groups + `matrix`) and the weekly `matrix-full` CI job, replaced by a tenancy matrix (`none`, `column`) + in the `database` group; and `docs/tools/schema-switches.md`, whose surviving content is in + `docs/tools/database.md`. +- Removed with the same approval: `Services\Database\CategoryRepository`, + `DefinitionsRepository`, `AuditRepository`, `HistoryRepository` and `ChangeRequestRepository`, + whose queries live on the models and in the actions; and `Models\Concerns\UsesSettingsSchema`, + replaced by `Models\Concerns\BelongsToTenant` on `SettingsModel`. + - Removed with the owner's approval (2026-11-10), before the first tag: `Http\ApiRoutes`, `Enums\Capability`, `Http\OpenApi\OpenApiDocument` and the `laranail::settings.openapi` command; `Http\Middleware\FreshControllers`; the seven action bundles (`SettingActions`, diff --git a/README.md b/README.md index a430354..2fe47ea 100644 --- a/README.md +++ b/README.md @@ -104,7 +104,6 @@ The hosted docs live at .mode` | `polymorphic` | `dedicated`: one owner alias, an `owner_id` foreign key to `owner.table`, owner rows only (migration-time) | +| `tables.definitions` | `settings_definitions` | the definitions table | +| `stores..mode` | `polymorphic` | `dedicated`: one owner alias, an `owner_id` foreign key to `owner.table`, owner rows only (read when migrating) | | `stores..owner` | — | dedicated stores: `table`, `key` (`id`), `type` (`bigint`/`uuid`/`ulid`; null follows db-tools) | | `stores..fallback` | the default store | dedicated stores: the polymorphic store that holds their global values | -| `stores..soft_deletes` | `false` | trash forgotten rows and restore them on the next write (migration-time) | -| `schema.path` | `database/settings-schema.php` (`LARANAIL_SETTINGS_SCHEMA_PATH`) | where the recorded schema shape lives | -| `identity.mode` | `slug_uid` | `slug_uid`, `slug_per_row` or `uid_only` (migration-time) | -| `ids.type` | `null` | `bigint`, `uuid` or `ulid`; null follows `laranail.db-tools.id_type` (migration-time) | -| `ids.owner_key` | `string` | `typed` types `settable_id` like the owners' keys (migration-time) | -| `translations.mode` | `lang` | `json` stores titles, labels and descriptions per locale (migration-time) | -| `categories.soft_deletes` | `false` | trash deleted categories and restore them when the slug is created again (migration-time) | +| `stores..soft_deletes` | `false` | trash forgotten rows and restore them on the next write | | `writes.retry_on_conflict` | `true` | retry a plain `set()` once after a concurrent change | | `readiness.flush_on` | the stancl and spatie tenancy events | events after which schema readiness is re-checked | -| `tenancy.mode` | `none` (`LARANAIL_SETTINGS_TENANCY`) | `column` adds a `tenant` column to the values, categories and audit tables; `database` relies on a database per tenant (migration-time) | +| `tenancy.mode` | `none` (`LARANAIL_SETTINGS_TENANCY`) | `column` adds a `tenant` column to the values, categories, audit, history and change requests tables; `database` relies on a database per tenant (read when migrating, and on every query) | | `tenancy.discriminator` | `auto` | who the current tenant is: `auto` (stancl/tenancy, then spatie/laravel-multitenancy, when installed), `null`, `stancl`, `spatie`, or a class implementing `TenantDiscriminator` | | `seed.enabled` | `true` (`LARANAIL_SETTINGS_SEED`) | whether `db:seed` creates the default categories | | `seed.stores` | `[]` | the stores to seed; empty means the default store | @@ -43,8 +37,7 @@ Every key in `config/laranail/settings.php`, read at `config('laranail.settings. | `layers..path` | — | JSON: a path on the disk containing `{store}`; PHP: a path from the application root | | `layers..prefix` | — | config driver: the config prefix to read | | `definitions` | options only | `key => attributes`; see [Definitions](tools/definitions.md). `table`, `sources` and `allowed_rules` are options, not keys | -| `definitions.table` | `false` | create the optional definitions table (migration-time) | -| `definitions.sources` | `code`, `config`, `database` | where definitions come from; `database` is read only when the table exists | +| `definitions.sources` | `code`, `config` | where definitions come from; add `database` to read rows edited at runtime (one query per store per request) | | `definitions.allowed_rules` | common rule names | the rules a definitions-table row may use | | `authentication.resolver` | `guard` (`LARANAIL_SETTINGS_ACTOR_RESOLVER`) | how `asCurrentActor()` finds the actor: `guard`, `sanctum` or a class | | `authentication.guards` | `[]` | guards tried in order; empty means the default guard | @@ -65,18 +58,16 @@ Every key in `config/laranail/settings.php`, read at `config('laranail.settings. | `cache.ttl` | `3600` | seconds a cached bag is fresh (at least 1) | | `cache.stale` | `300` | seconds after `ttl` a stale bag is still answered while it is refreshed (`Cache::flexible()`); `0` for none | | `tables.history` | `settings_history` | the history table's name (after `tables.prefix`) | -| `history.enabled` | `true` (`LARANAIL_SETTINGS_HISTORY`) | schema switch: create the history table and record every change in it | | `history.keep_days` | `365` | how long `prune-history` keeps history entries; null for no age limit | | `history.keep_versions` | `null` | how many versions of each setting `prune-history` keeps; null for all | | `stores..approvals.keys` | `[]` | key globs (`billing.*`) whose writes become change requests | | `tables.change_requests` | `settings_change_requests` | the change requests table (after `tables.prefix`), one per connection | | `tables.stores` | `settings_stores` | the persisted configuration table, on the default store's connection | -| `approvals.table` | `true` | schema switch: create the change requests table | | `approvals.min_approvals` | `1` | approvals that apply a change | | `approvals.allow_self` | `false` | let the requester approve their own request | | `approvals.expire_after` | `7` | days before an open request expires; null for never | | `approvals.keep_days` | `90` | days `prune-changes` keeps decided requests; null for ever | -| `configuration.persisted` | `false` (`LARANAIL_SETTINGS_PERSISTED_CONFIGURATION`) | schema switch: create `settings_stores` and read persisted stores and layers | +| `configuration.persisted` | `false` (`LARANAIL_SETTINGS_PERSISTED_CONFIGURATION`) | read and write the stores and layers saved in `settings_stores` | | `configuration.sources` | `['config', 'database', 'runtime']` | merge order of the file, persisted entries and runtime changes; later wins | | `importers` | `spatie`, `toolkit`, `akaunting` | importers `import --from=` can use, name => class | | `typed.classes` | `[]` | typed settings classes whose properties are registered as definitions | @@ -97,7 +88,7 @@ Every key in `config/laranail/settings.php`, read at `config('laranail.settings. Store names, keys, locales and owner aliases are validated, and a misconfiguration (an unknown driver, sink, verifier, resolver, level or ability included) raises `InvalidConfiguration` naming the config path on first use. The `password_confirmation` verifier also reads Laravel's own `auth.password_timeout`. -Migration-time switches (`tenancy.mode` among them) are read by `install` and `make-store` and recorded in the schema file; after that the package reads the file, and `doctor` reports configuration that differs from it. See [Schema switches](tools/schema-switches.md). +The table shape is fixed. The migration reads `tenancy.mode`, the table names and each store's `table`, `mode` and `owner`; change them before migrating, since the runtime reads the same keys. See [Database](tools/database.md). Approvals are described in [Approvals](tools/approvals.md), persisted configuration in [Persisted configuration](tools/persisted-configuration.md), the REST API in [REST API](tools/rest-api.md), typed classes in [Typed settings](tools/typed-settings.md), and import and export in [Import and export](tools/import-export.md). History is described in [History](tools/history.md), events and the built-in listeners in [Events](tools/events.md), alerts in [Alerts](tools/alerts.md). The cache is described in [Caching](tools/caching.md). Access, audit and logging are described in [Access control](tools/access-control.md) and [Audit and logging](tools/audit-and-logging.md); per-request changes in [Runtime configuration](tools/runtime-configuration.md). diff --git a/docs/getting-started.md b/docs/getting-started.md index 2a233d6..e7c805f 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -69,7 +69,7 @@ Definitions add types, defaults, validation, encryption, locks and inheritance. | Phase | Adds | |---|---| -| Schema switches | uuid/ulid ids, typed owner keys, other identity modes, dedicated stores, soft deletes, translated labels | +| Dedicated stores | an `owner_id` foreign key that deletes an owner's settings with it; soft deletes | | Performance | caching with stale-while-revalidate | | Governance | history and rollback, approvals, export and import, the full `doctor` | | Typed classes | strongly typed settings classes over the same engine | diff --git a/docs/installation.md b/docs/installation.md index 5ae38eb..8a5d7dd 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -42,13 +42,11 @@ php artisan migrate Install publishes `config/laranail/settings.php` (tag `laranail::settings-config`) and the package's one migration (tag `laranail::settings-migrations`, -`…_create_laranail_settings_tables.php`), and records the schema it will produce in -`database/settings-schema.php`. The migration creates, in order, `settings_categories`, the -optional `settings_definitions`, one values table per database store (`settings` for the default -store), `settings_audit`, `settings_history` (`history.enabled`), `settings_change_requests` -(`approvals.table`) and `settings_stores` (`configuration.persisted`), and `down()` drops them in -reverse. Set the -[schema switches](tools/schema-switches.md) and `tenancy.mode` before installing. The default store +`…_create_laranail_settings_tables.php`). The migration creates, in order, `settings_categories`, +`settings_definitions`, one values table per database store (`settings` for the default store), +`settings_audit`, `settings_history`, `settings_change_requests` and `settings_stores`, and +`down()` drops them in reverse. The table shape is fixed (see [Database](tools/database.md)); set +`tenancy.mode`, the table names and any dedicated stores before migrating. The default store reads the database first, so run the migrations before the first read; until then a read raises `DriverUnavailable`. diff --git a/docs/recipes/setting-up-multi-tenancy.md b/docs/recipes/setting-up-multi-tenancy.md index 35fc4e9..523b227 100644 --- a/docs/recipes/setting-up-multi-tenancy.md +++ b/docs/recipes/setting-up-multi-tenancy.md @@ -17,7 +17,7 @@ php artisan laranail::settings.install php artisan migrate ``` -The mode is a migration-time switch, recorded in the schema file; changing it later needs a migration. With `database` mode instead, publish the migration into the tenant migrations folder and let the tenancy package switch connections. +The migration reads the mode to decide whether to add the `tenant` column, and the runtime reads the same key, so changing it later needs a migration. With `database` mode instead, publish the migration into the tenant migrations folder and let the tenancy package switch connections. ## Tell the package who the tenant is diff --git a/docs/tools/approvals.md b/docs/tools/approvals.md index 456b405..1735272 100644 --- a/docs/tools/approvals.md +++ b/docs/tools/approvals.md @@ -69,7 +69,7 @@ Events, all dispatched after commit and carrying identifiers only: `ChangeReques ## Where requests are kept -The `settings_change_requests` table, one per connection a store uses (like the history), created when `approvals.table` is on (the default; a schema switch recorded in the schema file). A store without an active database layer, or a schema recorded without the table, cannot hold requests: a write that needs approval there raises `ApprovalUnavailable`. +The `settings_change_requests` table, one per connection a store uses (like the history). A store without an active database layer cannot hold requests: a write that needs approval there raises `ApprovalUnavailable`. Run `laranail::settings.prune-changes` on a schedule: it marks open requests past their expiry as `expired` and deletes decided ones older than `approvals.keep_days`. `doctor` warns about open requests past their expiry. diff --git a/docs/tools/commands.md b/docs/tools/commands.md index aa26332..c169009 100644 --- a/docs/tools/commands.md +++ b/docs/tools/commands.md @@ -6,10 +6,10 @@ Nineteen Artisan commands, all named `laranail::settings.`. | Command | Does | |---|---| -| `laranail::settings.install` | publishes the config and the package's one migration, records the schema file, syncs definitions once the table exists; refuses to run over a foreign table of the same name | -| `laranail::settings.make-store {store} [--owner=*] [--connection=]` | writes a new store's migration (a copy of the package migration pinned to that store), records it in the schema file and prints its configuration entry | +| `laranail::settings.install` | publishes the config and the package's one migration, syncs definitions once the table exists; refuses to run over a foreign table of the same name | +| `laranail::settings.make-store {store} [--owner=*] [--connection=]` | writes a new store's migration (a copy of the package migration pinned to that store) and prints its configuration entry | | `laranail::settings.promote [store] [--force] [--from=]` | copies values written before install from the runtime file into the database | -| `laranail::settings.doctor [--json] [--fix]` | checks readiness, schema drift against the schema file and rows the database cannot guard; `--fix` syncs definitions first | +| `laranail::settings.doctor [--json] [--fix]` | checks readiness, missing columns and rows the database cannot guard; `--fix` syncs definitions first | | `laranail::settings.show {key} [--store=] [--owner=] [--locale=] [--reveal]` | prints how one setting resolves: value, layer, scope, type, version, flags and the latest audit entry | | `laranail::settings.sync-definitions` | copies code and config definitions into the definitions table as system rows | | `laranail::settings.prune-orphans [--dry-run]` | removes the settings of owners that no longer exist | @@ -53,9 +53,8 @@ For every store with a database layer: | Check | Fails when | |---|---| -| schema file | the file is older than this release's shape version, or a database store has no entry (warns when there is no file, or when configuration differs from it) | | readiness | the connection does not answer or the table is missing (a warning in bootstrap mode) | -| schema | a column the recorded shape uses is missing, or `id` has the wrong type (warns on a column the shape does not have) | +| schema | a column the package uses is missing from the values, categories, audit, history or change requests table (and, on the default store's connection, the definitions and stores tables) | | scopes | a scope names a class instead of a morph alias (fails) or an alias the store does not list (warns) | | categories | a row points at a category of another store | | category keys | warns when a value's key does not start with its category's slug | @@ -139,8 +138,7 @@ version, through the same action as `rollback()`. See [History](history.md). system actor, is audited under its name, and delegates to the same action as the PHP API. `doctor` also checks, per database store: encrypted values no current or previous key can read, -open change requests past their expiry, schema drift on the history, change requests and -persisted configuration tables, and persisted configuration entries skipped as invalid. +open change requests past their expiry, and persisted configuration entries skipped as invalid. ## Pruning and access diff --git a/docs/tools/database.md b/docs/tools/database.md index 8d32c26..a5017d2 100644 --- a/docs/tools/database.md +++ b/docs/tools/database.md @@ -8,38 +8,84 @@ The `database` driver keeps a store's values in a table, through the query build |---|---| | `settings` (each store's own, `stores..table`) | one row per (scope, key, locale) | | `settings_categories` | categories of every store on the connection | +| `settings_definitions` | definitions synced from code and edited at runtime, on the default store's connection | | `settings_audit` | the audit trail of every store on the connection | -| `settings_definitions` | optional (`definitions.table`): definitions synced from code and edited at runtime | -| `settings_history` | `history.enabled`: every value by version, of every store on the connection; see [History](history.md) | +| `settings_history` | every value by version, of every store on the connection; see [History](history.md) | +| `settings_change_requests` | writes waiting for approval; see [Approvals](approvals.md) | +| `settings_stores` | stores and layers saved through the API, on the default store's connection | `tables.prefix` goes in front of all of them. Every connection a store uses has its own -categories, audit and history tables, so a store's foreign keys and transactions never cross connections. -One migration creates them all, in that order (`down()` in reverse): see -[Installation](../installation.md). In column-mode [tenancy](tenancy.md) the values, categories, -audit and history tables have a `tenant` column that leads their keys. +categories, audit, history and change requests tables, so a store's foreign keys and transactions +never cross connections. One migration creates them all, in that order (`down()` in reverse): see +[Installation](../installation.md). In column-mode [tenancy](tenancy.md) every table but +`settings_definitions` and `settings_stores` has a `tenant` column that leads its keys. -The values table, in the default shape (polymorphic owners, identity mode `slug_uid`, bigint ids, -string owner key). Every other shape is a [schema switch](schema-switches.md): `uuid` / `ulid` -keys, `slug_per_row` or `uid_only` identity, typed owner keys, dedicated stores with an `owner_id` -foreign key, soft deletes, JSON labels, and the optional `settings_definitions` table. The -package reads the shape recorded in `database/settings-schema.php`, not live configuration. +The shape is fixed: every table is keyed by a ULID, and titles, labels and descriptions are JSON +maps of locale to text, with `""` for the text that applies to any locale. The values table: | Column | Notes | |---|---| +| `id` | a ULID | | `scope` | `global` or `alias:id`; never null, so it can be part of the unique key | -| `settable_type`, `settable_id` | the owner's morph alias and id, for reporting and your own `morphTo` | +| `settable_type`, `settable_id` | the owner's morph alias and id (`string(36)`, so integer, UUID and ULID model keys all fit), for reporting and your own `morphTo` | | `key`, `locale` | with `scope`, the identity: `unique(scope, key, locale)` | +| `uid` | a ULID per row, unique; the history refers to a row by it | | `group` | the key's first segment unless the definition names one; at most 64 characters | -| `slug` | the key with `.` replaced by `-`, shared by every row of the key | -| `uid` | a ULID per row | | `value` | the encoded (and, for encrypted settings, encrypted) value; `NULL` means no value on this row | | `category_id`, `category_store` | the category, always of the row's own store (composite foreign key) | | `is_encrypted`, `is_locked`, `is_public`, `type` | from the definition and the lock API | | `version` | starts at 1, raised by every write | +| `deleted_at` | set on a forgotten row in a store with `soft_deletes` | -`scope`, `key`, `slug` and `locale` use a binary collation (`utf8mb4_bin` on MySQL, `"C"` on -Postgres), so `Theme` and `theme` never become one row on one database only. Keys are lower-cased -before they reach the table anyway. +`scope`, `key` and `locale` use a binary collation (`utf8mb4_bin` on MySQL, `"C"` on Postgres), +so `Theme` and `theme` never become one row on one database only. Keys are lower-cased before +they reach the table anyway. + +## Dedicated stores + +```php +'stores' => [ + 'settings' => ['layers' => ['database', 'runtime', 'shipped'], 'owners' => ['team']], + 'user_settings' => [ + 'layers' => ['database'], + 'owners' => ['user'], // exactly one alias + 'mode' => 'dedicated', + 'owner' => ['table' => 'users', 'key' => 'id', 'type' => null], // type: bigint, uuid, ulid; null follows db-tools + 'fallback' => 'settings', // default: the default store + 'inherits' => true, + ], +], +``` + +A dedicated store's table has an `owner_id` column in place of `settable_type` and +`settable_id`: a foreign key to the owner table with `cascadeOnDelete`, so deleting a user +removes its settings in the database itself. It holds owner rows only: a global write raises +`OwnerNotAllowed` naming the fallback store, and the global step of the cascade, and a read with +no owner, read the fallback store. The fallback must be a configured polymorphic store; a +dedicated store without exactly one owner alias or an owner table is refused when the store +registry is built. Configure it before migrating: the migration reads `mode` and `owner`. + +## Soft deletes + +With `stores..soft_deletes`, `forget()` and `flush()` set `deleted_at`; reads, lock checks +and orphan pruning skip trashed rows. The next write to a trashed key restores that row through +the same version check as any update: the writer continues the trashed row's version, the update +clears `deleted_at` and resets `is_locked`, labels, `meta` and the category to the new write. So +the unique index never collides, a restore is never read as a conflict, and a forgotten lock +never comes back. `lock()` on a trashed key restores the row as a value-less lock. Every values +table has the `deleted_at` column, so the option can be turned on at any time. + +## The definitions table + +`laranail::settings.sync-definitions` (also run by `install` once the table exists, and by +`doctor --fix`) copies code and config definitions in as read-only `is_system` rows, so UIs can +list them; system rows nothing defines any more are removed. + +Other rows are definitions edited at runtime. With `database` in `definitions.sources` they answer +for keys no code or config definition covers, so a row can never loosen a coded setting, and a row +sharing a coded key is reported as a conflict and left alone. A row's rules are filtered through +`definitions.allowed_rules` (no `exists`, `unique` or rule classes), its type must be a registered +caster alias, and an encrypted definition's default is never copied into the table. ## Reads @@ -63,7 +109,7 @@ version it expects (`SettingWrite::$expectedVersion`), raises `ConcurrentModific its events and its audit row share one transaction on the store's connection. With soft deletes a write to a trashed key restores the row through the same version check; see -[Schema switches](schema-switches.md#soft-deletes). +[Soft deletes](#soft-deletes). ## Failures diff --git a/docs/tools/history.md b/docs/tools/history.md index 9825616..b938f34 100644 --- a/docs/tools/history.md +++ b/docs/tools/history.md @@ -9,7 +9,7 @@ Every change to a setting on a database layer appends one history entry: the val | Field | Meaning | |---|---| | `store`, `scope`, `key`, `locale` | which setting; the history is always looked up by these four | -| `setting_ref` | the row's `uid` (or its id where the identity mode has no uid), as a string | +| `setting_ref` | the row's `uid` | | `operation` | `set`, `forget`, `lock`, `unlock` or `rollback` | | `old_value`, `new_value` | the payloads exactly as the values table stored them: encoded JSON, and still encrypted for an encrypted setting | | `old_type`, `new_type`, `old_encrypted`, `new_encrypted` | what is needed to read the payloads back | @@ -19,7 +19,7 @@ Every change to a setting on a database layer appends one history entry: the val A failed history insert rolls the change back with it, so the history never misses a change. -A `forget` writes a tombstone (no new value). Setting the key again continues its version from the history, so "version 3" always means one value: `set:1`, `forget:1`, `set:2`. `flush()` and promotion are audited but write no history entries. History is not written for file layers, or when the schema was recorded with `history.enabled` off. +A `forget` writes a tombstone (no new value). Setting the key again continues its version from the history, so "version 3" always means one value: `set:1`, `forget:1`, `set:2`. `flush()` and promotion are audited but write no history entries. History is not written for file layers. ## Reading the history @@ -62,9 +62,10 @@ The value of version 3 is read back from the history, decrypted and decoded, the `history.keep_days` drops entries older than that many days; `history.keep_versions` keeps only that many versions of each setting. Either may be null; `laranail::settings.prune-history` applies them (needs `prune`, audited, dispatches `HistoryPruned`). Retention covers every tenant. -## Switching it off +## Stores without history -`history.enabled` is a [schema switch](schema-switches.md): it decides whether the migration creates the table, and the package reads the recorded value, not live configuration. With it off, `history()`, `rollback()` and `historyDiff()` raise `HistoryUnavailable`, and a key set again after a forget starts at version 1. +Every store with an active database layer keeps history. For a store on file layers only, +`history()`, `rollback()` and `historyDiff()` raise `HistoryUnavailable`. `reencrypt` (rewriting payloads after a key rotation, history included) is not part of this release. diff --git a/docs/tools/models-and-factories.md b/docs/tools/models-and-factories.md index 01d20f3..28f8439 100644 --- a/docs/tools/models-and-factories.md +++ b/docs/tools/models-and-factories.md @@ -6,16 +6,22 @@ Four Eloquent models, `Setting`, `SettingCategory`, `SettingDefinition` and `Set | Model | Table | Notes | |---|---|---| -| `Models\SettingCategory` | categories | `parent()`, `children()`, `forStore()` scope; trashed rows hidden | -| `Models\Setting` | one store's values | `Setting::forStore('billing')`, `->inStore('billing')`; `category()`; trashed rows hidden | -| `Models\SettingDefinition` | the optional definitions table | shared by every tenant | -| `Models\SettingAuditEntry` | the audit trail | ULID key, no timestamps | - -Table names, key types and connections come from the recorded schema shape, so the models follow -the [schema switches](schema-switches.md): uuid and ulid keys are generated on create. In -column-mode [tenancy](tenancy.md) they are limited to the current tenant and stamp it on create. - -The engine never uses them: reads and writes go through the drivers on the query builder. A +| `Models\SettingCategory` | categories | `parent()`, `children()`, `forStore()` and `central()` scopes | +| `Models\Setting` | one store's values | `Setting::forStore('billing')`, `->inStore('billing')`; `category()`; trashed rows hidden in a soft-deleting store | +| `Models\SettingDefinition` | definitions | `forStore()` and `runtime()` scopes; shared by every tenant | +| `Models\SettingAuditEntry` | the audit trail | `matching(AuditFilter)` scope; no timestamps | +| `Models\SettingHistory` | the value history | `forSetting()` and `matching(HistoryFilter)` scopes | +| `Models\SettingChangeRequest` | change requests | `matching(ChangeFilter)`, `open()` and `overdue()` scopes | + +All of them extend `Models\SettingsModel`: ULID keys, the default store's connection unless a +query names another with `on()`, and table names from `tables`. In column-mode +[tenancy](tenancy.md) they are limited to the current tenant and stamp it on create; +`allTenants()` lifts that for maintenance. + +The package reads and writes categories, definitions, audit, history and change requests through +these models. Values are the exception: the database driver reads and writes them through the +query builder, because that path runs on every request, and takes the table name from +`Setting::tableFor()`. A change made through a model skips validation, casting, encryption, locks, authorization and the audit trail, and `Setting::$value` is the encoded payload, so application code changes settings and categories through `Settings::`. diff --git a/docs/tools/persisted-configuration.md b/docs/tools/persisted-configuration.md index 37a1efa..818e58b 100644 --- a/docs/tools/persisted-configuration.md +++ b/docs/tools/persisted-configuration.md @@ -7,13 +7,13 @@ Stores, layers and definitions saved in the database and edited through the PHP ```php // config/laranail/settings.php 'configuration' => [ - 'persisted' => true, // a schema switch: creates settings_stores + 'persisted' => true, // read and write settings_stores 'sources' => ['config', 'database', 'runtime'], // merge order, later wins ], -'definitions' => ['table' => true], // persisted definitions live here +'definitions' => ['sources' => ['code', 'config', 'database']], // read saved definitions ``` -Both are schema switches, recorded in the schema file: turn them on, then `laranail::settings.install` and `migrate`. +The migration always creates `settings_stores` and `settings_definitions`. ## Editing diff --git a/docs/tools/rest-api-reference.md b/docs/tools/rest-api-reference.md index cecb53b..9f3a14b 100644 --- a/docs/tools/rest-api-reference.md +++ b/docs/tools/rest-api-reference.md @@ -51,7 +51,7 @@ Status: `200`, `401`, `403`, `404` (`unknown-store`). ### `PUT /stores/{store}/definitions/{key}` -`definitions.update`, ability `manage_definitions`. Saves a definition in the definitions table (needs `definitions.table`). It only answers for keys no code or config definition covers. +`definitions.update`, ability `manage_definitions`. Saves a definition in the definitions table (read back with `database` in `definitions.sources`). It only answers for keys no code or config definition covers. ```json {"attributes": {"type": "string", "default": "free", "rules": ["in:free,pro"], "label": "Plan"}} diff --git a/docs/tools/schema-switches.md b/docs/tools/schema-switches.md deleted file mode 100644 index 5072e25..0000000 --- a/docs/tools/schema-switches.md +++ /dev/null @@ -1,131 +0,0 @@ -# Schema switches - -Eight schema switches choose the shape of the package's tables at migration time; the defaults are the recommended shape, and the package then reads the recorded shape, never live configuration. - -## The switches - -| Switch | Values (default first) | Effect | -|---|---|---| -| `identity.mode` | `slug_uid`, `slug_per_row`, `uid_only` | which identity columns a values row has besides (scope, key, locale) | -| `ids.type` | `null` (follows `laranail.db-tools.id_type`), `bigint`, `uuid`, `ulid` | the key of every package table and of every foreign key to one | -| `ids.owner_key` | `string`, `typed` | `settable_id` as `string(36)`, or typed like the owners' keys | -| `stores..mode` | `polymorphic`, `dedicated` | `settable_type` / `settable_id`, or a non-null `owner_id` foreign key to one owner table | -| `stores..soft_deletes` | `false`, `true` | forgotten rows are trashed, and restored by the next write | -| `translations.mode` | `lang`, `json` | titles, labels and descriptions as text, or as per-locale JSON maps | -| `definitions.table` | `false`, `true` | creates the optional `settings_definitions` table | -| `history.enabled` | `true`, `false` | creates `settings_history` and records every change in it ([History](history.md)) | - -`categories.soft_deletes` (default `false`) gives categories the same trash-and-restore rule. -`tables.prefix` and the table names (`tables.categories`, `tables.audit`, `tables.definitions`, -`tables.history`, `stores..table`) are recorded with the switches and honoured everywhere, including the -check that refuses to install over a table that is not the package's. - -## Identity modes - -| Mode | `slug` | `uid` | -|---|---|---| -| `slug_uid` | the key with `.` replaced by `-`, shared by every row of the key, indexed | a ULID per row, unique | -| `slug_per_row` | `sha1(scope|key|locale)`, unique per row | none | -| `uid_only` | none | a ULID per row, unique | - -## Keys and owner keys - -With `uuid` or `ulid` the package generates every key itself (`Str::orderedUuid()`, -`Str::ulid()`); `category_id`, `parent_id` and the definitions table's `category_id` take the same -type, so the composite foreign key from a values table to its store's categories always matches. - -`ids.owner_key = typed` types `settable_id` like `laranail.db-tools.id_type` (the key type of the -application's models). A write for an owner id of another shape (`user:abc` against bigint keys) -raises `OwnerNotAllowed`. The package itself never queries by `settable_id`: every read goes -through `scope`, so the owner key type never meets the column type. - -## Dedicated stores - -```php -'stores' => [ - 'settings' => ['layers' => ['database', 'runtime', 'shipped'], 'owners' => ['team']], - 'user_settings' => [ - 'layers' => ['database'], - 'owners' => ['user'], // exactly one alias - 'mode' => 'dedicated', - 'owner' => ['table' => 'users', 'key' => 'id', 'type' => null], // type: bigint, uuid, ulid; null follows db-tools - 'fallback' => 'settings', // default: the default store - 'inherits' => true, - ], -], -``` - -A dedicated store's `owner_id` is a foreign key to the owner table with `cascadeOnDelete`, so -deleting a user removes its settings in the database itself. It holds owner rows only: a global -write raises `OwnerNotAllowed` naming the fallback store, and the global step of the cascade, and -a read with no owner, read the fallback store. The fallback must be a configured polymorphic -store; a dedicated store without exactly one owner alias or an owner table is refused when the -store registry is built. - -## Soft deletes - -With `stores..soft_deletes`, `forget()` and `flush()` set `deleted_at`; reads, lock checks -and orphan pruning skip trashed rows. The next write to a trashed key restores that row through -the same version check as any update: the writer continues the trashed row's version, the update -clears `deleted_at` and resets `is_locked`, labels, `meta` and the category to the new write. So -the unique index never collides, a restore is never read as a conflict, and a forgotten lock -never comes back. `lock()` on a trashed key restores the row as a value-less lock. - -Under `categories.soft_deletes`, deleting a category trashes it (its children move to the top -level and its settings lose the link, as before), and creating the same slug again restores the -row with the same id. - -## JSON translations - -Under `translations.mode = json`, a category's title is stored as a JSON map with `""` for the -title that applies to any locale: - -```php -$settings->categories()->create(new NewCategory('mail', 'Mail', translations: ['fr' => 'Courrier'])); -$settings->categories()->get('mail')->titleIn('fr_CA'); // "Courrier" (locale, then language, then "") -``` - -Labels and descriptions in the definitions table are stored the same way. Under `lang`, titles are -plain text or translation keys and `translations` is ignored. - -## The definitions table - -`definitions.table = true` creates `settings_definitions`. Code and config -definitions are copied in as read-only `is_system` rows by -`laranail::settings.sync-definitions` (also run by `install` once the table exists, and by -`doctor --fix`), so UIs can list them; system rows nothing defines any more are removed. - -Other rows are definitions edited at runtime. They answer only for keys no code or config -definition covers, so a row can never loosen a coded setting, and a row sharing a coded key is -reported as a conflict and left alone. A row's rules are filtered through -`definitions.allowed_rules` (no `exists`, `unique` or rule classes), its type must be a -registered caster alias, and an encrypted definition's default is never copied into the table. -`definitions.sources` (`code`, `config`, `database`) turns the config map or the table off. - -## The schema file - -`install` writes `database/settings-schema.php` (or `schema.path`): a `shape_version`, the -switches (`tenancy` included), the table names and one entry per database store. `make-store` -adds its store's entry. The package migration and the runtime read this file, not configuration, so changing a switch after -migrating changes nothing until a migration does. Commit it. An existing record always wins: -recording again only adds stores that are new. - -`doctor` reports drift three ways: configuration against the file (a warning naming each -difference), the file's `shape_version` against this release (a release that adds columns raises -it; an older file means an upgrade migration was never published), and the live tables against -the file (a missing column fails, a column the shape does not have warns, an `id` of the wrong -type fails). A database store with no entry in the file fails. - -## Keeping the switches tested - -`tests/Feature/Database/SchemaMatrixTest.php` builds a pairwise set of shapes (every pair of -switch values meets in at least one; 11 shapes covering all 217 pairs of the ten switches, -`tenancy.mode` none and column and `history.enabled` on and off included, both counts asserted) -and runs each end to end, inside a tenant in column mode, reading the history where it is on, and -finishing with `doctor`. It runs on SQLite with the suite and on MySQL and PostgreSQL in the -`database` group; `LARANAIL_SETTINGS_MATRIX=full` runs all 2,304 shapes, which the weekly CI job -does. A schema file recorded before `history.enabled` existed reads as history off. (`database` mode adds no column, so it is not a separate shape.) - ---- - -[← Docs index](../../README.md#documentation) diff --git a/docs/tools/settings-api.md b/docs/tools/settings-api.md index 5b23b6b..c27a657 100644 --- a/docs/tools/settings-api.md +++ b/docs/tools/settings-api.md @@ -354,7 +354,7 @@ Resets cached values; stored values are untouched. Needs `manage_stores` with an ## History -All three need a store that keeps history (`history.enabled` when it was migrated); otherwise `HistoryUnavailable`. See [History](history.md). +All three need a store with an active database layer; otherwise `HistoryUnavailable`. See [History](history.md). ### `history()` diff --git a/docs/tools/tenancy.md b/docs/tools/tenancy.md index c282f0f..e910445 100644 --- a/docs/tools/tenancy.md +++ b/docs/tools/tenancy.md @@ -7,11 +7,11 @@ Three modes keep each tenant's settings apart: none, a tenant column, or a datab | `tenancy.mode` | What changes | For | |---|---|---| | `none` (default) | nothing: one set of settings | single-tenant applications | -| `column` | the values, categories and audit tables get a `tenant` column; every row is stamped with the current tenant and every query is limited to it | one database shared by every tenant | +| `column` | the values, categories, audit, history and change requests tables get a `tenant` column; every row is stamped with the current tenant and every query is limited to it | one database shared by every tenant | | `database` | no column: the tenancy package switches the connection, and the store follows it | a database per tenant | -The mode is migration-time, like the other [schema switches](schema-switches.md): set it before -`install`, and the schema file records it. In `column` mode the tenant leads the unique keys +The mode is the one switch in the table shape: the migration adds the column, and the runtime +reads the same key, so set it before migrating and change it only with a migration. In `column` mode the tenant leads the unique keys (`unique(tenant, scope, key, locale)` on values, `unique(tenant, store, slug)` on categories), so two tenants can hold the same key, and `''` is the central application's rows. The column is `string(64)` and binary-collated, like `scope`. From a1262433bac79a90e37dbc4de5f338bcc9bc9656 Mon Sep 17 00:00:00 2001 From: Imani Manyara Date: Tue, 10 Nov 2026 15:35:00 -0500 Subject: [PATCH 3/4] Declare the category key before its self-reference; write JSON labels --- database/migrations/create_laranail_settings_tables.php | 4 +++- tests/Feature/Database/SoftDeletesTest.php | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/database/migrations/create_laranail_settings_tables.php b/database/migrations/create_laranail_settings_tables.php index 7d81f90..33b0f6d 100644 --- a/database/migrations/create_laranail_settings_tables.php +++ b/database/migrations/create_laranail_settings_tables.php @@ -52,7 +52,9 @@ public function up(): void $schema->create($names->categories(), function (Blueprint $table) use ($names, $tenant): void { $name = $names->categories(); - $table->ulid('id')->primary(); + $table->ulid('id'); + // Declared before the self-referencing foreign key: Postgres needs the key to exist first. + $table->primary('id'); if ($tenant) { $table->string('tenant', 64)->default(''); diff --git a/tests/Feature/Database/SoftDeletesTest.php b/tests/Feature/Database/SoftDeletesTest.php index 56ea821..bc9d619 100644 --- a/tests/Feature/Database/SoftDeletesTest.php +++ b/tests/Feature/Database/SoftDeletesTest.php @@ -43,7 +43,7 @@ it('does not bring back the lock or labels of the forgotten row', function (): void { settings()->set('site.name', 'One'); settings()->lock('site.name'); - DB::table('settings')->update(['label' => 'Stale', 'meta' => '{"x":1}']); + DB::table('settings')->update(['label' => '{"":"Stale"}', 'meta' => '{"x":1}']); settings()->unlock('site.name'); settings()->lock('site.name'); DB::table('settings')->update(['deleted_at' => now()]); From 924e2cb9e89f5d8cc29a7d8b9b1fa46ab7722e54 Mon Sep 17 00:00:00 2001 From: Imani Manyara Date: Tue, 10 Nov 2026 15:46:34 -0500 Subject: [PATCH 4/4] Compare stored labels as decoded JSON, not text --- tests/Feature/Database/DefinitionsTableTest.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/Feature/Database/DefinitionsTableTest.php b/tests/Feature/Database/DefinitionsTableTest.php index 086a805..fc2f344 100644 --- a/tests/Feature/Database/DefinitionsTableTest.php +++ b/tests/Feature/Database/DefinitionsTableTest.php @@ -43,7 +43,7 @@ function runtimeDefinition(string $key, array $columns = []): void $password = DB::table('settings_definitions')->where('key', 'mail.password')->first(); expect($report)->toMatchArray(['synced' => 2, 'removed' => 1, 'conflicts' => []]) - ->and(DB::table('settings_definitions')->where('key', 'site.name')->value('label'))->toBe('{"":"Site name"}') + ->and(json_decode((string) DB::table('settings_definitions')->where('key', 'site.name')->value('label'), true))->toBe(['' => 'Site name']) ->and(DB::table('settings_definitions')->where('key', 'site.name')->value('default'))->toBe('"Acme"') ->and((bool) $password?->is_system)->toBeTrue() ->and($password?->default)->toBeNull() @@ -59,7 +59,7 @@ function runtimeDefinition(string $key, array $columns = []): void runtimeDefinition('site.name', ['label' => '{"":"Edited"}']); expect(app(SyncDefinitions::class)->handle()['conflicts'])->toBe(['settings.site.name']) - ->and(DB::table('settings_definitions')->value('label'))->toBe('{"":"Edited"}'); + ->and(json_decode((string) DB::table('settings_definitions')->value('label'), true))->toBe(['' => 'Edited']); }); it('answers for keys no code covers from runtime rows, never from system rows', function (): void {