From e7e0d6cc484266f931684f7c0be380309a8a576b Mon Sep 17 00:00:00 2001 From: Artur Kyryliuk Date: Sat, 5 Dec 2026 21:23:11 +0100 Subject: [PATCH 1/2] fix(migrations): keep the file_groups charset when making paths case-sensitive The 2026_10_11 migration converted file_groups.file to utf8mb4. On a MyISAM table with a utf8mb3 column that widens the indexed VARCHAR(255) to 1020 bytes, past the MyISAM key limit of 1000, and the update stops with error 1071. Change only the collation, to the binary one of the column's own character set, named as the server spells it (utf8_bin on MySQL 5.7). Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- ...0_make_file_groups_file_case_sensitive.php | 36 +++++++++++++++++-- .../Unit/FileGroupsSchemaAndModelTest.php | 16 +++++++++ 3 files changed, 50 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 1c81842a11..523082b461 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -454,7 +454,7 @@ The name check also catches the spellings Windows turns into such a file: traili | Rename, move or delete an existing entry (media browser too) | the top-level rule of the classic manager, measured from the manager's own `filemanager_path` (`canModifyExisting()` in `browser.php`) | | Delete a link | removing a symlink or junction (a passable one through the folder or file delete, any other through `deletelink`) removes the link only and never forgets the groups stored under its name, which apply again if the link returns | | Upload over an existing file | the file's own restrictions, not just the folder's (`fileManagerCanModifyExistingPath()`); the file keeps them and is **not** given the folder's groups | -| Copy / duplicate (both file managers) | access is an AND over the restricted folders on the way and the file itself, each an OR over its groups, which one set of groups on one key cannot say. `FileManagerAccess::carriedRestrictions()` keeps the groups that satisfy every set the destination does not already enforce; the copy is refused when there are none, and when the destination is the ACL root itself or lies outside it (no per-entry row can be stored there). Never store the union of the groups. A copy takes `replaceRestrictions()` and a rename or move takes `moveRestrictions()`, which first drops rows left at the free destination by files removed outside the CMS. Rows are matched by the exact stored path (`exactRows()`), and the `file_groups.file` column is case-sensitive (`utf8mb4_bin` on MySQL), because on a case-sensitive file system `report.txt` and `REPORT.txt` are two files | +| Copy / duplicate (both file managers) | access is an AND over the restricted folders on the way and the file itself, each an OR over its groups, which one set of groups on one key cannot say. `FileManagerAccess::carriedRestrictions()` keeps the groups that satisfy every set the destination does not already enforce; the copy is refused when there are none, and when the destination is the ACL root itself or lies outside it (no per-entry row can be stored there). Never store the union of the groups. A copy takes `replaceRestrictions()` and a rename or move takes `moveRestrictions()`, which first drops rows left at the free destination by files removed outside the CMS. Rows are matched by the exact stored path (`exactRows()`), and the `file_groups.file` column is case-sensitive (on MySQL the binary collation of the column's own character set: converting it to utf8mb4 would push the indexed column past the MyISAM key limit), because on a case-sensitive file system `report.txt` and `REPORT.txt` are two files | | Any name the media browser writes (copy, move, upload, thumbnail) | the destination is free, a dangling symlink counts as taken (`isTaken()`), and copies are made exclusively with `copyExclusive()` (`fopen` mode `x`), never `copy()` through a link | | Move (media browser) | the same `carriedRestrictions()`, read before the move and applied with `replaceRestrictions()` after it (a moved file brings its own, possibly wider, groups); refused when no set expresses it | | ZIP extraction | the archive and the target folder, and **each entry** via `fileManagerZipWriteGuard()` | diff --git a/core/database/migrations/2026_10_11_000000_make_file_groups_file_case_sensitive.php b/core/database/migrations/2026_10_11_000000_make_file_groups_file_case_sensitive.php index 19dcb99585..8aa04f3f5f 100644 --- a/core/database/migrations/2026_10_11_000000_make_file_groups_file_case_sensitive.php +++ b/core/database/migrations/2026_10_11_000000_make_file_groups_file_case_sensitive.php @@ -8,6 +8,10 @@ * File group keys are paths, and on a case-sensitive file system report.txt and REPORT.txt are two * files. A case-insensitive column collation (the database default for utf8mb4_unicode_ci) treats * their rows as one, and the unique index then refuses the second one: the copy stays unrestricted. + * + * Only the collation changes, to the binary one of the column's own character set. Converting the + * character set as well (utf8mb3 to utf8mb4) widens the indexed column past the key limit of + * MyISAM (1000 bytes) or of an old InnoDB row format (767 bytes), and the update stops there. */ class MakeFileGroupsFileCaseSensitive extends Migration { @@ -19,15 +23,41 @@ public function up() $table = DB::getTablePrefix() . 'file_groups'; $current = DB::selectOne( - 'SELECT COLLATION_NAME AS collation FROM information_schema.COLUMNS' + 'SELECT CHARACTER_SET_NAME AS charset, COLLATION_NAME AS collation FROM information_schema.COLUMNS' . ' WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?', [$table, 'file'] ); - if (!$current || str_ends_with((string) $current->collation, '_bin')) { + if (!$current || empty($current->charset) || str_ends_with((string) $current->collation, '_bin')) { return; } - DB::statement("ALTER TABLE `{$table}` MODIFY `file` VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL DEFAULT ''"); + $charset = (string) $current->charset; + // Ask the server how it spells the binary collation: names differ between MySQL and MariaDB versions (utf8 / utf8mb3). + $binary = DB::selectOne( + 'SELECT COLLATION_NAME AS collation FROM information_schema.COLLATIONS' + . " WHERE CHARACTER_SET_NAME = ? AND COLLATION_NAME LIKE '%\\_bin'" + . ' ORDER BY COLLATION_NAME = CONCAT(?, \'_bin\') DESC, CHAR_LENGTH(COLLATION_NAME), COLLATION_NAME LIMIT 1', + [$charset, $charset] + ); + if (!$binary || empty($binary->collation)) { + return; + } + + DB::statement(static::modifyStatement($table, $charset, (string) $binary->collation)); + } + + /** + * The ALTER that gives the column a binary collation and keeps its character set. + */ + public static function modifyStatement(string $table, string $charset, string $collation): string + { + foreach ([$table, $charset, $collation] as $identifier) { + if (!preg_match('/^[A-Za-z0-9_$]+$/', $identifier)) { + throw new InvalidArgumentException('Unexpected identifier: ' . $identifier); + } + } + + return "ALTER TABLE `{$table}` MODIFY `file` VARCHAR(255) CHARACTER SET {$charset} COLLATE {$collation} NOT NULL DEFAULT ''"; } public function down() diff --git a/core/tests/Unit/FileGroupsSchemaAndModelTest.php b/core/tests/Unit/FileGroupsSchemaAndModelTest.php index 38063a30e8..7aaf534623 100644 --- a/core/tests/Unit/FileGroupsSchemaAndModelTest.php +++ b/core/tests/Unit/FileGroupsSchemaAndModelTest.php @@ -30,3 +30,19 @@ expect($source)->toContain('public function fileGroups(): Eloquent\Relations\HasMany') ->and($source)->toContain("return \$this->hasMany(FileGroup::class, 'document_group');"); }); + +test('case-sensitive file groups migration keeps the column character set', function () { + require_once dirname(__DIR__, 2) . '/database/migrations/2026_10_11_000000_make_file_groups_file_case_sensitive.php'; + $source = (string) file_get_contents(dirname(__DIR__, 2) . '/database/migrations/2026_10_11_000000_make_file_groups_file_case_sensitive.php'); + + // utf8mb3 -> utf8mb4 widens the indexed column to 1020 bytes, past the MyISAM key limit of 1000 (error 1071) + expect(MakeFileGroupsFileCaseSensitive::modifyStatement('evo_file_groups', 'utf8mb3', 'utf8mb3_bin')) + ->toBe("ALTER TABLE `evo_file_groups` MODIFY `file` VARCHAR(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_bin NOT NULL DEFAULT ''") + ->and(MakeFileGroupsFileCaseSensitive::modifyStatement('file_groups', 'utf8mb4', 'utf8mb4_bin')) + ->toContain('CHARACTER SET utf8mb4 COLLATE utf8mb4_bin') + ->and($source)->toContain('CHARACTER_SET_NAME AS charset') + ->and($source)->not->toContain('CHARACTER SET utf8mb4'); + + expect(fn () => MakeFileGroupsFileCaseSensitive::modifyStatement('file_groups', 'utf8mb4; DROP', 'utf8mb4_bin')) + ->toThrow(InvalidArgumentException::class); +}); From 686bb62326419ae7f788af621d4fa7e6968869c8 Mon Sep 17 00:00:00 2001 From: Artur Kyryliuk Date: Sat, 5 Dec 2026 22:52:58 +0100 Subject: [PATCH 2/2] fix(migrations): fit file_groups to the MyISAM key limit and test MySQL engines in CI MyISAM is a supported engine: the installers write it for older servers and sites keep it, often with a utf8 (utf8mb3) connection. The file_groups migrations now respect its 1000-byte key limit: - core/includes/file_groups_schema.php, loaded by path: the engine and charset a new table gets, bytes per character, the binary collation as the server names it (RIGHT(), not LIKE '%\_bin', which matches nothing under NO_BACKSLASH_ESCAPES), and the longest `file` the unique key allows. - The create migration (both copies) declares the binary collation itself and, on MyISAM with utf8mb4, creates `file` as VARCHAR(249). - 2026_10_11 keeps the column length as well as its charset. - 2026_12_05_000000_restore_file_groups_indexes puts back the indexes a create that hit the key limit left out, drops the duplicates it let in, and keeps rows whose path is longer than the key allows. CI: an install leg on MySQL with MyISAM, a nightly upgrade of a site turned MyISAM / utf8mb3 (legacy-myisam.php), smoke checks for the file_groups key and collation and the engine of every table, and FileGroupsMysqlTest run against a real server (EVO_TEST_MYSQL) in both SQL modes. AGENTS.md lists the rules. Co-Authored-By: Claude Opus 5.5 --- .github/docker/ci/install-and-smoke.sh | 7 + .github/docker/ci/legacy-myisam.php | 36 +++ .github/docker/ci/smoke.php | 29 +++ .github/docker/ci/upgrade-and-smoke.sh | 9 + .github/workflows/ci.yml | 22 +- .github/workflows/upgrade.yml | 14 +- AGENTS.md | 28 +++ ..._03_29_000000_create_file_groups_table.php | 25 +- ...0_make_file_groups_file_case_sensitive.php | 48 ++-- ..._05_000000_restore_file_groups_indexes.php | 129 ++++++++++ core/includes/file_groups_schema.php | 126 ++++++++++ .../Unit/FileGroupsSchemaAndModelTest.php | 16 -- .../Unit/Install/FileGroupsMysqlTest.php | 236 ++++++++++++++++++ .../Install/FileGroupsStorageEngineTest.php | 162 ++++++++++++ ..._03_29_000000_create_file_groups_table.php | 25 +- 15 files changed, 855 insertions(+), 57 deletions(-) create mode 100644 .github/docker/ci/legacy-myisam.php create mode 100644 core/database/migrations/2026_12_05_000000_restore_file_groups_indexes.php create mode 100644 core/includes/file_groups_schema.php create mode 100644 core/tests/Unit/Install/FileGroupsMysqlTest.php create mode 100644 core/tests/Unit/Install/FileGroupsStorageEngineTest.php diff --git a/.github/docker/ci/install-and-smoke.sh b/.github/docker/ci/install-and-smoke.sh index bd1f89a9cf..f8c021cd38 100755 --- a/.github/docker/ci/install-and-smoke.sh +++ b/.github/docker/ci/install-and-smoke.sh @@ -34,6 +34,13 @@ export EVO_LANGUAGE=${EVO_LANGUAGE:-en} LOG=/tmp/install.log UPDATE_LOG=/tmp/update.log +# EVO_DB_ENGINE (mysql): the storage engine to install on, through DB_ENGINE of the +# connection config. MyISAM is supported, and its key limit is 1000 bytes: smoke.php +# then also checks that every table got it. +if [ -n "${EVO_DB_ENGINE:-}" ]; then + export DB_ENGINE=$EVO_DB_ENGINE +fi + wait_for_db say "Installing Evolution CMS (${EVO_DB_TYPE}, database '${EVO_DB_NAME}', prefix '${EVO_DB_PREFIX}')" diff --git a/.github/docker/ci/legacy-myisam.php b/.github/docker/ci/legacy-myisam.php new file mode 100644 index 0000000000..b8989fc814 --- /dev/null +++ b/.github/docker/ci/legacy-myisam.php @@ -0,0 +1,36 @@ + + */ +$root = rtrim($argv[1] ?? '', '/'); +if (!function_exists('env')) { + function env(string $key, $default = null) + { + $value = getenv($key); + + return $value === false ? $default : $value; + } +} +$config = require $root . '/core/config/database/connections/default.php'; +if (($config['driver'] ?? '') !== 'mysql') { + fwrite(STDERR, 'legacy-myisam: mysql only, not ' . ($config['driver'] ?? '?') . PHP_EOL); + exit(1); +} + +$pdo = new PDO( + 'mysql:host=' . $config['host'] . ';port=' . $config['port'] . ';dbname=' . $config['database'], + $config['username'], + $config['password'], + [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION] +); +$tables = $pdo->prepare("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_TYPE = 'BASE TABLE' AND LEFT(TABLE_NAME, CHAR_LENGTH(?)) = ?"); +$tables->execute([$config['prefix'], $config['prefix']]); +foreach ($tables->fetchAll(PDO::FETCH_COLUMN) as $table) { + $pdo->exec('ALTER TABLE `' . str_replace('`', '``', $table) . '` ENGINE=MyISAM, CONVERT TO CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci'); + echo ' MyISAM utf8mb3: ' . $table . PHP_EOL; +} diff --git a/.github/docker/ci/smoke.php b/.github/docker/ci/smoke.php index c2c26d6e5d..e4461d4129 100644 --- a/.github/docker/ci/smoke.php +++ b/.github/docker/ci/smoke.php @@ -260,6 +260,35 @@ function setting(string $name) check('the old installer log is in migrations', $notCopied === 0, 'missing: ' . $notCopied); } +if ($driver === 'mysql') { + echo PHP_EOL . 'MySQL storage' . PHP_EOL; + // File group keys are case-exact paths under one unique key, on every engine. A create that ran + // into the MyISAM key limit (1000 bytes) used to leave the table without its indexes. + $column = $pdo->prepare('SELECT COLLATION_NAME FROM information_schema.COLUMNS' + . ' WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?'); + $column->execute([$prefix . 'file_groups', 'file']); + $collation = (string) $column->fetchColumn(); + check('file_groups.file compares paths case-sensitively', str_ends_with($collation, '_bin'), 'collation: ' . $collation); + $unique = $pdo->query('SHOW INDEX FROM ' . t('file_groups') . " WHERE Non_unique = 0 AND Key_name <> 'PRIMARY'")->fetchAll(); + $uniqueColumns = implode(', ', array_column($unique, 'Column_name')); + check('file_groups has its unique key (document_group, file)', $uniqueColumns === 'document_group, file', 'unique: ' . $uniqueColumns); + + // EVO_DB_ENGINE: the engine the run asked for (DB_ENGINE), which every table has to have. + $engine = (string) getenv('EVO_DB_ENGINE'); + if ($engine !== '') { + $tables = $pdo->prepare('SELECT TABLE_NAME, ENGINE FROM information_schema.TABLES' + . " WHERE TABLE_SCHEMA = DATABASE() AND TABLE_TYPE = 'BASE TABLE' AND LEFT(TABLE_NAME, CHAR_LENGTH(?)) = ?"); + $tables->execute([$prefix, $prefix]); + $other = []; + foreach ($tables->fetchAll() as $table) { + if (strcasecmp((string) $table['ENGINE'], $engine) !== 0) { + $other[] = $table['TABLE_NAME'] . ' ' . $table['ENGINE']; + } + } + check('every table uses ' . $engine, $other === [], implode(', ', $other)); + } +} + echo PHP_EOL . 'Seeded content' . PHP_EOL; // An upgraded site carries the content the older release seeded and whatever // its owner added since, so only a fresh install can be held to one document diff --git a/.github/docker/ci/upgrade-and-smoke.sh b/.github/docker/ci/upgrade-and-smoke.sh index 5f44c148d0..af2a59c990 100755 --- a/.github/docker/ci/upgrade-and-smoke.sh +++ b/.github/docker/ci/upgrade-and-smoke.sh @@ -82,6 +82,15 @@ if grep -nE 'SQLSTATE\[|Fatal error:' "$SOURCE_LOG"; then fail "the ${from_version} installer failed to build a database to upgrade" fi +# EVO_DB_LEGACY=myisam (mysql): the site an old installation still is - every table MyISAM +# with utf8mb3 text, and a connection config that says so (engine MyISAM, charset utf8). +# The migration chain has to get through it as it is. +if [ "${EVO_DB_LEGACY:-}" = "myisam" ]; then + say "Turning the ${from_version} database into an old MyISAM / utf8mb3 site" + php "$NEW_DIR/.github/docker/ci/legacy-myisam.php" "$APP_DIR" || fail "could not convert the ${from_version} database" + export DB_ENGINE=MyISAM DB_CHARSET=utf8 DB_COLLATION=utf8_general_ci EVO_DB_ENGINE=MyISAM +fi + say "Recording what ${from_version} left in the database" php "$SMOKE" --mode=baseline "$APP_DIR" || fail "the ${from_version} install is not usable as an upgrade source" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e79fe2aea0..bb5741a42d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -96,7 +96,7 @@ jobs: uses: shivammathur/setup-php@v2 with: php-version: ${{ matrix.php }} - extensions: ${{ env.PHP_EXTENSIONS }} + extensions: ${{ env.PHP_EXTENSIONS }}, pdo_mysql coverage: none tools: composer:v2 @@ -118,14 +118,22 @@ jobs: - name: Install test tools separately from core dependencies run: composer install --no-interaction --no-progress --prefer-dist + # The MySQL tests (FileGroupsMysqlTest: the file_groups migrations on MyISAM and under + # NO_BACKSLASH_ESCAPES, which sqlite cannot show) skip without a server; the lowest + # PHP version runs them. + - name: Start mysql + if: matrix.php == needs.php.outputs.lowest + run: docker compose -f .github/docker/ci/docker-compose.yml --profile mysql up -d --wait mysql + - name: Run Pest working-directory: core - # env: + env: + EVO_TEST_MYSQL: ${{ matrix.php == needs.php.outputs.lowest && 'root:secret@127.0.0.1:3306' || '' }} # EVO_TEST_REDIS: 127.0.0.1:6379 run: composer test -- --compact --fail-on-warning --fail-on-risky --fail-on-deprecation install: - name: Install on ${{ matrix.db }} + name: Install on ${{ matrix.db }}${{ matrix.engine && format(' ({0})', matrix.engine) || '' }} needs: php runs-on: ubuntu-latest strategy: @@ -141,6 +149,13 @@ jobs: - db: mysql user: root password: secret + # MyISAM is a supported engine (the installers write it for older + # servers, sites keep it), and its key limit of 1000 bytes is one a + # utf8mb4 index has to fit; the suite runs on sqlite and never sees it. + - db: mysql + engine: MyISAM + user: root + password: secret - db: pgsql user: evo password: secret @@ -187,6 +202,7 @@ jobs: EVO_DB_PASSWORD: ${{ matrix.password }} EVO_DB_NAME: evolution EVO_DB_PREFIX: evo_ + EVO_DB_ENGINE: ${{ matrix.engine || '' }} run: .github/docker/ci/install-and-smoke.sh - name: Database server log diff --git a/.github/workflows/upgrade.yml b/.github/workflows/upgrade.yml index 74839c0a2e..39d0d07e68 100644 --- a/.github/workflows/upgrade.yml +++ b/.github/workflows/upgrade.yml @@ -33,6 +33,11 @@ on: from_repo: description: 'Repository the source versions are taken from' default: 'evolution-cms/evolution' + legacy: + description: 'mysql legs - turn the older site into MyISAM / utf8mb3 before upgrading it' + type: choice + default: none + options: [none, myisam] permissions: contents: read @@ -58,18 +63,20 @@ jobs: env: FROM: ${{ inputs.from }} DB: ${{ inputs.db || 'all' }} + LEGACY: ${{ inputs.legacy || 'none' }} run: | if [ -z "${FROM:-}" ]; then # The nightly sweep: the oldest version still worth supporting, the # last release, and sqlite from the branch that introduced it. - legs='[{"db":"mysql","from":"3.2.7"},{"db":"mysql","from":"3.5.7"},{"db":"pgsql","from":"3.2.7"},{"db":"pgsql","from":"3.5.7"},{"db":"sqlite","from":"nightly-3.5.x"}]' + legs='[{"db":"mysql","from":"3.2.7"},{"db":"mysql","from":"3.5.7"},{"db":"mysql","from":"3.5.7","legacy":"myisam"},{"db":"pgsql","from":"3.2.7"},{"db":"pgsql","from":"3.5.7"},{"db":"sqlite","from":"nightly-3.5.x"}]' else dbs=$([ "$DB" = "all" ] && echo "mysql pgsql sqlite" || echo "$DB") legs=$( for db in $dbs; do echo "$FROM" | tr ',' '\n' | while read -r ref; do ref=$(echo "$ref" | tr -d '[:space:]') - [ -n "$ref" ] && printf '{"db":"%s","from":"%s"}\n' "$db" "$ref" + legacy=$([ "$db" = "mysql" ] && [ "$LEGACY" != "none" ] && echo "$LEGACY" || true) + [ -n "$ref" ] && printf '{"db":"%s","from":"%s","legacy":"%s"}\n' "$db" "$ref" "$legacy" done done | paste -sd, - | sed 's/^/[/; s/$/]/' ) @@ -78,7 +85,7 @@ jobs: echo "$legs" upgrade: - name: ${{ matrix.leg.from }} -> ${{ inputs.to || 'this tree' }} on ${{ matrix.leg.db }} + name: ${{ matrix.leg.from }} -> ${{ inputs.to || 'this tree' }} on ${{ matrix.leg.db }}${{ matrix.leg.legacy && format(' ({0})', matrix.leg.legacy) || '' }} needs: matrix runs-on: ubuntu-latest strategy: @@ -144,6 +151,7 @@ jobs: EVO_DB_PASSWORD: secret EVO_DB_NAME: evolution EVO_DB_PREFIX: evo_ + EVO_DB_LEGACY: ${{ matrix.leg.legacy || '' }} run: new/.github/docker/ci/upgrade-and-smoke.sh - name: Database server log diff --git a/AGENTS.md b/AGENTS.md index 523082b461..2f96d59899 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -207,6 +207,34 @@ are resolved), never of the way it was found; `plan()` and `planInstall()` refus `composerRuntimePackages()` for it, and `make:site` asks them on every update that runs it, custom packages or not (an update package's `vendor/` may differ from its lock: 3.5.8's does). +### Migrations on MySQL: MyISAM and older charsets + +MyISAM is a supported engine, not a legacy one: the installers write it into the connection config for +servers older than MySQL 5.7.6, and sites keep it, often with `charset` `utf8` (utf8mb3) and +`engine` `MyISAM` in `core/config/database/connections/default.php`. A migration has to get through +such a site as it is. Never make an update depend on converting tables to InnoDB or utf8mb4. + +- An index key on MyISAM holds at most 1000 bytes (InnoDB with the DYNAMIC row format: 3072). A + utf8mb4 character counts 4 bytes, utf8mb3 3: a utf8mb4 `VARCHAR(255)` (1020) cannot be indexed on + MyISAM, and a unique `(INT, VARCHAR)` fits up to `VARCHAR(249)`. Size an indexed string column for the + engine and charset the table really gets (`core/includes/file_groups_schema.php`: `newTableEngine()`, + `newTableCharset()`, `fittingLength()`), never a prefix on a unique key. +- Change only what the migration is for. Reaching a collation through `CHARACTER SET utf8mb4` converts + the column too and widens its keys (error 1071 in `2026_10_11_000000_make_file_groups_file_case_sensitive` + up to 3.5.12). Read charset, collation and length from `information_schema` and keep them; take + collation names from `information_schema.COLLATIONS` (`utf8_bin` on MySQL 5.7, `utf8mb3_bin` on 8.0), + and expect a config that says `utf8` where MySQL 8.0.30+ lists only `utf8mb3`. +- A `Schema::create()` that fails after the table exists leaves it behind without its indexes, and the + next run skips a create guarded by `hasTable()`. Make sure the create cannot fail on a supported + configuration; where one already did, ship an idempotent repair + (`2026_12_05_000000_restore_file_groups_indexes`). +- The installer runs `install/stubs/migrations`, artisan `core/database/migrations`: a migration in both + changes in both. A migration loads shared code by path (`require EVO_CORE_PATH . 'includes/...'`), not + through a new class: the web installer migrates before it rebuilds the authoritative classmap. +- Pest runs on SQLite and never meets these limits. The `install` job of `ci.yml` installs on MySQL with + MyISAM as well (`EVO_DB_ENGINE`), and `upgrade.yml` upgrades a site turned MyISAM / utf8mb3 + (`EVO_DB_LEGACY=myisam`, nightly and on demand); check a migration with MySQL DDL against both. + ### Installing Evolution CMS packages Install Composer packages from the `core/` directory through the Evolution CMS package installer: diff --git a/core/database/migrations/2026_03_29_000000_create_file_groups_table.php b/core/database/migrations/2026_03_29_000000_create_file_groups_table.php index 9be481ddc8..e4b26015ee 100644 --- a/core/database/migrations/2026_03_29_000000_create_file_groups_table.php +++ b/core/database/migrations/2026_03_29_000000_create_file_groups_table.php @@ -2,6 +2,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; +use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; class CreateFileGroupsTable extends Migration { @@ -10,11 +11,31 @@ public function up() { return; } - Schema::create('file_groups', function(Blueprint $table) { + // File group keys are paths and must stay case-sensitive; on MySQL the column takes the + // binary collation of the connection's charset, and on MyISAM a length its key limit allows. + $length = 255; + $collation = null; + $connection = DB::connection(); + $schema = require EVO_CORE_PATH . 'includes/file_groups_schema.php'; + if ($schema->isMysql($connection)) { + $charset = $schema->newTableCharset($connection); + if ($charset !== null) { + $collation = $schema->binaryCollation($connection, $charset); + $length = $schema->fittingLength( + $schema->keyLimit($schema->newTableEngine($connection)), + $schema->bytesPerCharacter($connection, $charset) + ); + } + } + + Schema::create('file_groups', function(Blueprint $table) use ($length, $collation) { $indexPrefix = \DB::getTablePrefix() . $table->getTable(); $table->integer('id', true); $table->integer('document_group')->default(0)->index("{$indexPrefix}_document_group"); - $table->string('file', 255)->default('')->index("{$indexPrefix}_file"); + $file = $table->string('file', $length)->default('')->index("{$indexPrefix}_file"); + if ($collation !== null) { + $file->collation($collation); + } $table->unique(['document_group', 'file'], "{$indexPrefix}_ix_fg_id"); }); } diff --git a/core/database/migrations/2026_10_11_000000_make_file_groups_file_case_sensitive.php b/core/database/migrations/2026_10_11_000000_make_file_groups_file_case_sensitive.php index 8aa04f3f5f..264cf707bd 100644 --- a/core/database/migrations/2026_10_11_000000_make_file_groups_file_case_sensitive.php +++ b/core/database/migrations/2026_10_11_000000_make_file_groups_file_case_sensitive.php @@ -9,55 +9,41 @@ * files. A case-insensitive column collation (the database default for utf8mb4_unicode_ci) treats * their rows as one, and the unique index then refuses the second one: the copy stays unrestricted. * - * Only the collation changes, to the binary one of the column's own character set. Converting the - * character set as well (utf8mb3 to utf8mb4) widens the indexed column past the key limit of - * MyISAM (1000 bytes) or of an old InnoDB row format (767 bytes), and the update stops there. + * Only the collation changes, to the binary one of the column's own character set; length and + * character set stay. Converting utf8mb3 to utf8mb4 would widen the indexed column past the key + * limit of MyISAM (1000 bytes), and the update would stop there. */ class MakeFileGroupsFileCaseSensitive extends Migration { public function up() { - if (!Schema::hasTable('file_groups') || DB::connection()->getDriverName() !== 'mysql') { + $connection = DB::connection(); + $schema = require EVO_CORE_PATH . 'includes/file_groups_schema.php'; + if (!Schema::hasTable('file_groups') || !$schema->isMysql($connection)) { return; } $table = DB::getTablePrefix() . 'file_groups'; - $current = DB::selectOne( - 'SELECT CHARACTER_SET_NAME AS charset, COLLATION_NAME AS collation FROM information_schema.COLUMNS' - . ' WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?', + $current = $connection->selectOne( + 'SELECT CHARACTER_SET_NAME AS charset, COLLATION_NAME AS collation, CHARACTER_MAXIMUM_LENGTH AS length' + . ' FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?', [$table, 'file'] ); if (!$current || empty($current->charset) || str_ends_with((string) $current->collation, '_bin')) { return; } - $charset = (string) $current->charset; - // Ask the server how it spells the binary collation: names differ between MySQL and MariaDB versions (utf8 / utf8mb3). - $binary = DB::selectOne( - 'SELECT COLLATION_NAME AS collation FROM information_schema.COLLATIONS' - . " WHERE CHARACTER_SET_NAME = ? AND COLLATION_NAME LIKE '%\\_bin'" - . ' ORDER BY COLLATION_NAME = CONCAT(?, \'_bin\') DESC, CHAR_LENGTH(COLLATION_NAME), COLLATION_NAME LIMIT 1', - [$charset, $charset] - ); - if (!$binary || empty($binary->collation)) { + $collation = $schema->binaryCollation($connection, (string) $current->charset); + if ($collation === null) { return; } - DB::statement(static::modifyStatement($table, $charset, (string) $binary->collation)); - } - - /** - * The ALTER that gives the column a binary collation and keeps its character set. - */ - public static function modifyStatement(string $table, string $charset, string $collation): string - { - foreach ([$table, $charset, $collation] as $identifier) { - if (!preg_match('/^[A-Za-z0-9_$]+$/', $identifier)) { - throw new InvalidArgumentException('Unexpected identifier: ' . $identifier); - } - } - - return "ALTER TABLE `{$table}` MODIFY `file` VARCHAR(255) CHARACTER SET {$charset} COLLATE {$collation} NOT NULL DEFAULT ''"; + $connection->statement($schema->modifyFileStatement( + $table, + (string) $current->charset, + $collation, + (int) $current->length ?: $schema::LENGTH + )); } public function down() diff --git a/core/database/migrations/2026_12_05_000000_restore_file_groups_indexes.php b/core/database/migrations/2026_12_05_000000_restore_file_groups_indexes.php new file mode 100644 index 0000000000..66f52ec26a --- /dev/null +++ b/core/database/migrations/2026_12_05_000000_restore_file_groups_indexes.php @@ -0,0 +1,129 @@ +isMysql($connection)) { + return; + } + + $table = $schema->identifier(DB::getTablePrefix() . 'file_groups'); + $indexes = $this->indexes($connection, $table); + $hasGroup = in_array(['document_group'], $indexes['all'], true); + $hasFile = in_array(['file'], $indexes['all'], true); + $hasUnique = in_array(['document_group', 'file'], $indexes['unique'], true); + if ($hasGroup && $hasFile && $hasUnique) { + return; + } + + $column = $connection->selectOne( + 'SELECT c.CHARACTER_SET_NAME AS charset, c.COLLATION_NAME AS collation, c.CHARACTER_MAXIMUM_LENGTH AS length, t.ENGINE AS engine' + . ' FROM information_schema.COLUMNS c JOIN information_schema.TABLES t ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME' + . ' WHERE c.TABLE_SCHEMA = DATABASE() AND c.TABLE_NAME = ? AND c.COLUMN_NAME = ?', + [$table, 'file'] + ); + if (!$column || empty($column->charset) || empty($column->collation)) { + return; + } + + $length = (int) $column->length; + $fits = $schema->fittingLength( + $schema->keyLimit((string) $column->engine), + $schema->bytesPerCharacter($connection, (string) $column->charset) + ); + if ($length > $fits && (!$hasFile || !$hasUnique)) { + $longest = (int) ($connection->selectOne("SELECT MAX(CHAR_LENGTH(`file`)) AS longest FROM `{$table}`")->longest ?? 0); + if ($longest > $fits) { + // shortening would cut stored paths: keep the rows, restore what fits + $this->report("file_groups keeps no index on `file`: a stored path has {$longest} characters," + . " the {$column->engine} key limit allows {$fits}."); + $hasFile = $hasUnique = true; + } else { + $connection->statement($schema->modifyFileStatement($table, (string) $column->charset, (string) $column->collation, $fits)); + } + } + + if (!$hasUnique) { + // the unique key compares as the column does (binary after 2026_10_11): keep the oldest row of each pair + $connection->statement( + "DELETE newer FROM `{$table}` newer JOIN `{$table}` older" + . ' ON older.document_group = newer.document_group AND older.`file` = newer.`file` AND older.id < newer.id' + ); + } + + $prefix = $table; + Schema::table('file_groups', function ($blueprint) use ($prefix, $hasGroup, $hasFile, $hasUnique) { + if (!$hasGroup) { + $blueprint->index('document_group', "{$prefix}_document_group"); + } + if (!$hasFile) { + $blueprint->index('file', "{$prefix}_file"); + } + if (!$hasUnique) { + $blueprint->unique(['document_group', 'file'], "{$prefix}_ix_fg_id"); + } + }); + } + + public function down() + { + // the indexes belong to the table; nothing to restore + } + + /** + * Columns of each index, in key order: every index under 'all', unique ones also under 'unique'. + */ + private function indexes($connection, string $table): array + { + $keys = []; + $unique = []; + foreach ($connection->select("SHOW INDEX FROM `{$table}`") as $row) { + $row = array_change_key_case((array) $row, CASE_LOWER); + $keys[$row['key_name']][(int) $row['seq_in_index']] = $row['column_name']; + if ((int) $row['non_unique'] === 0) { + $unique[$row['key_name']] = true; + } + } + + $all = []; + $uniqueColumns = []; + foreach ($keys as $name => $columns) { + ksort($columns); + $all[] = array_values($columns); + if (isset($unique[$name])) { + $uniqueColumns[] = array_values($columns); + } + } + + return ['all' => $all, 'unique' => $uniqueColumns]; + } + + private function report(string $message): void + { + // the event log exists only where the CMS itself runs the migration + $app = \Illuminate\Support\Facades\Facade::getFacadeApplication(); + if ($app instanceof \EvolutionCMS\Core) { + try { + $app->logEvent(0, 2, $message, 'Migrations'); + } catch (\Throwable $exception) { + } + } + } +} diff --git a/core/includes/file_groups_schema.php b/core/includes/file_groups_schema.php new file mode 100644 index 0000000000..f4be8a37f7 --- /dev/null +++ b/core/includes/file_groups_schema.php @@ -0,0 +1,126 @@ +getDriverName(), ['mysql', 'mariadb'], true); + } + + /** + * Key limit of a storage engine, in bytes. InnoDB with the DYNAMIC row format (the default + * since MySQL 5.7.9 / MariaDB 10.2.2) allows 3072; anything else gets the MyISAM limit. + */ + public function keyLimit(string $engine): int + { + return strtolower(trim($engine)) === 'innodb' ? 3072 : 1000; + } + + /** The longest `file` that keeps the unique key within the limit. */ + public function fittingLength(int $keyLimit, int $bytesPerCharacter): int + { + return min(self::LENGTH, intdiv($keyLimit - self::GROUP_BYTES, max(1, $bytesPerCharacter))); + } + + /** Engine a new table of this connection gets: the connection's own, else the server default. */ + public function newTableEngine(Connection $connection): string + { + $engine = trim((string) $connection->getConfig('engine')); + if ($engine === '') { + $engine = (string) ($connection->selectOne('SELECT @@default_storage_engine AS engine')->engine ?? ''); + } + + // the config may carry more than the name ("InnoDB ROW_FORMAT=DYNAMIC") + return strtok($engine, ' ') ?: 'InnoDB'; + } + + /** Character set a new table of this connection gets: the connection's own, else the database default. */ + public function newTableCharset(Connection $connection): ?string + { + $charset = trim((string) $connection->getConfig('charset')); + if ($charset === '') { + $charset = (string) ($connection->selectOne('SELECT @@character_set_database AS charset')->charset ?? ''); + } + + return $charset === '' ? null : $this->charset($connection, $charset); + } + + /** + * The server's name of a character set: MySQL 8.0.30+ lists utf8 only as utf8mb3. + */ + public function charset(Connection $connection, string $charset): ?string + { + foreach (array_unique([$charset, strtolower($charset) === 'utf8' ? 'utf8mb3' : $charset]) as $name) { + $row = $connection->selectOne( + 'SELECT CHARACTER_SET_NAME AS charset FROM information_schema.CHARACTER_SETS WHERE CHARACTER_SET_NAME = ?', + [$name] + ); + if ($row && !empty($row->charset)) { + return (string) $row->charset; + } + } + + return null; + } + + public function bytesPerCharacter(Connection $connection, string $charset): int + { + $row = $connection->selectOne( + 'SELECT MAXLEN AS bytes FROM information_schema.CHARACTER_SETS WHERE CHARACTER_SET_NAME = ?', + [$charset] + ); + + // unknown: assume the widest, so the key still fits + return $row && (int) $row->bytes > 0 ? (int) $row->bytes : 4; + } + + /** + * The binary collation of a character set, as the server spells it (utf8_bin on MySQL 5.7, + * utf8mb3_bin on 8.0, utf8mb4_bin rather than utf8mb4_0900_bin). + */ + public function binaryCollation(Connection $connection, string $charset): ?string + { + $row = $connection->selectOne( + 'SELECT COLLATION_NAME AS collation FROM information_schema.COLLATIONS' + // RIGHT(), not LIKE: under NO_BACKSLASH_ESCAPES a backslash no longer escapes the underscore + . " WHERE CHARACTER_SET_NAME = ? AND RIGHT(COLLATION_NAME, 4) = '_bin'" + . " ORDER BY COLLATION_NAME = CONCAT(?, '_bin') DESC, CHAR_LENGTH(COLLATION_NAME), COLLATION_NAME LIMIT 1", + [$charset, $charset] + ); + + return $row && !empty($row->collation) ? (string) $row->collation : null; + } + + /** An identifier from information_schema, checked before it goes into DDL. */ + public function identifier(string $value): string + { + if (!preg_match('/^[A-Za-z0-9_$]+$/', $value)) { + throw new InvalidArgumentException('Unexpected identifier: ' . $value); + } + + return $value; + } + + /** The ALTER that gives `file` a charset, collation and length, keeping its default. */ + public function modifyFileStatement(string $table, string $charset, string $collation, int $length): string + { + return 'ALTER TABLE `' . $this->identifier($table) . '` MODIFY `file` VARCHAR(' . max(1, $length) . ')' + . ' CHARACTER SET ' . $this->identifier($charset) . ' COLLATE ' . $this->identifier($collation) + . " NOT NULL DEFAULT ''"; + } +}; diff --git a/core/tests/Unit/FileGroupsSchemaAndModelTest.php b/core/tests/Unit/FileGroupsSchemaAndModelTest.php index 7aaf534623..38063a30e8 100644 --- a/core/tests/Unit/FileGroupsSchemaAndModelTest.php +++ b/core/tests/Unit/FileGroupsSchemaAndModelTest.php @@ -30,19 +30,3 @@ expect($source)->toContain('public function fileGroups(): Eloquent\Relations\HasMany') ->and($source)->toContain("return \$this->hasMany(FileGroup::class, 'document_group');"); }); - -test('case-sensitive file groups migration keeps the column character set', function () { - require_once dirname(__DIR__, 2) . '/database/migrations/2026_10_11_000000_make_file_groups_file_case_sensitive.php'; - $source = (string) file_get_contents(dirname(__DIR__, 2) . '/database/migrations/2026_10_11_000000_make_file_groups_file_case_sensitive.php'); - - // utf8mb3 -> utf8mb4 widens the indexed column to 1020 bytes, past the MyISAM key limit of 1000 (error 1071) - expect(MakeFileGroupsFileCaseSensitive::modifyStatement('evo_file_groups', 'utf8mb3', 'utf8mb3_bin')) - ->toBe("ALTER TABLE `evo_file_groups` MODIFY `file` VARCHAR(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_bin NOT NULL DEFAULT ''") - ->and(MakeFileGroupsFileCaseSensitive::modifyStatement('file_groups', 'utf8mb4', 'utf8mb4_bin')) - ->toContain('CHARACTER SET utf8mb4 COLLATE utf8mb4_bin') - ->and($source)->toContain('CHARACTER_SET_NAME AS charset') - ->and($source)->not->toContain('CHARACTER SET utf8mb4'); - - expect(fn () => MakeFileGroupsFileCaseSensitive::modifyStatement('file_groups', 'utf8mb4; DROP', 'utf8mb4_bin')) - ->toThrow(InvalidArgumentException::class); -}); diff --git a/core/tests/Unit/Install/FileGroupsMysqlTest.php b/core/tests/Unit/Install/FileGroupsMysqlTest.php new file mode 100644 index 0000000000..437904a2d8 --- /dev/null +++ b/core/tests/Unit/Install/FileGroupsMysqlTest.php @@ -0,0 +1,236 @@ + $url['host'] ?? '127.0.0.1', + 'port' => (int) ($url['port'] ?? 3306), + 'username' => urldecode($url['user'] ?? 'root'), + 'password' => urldecode($url['pass'] ?? ''), + ]; +} + +/** A fresh database on the server, and Capsule plus the facades the migrations use wired to it. */ +function bootFileGroupsMysql(string $engine, string $charset, string $collation, string $mode): Capsule +{ + $server = fileGroupsMysqlServer(); + $database = 'evo_fg_test_' . getmypid(); + $root = new PDO('mysql:host=' . $server['host'] . ';port=' . $server['port'], $server['username'], $server['password']); + $root->exec("DROP DATABASE IF EXISTS `{$database}`"); + $root->exec("CREATE DATABASE `{$database}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"); + + $capsule = new Capsule(); + $capsule->addConnection($server + [ + 'driver' => 'mysql', + 'database' => $database, + 'prefix' => 'evo_', + 'charset' => $charset, + 'collation' => $collation, + 'engine' => $engine, + 'strict' => false, + 'modes' => $mode === '' ? ['NO_ENGINE_SUBSTITUTION'] : ['NO_ENGINE_SUBSTITUTION', $mode], + ]); + $capsule->setAsGlobal(); + $container = $capsule->getContainer(); + $container->instance('db', $capsule->getDatabaseManager()); + $container->bind('db.schema', fn () => $capsule->getConnection()->getSchemaBuilder()); + Facade::clearResolvedInstances(); + Facade::setFacadeApplication($container); + class_exists('DB', false) || class_alias(\Illuminate\Support\Facades\DB::class, 'DB'); + + $migrations = dirname(__DIR__, 3) . '/database/migrations/'; + class_exists('CreateFileGroupsTable', false) || require $migrations . '2026_03_29_000000_create_file_groups_table.php'; + class_exists('MakeFileGroupsFileCaseSensitive', false) || require $migrations . '2026_10_11_000000_make_file_groups_file_case_sensitive.php'; + class_exists('RestoreFileGroupsIndexes', false) || require $migrations . '2026_12_05_000000_restore_file_groups_indexes.php'; + + return $capsule; +} + +/** @return array{engine: string, charset: string, collation: string, length: int, indexes: array} */ +function fileGroupsMysqlState(Capsule $capsule): array +{ + $db = $capsule->getConnection(); + $column = $db->selectOne( + 'SELECT t.ENGINE AS engine, c.CHARACTER_SET_NAME AS charset, c.COLLATION_NAME AS collation, c.CHARACTER_MAXIMUM_LENGTH AS length' + . ' FROM information_schema.COLUMNS c JOIN information_schema.TABLES t ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME' + . " WHERE c.TABLE_SCHEMA = DATABASE() AND c.TABLE_NAME = 'evo_file_groups' AND c.COLUMN_NAME = 'file'" + ); + $keys = []; + foreach ($db->select('SHOW INDEX FROM `evo_file_groups`') as $row) { + $row = array_change_key_case((array) $row, CASE_LOWER); + $keys[$row['key_name']][(int) $row['seq_in_index']] = $row['column_name']; + $keys[$row['key_name']][0] = (int) $row['non_unique'] === 0 ? 'unique' : 'index'; + } + $indexes = []; + foreach ($keys as $name => $parts) { + ksort($parts); + $indexes[$name] = array_shift($parts) . ' ' . implode(',', $parts); + } + // the server lists unique keys first + ksort($indexes, SORT_STRING); + + return [ + 'engine' => (string) $column->engine, + 'charset' => (string) $column->charset, + 'collation' => (string) $column->collation, + 'length' => (int) $column->length, + 'indexes' => $indexes, + ]; +} + +function dropFileGroupsMysql(Capsule $capsule): void +{ + $db = $capsule->getConnection(); + $db->statement('DROP DATABASE IF EXISTS `' . $db->getDatabaseName() . '`'); + $db->disconnect(); + Facade::clearResolvedInstances(); +} + +dataset('sql modes', ['default' => '', 'NO_BACKSLASH_ESCAPES' => 'NO_BACKSLASH_ESCAPES']); + +const FILE_GROUPS_FULL_INDEXES = [ + 'PRIMARY' => 'unique id', + 'evo_file_groups_document_group' => 'index document_group', + 'evo_file_groups_file' => 'index file', + 'evo_file_groups_ix_fg_id' => 'unique document_group,file', +]; + +test('the binary collation is found in every SQL mode', function (string $mode) { + $capsule = bootFileGroupsMysql('InnoDB', 'utf8mb4', 'utf8mb4_unicode_ci', $mode); + $schema = require EVO_CORE_PATH . 'includes/file_groups_schema.php'; + $db = $capsule->getConnection(); + + try { + expect($schema->binaryCollation($db, 'utf8mb4'))->toBe('utf8mb4_bin') + ->and($schema->binaryCollation($db, (string) $schema->charset($db, 'utf8')))->toEndWith('_bin') + ->and($schema->binaryCollation($db, 'latin1'))->toBe('latin1_bin'); + } finally { + dropFileGroupsMysql($capsule); + } +})->with('sql modes')->skip(fn () => fileGroupsMysqlServer() === null, 'needs pdo_mysql and EVO_TEST_MYSQL=user:password@host:port'); + +test('an old MyISAM utf8mb3 table keeps its charset and length and becomes case-sensitive', function (string $mode) { + $capsule = bootFileGroupsMysql('MyISAM', 'utf8', 'utf8_general_ci', $mode); + $db = $capsule->getConnection(); + + try { + // the table as the create migration made it before it knew collations + $db->statement("CREATE TABLE evo_file_groups (id int NOT NULL AUTO_INCREMENT PRIMARY KEY, document_group int NOT NULL DEFAULT 0, + `file` varchar(255) NOT NULL DEFAULT '', KEY evo_file_groups_document_group (document_group), KEY evo_file_groups_file (`file`), + UNIQUE KEY evo_file_groups_ix_fg_id (document_group, `file`)) ENGINE=MyISAM DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci"); + $db->table('file_groups')->insert(['document_group' => 1, 'file' => 'assets/files/report.txt']); + + (new MakeFileGroupsFileCaseSensitive())->up(); + (new RestoreFileGroupsIndexes())->up(); + $db->table('file_groups')->insert(['document_group' => 1, 'file' => 'assets/files/REPORT.txt']); + + $state = fileGroupsMysqlState($capsule); + expect($state['charset'])->toBeIn(['utf8', 'utf8mb3']) + ->and($state['collation'])->toEndWith('_bin') + ->and($state['length'])->toBe(255) + ->and($state['indexes'])->toBe(FILE_GROUPS_FULL_INDEXES) + ->and($db->table('file_groups')->count())->toBe(2); + } finally { + dropFileGroupsMysql($capsule); + } +})->with('sql modes')->skip(fn () => fileGroupsMysqlServer() === null, 'needs pdo_mysql and EVO_TEST_MYSQL=user:password@host:port'); + +test('a new table on MyISAM utf8mb4 gets a key that fits, and nothing is left to change', function (string $mode) { + $capsule = bootFileGroupsMysql('MyISAM', 'utf8mb4', 'utf8mb4_unicode_ci', $mode); + + try { + (new CreateFileGroupsTable())->up(); + $created = fileGroupsMysqlState($capsule); + (new MakeFileGroupsFileCaseSensitive())->up(); + (new RestoreFileGroupsIndexes())->up(); + + expect($created)->toBe([ + 'engine' => 'MyISAM', + 'charset' => 'utf8mb4', + 'collation' => 'utf8mb4_bin', + 'length' => 249, + 'indexes' => FILE_GROUPS_FULL_INDEXES, + ])->and(fileGroupsMysqlState($capsule))->toBe($created); + } finally { + dropFileGroupsMysql($capsule); + } +})->with('sql modes')->skip(fn () => fileGroupsMysqlServer() === null, 'needs pdo_mysql and EVO_TEST_MYSQL=user:password@host:port'); + +test('a new table on InnoDB keeps 255 characters', function () { + $capsule = bootFileGroupsMysql('InnoDB', 'utf8mb4', 'utf8mb4_unicode_ci', ''); + + try { + (new CreateFileGroupsTable())->up(); + $state = fileGroupsMysqlState($capsule); + expect([$state['engine'], $state['collation'], $state['length'], $state['indexes']]) + ->toBe(['InnoDB', 'utf8mb4_bin', 255, FILE_GROUPS_FULL_INDEXES]); + } finally { + dropFileGroupsMysql($capsule); + } +})->skip(fn () => fileGroupsMysqlServer() === null, 'needs pdo_mysql and EVO_TEST_MYSQL=user:password@host:port'); + +test('a table the MyISAM key limit left without indexes gets them back, duplicates dropped', function (string $mode) { + $capsule = bootFileGroupsMysql('MyISAM', 'utf8mb4', 'utf8mb4_unicode_ci', $mode); + $db = $capsule->getConnection(); + + try { + // what a failed create left: the table, no indexes, and rows the unique key would have refused + $db->statement("CREATE TABLE evo_file_groups (id int NOT NULL AUTO_INCREMENT PRIMARY KEY, document_group int NOT NULL DEFAULT 0, + `file` varchar(255) NOT NULL DEFAULT '') ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"); + $db->table('file_groups')->insert([ + ['document_group' => 1, 'file' => 'assets/files/report.txt'], + ['document_group' => 1, 'file' => 'assets/files/report.txt'], + ['document_group' => 1, 'file' => 'assets/files/REPORT.txt'], + ['document_group' => 2, 'file' => 'assets/files/report.txt'], + ]); + + (new MakeFileGroupsFileCaseSensitive())->up(); + (new RestoreFileGroupsIndexes())->up(); + (new RestoreFileGroupsIndexes())->up(); + + $state = fileGroupsMysqlState($capsule); + expect([$state['collation'], $state['length'], $state['indexes']]) + ->toBe(['utf8mb4_bin', 249, FILE_GROUPS_FULL_INDEXES]) + ->and($db->table('file_groups')->orderBy('id')->pluck('id')->map(fn ($id) => (int) $id)->all())->toBe([1, 3, 4]); + } finally { + dropFileGroupsMysql($capsule); + } +})->with('sql modes')->skip(fn () => fileGroupsMysqlServer() === null, 'needs pdo_mysql and EVO_TEST_MYSQL=user:password@host:port'); + +test('a stored path longer than the key allows is kept, and only the group index comes back', function () { + $capsule = bootFileGroupsMysql('MyISAM', 'utf8mb4', 'utf8mb4_unicode_ci', ''); + $db = $capsule->getConnection(); + + try { + $db->statement("CREATE TABLE evo_file_groups (id int NOT NULL AUTO_INCREMENT PRIMARY KEY, document_group int NOT NULL DEFAULT 0, + `file` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL DEFAULT '') ENGINE=MyISAM DEFAULT CHARSET=utf8mb4"); + $long = 'assets/files/' . str_repeat('a', 240); + $db->table('file_groups')->insert(['document_group' => 1, 'file' => $long]); + + (new RestoreFileGroupsIndexes())->up(); + + $state = fileGroupsMysqlState($capsule); + expect([$state['length'], $state['indexes']]) + ->toBe([255, ['PRIMARY' => 'unique id', 'evo_file_groups_document_group' => 'index document_group']]) + ->and($db->table('file_groups')->value('file'))->toBe($long); + } finally { + dropFileGroupsMysql($capsule); + } +})->skip(fn () => fileGroupsMysqlServer() === null, 'needs pdo_mysql and EVO_TEST_MYSQL=user:password@host:port'); diff --git a/core/tests/Unit/Install/FileGroupsStorageEngineTest.php b/core/tests/Unit/Install/FileGroupsStorageEngineTest.php new file mode 100644 index 0000000000..81c1d996e9 --- /dev/null +++ b/core/tests/Unit/Install/FileGroupsStorageEngineTest.php @@ -0,0 +1,162 @@ +answers as $needle => $answer) { + if (str_contains($query, $needle)) { + $answer = is_callable($answer) ? $answer($bindings) : $answer; + + return $answer === null ? null : (object) $answer; + } + } + + return null; + } + }; +} + +function bootFileGroupsSqlite(): Capsule +{ + $capsule = new Capsule(); + $capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => 'evo_']); + $capsule->setAsGlobal(); + $container = $capsule->getContainer(); + $container->instance('db', $capsule->getDatabaseManager()); + $container->bind('db.schema', fn () => $capsule->getConnection()->getSchemaBuilder()); + Facade::clearResolvedInstances(); + Facade::setFacadeApplication($container); + class_exists('DB', false) || class_alias(\Illuminate\Support\Facades\DB::class, 'DB'); + + return $capsule; +} + +test('the unique key of file_groups fits the key limit of the storage engine', function () { + $schema = fileGroupsSchema(); + + // MyISAM allows 1000 bytes: 4 for document_group, 996 for the path + expect($schema->fittingLength($schema->keyLimit('MyISAM'), 4))->toBe(249) + ->and($schema->fittingLength($schema->keyLimit('myisam'), 3))->toBe(255) + ->and($schema->fittingLength($schema->keyLimit('MyISAM'), 1))->toBe(255) + ->and($schema->fittingLength($schema->keyLimit('InnoDB'), 4))->toBe(255) + // an engine the migrations do not know gets the smaller limit + ->and($schema->keyLimit('Aria'))->toBe(1000); +}); + +test('a new table takes the engine and charset of the connection, else the server defaults', function () { + $schema = fileGroupsSchema(); + $charsets = ['information_schema.CHARACTER_SETS WHERE' => fn ($bindings) => in_array($bindings[0], ['utf8mb3', 'utf8mb4'], true) + ? ['charset' => $bindings[0], 'bytes' => $bindings[0] === 'utf8mb3' ? 3 : 4] + : null]; + + $configured = fakeMysqlConnection(['engine' => 'InnoDB ROW_FORMAT=DYNAMIC', 'charset' => 'utf8'], $charsets); + expect($schema->newTableEngine($configured))->toBe('InnoDB') + // MySQL 8.0.30+ lists utf8 only as utf8mb3 + ->and($schema->newTableCharset($configured))->toBe('utf8mb3') + ->and($schema->bytesPerCharacter($configured, 'utf8mb3'))->toBe(3); + + $defaults = fakeMysqlConnection(['engine' => null, 'charset' => ''], $charsets + [ + '@@default_storage_engine' => ['engine' => 'MyISAM'], + '@@character_set_database' => ['charset' => 'utf8mb4'], + ]); + expect($schema->newTableEngine($defaults))->toBe('MyISAM') + ->and($schema->newTableCharset($defaults))->toBe('utf8mb4') + ->and($schema->bytesPerCharacter($defaults, 'unknown'))->toBe(4); +}); + +test('the binary collation is the one the server names for the charset', function () { + $schema = fileGroupsSchema(); + $connection = fakeMysqlConnection([], [ + 'information_schema.COLLATIONS' => fn ($bindings) => ['collation' => $bindings[0] === 'utf8' ? 'utf8_bin' : $bindings[0] . '_bin'], + ]); + + expect($schema->binaryCollation($connection, 'utf8'))->toBe('utf8_bin') + ->and($schema->binaryCollation($connection, 'utf8mb4'))->toBe('utf8mb4_bin'); +}); + +test('changing the file column keeps its charset and length', function () { + $schema = fileGroupsSchema(); + + // utf8mb3 -> utf8mb4 would widen the indexed column past the MyISAM key limit (error 1071) + expect($schema->modifyFileStatement('evo_file_groups', 'utf8mb3', 'utf8mb3_bin', 255)) + ->toBe("ALTER TABLE `evo_file_groups` MODIFY `file` VARCHAR(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_bin NOT NULL DEFAULT ''") + ->and($schema->modifyFileStatement('evo_file_groups', 'utf8mb4', 'utf8mb4_bin', 249)) + ->toContain('VARCHAR(249) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin'); + + expect(fn () => $schema->modifyFileStatement('file_groups', 'utf8mb4; DROP', 'utf8mb4_bin', 255)) + ->toThrow(InvalidArgumentException::class); +}); + +test('the file_groups migrations read the column instead of assuming utf8mb4 or 255', function () { + $migrations = dirname(__DIR__, 3) . '/database/migrations/'; + $caseSensitive = (string) file_get_contents($migrations . '2026_10_11_000000_make_file_groups_file_case_sensitive.php'); + $create = (string) file_get_contents($migrations . '2026_03_29_000000_create_file_groups_table.php'); + + expect($caseSensitive)->toContain('CHARACTER_SET_NAME AS charset') + ->and($caseSensitive)->toContain('CHARACTER_MAXIMUM_LENGTH AS length') + ->and($caseSensitive)->not->toContain('CHARACTER SET utf8mb4') + // a LIKE with an escaped underscore matches nothing under NO_BACKSLASH_ESCAPES + ->and((string) file_get_contents(dirname(__DIR__, 3) . '/includes/file_groups_schema.php'))->not->toContain('COLLATION_NAME LIKE') + ->and($create)->toContain('fittingLength(') + ->and($create)->toContain('->collation($collation)') + // the installer runs its own copy of the create migration + ->and((string) file_get_contents(dirname(__DIR__, 4) . '/install/stubs/migrations/2026_03_29_000000_create_file_groups_table.php')) + ->toBe($create); +}); + +test('the file_groups migrations build the table on sqlite and leave it alone afterwards', function () { + $capsule = bootFileGroupsSqlite(); + $migrations = dirname(__DIR__, 3) . '/database/migrations/'; + class_exists('CreateFileGroupsTable', false) || require $migrations . '2026_03_29_000000_create_file_groups_table.php'; + class_exists('MakeFileGroupsFileCaseSensitive', false) || require $migrations . '2026_10_11_000000_make_file_groups_file_case_sensitive.php'; + class_exists('RestoreFileGroupsIndexes', false) || require $migrations . '2026_12_05_000000_restore_file_groups_indexes.php'; + + (new CreateFileGroupsTable())->up(); + (new MakeFileGroupsFileCaseSensitive())->up(); + (new RestoreFileGroupsIndexes())->up(); + (new RestoreFileGroupsIndexes())->up(); + + $indexes = []; + foreach ($capsule->getConnection()->getSchemaBuilder()->getIndexes('file_groups') as $index) { + $indexes[$index['name']] = [$index['columns'], $index['unique']]; + } + expect($indexes['evo_file_groups_ix_fg_id'] ?? null)->toBe([['document_group', 'file'], true]) + ->and($indexes['evo_file_groups_file'] ?? null)->toBe([['file'], false]) + ->and($indexes['evo_file_groups_document_group'] ?? null)->toBe([['document_group'], false]) + ->and($indexes)->toHaveCount(4); + + $capsule->getConnection()->table('file_groups')->insert([ + ['document_group' => 1, 'file' => 'assets/files/report.txt'], + ['document_group' => 1, 'file' => 'assets/files/REPORT.txt'], + ]); + expect($capsule->getConnection()->table('file_groups')->count())->toBe(2); + $capsule->getConnection()->disconnect(); +}); diff --git a/install/stubs/migrations/2026_03_29_000000_create_file_groups_table.php b/install/stubs/migrations/2026_03_29_000000_create_file_groups_table.php index 9be481ddc8..e4b26015ee 100644 --- a/install/stubs/migrations/2026_03_29_000000_create_file_groups_table.php +++ b/install/stubs/migrations/2026_03_29_000000_create_file_groups_table.php @@ -2,6 +2,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; +use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; class CreateFileGroupsTable extends Migration { @@ -10,11 +11,31 @@ public function up() { return; } - Schema::create('file_groups', function(Blueprint $table) { + // File group keys are paths and must stay case-sensitive; on MySQL the column takes the + // binary collation of the connection's charset, and on MyISAM a length its key limit allows. + $length = 255; + $collation = null; + $connection = DB::connection(); + $schema = require EVO_CORE_PATH . 'includes/file_groups_schema.php'; + if ($schema->isMysql($connection)) { + $charset = $schema->newTableCharset($connection); + if ($charset !== null) { + $collation = $schema->binaryCollation($connection, $charset); + $length = $schema->fittingLength( + $schema->keyLimit($schema->newTableEngine($connection)), + $schema->bytesPerCharacter($connection, $charset) + ); + } + } + + Schema::create('file_groups', function(Blueprint $table) use ($length, $collation) { $indexPrefix = \DB::getTablePrefix() . $table->getTable(); $table->integer('id', true); $table->integer('document_group')->default(0)->index("{$indexPrefix}_document_group"); - $table->string('file', 255)->default('')->index("{$indexPrefix}_file"); + $file = $table->string('file', $length)->default('')->index("{$indexPrefix}_file"); + if ($collation !== null) { + $file->collation($collation); + } $table->unique(['document_group', 'file'], "{$indexPrefix}_ix_fg_id"); }); }