|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +use Illuminate\Database\Migrations\Migration; |
| 6 | +use Illuminate\Database\Schema\Blueprint; |
| 7 | +use Illuminate\Support\Facades\DB; |
| 8 | +use Illuminate\Support\Facades\Schema; |
| 9 | +use Relaticle\CustomFields\Enums\CustomFieldsFeature; |
| 10 | +use Relaticle\CustomFields\FeatureSystem\FeatureManager; |
| 11 | + |
| 12 | +/* |
| 13 | + * `onlySections()` (see BaseBuilder::onlySections()) lets consumers that version their |
| 14 | + * form definitions scope custom-field resolution by section id instead of by code, so a |
| 15 | + * cloned section can carry a field whose code already exists on its sibling section. The |
| 16 | + * unique key created by create_custom_fields_table.php — (code, entity_type[, tenant]) — |
| 17 | + * blocks exactly that data shape at the database level, so any consumer of onlySections() |
| 18 | + * would fail to save the second field unless this key is widened to also include |
| 19 | + * custom_field_section_id. |
| 20 | + * |
| 21 | + * custom_field_sections is deliberately left untouched: onlySections() scopes by section |
| 22 | + * id, never by section code, so nothing here requires sections to share a code. |
| 23 | + * |
| 24 | + * custom_field_section_id is nullable, and both MySQL and Postgres treat NULL as distinct |
| 25 | + * in a unique index — including within a composite one. So after this migration, two rows |
| 26 | + * that both have custom_field_section_id IS NULL can still share (code, entity_type[, |
| 27 | + * tenant]): the wide key does not constrain them, because NULL never equals NULL for |
| 28 | + * uniqueness purposes. That's a protection existing installs have today (every row is |
| 29 | + * globally unique per entity type) and silently lose once this ships. There is no schema |
| 30 | + * workaround for this — a consumer that needs collision protection for sectionless fields |
| 31 | + * must keep them out of this data shape or enforce it at the application layer. |
| 32 | + */ |
| 33 | +return new class extends Migration |
| 34 | +{ |
| 35 | + public function up(): void |
| 36 | + { |
| 37 | + $this->swapUniqueKey( |
| 38 | + from: $this->narrowColumns(), |
| 39 | + fromIndexName: null, |
| 40 | + to: $this->wideColumns(), |
| 41 | + toIndexName: $this->wideIndexName(), |
| 42 | + ); |
| 43 | + } |
| 44 | + |
| 45 | + public function down(): void |
| 46 | + { |
| 47 | + $this->assertNoDuplicatesUnderNarrowKey(); |
| 48 | + |
| 49 | + $this->swapUniqueKey( |
| 50 | + from: $this->wideColumns(), |
| 51 | + fromIndexName: $this->wideIndexName(), |
| 52 | + to: $this->narrowColumns(), |
| 53 | + toIndexName: null, |
| 54 | + ); |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * MySQL runs each ALTER TABLE as its own auto-committing DDL statement, so dropping |
| 59 | + * the wide key and adding the narrow one are not transactional together. If rows exist |
| 60 | + * that share (code, entity_type[, tenant]) across different sections — exactly the |
| 61 | + * shape the wide key exists to allow — the DROP succeeds and the subsequent ADD fails |
| 62 | + * on the duplicate, leaving the table with neither unique key. Check first and abort |
| 63 | + * before touching anything. |
| 64 | + */ |
| 65 | + private function assertNoDuplicatesUnderNarrowKey(): void |
| 66 | + { |
| 67 | + $table = config('custom-fields.database.table_names.custom_fields'); |
| 68 | + |
| 69 | + if (! Schema::hasColumn($table, 'custom_field_section_id')) { |
| 70 | + return; |
| 71 | + } |
| 72 | + |
| 73 | + $columns = $this->narrowColumns(); |
| 74 | + |
| 75 | + $duplicateCodes = DB::table($table) |
| 76 | + ->select($columns) |
| 77 | + ->groupBy($columns) |
| 78 | + ->havingRaw('count(*) > 1') |
| 79 | + ->pluck('code'); |
| 80 | + |
| 81 | + if ($duplicateCodes->isEmpty()) { |
| 82 | + return; |
| 83 | + } |
| 84 | + |
| 85 | + throw new RuntimeException(sprintf( |
| 86 | + 'Cannot roll back the custom_fields unique key: %d code(s) — including "%s" — are shared by more than one row for the same (%s), only differing by custom_field_section_id. onlySections() allows this under the wide key, but the narrow key being restored cannot. Resolve or remove the duplicate rows before rolling back this migration.', |
| 87 | + $duplicateCodes->count(), |
| 88 | + $duplicateCodes->first(), |
| 89 | + implode(', ', $columns) |
| 90 | + )); |
| 91 | + } |
| 92 | + |
| 93 | + /** |
| 94 | + * Drops $from's unique key if present and adds $to's if absent. Shared by both |
| 95 | + * directions: up() widens (code, entity_type[, tenant]) to also include |
| 96 | + * custom_field_section_id; down() narrows it back to the original key. |
| 97 | + * |
| 98 | + * @param array<int, string> $from |
| 99 | + * @param array<int, string> $to |
| 100 | + */ |
| 101 | + private function swapUniqueKey(array $from, ?string $fromIndexName, array $to, ?string $toIndexName): void |
| 102 | + { |
| 103 | + $table = config('custom-fields.database.table_names.custom_fields'); |
| 104 | + |
| 105 | + if (! Schema::hasColumn($table, 'custom_field_section_id')) { |
| 106 | + return; |
| 107 | + } |
| 108 | + |
| 109 | + $fromIndexName ??= $this->defaultUniqueIndexName($table, $from); |
| 110 | + $toIndexName ??= $this->defaultUniqueIndexName($table, $to); |
| 111 | + $existingIndexes = collect(Schema::getIndexes($table))->pluck('name'); |
| 112 | + |
| 113 | + Schema::table($table, function (Blueprint $blueprint) use ($existingIndexes, $fromIndexName, $to, $toIndexName): void { |
| 114 | + if ($existingIndexes->contains($fromIndexName)) { |
| 115 | + $blueprint->dropUnique($fromIndexName); |
| 116 | + } |
| 117 | + |
| 118 | + if (! $existingIndexes->contains($toIndexName)) { |
| 119 | + $blueprint->unique($to, $toIndexName); |
| 120 | + } |
| 121 | + }); |
| 122 | + } |
| 123 | + |
| 124 | + /** |
| 125 | + * @return array<int, string> |
| 126 | + */ |
| 127 | + private function narrowColumns(): array |
| 128 | + { |
| 129 | + $columns = ['code', 'entity_type']; |
| 130 | + |
| 131 | + if (FeatureManager::isEnabled(CustomFieldsFeature::SYSTEM_MULTI_TENANCY)) { |
| 132 | + $columns[] = config('custom-fields.database.column_names.tenant_foreign_key'); |
| 133 | + } |
| 134 | + |
| 135 | + return $columns; |
| 136 | + } |
| 137 | + |
| 138 | + /** |
| 139 | + * @return array<int, string> |
| 140 | + */ |
| 141 | + private function wideColumns(): array |
| 142 | + { |
| 143 | + return [...$this->narrowColumns(), 'custom_field_section_id']; |
| 144 | + } |
| 145 | + |
| 146 | + private function wideIndexName(): string |
| 147 | + { |
| 148 | + return FeatureManager::isEnabled(CustomFieldsFeature::SYSTEM_MULTI_TENANCY) |
| 149 | + ? 'cf_code_entity_tenant_section_unique' |
| 150 | + : 'cf_code_entity_section_unique'; |
| 151 | + } |
| 152 | + |
| 153 | + /** |
| 154 | + * Mirrors Laravel's own auto-generated unique-index name (Blueprint::createIndexName()) |
| 155 | + * so the drop target matches exactly what create_custom_fields_table.php produced, |
| 156 | + * without hardcoding a name that would drift if a configured column name changes. |
| 157 | + * |
| 158 | + * Laravel's shipped config/database.php enables `prefix_indexes` for mysql and pgsql, |
| 159 | + * which makes Blueprint::createIndexName() fold the connection's table prefix into the |
| 160 | + * name it generates. Skipping that step here would compute a drop target that never |
| 161 | + * matches the real index name on a prefixed install, so the drop would silently no-op. |
| 162 | + * |
| 163 | + * @param array<int, string> $columns |
| 164 | + */ |
| 165 | + private function defaultUniqueIndexName(string $table, array $columns): string |
| 166 | + { |
| 167 | + $connection = Schema::getConnection(); |
| 168 | + |
| 169 | + $prefixedTable = $connection->getConfig('prefix_indexes') |
| 170 | + ? $this->applyTablePrefix($table, $connection->getTablePrefix()) |
| 171 | + : $table; |
| 172 | + |
| 173 | + $index = strtolower($prefixedTable.'_'.implode('_', $columns).'_unique'); |
| 174 | + |
| 175 | + return str_replace(['-', '.'], '_', $index); |
| 176 | + } |
| 177 | + |
| 178 | + private function applyTablePrefix(string $table, string $prefix): string |
| 179 | + { |
| 180 | + return str_contains($table, '.') |
| 181 | + ? substr_replace($table, '.'.$prefix, strrpos($table, '.'), 1) |
| 182 | + : $prefix.$table; |
| 183 | + } |
| 184 | +}; |
0 commit comments