diff --git a/composer.json b/composer.json index a3c194e9bc..7cb93cdb33 100644 --- a/composer.json +++ b/composer.json @@ -26,8 +26,8 @@ "ext-curl": "*", "ext-openssl": "*", "appwrite/appwrite": "19.*", - "utopia-php/database": "dev-big-init as 5.4", - "utopia-php/storage": "1.0.*", + "utopia-php/database": "dev-big-init as 5.77", + "utopia-php/storage": "2.*", "utopia-php/dsn": "0.2.*", "halaxa/json-machine": "^1.2" }, diff --git a/composer.lock b/composer.lock index 6a9d20728a..5a9224b0e1 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "16a5b9e9382b5fa55ea40c8ec5a9cc00", + "content-hash": "ae396ad0e75429f13de6f2891f3cfae3", "packages": [ { "name": "appwrite/appwrite", @@ -187,23 +187,23 @@ }, { "name": "google/protobuf", - "version": "v4.33.5", + "version": "v4.33.6", "source": { "type": "git", "url": "https://github.com/protocolbuffers/protobuf-php.git", - "reference": "ebe8010a61b2ae0cff0d246fe1c4d44e9f7dfa6d" + "reference": "84b008c23915ed94536737eae46f41ba3bccfe67" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/protocolbuffers/protobuf-php/zipball/ebe8010a61b2ae0cff0d246fe1c4d44e9f7dfa6d", - "reference": "ebe8010a61b2ae0cff0d246fe1c4d44e9f7dfa6d", + "url": "https://api.github.com/repos/protocolbuffers/protobuf-php/zipball/84b008c23915ed94536737eae46f41ba3bccfe67", + "reference": "84b008c23915ed94536737eae46f41ba3bccfe67", "shasum": "" }, "require": { "php": ">=8.1.0" }, "require-dev": { - "phpunit/phpunit": ">=5.0.0 <8.5.27" + "phpunit/phpunit": ">=10.5.62 <11.0.0" }, "suggest": { "ext-bcmath": "Need to support JSON deserialization" @@ -225,9 +225,9 @@ "proto" ], "support": { - "source": "https://github.com/protocolbuffers/protobuf-php/tree/v4.33.5" + "source": "https://github.com/protocolbuffers/protobuf-php/tree/v4.33.6" }, - "time": "2026-01-29T20:49:00+00:00" + "time": "2026-03-18T17:32:05+00:00" }, { "name": "halaxa/json-machine", @@ -514,16 +514,16 @@ }, { "name": "open-telemetry/api", - "version": "1.8.0", + "version": "1.9.0", "source": { "type": "git", "url": "https://github.com/opentelemetry-php/api.git", - "reference": "df5197c6fd0ddd8e9883b87de042d9341300e2ad" + "reference": "6f8d237ce2c304ca85f31970f788e7f074d147be" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/opentelemetry-php/api/zipball/df5197c6fd0ddd8e9883b87de042d9341300e2ad", - "reference": "df5197c6fd0ddd8e9883b87de042d9341300e2ad", + "url": "https://api.github.com/repos/opentelemetry-php/api/zipball/6f8d237ce2c304ca85f31970f788e7f074d147be", + "reference": "6f8d237ce2c304ca85f31970f788e7f074d147be", "shasum": "" }, "require": { @@ -580,20 +580,20 @@ "issues": "https://github.com/open-telemetry/opentelemetry-php/issues", "source": "https://github.com/open-telemetry/opentelemetry-php" }, - "time": "2026-01-21T04:14:03+00:00" + "time": "2026-02-25T13:24:05+00:00" }, { "name": "open-telemetry/context", - "version": "1.4.0", + "version": "1.5.0", "source": { "type": "git", "url": "https://github.com/opentelemetry-php/context.git", - "reference": "d4c4470b541ce72000d18c339cfee633e4c8e0cf" + "reference": "3c414b246e0dabb7d6145404e6a5e4536ca18d07" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/opentelemetry-php/context/zipball/d4c4470b541ce72000d18c339cfee633e4c8e0cf", - "reference": "d4c4470b541ce72000d18c339cfee633e4c8e0cf", + "url": "https://api.github.com/repos/opentelemetry-php/context/zipball/3c414b246e0dabb7d6145404e6a5e4536ca18d07", + "reference": "3c414b246e0dabb7d6145404e6a5e4536ca18d07", "shasum": "" }, "require": { @@ -635,11 +635,11 @@ ], "support": { "chat": "https://app.slack.com/client/T08PSQ7BQ/C01NFPCV44V", - "docs": "https://opentelemetry.io/docs/php", + "docs": "https://opentelemetry.io/docs/languages/php", "issues": "https://github.com/open-telemetry/opentelemetry-php/issues", "source": "https://github.com/open-telemetry/opentelemetry-php" }, - "time": "2025-09-19T00:05:49+00:00" + "time": "2025-10-19T06:44:33+00:00" }, { "name": "open-telemetry/exporter-otlp", @@ -707,16 +707,16 @@ }, { "name": "open-telemetry/gen-otlp-protobuf", - "version": "1.8.0", + "version": "1.9.0", "source": { "type": "git", "url": "https://github.com/opentelemetry-php/gen-otlp-protobuf.git", - "reference": "673af5b06545b513466081884b47ef15a536edde" + "reference": "a229cf161d42001d64c8f21e8f678581fe1c66b9" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/opentelemetry-php/gen-otlp-protobuf/zipball/673af5b06545b513466081884b47ef15a536edde", - "reference": "673af5b06545b513466081884b47ef15a536edde", + "url": "https://api.github.com/repos/opentelemetry-php/gen-otlp-protobuf/zipball/a229cf161d42001d64c8f21e8f678581fe1c66b9", + "reference": "a229cf161d42001d64c8f21e8f678581fe1c66b9", "shasum": "" }, "require": { @@ -762,30 +762,30 @@ ], "support": { "chat": "https://app.slack.com/client/T08PSQ7BQ/C01NFPCV44V", - "docs": "https://opentelemetry.io/docs/php", + "docs": "https://opentelemetry.io/docs/languages/php", "issues": "https://github.com/open-telemetry/opentelemetry-php/issues", "source": "https://github.com/open-telemetry/opentelemetry-php" }, - "time": "2025-09-17T23:10:12+00:00" + "time": "2025-10-19T06:44:33+00:00" }, { "name": "open-telemetry/sdk", - "version": "1.13.0", + "version": "1.14.0", "source": { "type": "git", "url": "https://github.com/opentelemetry-php/sdk.git", - "reference": "c76f91203bf7ef98ab3f4e0a82ca21699af185e1" + "reference": "6e3d0ce93e76555dd5e2f1d19443ff45b990e410" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/opentelemetry-php/sdk/zipball/c76f91203bf7ef98ab3f4e0a82ca21699af185e1", - "reference": "c76f91203bf7ef98ab3f4e0a82ca21699af185e1", + "url": "https://api.github.com/repos/opentelemetry-php/sdk/zipball/6e3d0ce93e76555dd5e2f1d19443ff45b990e410", + "reference": "6e3d0ce93e76555dd5e2f1d19443ff45b990e410", "shasum": "" }, "require": { "ext-json": "*", "nyholm/psr7-server": "^1.1", - "open-telemetry/api": "^1.7", + "open-telemetry/api": "^1.8", "open-telemetry/context": "^1.4", "open-telemetry/sem-conv": "^1.0", "php": "^8.1", @@ -863,7 +863,7 @@ "issues": "https://github.com/open-telemetry/opentelemetry-php/issues", "source": "https://github.com/open-telemetry/opentelemetry-php" }, - "time": "2026-01-28T11:38:11+00:00" + "time": "2026-03-21T11:50:01+00:00" }, { "name": "open-telemetry/sem-conv", @@ -1487,16 +1487,16 @@ }, { "name": "symfony/http-client", - "version": "v7.4.5", + "version": "v7.4.8", "source": { "type": "git", "url": "https://github.com/symfony/http-client.git", - "reference": "84bb634857a893cc146cceb467e31b3f02c5fe9f" + "reference": "01933e626c3de76bea1e22641e205e78f6a34342" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/http-client/zipball/84bb634857a893cc146cceb467e31b3f02c5fe9f", - "reference": "84bb634857a893cc146cceb467e31b3f02c5fe9f", + "url": "https://api.github.com/repos/symfony/http-client/zipball/01933e626c3de76bea1e22641e205e78f6a34342", + "reference": "01933e626c3de76bea1e22641e205e78f6a34342", "shasum": "" }, "require": { @@ -1564,7 +1564,7 @@ "http" ], "support": { - "source": "https://github.com/symfony/http-client/tree/v7.4.5" + "source": "https://github.com/symfony/http-client/tree/v7.4.8" }, "funding": [ { @@ -1584,7 +1584,7 @@ "type": "tidelift" } ], - "time": "2026-01-27T16:16:02+00:00" + "time": "2026-03-30T12:55:43+00:00" }, { "name": "symfony/http-client-contracts", @@ -1666,16 +1666,16 @@ }, { "name": "symfony/polyfill-mbstring", - "version": "v1.33.0", + "version": "v1.37.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-mbstring.git", - "reference": "6d857f4d76bd4b343eac26d6b539585d2bc56493" + "reference": "6a21eb99c6973357967f6ce3708cd55a6bec6315" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/6d857f4d76bd4b343eac26d6b539585d2bc56493", - "reference": "6d857f4d76bd4b343eac26d6b539585d2bc56493", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/6a21eb99c6973357967f6ce3708cd55a6bec6315", + "reference": "6a21eb99c6973357967f6ce3708cd55a6bec6315", "shasum": "" }, "require": { @@ -1727,7 +1727,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.33.0" + "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.37.0" }, "funding": [ { @@ -1747,20 +1747,20 @@ "type": "tidelift" } ], - "time": "2024-12-23T08:48:59+00:00" + "time": "2026-04-10T17:25:58+00:00" }, { "name": "symfony/polyfill-php82", - "version": "v1.33.0", + "version": "v1.37.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-php82.git", - "reference": "5d2ed36f7734637dacc025f179698031951b1692" + "reference": "34808efe3e68f69685796f7c253a2f1d8ea9df59" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php82/zipball/5d2ed36f7734637dacc025f179698031951b1692", - "reference": "5d2ed36f7734637dacc025f179698031951b1692", + "url": "https://api.github.com/repos/symfony/polyfill-php82/zipball/34808efe3e68f69685796f7c253a2f1d8ea9df59", + "reference": "34808efe3e68f69685796f7c253a2f1d8ea9df59", "shasum": "" }, "require": { @@ -1807,7 +1807,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-php82/tree/v1.33.0" + "source": "https://github.com/symfony/polyfill-php82/tree/v1.37.0" }, "funding": [ { @@ -1827,20 +1827,20 @@ "type": "tidelift" } ], - "time": "2024-09-09T11:45:10+00:00" + "time": "2026-04-10T16:19:22+00:00" }, { "name": "symfony/polyfill-php83", - "version": "v1.33.0", + "version": "v1.37.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-php83.git", - "reference": "17f6f9a6b1735c0f163024d959f700cfbc5155e5" + "reference": "3600c2cb22399e25bb226e4a135ce91eeb2a6149" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php83/zipball/17f6f9a6b1735c0f163024d959f700cfbc5155e5", - "reference": "17f6f9a6b1735c0f163024d959f700cfbc5155e5", + "url": "https://api.github.com/repos/symfony/polyfill-php83/zipball/3600c2cb22399e25bb226e4a135ce91eeb2a6149", + "reference": "3600c2cb22399e25bb226e4a135ce91eeb2a6149", "shasum": "" }, "require": { @@ -1887,7 +1887,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-php83/tree/v1.33.0" + "source": "https://github.com/symfony/polyfill-php83/tree/v1.37.0" }, "funding": [ { @@ -1907,20 +1907,20 @@ "type": "tidelift" } ], - "time": "2025-07-08T02:45:35+00:00" + "time": "2026-04-10T17:25:58+00:00" }, { "name": "symfony/polyfill-php85", - "version": "v1.33.0", + "version": "v1.37.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-php85.git", - "reference": "d4e5fcd4ab3d998ab16c0db48e6cbb9a01993f91" + "reference": "fcfa4973a9917cef23f2e38774da74a2b7d115ee" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php85/zipball/d4e5fcd4ab3d998ab16c0db48e6cbb9a01993f91", - "reference": "d4e5fcd4ab3d998ab16c0db48e6cbb9a01993f91", + "url": "https://api.github.com/repos/symfony/polyfill-php85/zipball/fcfa4973a9917cef23f2e38774da74a2b7d115ee", + "reference": "fcfa4973a9917cef23f2e38774da74a2b7d115ee", "shasum": "" }, "require": { @@ -1967,7 +1967,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-php85/tree/v1.33.0" + "source": "https://github.com/symfony/polyfill-php85/tree/v1.37.0" }, "funding": [ { @@ -1987,7 +1987,7 @@ "type": "tidelift" } ], - "time": "2025-06-23T16:12:55+00:00" + "time": "2026-04-26T13:10:57+00:00" }, { "name": "symfony/service-contracts", @@ -2130,16 +2130,16 @@ }, { "name": "utopia-php/cache", - "version": "1.0.0", + "version": "1.0.1", "source": { "type": "git", "url": "https://github.com/utopia-php/cache.git", - "reference": "7068870c086a6aea16173563a26b93ef3e408439" + "reference": "05ceba981436a4022553f7aaa2a05fa049d0f71c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/cache/zipball/7068870c086a6aea16173563a26b93ef3e408439", - "reference": "7068870c086a6aea16173563a26b93ef3e408439", + "url": "https://api.github.com/repos/utopia-php/cache/zipball/05ceba981436a4022553f7aaa2a05fa049d0f71c", + "reference": "05ceba981436a4022553f7aaa2a05fa049d0f71c", "shasum": "" }, "require": { @@ -2176,9 +2176,9 @@ ], "support": { "issues": "https://github.com/utopia-php/cache/issues", - "source": "https://github.com/utopia-php/cache/tree/1.0.0" + "source": "https://github.com/utopia-php/cache/tree/1.0.1" }, - "time": "2026-01-28T10:55:44+00:00" + "time": "2026-03-12T03:39:09+00:00" }, { "name": "utopia-php/console", @@ -2234,18 +2234,19 @@ "source": { "type": "git", "url": "https://github.com/utopia-php/database.git", - "reference": "ef5c77972a95129eb929cce6c8f7c674db930ec9" + "reference": "ee8895a3ae835978fa4eb143619e4950e7001648" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/database/zipball/ef5c77972a95129eb929cce6c8f7c674db930ec9", - "reference": "ef5c77972a95129eb929cce6c8f7c674db930ec9", + "url": "https://api.github.com/repos/utopia-php/database/zipball/ee8895a3ae835978fa4eb143619e4950e7001648", + "reference": "ee8895a3ae835978fa4eb143619e4950e7001648", "shasum": "" }, "require": { "ext-mbstring": "*", "ext-mongodb": "*", "ext-pdo": "*", + "ext-redis": "*", "php": ">=8.4", "utopia-php/cache": "1.*", "utopia-php/console": "0.1.*", @@ -2285,7 +2286,7 @@ "issues": "https://github.com/utopia-php/database/issues", "source": "https://github.com/utopia-php/database/tree/big-init" }, - "time": "2026-03-30T06:31:05+00:00" + "time": "2026-05-05T13:27:52+00:00" }, { "name": "utopia-php/dsn", @@ -2336,16 +2337,16 @@ }, { "name": "utopia-php/mongo", - "version": "1.0.0", + "version": "1.1.0", "source": { "type": "git", "url": "https://github.com/utopia-php/mongo.git", - "reference": "45bedf36c2c946ec7a0a3e59b9f12f772de0b01d" + "reference": "73593682deee4696525a04e26524c1c1226e1530" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/mongo/zipball/45bedf36c2c946ec7a0a3e59b9f12f772de0b01d", - "reference": "45bedf36c2c946ec7a0a3e59b9f12f772de0b01d", + "url": "https://api.github.com/repos/utopia-php/mongo/zipball/73593682deee4696525a04e26524c1c1226e1530", + "reference": "73593682deee4696525a04e26524c1c1226e1530", "shasum": "" }, "require": { @@ -2391,22 +2392,22 @@ ], "support": { "issues": "https://github.com/utopia-php/mongo/issues", - "source": "https://github.com/utopia-php/mongo/tree/1.0.0" + "source": "https://github.com/utopia-php/mongo/tree/1.1.0" }, - "time": "2026-02-12T05:54:06+00:00" + "time": "2026-04-24T06:15:10+00:00" }, { "name": "utopia-php/pools", - "version": "1.0.2", + "version": "1.0.3", "source": { "type": "git", "url": "https://github.com/utopia-php/pools.git", - "reference": "b7d8dd00306cdd8bf3ff6f1dc90caeaf27dabeb1" + "reference": "74de7c5457a2c447f27e7ec4d72e8412a7d68c10" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/pools/zipball/b7d8dd00306cdd8bf3ff6f1dc90caeaf27dabeb1", - "reference": "b7d8dd00306cdd8bf3ff6f1dc90caeaf27dabeb1", + "url": "https://api.github.com/repos/utopia-php/pools/zipball/74de7c5457a2c447f27e7ec4d72e8412a7d68c10", + "reference": "74de7c5457a2c447f27e7ec4d72e8412a7d68c10", "shasum": "" }, "require": { @@ -2444,22 +2445,22 @@ ], "support": { "issues": "https://github.com/utopia-php/pools/issues", - "source": "https://github.com/utopia-php/pools/tree/1.0.2" + "source": "https://github.com/utopia-php/pools/tree/1.0.3" }, - "time": "2026-01-28T13:12:36+00:00" + "time": "2026-02-26T08:42:40+00:00" }, { "name": "utopia-php/storage", - "version": "1.0.0", + "version": "2.0.0", "source": { "type": "git", "url": "https://github.com/utopia-php/storage.git", - "reference": "f672e8865938e5d1d6dc3bd149ceba4e5582199e" + "reference": "52d1f89a47165ef0d3deff63043cda182175adfb" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/storage/zipball/f672e8865938e5d1d6dc3bd149ceba4e5582199e", - "reference": "f672e8865938e5d1d6dc3bd149ceba4e5582199e", + "url": "https://api.github.com/repos/utopia-php/storage/zipball/52d1f89a47165ef0d3deff63043cda182175adfb", + "reference": "52d1f89a47165ef0d3deff63043cda182175adfb", "shasum": "" }, "require": { @@ -2473,9 +2474,8 @@ "utopia-php/validators": "0.2.*" }, "require-dev": { - "laravel/pint": "1.2.*", - "phpunit/phpunit": "^9.3", - "vimeo/psalm": "4.0.1" + "laravel/pint": "^1.21", + "phpunit/phpunit": "^9.3" }, "type": "library", "autoload": { @@ -2497,22 +2497,22 @@ ], "support": { "issues": "https://github.com/utopia-php/storage/issues", - "source": "https://github.com/utopia-php/storage/tree/1.0.0" + "source": "https://github.com/utopia-php/storage/tree/2.0.0" }, - "time": "2026-02-17T04:37:10+00:00" + "time": "2026-04-27T11:39:32+00:00" }, { "name": "utopia-php/system", - "version": "0.10.0", + "version": "0.10.1", "source": { "type": "git", "url": "https://github.com/utopia-php/system.git", - "reference": "6441a9c180958a373e5ddb330264dd638539dfdb" + "reference": "7c1669533bb9c285de19191270c8c1439161a78a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/system/zipball/6441a9c180958a373e5ddb330264dd638539dfdb", - "reference": "6441a9c180958a373e5ddb330264dd638539dfdb", + "url": "https://api.github.com/repos/utopia-php/system/zipball/7c1669533bb9c285de19191270c8c1439161a78a", + "reference": "7c1669533bb9c285de19191270c8c1439161a78a", "shasum": "" }, "require": { @@ -2553,9 +2553,9 @@ ], "support": { "issues": "https://github.com/utopia-php/system/issues", - "source": "https://github.com/utopia-php/system/tree/0.10.0" + "source": "https://github.com/utopia-php/system/tree/0.10.1" }, - "time": "2025-10-15T19:12:00+00:00" + "time": "2026-03-15T21:07:41+00:00" }, { "name": "utopia-php/telemetry", @@ -2723,16 +2723,16 @@ }, { "name": "laravel/pint", - "version": "v1.27.1", + "version": "v1.2.1", "source": { "type": "git", "url": "https://github.com/laravel/pint.git", - "reference": "54cca2de13790570c7b6f0f94f37896bee4abcb5" + "reference": "e60e2112ee779ce60f253695b273d1646a17d6f1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/pint/zipball/54cca2de13790570c7b6f0f94f37896bee4abcb5", - "reference": "54cca2de13790570c7b6f0f94f37896bee4abcb5", + "url": "https://api.github.com/repos/laravel/pint/zipball/e60e2112ee779ce60f253695b273d1646a17d6f1", + "reference": "e60e2112ee779ce60f253695b273d1646a17d6f1", "shasum": "" }, "require": { @@ -2740,16 +2740,16 @@ "ext-mbstring": "*", "ext-tokenizer": "*", "ext-xml": "*", - "php": "^8.2.0" + "php": "^8.0" }, "require-dev": { - "friendsofphp/php-cs-fixer": "^3.93.1", - "illuminate/view": "^12.51.0", - "larastan/larastan": "^3.9.2", - "laravel-zero/framework": "^12.0.5", - "mockery/mockery": "^1.6.12", - "nunomaduro/termwind": "^2.3.3", - "pestphp/pest": "^3.8.5" + "friendsofphp/php-cs-fixer": "^3.11.0", + "illuminate/view": "^9.32.0", + "laravel-zero/framework": "^9.2.0", + "mockery/mockery": "^1.5.1", + "nunomaduro/larastan": "^2.2.0", + "nunomaduro/termwind": "^1.14.0", + "pestphp/pest": "^1.22.1" }, "bin": [ "builds/pint" @@ -2775,7 +2775,6 @@ "description": "An opinionated code formatter for PHP.", "homepage": "https://laravel.com", "keywords": [ - "dev", "format", "formatter", "lint", @@ -2786,7 +2785,7 @@ "issues": "https://github.com/laravel/pint/issues", "source": "https://github.com/laravel/pint" }, - "time": "2026-02-10T20:00:20+00:00" + "time": "2022-11-29T16:25:20+00:00" }, { "name": "myclabs/deep-copy", @@ -3101,11 +3100,11 @@ }, { "name": "phpstan/phpstan", - "version": "1.12.32", + "version": "1.12.33", "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpstan/zipball/2770dcdf5078d0b0d53f94317e06affe88419aa8", - "reference": "2770dcdf5078d0b0d53f94317e06affe88419aa8", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/37982d6fc7cbb746dda7773530cda557cdf119e1", + "reference": "37982d6fc7cbb746dda7773530cda557cdf119e1", "shasum": "" }, "require": { @@ -3150,7 +3149,7 @@ "type": "github" } ], - "time": "2025-09-30T10:16:31+00:00" + "time": "2026-02-28T20:30:03+00:00" }, { "name": "phpunit/php-code-coverage", @@ -3501,16 +3500,16 @@ }, { "name": "phpunit/phpunit", - "version": "11.5.53", + "version": "11.5.55", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/phpunit.git", - "reference": "a997a653a82845f1240d73ee73a8a4e97e4b0607" + "reference": "adc7262fccc12de2b30f12a8aa0b33775d814f00" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/a997a653a82845f1240d73ee73a8a4e97e4b0607", - "reference": "a997a653a82845f1240d73ee73a8a4e97e4b0607", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/adc7262fccc12de2b30f12a8aa0b33775d814f00", + "reference": "adc7262fccc12de2b30f12a8aa0b33775d814f00", "shasum": "" }, "require": { @@ -3583,7 +3582,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/phpunit/issues", "security": "https://github.com/sebastianbergmann/phpunit/security/policy", - "source": "https://github.com/sebastianbergmann/phpunit/tree/11.5.53" + "source": "https://github.com/sebastianbergmann/phpunit/tree/11.5.55" }, "funding": [ { @@ -3607,7 +3606,7 @@ "type": "tidelift" } ], - "time": "2026-02-10T12:28:25+00:00" + "time": "2026-02-18T12:37:06+00:00" }, { "name": "sebastian/cli-parser", @@ -4649,16 +4648,16 @@ }, { "name": "symfony/polyfill-ctype", - "version": "v1.33.0", + "version": "v1.37.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-ctype.git", - "reference": "a3cc8b044a6ea513310cbd48ef7333b384945638" + "reference": "141046a8f9477948ff284fa65be2095baafb94f2" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/a3cc8b044a6ea513310cbd48ef7333b384945638", - "reference": "a3cc8b044a6ea513310cbd48ef7333b384945638", + "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/141046a8f9477948ff284fa65be2095baafb94f2", + "reference": "141046a8f9477948ff284fa65be2095baafb94f2", "shasum": "" }, "require": { @@ -4708,7 +4707,7 @@ "portable" ], "support": { - "source": "https://github.com/symfony/polyfill-ctype/tree/v1.33.0" + "source": "https://github.com/symfony/polyfill-ctype/tree/v1.37.0" }, "funding": [ { @@ -4728,20 +4727,20 @@ "type": "tidelift" } ], - "time": "2024-09-09T11:45:10+00:00" + "time": "2026-04-10T16:19:22+00:00" }, { "name": "symfony/polyfill-php80", - "version": "v1.33.0", + "version": "v1.37.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-php80.git", - "reference": "0cc9dd0f17f61d8131e7df6b84bd344899fe2608" + "reference": "dfb55726c3a76ea3b6459fcfda1ec2d80a682411" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/0cc9dd0f17f61d8131e7df6b84bd344899fe2608", - "reference": "0cc9dd0f17f61d8131e7df6b84bd344899fe2608", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/dfb55726c3a76ea3b6459fcfda1ec2d80a682411", + "reference": "dfb55726c3a76ea3b6459fcfda1ec2d80a682411", "shasum": "" }, "require": { @@ -4792,7 +4791,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-php80/tree/v1.33.0" + "source": "https://github.com/symfony/polyfill-php80/tree/v1.37.0" }, "funding": [ { @@ -4812,7 +4811,7 @@ "type": "tidelift" } ], - "time": "2025-01-02T08:10:11+00:00" + "time": "2026-04-10T16:19:22+00:00" }, { "name": "theseer/tokenizer", @@ -4953,8 +4952,8 @@ { "package": "utopia-php/database", "version": "dev-big-init", - "alias": "5.4", - "alias_normalized": "5.4.0.0" + "alias": "5.77", + "alias_normalized": "5.77.0.0" } ], "minimum-stability": "stable", diff --git a/src/Migration/Destinations/Appwrite.php b/src/Migration/Destinations/Appwrite.php index 49cadb72e1..41edaa6e44 100644 --- a/src/Migration/Destinations/Appwrite.php +++ b/src/Migration/Destinations/Appwrite.php @@ -63,6 +63,29 @@ use Utopia\Migration\Transfer; class Appwrite extends Destination { + /** Names of the project-DB collections holding Appwrite schema metadata. */ + private const META_DATABASES = 'databases'; + private const META_ATTRIBUTES = 'attributes'; + private const META_INDEXES = 'indexes'; + + /** Attribute fields the SDK can't update in place (no per-type updateX endpoint exposes them); a change here forces drop+recreate. */ + private const ATTRIBUTE_IMMUTABLE_FIELDS = [ + 'type', + 'array', + 'signed', + 'format', + 'formatOptions', + 'filters', + ]; + + /** Relationship options fields the SDK can't update in place (only onDelete/newKey are SDK-reachable); a change here forces drop+recreate. */ + private const RELATIONSHIP_IMMUTABLE_FIELDS = [ + 'relationType', + 'twoWay', + 'twoWayKey', + 'relatedCollection', + ]; + protected Client $client; protected string $project; @@ -85,6 +108,29 @@ class Appwrite extends Destination */ private array $rowBuffer = []; + /** + * Overwrite-mode orphan tracking, keyed by (database, table). Orphans are + * destination keys not in `attributeKeys` / `indexKeys`. Entries removed + * after their cleanup runs so the end-of-run sweep only visits tables + * that had no rows. + * + * @var array, + * indexKeys: list, + * }> + */ + private array $orphansByTable = []; + + /** + * Two-way pairs already reconciled this run; partner pass short-circuits. + * + * @var array + */ + private array $processedTwoWayPairs = []; + /** * @param string $project * @param string $endpoint @@ -92,6 +138,7 @@ class Appwrite extends Destination * @param UtopiaDatabase $dbForProject * @param callable(UtopiaDocument $database):UtopiaDatabase $getDatabasesDB * @param array> $collectionStructure + * @param OnDuplicate $onDuplicate Behavior when a row with an existing $id is encountered. */ public function __construct( string $project, @@ -99,7 +146,8 @@ class Appwrite extends Destination string $key, protected UtopiaDatabase $dbForProject, callable $getDatabasesDB, - protected array $collectionStructure + protected array $collectionStructure, + protected OnDuplicate $onDuplicate = OnDuplicate::Fail, ) { $this->project = $project; $this->endpoint = $endpoint; @@ -120,6 +168,27 @@ class Appwrite extends Destination $this->getDatabasesDB = $getDatabasesDB; } + /** Orphan cleanup runs only after a successful migration — a mid-run throw preserves the destination as-is. */ + #[Override] + public function run( + array $resources, + callable $callback, + string $rootResourceId = '', + string $rootResourceType = '', + ): void { + $this->resetRunState(); + parent::run($resources, $callback, $rootResourceId, $rootResourceType); + $this->cleanupOverwriteOrphans(); + } + + /** Per-run state must not leak across run() invocations on a reused instance. */ + private function resetRunState(): void + { + $this->rowBuffer = []; + $this->orphansByTable = []; + $this->processedTwoWayPairs = []; + } + public static function getName(): string { return 'Appwrite'; @@ -169,6 +238,9 @@ class Appwrite extends Destination Resource::TYPE_SITE, Resource::TYPE_SITE_DEPLOYMENT, Resource::TYPE_SITE_VARIABLE, + + // Backups + Resource::TYPE_BACKUP_POLICY, ]; } @@ -281,7 +353,6 @@ class Appwrite extends Destination $scope = 'sites.write'; $this->sites->create('', '', Framework::OTHER(), BuildRuntime::STATIC1()); } - } catch (AppwriteException $e) { if ($e->getCode() === 403) { throw new \Exception( @@ -325,6 +396,7 @@ class Appwrite extends Destination Transfer::GROUP_FUNCTIONS => $this->importFunctionResource($resource), Transfer::GROUP_MESSAGING => $this->importMessagingResource($resource), Transfer::GROUP_SITES => $this->importSiteResource($resource), + Transfer::GROUP_BACKUPS => $this->importBackupResource($resource), default => throw new \Exception('Invalid resource group', Exception::CODE_VALIDATION), }; } catch (\Throwable $e) { @@ -420,7 +492,45 @@ class Appwrite extends Destination $createdAt = $this->normalizeDateTime($resource->getCreatedAt()); $updatedAt = $this->normalizeDateTime($resource->getUpdatedAt(), $createdAt); - $database = $this->dbForProject->createDocument('databases', new UtopiaDocument([ + if ($this->onDuplicate !== OnDuplicate::Fail) { + $existing = $this->dbForProject->getDocument(self::META_DATABASES, $resource->getId()); + $action = $this->onDuplicate->resolveSchemaAction( + !$existing->isEmpty(), + $updatedAt, + $existing->getUpdatedAt(), + ); + // Spec match → skip work. Create excluded; nothing on dest to match against. + if ($action !== SchemaAction::Create && $this->databaseSpecMatches($existing, $resource)) { + $action = SchemaAction::Skip; + } + + $earlyReturn = match ($action) { + SchemaAction::Skip => (function () use ($resource, $existing): bool { + $resource->setSequence($existing->getSequence()); + $resource->setStatus(Resource::STATUS_SKIPPED, 'Already exists on destination'); + return false; + })(), + SchemaAction::Overwrite => (function () use ($resource, $existing, $updatedAt): bool { + $this->dbForProject->updateDocument(self::META_DATABASES, $existing->getId(), new UtopiaDocument([ + 'name' => $resource->getDatabaseName(), + 'search' => implode(' ', [$resource->getId(), $resource->getDatabaseName()]), + 'enabled' => $resource->getEnabled(), + 'type' => empty($resource->getType()) ? 'legacy' : $resource->getType(), + 'originalId' => empty($resource->getOriginalId()) ? null : $resource->getOriginalId(), + 'database' => $resource->getDatabase(), + '$updatedAt' => $updatedAt, + ])); + $resource->setSequence($existing->getSequence()); + return true; + })(), + SchemaAction::Create => null, + }; + if ($earlyReturn !== null) { + return $earlyReturn; + } + } + + $database = $this->dbForProject->createDocument(self::META_DATABASES, new UtopiaDocument([ '$id' => $resource->getId(), 'name' => $resource->getDatabaseName(), 'enabled' => $resource->getEnabled(), @@ -446,7 +556,7 @@ class Appwrite extends Destination ); $this->dbForProject->createCollection( - 'database_' . $database->getSequence(), + $this->databaseCollectionId($database), $columns, $indexes ); @@ -478,7 +588,7 @@ class Appwrite extends Destination } $database = $this->dbForProject->getDocument( - 'databases', + self::META_DATABASES, $resource->getDatabase()->getId() ); @@ -501,7 +611,51 @@ class Appwrite extends Destination $dbForDatabases->create(); } - $table = $this->dbForProject->createDocument('database_' . $database->getSequence(), new UtopiaDocument([ + if ($this->onDuplicate !== OnDuplicate::Fail) { + $existing = $this->dbForProject->getDocument( + $this->databaseCollectionId($database), + $resource->getId() + ); + $action = $this->onDuplicate->resolveSchemaAction( + !$existing->isEmpty(), + $updatedAt, + $existing->getUpdatedAt(), + ); + // Spec match → skip work. Create excluded; nothing on dest to match against. + if ($action !== SchemaAction::Create && $this->tableSpecMatches($existing, $resource)) { + $action = SchemaAction::Skip; + } + + $earlyReturn = match ($action) { + SchemaAction::Skip => (function () use ($resource, $existing): bool { + $resource->setSequence($existing->getSequence()); + $resource->setStatus(Resource::STATUS_SKIPPED, 'Already exists on destination'); + return false; + })(), + SchemaAction::Overwrite => (function () use ($resource, $existing, $database, $updatedAt): bool { + $this->dbForProject->updateDocument( + $this->databaseCollectionId($database), + $existing->getId(), + new UtopiaDocument([ + 'name' => $resource->getTableName(), + 'search' => implode(' ', [$resource->getId(), $resource->getTableName()]), + 'enabled' => $resource->getEnabled(), + '$permissions' => Permission::aggregate($resource->getPermissions()), + 'documentSecurity' => $resource->getRowSecurity(), + '$updatedAt' => $updatedAt, + ]) + ); + $resource->setSequence($existing->getSequence()); + return true; + })(), + SchemaAction::Create => null, + }; + if ($earlyReturn !== null) { + return $earlyReturn; + } + } + + $table = $this->dbForProject->createDocument($this->databaseCollectionId($database), new UtopiaDocument([ '$id' => $resource->getId(), 'databaseInternalId' => $database->getSequence(), 'databaseId' => $resource->getDatabase()->getId(), @@ -517,7 +671,7 @@ class Appwrite extends Destination $resource->setSequence($table->getSequence()); $dbForDatabases->createCollection( - 'database_' . $database->getSequence() . '_collection_' . $resource->getSequence(), + $this->tableCollectionId($database, $table), permissions: $resource->getPermissions(), documentSecurity: $resource->getRowSecurity() ); @@ -566,7 +720,7 @@ class Appwrite extends Destination }; $database = $this->dbForProject->getDocument( - 'databases', + self::META_DATABASES, $resource->getTable()->getDatabase()->getId(), ); @@ -580,7 +734,7 @@ class Appwrite extends Destination } $table = $this->dbForProject->getDocument( - 'database_' . $database->getSequence(), + $this->databaseCollectionId($database), $resource->getTable()->getId(), ); @@ -625,7 +779,7 @@ class Appwrite extends Destination if ($type === UtopiaDatabase::VAR_RELATIONSHIP) { $resource->getOptions()['side'] = UtopiaDatabase::RELATION_SIDE_PARENT; $relatedTable = $this->dbForProject->getDocument( - 'database_' . $database->getSequence(), + $this->databaseCollectionId($database), $resource->getOptions()['relatedCollection'] ); if ($relatedTable->isEmpty()) { @@ -641,9 +795,61 @@ class Appwrite extends Destination $createdAt = $this->normalizeDateTime($resource->getCreatedAt()); $updatedAt = $this->normalizeDateTime($resource->getUpdatedAt(), $createdAt); $dbForDatabases = ($this->getDatabasesDB)($database); + + $this->trackOrphanCandidate($database, $table, 'attributeKeys', $resource->getKey(), $dbForDatabases); + + $isRelationship = $type === UtopiaDatabase::VAR_RELATIONSHIP; + + // Source emits both sides of a two-way; processing one side reconciles both. Partner skip. + $twoWayPairKey = $this->twoWayPairKey($database, $table, $resource, $type); + if ($twoWayPairKey !== null && isset($this->processedTwoWayPairs[$twoWayPairKey])) { + $resource->setStatus(Resource::STATUS_SKIPPED, 'Two-way partner already reconciled'); + return false; + } + + $attributeMetaId = $this->attributeIndexMetaId($database, $table, $resource->getKey()); + if ($this->onDuplicate !== OnDuplicate::Fail) { + $existingAttr = $this->dbForProject->getDocument(self::META_ATTRIBUTES, $attributeMetaId); + $action = $this->onDuplicate->resolveSchemaAction( + !$existingAttr->isEmpty(), + $updatedAt, + $existingAttr->getUpdatedAt(), + ); + // Spec match → skip work. Create excluded; nothing on dest to match against. + if ($action !== SchemaAction::Create && $this->attributeSpecMatches($existingAttr, $resource, $type, $isRelationship)) { + $action = SchemaAction::Skip; + } + + $earlyReturn = match ($action) { + SchemaAction::Skip => (function () use ($resource, $database, $table, $dbForDatabases): bool { + $this->purgeTableCaches($database, $table, $dbForDatabases); + $resource->setStatus(Resource::STATUS_SKIPPED, 'Already exists on destination'); + return false; + })(), + SchemaAction::Overwrite => ($isRelationship + ? $this->updateRelationshipInPlace($database, $table, $resource, $type, $updatedAt, $existingAttr, $dbForDatabases) + : $this->updateAttributeInPlace($database, $table, $resource, $type, $updatedAt, $existingAttr, $dbForDatabases)) + ? true + : null, + SchemaAction::Create => null, + }; + if ($earlyReturn !== null) { + if ($twoWayPairKey !== null) { + $this->processedTwoWayPairs[$twoWayPairKey] = true; + } + return $earlyReturn; + } + + if ($action === SchemaAction::Overwrite) { + $this->dropAttributeForRecreate($database, $table, $resource, $dbForDatabases, $existingAttr); + // Reload $table — in-memory copy still holds the dropped attribute, so checkAttribute would over-count. + $table = $this->dbForProject->getDocument($this->databaseCollectionId($database), $table->getId()); + } + } + try { $column = new UtopiaDocument([ - '$id' => ID::custom($database->getSequence() . '_' . $table->getSequence() . '_' . $resource->getKey()), + '$id' => ID::custom($attributeMetaId), 'key' => $resource->getKey(), 'databaseInternalId' => $database->getSequence(), 'databaseId' => $database->getId(), @@ -666,7 +872,7 @@ class Appwrite extends Destination $this->dbForProject->checkAttribute($table, $column); - $column = $this->dbForProject->createDocument('attributes', $column); + $column = $this->dbForProject->createDocument(self::META_ATTRIBUTES, $column); } catch (DuplicateException) { throw new Exception( resourceName: $resource->getName(), @@ -682,13 +888,11 @@ class Appwrite extends Destination message: 'Attribute limit exceeded', ); } catch (\Throwable $e) { - $this->dbForProject->purgeCachedDocument('database_' . $database->getSequence(), $table->getId()); - $dbForDatabases->purgeCachedCollection('database_' . $database->getSequence() . '_collection_' . $table->getSequence()); + $this->purgeTableCaches($database, $table, $dbForDatabases); throw $e; } - $this->dbForProject->purgeCachedDocument('database_' . $database->getSequence(), $table->getId()); - $dbForDatabases->purgeCachedCollection('database_' . $database->getSequence() . '_collection_' . $table->getSequence()); + $this->purgeTableCaches($database, $table, $dbForDatabases); $options = $resource->getOptions(); $twoWayKey = null; @@ -701,7 +905,7 @@ class Appwrite extends Destination try { $twoWayAttribute = new UtopiaDocument([ - '$id' => ID::custom($database->getSequence() . '_' . $relatedTable->getSequence() . '_' . $twoWayKey), + '$id' => ID::custom($this->attributeIndexMetaId($database, $relatedTable, $twoWayKey)), 'key' => $twoWayKey, 'databaseInternalId' => $database->getSequence(), 'databaseId' => $database->getId(), @@ -722,9 +926,10 @@ class Appwrite extends Destination '$updatedAt' => $updatedAt, ]); - $this->dbForProject->createDocument('attributes', $twoWayAttribute); + $this->dbForProject->createDocument(self::META_ATTRIBUTES, $twoWayAttribute); + $this->trackOrphanCandidate($database, $relatedTable, 'attributeKeys', $twoWayKey, $dbForDatabases); } catch (DuplicateException) { - $this->dbForProject->deleteDocument('attributes', $column->getId()); + $this->dbForProject->deleteDocument(self::META_ATTRIBUTES, $column->getId()); throw new Exception( resourceName: $resource->getName(), @@ -733,17 +938,16 @@ class Appwrite extends Destination message: 'Attribute already exists', ); } catch (LimitException) { - $this->dbForProject->deleteDocument('attributes', $column->getId()); + $this->dbForProject->deleteDocument(self::META_ATTRIBUTES, $column->getId()); throw new Exception( resourceName: $resource->getName(), resourceGroup: $resource->getGroup(), resourceId: $resource->getId(), - message: 'Column limit exceeded', + message: 'Attribute limit exceeded', ); } catch (\Throwable $e) { - $this->dbForProject->purgeCachedDocument('database_' . $database->getSequence(), $relatedTable->getId()); - $dbForDatabases->purgeCachedCollection('database_' . $database->getSequence() . '_collection_' . $relatedTable->getSequence()); + $this->purgeTableCaches($database, $relatedTable, $dbForDatabases); throw $e; } } @@ -752,8 +956,9 @@ class Appwrite extends Destination switch ($type) { case UtopiaDatabase::VAR_RELATIONSHIP: if (!$dbForDatabases->createRelationship( - collection: 'database_' . $database->getSequence() . '_collection_' . $table->getSequence(), - relatedCollection: 'database_' . $database->getSequence() . '_collection_' . $relatedTable->getSequence(), + collection: $this->tableCollectionId($database, $table), + // @phpstan-ignore-next-line — $relatedTable is set when type is VAR_RELATIONSHIP. + relatedCollection: $this->tableCollectionId($database, $relatedTable), type: $options['relationType'], twoWay: $options['twoWay'], id: $resource->getKey(), @@ -770,7 +975,7 @@ class Appwrite extends Destination break; default: if (!$dbForDatabases->createAttribute( - 'database_' . $database->getSequence() . '_collection_' . $table->getSequence(), + $this->tableCollectionId($database, $table), $resource->getKey(), $type, $resource->getSize(), @@ -786,10 +991,10 @@ class Appwrite extends Destination } } } catch (\Throwable) { - $this->dbForProject->deleteDocument('attributes', $column->getId()); + $this->dbForProject->deleteDocument(self::META_ATTRIBUTES, $column->getId()); if (isset($twoWayAttribute)) { - $this->dbForProject->deleteDocument('attributes', $twoWayAttribute->getId()); + $this->dbForProject->deleteDocument(self::META_ATTRIBUTES, $twoWayAttribute->getId()); } throw new Exception( @@ -801,11 +1006,15 @@ class Appwrite extends Destination } if ($type === UtopiaDatabase::VAR_RELATIONSHIP && $options['twoWay']) { - $this->dbForProject->purgeCachedDocument('database_' . $database->getSequence(), $relatedTable->getId()); + // @phpstan-ignore-next-line — $relatedTable is set when type is VAR_RELATIONSHIP. + $this->dbForProject->purgeCachedDocument($this->databaseCollectionId($database), $relatedTable->getId()); } - $this->dbForProject->purgeCachedDocument('database_' . $database->getSequence(), $table->getId()); - $dbForDatabases->purgeCachedCollection('database_' . $database->getSequence() . '_collection_' . $table->getSequence()); + $this->purgeTableCaches($database, $table, $dbForDatabases); + + if ($twoWayPairKey !== null) { + $this->processedTwoWayPairs[$twoWayPairKey] = true; + } return true; } @@ -817,7 +1026,7 @@ class Appwrite extends Destination protected function createIndex(Index $resource): bool { $database = $this->dbForProject->getDocument( - 'databases', + self::META_DATABASES, $resource->getTable()->getDatabase()->getId(), ); if ($database->isEmpty()) { @@ -830,7 +1039,7 @@ class Appwrite extends Destination } $table = $this->dbForProject->getDocument( - 'database_' . $database->getSequence(), + $this->databaseCollectionId($database), $resource->getTable()->getId(), ); if ($table->isEmpty()) { @@ -843,7 +1052,51 @@ class Appwrite extends Destination } $dbForDatabases = ($this->getDatabasesDB)($database); - $count = $this->dbForProject->count('indexes', [ + $createdAt = $this->normalizeDateTime($resource->getCreatedAt()); + $updatedAt = $this->normalizeDateTime($resource->getUpdatedAt(), $createdAt); + + $this->trackOrphanCandidate($database, $table, 'indexKeys', $resource->getKey(), $dbForDatabases); + + $indexMetaId = $this->attributeIndexMetaId($database, $table, $resource->getKey()); + + // Pre-check + drop runs BEFORE count/validator so the to-be-dropped index isn't included in + // the limit count or in IndexValidator's $tableIndexes (otherwise an Overwrite recreate at the + // ceiling throws "Index limit reached" or "Invalid index" even though the net change is zero). + if ($this->onDuplicate !== OnDuplicate::Fail) { + $existingIdx = $this->dbForProject->getDocument(self::META_INDEXES, $indexMetaId); + $action = $this->onDuplicate->resolveSchemaAction( + !$existingIdx->isEmpty(), + $updatedAt, + $existingIdx->getUpdatedAt(), + ); + // Spec match → skip work. Create excluded; nothing on dest to match against. + if ($action !== SchemaAction::Create && $this->indexSpecMatches($existingIdx, $resource)) { + $action = SchemaAction::Skip; + } + + // Indexes have no in-place primitive — any action other than Skip falls through to drop+recreate. + $earlyReturn = match ($action) { + SchemaAction::Skip => (function () use ($resource, $database, $table): bool { + $this->dbForProject->purgeCachedDocument($this->databaseCollectionId($database), $table->getId()); + $resource->setStatus(Resource::STATUS_SKIPPED, 'Already exists on destination'); + return false; + })(), + SchemaAction::Overwrite, SchemaAction::Create => null, + }; + if ($earlyReturn !== null) { + return $earlyReturn; + } + + if ($action === SchemaAction::Overwrite) { + $dbForDatabases->deleteIndex($this->tableCollectionId($database, $table), $resource->getKey()); + $this->dbForProject->deleteDocument(self::META_INDEXES, $indexMetaId); + $this->dbForProject->purgeCachedDocument($this->databaseCollectionId($database), $table->getId()); + // Reload $table — in-memory copy still holds the dropped index, so IndexValidator below would over-count. + $table = $this->dbForProject->getDocument($this->databaseCollectionId($database), $table->getId()); + } + } + + $count = $this->dbForProject->count(self::META_INDEXES, [ Query::equal('collectionInternalId', [$table->getSequence()]), Query::equal('databaseInternalId', [$database->getSequence()]) ], $dbForDatabases->getLimitForIndexes()); @@ -864,11 +1117,8 @@ class Appwrite extends Destination $this->validateFieldsForIndexes($resource, $table, $lengths); } - $createdAt = $this->normalizeDateTime($resource->getCreatedAt()); - $updatedAt = $this->normalizeDateTime($resource->getUpdatedAt(), $createdAt); - $index = new UtopiaDocument([ - '$id' => ID::custom($database->getSequence() . '_' . $table->getSequence() . '_' . $resource->getKey()), + '$id' => ID::custom($indexMetaId), 'key' => $resource->getKey(), 'status' => 'available', // processing, available, failed, deleting, stuck 'databaseInternalId' => $database->getSequence(), @@ -909,7 +1159,6 @@ class Appwrite extends Destination $dbForDatabases->getAdapter()->getSupportForFulltextIndex() ); - if (!$validator->isValid($index)) { throw new Exception( resourceName: $resource->getName(), @@ -919,11 +1168,11 @@ class Appwrite extends Destination ); } - $index = $this->dbForProject->createDocument('indexes', $index); + $index = $this->dbForProject->createDocument(self::META_INDEXES, $index); try { $result = $dbForDatabases->createIndex( - 'database_' . $database->getSequence() . '_collection_' . $table->getSequence(), + $this->tableCollectionId($database, $table), $resource->getKey(), $resource->getType(), $resource->getColumns(), @@ -940,7 +1189,7 @@ class Appwrite extends Destination ); } } catch (\Throwable $th) { - $this->dbForProject->deleteDocument('indexes', $index->getId()); + $this->dbForProject->deleteDocument(self::META_INDEXES, $index->getId()); throw new Exception( resourceName: $resource->getName(), @@ -950,10 +1199,7 @@ class Appwrite extends Destination ); } - $this->dbForProject->purgeCachedDocument( - 'database_' . $database->getSequence(), - $table->getId() - ); + $this->dbForProject->purgeCachedDocument($this->databaseCollectionId($database), $table->getId()); return true; } @@ -1030,22 +1276,25 @@ class Appwrite extends Destination if ($isLast) { try { $database = $this->dbForProject->getDocument( - 'databases', + self::META_DATABASES, $resource->getTable()->getDatabase()->getId(), ); $table = $this->dbForProject->getDocument( - 'database_' . $database->getSequence(), + $this->databaseCollectionId($database), $resource->getTable()->getId(), ); - $databaseInternalId = $database->getSequence(); - $tableInternalId = $table->getSequence(); $dbForDatabases = ($this->getDatabasesDB)($database); - /** - * This is in case an attribute was deleted from Appwrite attributes collection but was not deleted from the table - * When creating an archive we select * which will include orphan attribute from the schema - */ + + // Drop schema orphans before rows land so the Structure validator doesn't reject on orphan required columns. + $this->cleanupOverwriteOrphansForTable($this->tableIdentity($database, $table)); + // Reload $table — in-memory copy still holds the dropped attributes, so the strip loop below would over-keep. + $table = $this->dbForProject->getDocument( + $this->databaseCollectionId($database), + $resource->getTable()->getId(), + ); + // Strip row payload fields the table doesn't declare — guards against orphans surviving in source archives. if ($dbForDatabases->getAdapter()->getSupportForAttributes()) { foreach ($this->rowBuffer as $row) { foreach ($row as $key => $value) { @@ -1068,11 +1317,21 @@ class Appwrite extends Destination } } } - $dbForDatabases->skipRelationshipsExistCheck(fn () => $dbForDatabases->createDocuments( - 'database_' . $databaseInternalId . '_collection_' . $tableInternalId, - $this->rowBuffer - )); + $collectionId = $this->tableCollectionId($database, $table); + match ($this->onDuplicate) { + OnDuplicate::Overwrite => $dbForDatabases->skipRelationshipsExistCheck( + fn () => $dbForDatabases->upsertDocuments($collectionId, $this->rowBuffer) + ), + OnDuplicate::Skip => $dbForDatabases->skipDuplicates( + fn () => $dbForDatabases->skipRelationshipsExistCheck( + fn () => $dbForDatabases->createDocuments($collectionId, $this->rowBuffer) + ) + ), + OnDuplicate::Fail => $dbForDatabases->skipRelationshipsExistCheck( + fn () => $dbForDatabases->createDocuments($collectionId, $this->rowBuffer) + ), + }; } finally { $this->rowBuffer = []; } @@ -1082,6 +1341,516 @@ class Appwrite extends Destination return true; } + /** Relationships route through deleteRelationship since deleteAttribute throws for VAR_RELATIONSHIP. */ + private function dropAttributeForRecreate( + UtopiaDocument $database, + UtopiaDocument $table, + Column|Attribute $resource, + UtopiaDatabase $dbForDatabases, + UtopiaDocument $existingAttr, + ): void { + $collectionId = $this->tableCollectionId($database, $table); + $attributeMetaId = $this->attributeIndexMetaId($database, $table, $resource->getKey()); + $isRelationship = $resource->getType() === Column::TYPE_RELATIONSHIP; + + if ($isRelationship) { + $dbForDatabases->deleteRelationship($collectionId, $resource->getKey()); + } else { + $dbForDatabases->deleteAttribute($collectionId, $resource->getKey()); + } + + $this->dbForProject->deleteDocument(self::META_ATTRIBUTES, $attributeMetaId); + + // Use dest's options for partner lookup — drop fires when relatedCollection/twoWayKey differ, so source points to the NEW partner. + if ($isRelationship) { + $partner = $this->resolveTwoWayPartner($database, (array) $existingAttr->getAttribute('options', [])); + if ($partner !== null) { + $this->bestEffort(fn () => $this->dbForProject->deleteDocument(self::META_ATTRIBUTES, $partner['partnerMetaId'])); + } + } + + $this->purgeTableCaches($database, $table, $dbForDatabases); + } + + /** Returns false when the source change isn't SDK-expressible — caller falls through to drop+recreate. */ + private function updateAttributeInPlace( + UtopiaDocument $database, + UtopiaDocument $table, + Column|Attribute $resource, + string $type, + string $updatedAt, + UtopiaDocument $existingAttr, + UtopiaDatabase $dbForDatabases, + ): bool { + $sourceFields = [ + 'type' => $type, + 'array' => $resource->isArray(), + 'signed' => $resource->isSigned(), + 'format' => $resource->getFormat(), + 'formatOptions' => $resource->getFormatOptions(), + 'filters' => $resource->getFilters(), + ]; + + $existingFields = []; + foreach (self::ATTRIBUTE_IMMUTABLE_FIELDS as $field) { + $existingFields[$field] = $existingAttr->getAttribute($field); + } + + if ($this->arraysDifferOnKeys($sourceFields, $existingFields, self::ATTRIBUTE_IMMUTABLE_FIELDS)) { + return false; + } + + // Pass existing values for non-SDK fields so utopia doesn't trigger an ALTER for unchanged fields. + $dbForDatabases->updateAttribute( + collection: $this->tableCollectionId($database, $table), + id: $resource->getKey(), + type: $type, + size: $resource->getSize(), + required: $resource->isRequired(), + default: $resource->getDefault(), + signed: $existingAttr->getAttribute('signed'), + array: $existingAttr->getAttribute('array'), + format: $resource->getFormat(), + formatOptions: $resource->getFormatOptions(), + filters: $existingAttr->getAttribute('filters'), + ); + + $this->dbForProject->updateDocument(self::META_ATTRIBUTES, $existingAttr->getId(), new UtopiaDocument([ + 'key' => $resource->getKey(), + 'type' => $type, + 'size' => $resource->getSize(), + 'required' => $resource->isRequired(), + 'signed' => $resource->isSigned(), + 'default' => $resource->getDefault(), + 'array' => $resource->isArray(), + 'format' => $resource->getFormat(), + 'formatOptions' => $resource->getFormatOptions(), + 'filters' => $resource->getFilters(), + '$updatedAt' => $updatedAt, + ])); + + $this->purgeTableCaches($database, $table, $dbForDatabases); + return true; + } + + /** + * Returns false when the source change isn't SDK-expressible — caller falls through to drop+recreate. + * One-way + onDelete change is also rejected: utopia's updateRelationship partner-cascade throws on one-way. + */ + private function updateRelationshipInPlace( + UtopiaDocument $database, + UtopiaDocument $table, + Column|Attribute $resource, + string $type, + string $updatedAt, + UtopiaDocument $existingAttr, + UtopiaDatabase $dbForDatabases, + ): bool { + $sourceOptions = $resource->getOptions(); + $destOptions = $existingAttr->getAttribute('options', []); + + if ($this->arraysDifferOnKeys($sourceOptions, $destOptions, self::RELATIONSHIP_IMMUTABLE_FIELDS)) { + return false; + } + + $isTwoWay = (bool) ($destOptions['twoWay'] ?? false); + $onDeleteChanged = ($sourceOptions['onDelete'] ?? null) !== ($destOptions['onDelete'] ?? null); + + if (!$isTwoWay && $onDeleteChanged) { + return false; + } + + if ($onDeleteChanged) { + $dbForDatabases->updateRelationship( + collection: $this->tableCollectionId($database, $table), + id: $resource->getKey(), + onDelete: (string) ($sourceOptions['onDelete'] ?? ''), + ); + } + + $this->dbForProject->updateDocument(self::META_ATTRIBUTES, $existingAttr->getId(), new UtopiaDocument([ + 'key' => $resource->getKey(), + 'type' => $type, + 'options' => array_merge($destOptions, [ + 'onDelete' => $sourceOptions['onDelete'] ?? $destOptions['onDelete'] ?? null, + ]), + '$updatedAt' => $updatedAt, + ])); + + $this->purgeTableCaches($database, $table, $dbForDatabases); + + // utopia syncs both physical sides; partner's Appwrite-level meta doc has to be refreshed by hand. + if ($isTwoWay) { + $this->refreshTwoWayPartnerOnDelete($database, $destOptions, $sourceOptions, $updatedAt, $dbForDatabases); + } + + return true; + } + + /** + * @param array $destOptions + * @param array $sourceOptions + */ + private function refreshTwoWayPartnerOnDelete( + UtopiaDocument $database, + array $destOptions, + array $sourceOptions, + string $updatedAt, + UtopiaDatabase $dbForDatabases, + ): void { + $partner = $this->resolveTwoWayPartner($database, $destOptions); + if ($partner === null) { + return; + } + + $partnerMeta = $this->dbForProject->getDocument(self::META_ATTRIBUTES, $partner['partnerMetaId']); + if ($partnerMeta->isEmpty()) { + return; + } + + $partnerOptions = $partnerMeta->getAttribute('options', []); + $this->dbForProject->updateDocument(self::META_ATTRIBUTES, $partnerMeta->getId(), new UtopiaDocument([ + 'options' => array_merge($partnerOptions, [ + 'onDelete' => $sourceOptions['onDelete'] ?? $partnerOptions['onDelete'] ?? null, + ]), + '$updatedAt' => $updatedAt, + ])); + $this->purgeTableCaches($database, $partner['relatedTable'], $dbForDatabases); + } + + private function databaseSpecMatches(UtopiaDocument $existing, Database $resource): bool + { + $sourceType = empty($resource->getType()) ? 'legacy' : $resource->getType(); + $sourceOriginalId = empty($resource->getOriginalId()) ? null : $resource->getOriginalId(); + + return $existing->getAttribute('name') === $resource->getDatabaseName() + && $existing->getAttribute('enabled') === $resource->getEnabled() + && $existing->getAttribute('type') === $sourceType + && $existing->getAttribute('originalId') === $sourceOriginalId + && $existing->getAttribute('database') === $resource->getDatabase(); + } + + private function tableSpecMatches(UtopiaDocument $existing, Table $resource): bool + { + if ($existing->getAttribute('name') !== $resource->getTableName() + || $existing->getAttribute('enabled') !== $resource->getEnabled() + || $existing->getAttribute('documentSecurity') !== $resource->getRowSecurity()) { + return false; + } + + $sourcePerms = Permission::aggregate($resource->getPermissions()); + /** @var list $destPerms */ + $destPerms = $existing->getAttribute('$permissions', []); + \sort($sourcePerms); + \sort($destPerms); + return $sourcePerms === $destPerms; + } + + /** Full-spec equality: short-circuits Overwrite to Skip when nothing changed. */ + private function attributeSpecMatches(UtopiaDocument $existing, Column|Attribute $resource, string $type, bool $isRelationship): bool + { + if ($existing->getAttribute('type') !== $type) { + return false; + } + if ($isRelationship) { + $sourceOptions = $resource->getOptions(); + /** @var array $destOptions */ + $destOptions = $existing->getAttribute('options', []); + foreach (self::RELATIONSHIP_IMMUTABLE_FIELDS as $field) { + if (!$this->valuesMatch($sourceOptions[$field] ?? null, $destOptions[$field] ?? null)) { + return false; + } + } + return $this->valuesMatch($sourceOptions['onDelete'] ?? null, $destOptions['onDelete'] ?? null); + } + + return $existing->getAttribute('size') === $resource->getSize() + && $existing->getAttribute('required') === $resource->isRequired() + && $existing->getAttribute('default') === $resource->getDefault() + && $existing->getAttribute('array') === $resource->isArray() + && $existing->getAttribute('signed') === $resource->isSigned() + && $existing->getAttribute('format') === $resource->getFormat() + && $this->valuesMatch($existing->getAttribute('formatOptions'), $resource->getFormatOptions()) + && $existing->getAttribute('filters') === $resource->getFilters(); + } + + /** + * `lengths` is intentionally not compared: it's derived per-column from + * the adapter's index validator and not settable on the Index resource. + */ + private function indexSpecMatches(UtopiaDocument $existingIdx, Index $resource): bool + { + return $existingIdx->getAttribute('type') === $resource->getType() + && $existingIdx->getAttribute('attributes') === $resource->getColumns() + && $existingIdx->getAttribute('orders') === $resource->getOrders(); + } + + private function tableIdentity(UtopiaDocument $database, UtopiaDocument $table): string + { + return $database->getSequence() . ':' . $table->getSequence(); + } + + /** + * @param array $options + * @return array{relatedTable: UtopiaDocument, partnerKey: string, partnerMetaId: string}|null + */ + private function resolveTwoWayPartner(UtopiaDocument $database, array $options): ?array + { + if (empty($options['twoWay'])) { + return null; + } + $relatedTableId = (string) ($options['relatedCollection'] ?? ''); + $partnerKey = (string) ($options['twoWayKey'] ?? ''); + if ($relatedTableId === '' || $partnerKey === '') { + return null; + } + $relatedTable = $this->dbForProject->getDocument( + $this->databaseCollectionId($database), + $relatedTableId, + ); + if ($relatedTable->isEmpty()) { + return null; + } + return [ + 'relatedTable' => $relatedTable, + 'partnerKey' => $partnerKey, + 'partnerMetaId' => $this->attributeIndexMetaId($database, $relatedTable, $partnerKey), + ]; + } + + /** Canonical pair-key — same string regardless of which side is being processed. */ + private function twoWayPairKey( + UtopiaDocument $database, + UtopiaDocument $table, + Column|Attribute $resource, + string $type, + ): ?string { + if ($type !== UtopiaDatabase::VAR_RELATIONSHIP) { + return null; + } + $options = $resource->getOptions(); + if (empty($options['twoWay'])) { + return null; + } + $twoWayKey = (string) ($options['twoWayKey'] ?? ''); + $relatedTableId = (string) ($options['relatedCollection'] ?? ''); + if ($twoWayKey === '' || $relatedTableId === '') { + return null; + } + + $thisSide = $table->getId() . '::' . $resource->getKey(); + $partnerSide = $relatedTableId . '::' . $twoWayKey; + $pair = [$thisSide, $partnerSide]; + \sort($pair); + return $database->getSequence() . '@' . \implode('<->', $pair); + } + + private function databaseCollectionId(UtopiaDocument $database): string + { + return 'database_' . $database->getSequence(); + } + + private function tableCollectionId(UtopiaDocument $database, UtopiaDocument $table): string + { + return $this->databaseCollectionId($database) . '_collection_' . $table->getSequence(); + } + + private function attributeIndexMetaId(UtopiaDocument $database, UtopiaDocument $table, string $key): string + { + return $database->getSequence() . '_' . $table->getSequence() . '_' . $key; + } + + /** Stale platform/per-database cache shows the pre-change schema; evict after every structural change. */ + private function purgeTableCaches( + UtopiaDocument $database, + UtopiaDocument $table, + UtopiaDatabase $dbForDatabases, + ): void { + $this->dbForProject->purgeCachedDocument($this->databaseCollectionId($database), $table->getId()); + $dbForDatabases->purgeCachedCollection($this->tableCollectionId($database, $table)); + } + + /** + * @param array $a + * @param array $b + * @param list $keys + */ + private function arraysDifferOnKeys(array $a, array $b, array $keys): bool + { + foreach ($keys as $key) { + if (!$this->valuesMatch($a[$key] ?? null, $b[$key] ?? null)) { + return true; + } + } + return false; + } + + /** + * `===` on associative arrays is order-sensitive on keys; ksort both sides + * before comparing so {min, max} matches {max, min}. Lists (numeric keys) + * are left alone — order is semantically meaningful for filters/columns. + */ + private function valuesMatch(mixed $a, mixed $b): bool + { + if (\is_array($a) && \is_array($b) && !\array_is_list($a) && !\array_is_list($b)) { + \ksort($a); + \ksort($b); + } + return $a === $b; + } + + /** $kind is 'attributeKeys' or 'indexKeys'. */ + private function trackOrphanCandidate( + UtopiaDocument $database, + UtopiaDocument $table, + string $kind, + string $key, + UtopiaDatabase $dbForDatabases, + ): void { + if ($this->onDuplicate !== OnDuplicate::Overwrite) { + return; + } + $tableId = $this->tableIdentity($database, $table); + if (!isset($this->orphansByTable[$tableId])) { + $this->orphansByTable[$tableId] = [ + 'database' => $database, + 'table' => $table, + 'dbForDatabases' => $dbForDatabases, + 'attributeKeys' => [], + 'indexKeys' => [], + ]; + } + $this->orphansByTable[$tableId][$kind][] = $key; + } + + /** End-of-migration sweep — only visits tables that had no rows (rest were cleaned per-table in createRecord). */ + private function cleanupOverwriteOrphans(): void + { + foreach (\array_keys($this->orphansByTable) as $tableId) { + $this->cleanupOverwriteOrphansForTable($tableId); + } + } + + /** Called per-table from createRecord before rows land so Structure validator sees the post-cleanup schema. */ + private function cleanupOverwriteOrphansForTable(string $tableId): void + { + if ($this->onDuplicate !== OnDuplicate::Overwrite) { + return; + } + if (!isset($this->orphansByTable[$tableId])) { + return; + } + + $tracked = $this->orphansByTable[$tableId]; + $database = $tracked['database']; + $table = $tracked['table']; + $dbForDatabases = $tracked['dbForDatabases']; + + $this->dropOrphansByKind( + self::META_ATTRIBUTES, + $tracked['attributeKeys'], + $database, + $table, + fn (UtopiaDocument $doc) => $this->dropOrphanAttribute($database, $table, $doc, $dbForDatabases), + ); + + $this->dropOrphansByKind( + self::META_INDEXES, + $tracked['indexKeys'], + $database, + $table, + fn (UtopiaDocument $doc) => $this->dropOrphanIndex( + $database, + $table, + (string) $doc->getAttribute('key'), + $dbForDatabases, + ), + ); + + unset($this->orphansByTable[$tableId]); + } + + /** + * @param list $processedKeys + * @param callable(UtopiaDocument): void $drop + */ + private function dropOrphansByKind( + string $metaCollection, + array $processedKeys, + UtopiaDocument $database, + UtopiaDocument $table, + callable $drop, + ): void { + $destDocs = $this->dbForProject->find($metaCollection, [ + Query::equal('databaseInternalId', [$database->getSequence()]), + Query::equal('collectionInternalId', [$table->getSequence()]), + Query::limit(PHP_INT_MAX), + ]); + foreach ($destDocs as $destDoc) { + if (!\in_array($destDoc->getAttribute('key'), $processedKeys, true)) { + $drop($destDoc); + } + } + } + + /** Reads dest's own meta doc as source of truth — there's no source resource for an orphan. */ + private function dropOrphanAttribute( + UtopiaDocument $database, + UtopiaDocument $table, + UtopiaDocument $attrDoc, + UtopiaDatabase $dbForDatabases, + ): void { + $key = (string) $attrDoc->getAttribute('key'); + $type = (string) $attrDoc->getAttribute('type'); + $options = $attrDoc->getAttribute('options', []); + $collectionId = $this->tableCollectionId($database, $table); + + if ($type === UtopiaDatabase::VAR_RELATIONSHIP) { + $this->bestEffort(fn () => $dbForDatabases->deleteRelationship($collectionId, $key)); + } else { + $this->bestEffort(fn () => $dbForDatabases->deleteAttribute($collectionId, $key)); + } + $this->bestEffort(fn () => $this->dbForProject->deleteDocument(self::META_ATTRIBUTES, $attrDoc->getId())); + $this->dbForProject->purgeCachedDocument($this->databaseCollectionId($database), $table->getId()); + $dbForDatabases->purgeCachedCollection($collectionId); + + if ($type !== UtopiaDatabase::VAR_RELATIONSHIP) { + return; + } + $partner = $this->resolveTwoWayPartner($database, $options); + if ($partner === null) { + return; + } + + // deleteRelationship already dropped the partner physical column; only the Appwrite-level meta doc remains. + $this->bestEffort(fn () => $this->dbForProject->deleteDocument(self::META_ATTRIBUTES, $partner['partnerMetaId'])); + $this->purgeTableCaches($database, $partner['relatedTable'], $dbForDatabases); + } + + private function dropOrphanIndex( + UtopiaDocument $database, + UtopiaDocument $table, + string $indexKey, + UtopiaDatabase $dbForDatabases, + ): void { + $collectionId = $this->tableCollectionId($database, $table); + $indexMetaId = $this->attributeIndexMetaId($database, $table, $indexKey); + + $this->bestEffort(fn () => $dbForDatabases->deleteIndex($collectionId, $indexKey)); + $this->bestEffort(fn () => $this->dbForProject->deleteDocument(self::META_INDEXES, $indexMetaId)); + $this->dbForProject->purgeCachedDocument($this->databaseCollectionId($database), $table->getId()); + } + + /** Swallows deletion errors — a prior run or relationship cascade may have already removed the target. */ + private function bestEffort(callable $fn): void + { + try { + $fn(); + } catch (\Throwable) { + // already gone + } + } + /** * @throws \Exception */ @@ -1129,6 +1898,7 @@ class Appwrite extends Destination 'none' => Compression::NONE(), 'gzip' => Compression::GZIP(), 'zstd' => Compression::ZSTD(), + // no break default => throw new \Exception('Invalid Compression: ' . $resource->getCompression(), Exception::CODE_VALIDATION), }; @@ -1452,6 +2222,7 @@ class Appwrite extends Destination 'bun-1.0' => Runtime::BUN10(), 'bun-1.1' => Runtime::BUN11(), 'go-1.23' => Runtime::GO123(), + // no break default => throw new \Exception('Invalid Runtime: ' . $resource->getRuntime(), Exception::CODE_VALIDATION), }; @@ -1489,6 +2260,13 @@ class Appwrite extends Destination return $resource; } + public function importBackupResource(Resource $resource): Resource + { + $resource->setStatus(Resource::STATUS_SKIPPED); + + return $resource; + } + /** * @throws AppwriteException * @throws \Exception @@ -1671,6 +2449,7 @@ class Appwrite extends Destination 'flutter-3.29' => BuildRuntime::FLUTTER329(), 'flutter-3.32' => BuildRuntime::FLUTTER332(), 'flutter-3.35' => BuildRuntime::FLUTTER335(), + // no break default => throw new \Exception('Invalid Build Runtime: ' . $resource->getBuildRuntime(), Exception::CODE_VALIDATION), }; diff --git a/src/Migration/Destinations/JSON.php b/src/Migration/Destinations/JSON.php index 91016ef589..6660ab5a06 100644 --- a/src/Migration/Destinations/JSON.php +++ b/src/Migration/Destinations/JSON.php @@ -316,5 +316,4 @@ class JSON extends Destination return $this->convertValueToJSON($item); }, $value); } - } diff --git a/src/Migration/Destinations/OnDuplicate.php b/src/Migration/Destinations/OnDuplicate.php new file mode 100644 index 0000000000..a88ebf8033 --- /dev/null +++ b/src/Migration/Destinations/OnDuplicate.php @@ -0,0 +1,70 @@ + + */ + public static function values(): array + { + return \array_values(\array_map(fn (self $case) => $case->value, self::cases())); + } + + /** + * Coarse routing for re-migration. The caller follows up with a spec-match + * check that overrides Overwrite to Skip when source and dest + * already have identical spec — see DestinationAppwrite for the full flow. + */ + public function resolveSchemaAction( + bool $exists, + ?string $sourceUpdatedAt = null, + ?string $destUpdatedAt = null, + ): SchemaAction { + if (!$exists) { + return SchemaAction::Create; + } + return match ($this) { + self::Fail => SchemaAction::Create, + self::Skip => SchemaAction::Skip, + self::Overwrite => $this->sourceIsNewer($sourceUpdatedAt, $destUpdatedAt) + ? SchemaAction::Overwrite + : SchemaAction::Skip, + }; + } + + private function sourceIsNewer(?string $source, ?string $dest): bool + { + $src = $this->parseTimestamp($source); + $dst = $this->parseTimestamp($dest); + return $src !== null && $dst !== null && $src > $dst; + } + + /** + * strtotime accepts '0000-00-00' leniently (returns a large negative epoch, + * not false), so non-positive epochs are rejected too. + */ + private function parseTimestamp(?string $value): ?int + { + if ($value === null || $value === '') { + return null; + } + $epoch = \strtotime($value); + if ($epoch === false || $epoch <= 0) { + return null; + } + return $epoch; + } +} diff --git a/src/Migration/Resource.php b/src/Migration/Resource.php index 1dc198c6ca..2fc102c553 100644 --- a/src/Migration/Resource.php +++ b/src/Migration/Resource.php @@ -75,6 +75,9 @@ abstract class Resource implements \JsonSerializable public const TYPE_MESSAGE = 'message'; + // Backups + public const TYPE_BACKUP_POLICY = 'backup-policy'; + // legacy terminologies public const TYPE_DOCUMENT = 'document'; public const TYPE_ATTRIBUTE = 'attribute'; @@ -110,6 +113,7 @@ abstract class Resource implements \JsonSerializable self::TYPE_TOPIC, self::TYPE_SUBSCRIBER, self::TYPE_MESSAGE, + self::TYPE_BACKUP_POLICY, // legacy self::TYPE_DOCUMENT, diff --git a/src/Migration/Resources/Backups/Policy.php b/src/Migration/Resources/Backups/Policy.php new file mode 100644 index 0000000000..d5358b4287 --- /dev/null +++ b/src/Migration/Resources/Backups/Policy.php @@ -0,0 +1,115 @@ + $services + * @param int $retention + * @param string $schedule + * @param bool $enabled + * @param string $resourceId + * @param string $resourceType + */ + public function __construct( + string $id = '', + private readonly string $name = '', + private readonly array $services = [], + private readonly int $retention = 0, + private readonly string $schedule = '', + private readonly bool $enabled = true, + private readonly string $resourceId = '', + private readonly string $resourceType = '', + ) { + $this->id = $id; + } + + /** + * @param array $array + * @return self + */ + public static function fromArray(array $array): self + { + return new self( + $array['id'], + $array['name'] ?? '', + $array['services'] ?? [], + $array['retention'] ?? 0, + $array['schedule'] ?? '', + $array['enabled'] ?? true, + $array['resourceId'] ?? '', + $array['resourceType'] ?? '', + ); + } + + /** + * @return array + */ + public function jsonSerialize(): array + { + return [ + 'id' => $this->id, + 'name' => $this->name, + 'services' => $this->services, + 'retention' => $this->retention, + 'schedule' => $this->schedule, + 'enabled' => $this->enabled, + 'resourceId' => $this->resourceId, + 'resourceType' => $this->resourceType, + ]; + } + + public static function getName(): string + { + return Resource::TYPE_BACKUP_POLICY; + } + + public function getGroup(): string + { + return Transfer::GROUP_BACKUPS; + } + + public function getPolicyName(): string + { + return $this->name; + } + + /** + * @return array + */ + public function getServices(): array + { + return $this->services; + } + + public function getRetention(): int + { + return $this->retention; + } + + public function getSchedule(): string + { + return $this->schedule; + } + + public function getEnabled(): bool + { + return $this->enabled; + } + + public function getResourceId(): string + { + return $this->resourceId; + } + + public function getResourceType(): string + { + return $this->resourceType; + } +} diff --git a/src/Migration/Resources/Database/Table.php b/src/Migration/Resources/Database/Table.php index 889d90fe1f..0ba04a5cda 100644 --- a/src/Migration/Resources/Database/Table.php +++ b/src/Migration/Resources/Database/Table.php @@ -53,7 +53,7 @@ class Table extends Resource Database::fromArray($array['database']), name: $array['name'], id: $array['id'], - rowSecurity: $array['rowSecurity'] ?? $array['documentSecurity'], + rowSecurity: (bool) ($array['rowSecurity'] ?? $array['documentSecurity'] ?? false), permissions: $array['permissions'] ?? [], createdAt: $array['createdAt'] ?? '', updatedAt: $array['updatedAt'] ?? '', diff --git a/src/Migration/Resources/Sites/EnvVar.php b/src/Migration/Resources/Sites/EnvVar.php index 78fce7e18b..a2300f3030 100644 --- a/src/Migration/Resources/Sites/EnvVar.php +++ b/src/Migration/Resources/Sites/EnvVar.php @@ -67,5 +67,4 @@ class EnvVar extends Resource { return $this->value; } - } diff --git a/src/Migration/Source.php b/src/Migration/Source.php index b6eb8c429d..cd38ebbd4c 100644 --- a/src/Migration/Source.php +++ b/src/Migration/Source.php @@ -46,6 +46,11 @@ abstract class Source extends Target return static::$defaultBatchSize; } + public function getBackupsBatchSize(): int + { + return static::$defaultBatchSize; + } + /** * @param array $resources * @return void @@ -109,6 +114,7 @@ abstract class Source extends Target Transfer::GROUP_FUNCTIONS => Transfer::GROUP_FUNCTIONS_RESOURCES, Transfer::GROUP_MESSAGING => Transfer::GROUP_MESSAGING_RESOURCES, Transfer::GROUP_SITES => Transfer::GROUP_SITES_RESOURCES, + Transfer::GROUP_BACKUPS => Transfer::GROUP_BACKUPS_RESOURCES, ]; foreach ($mapping as $group => $resources) { @@ -143,6 +149,9 @@ abstract class Source extends Target case Transfer::GROUP_SITES: $this->exportGroupSites($this->getSitesBatchSize(), $resources); break; + case Transfer::GROUP_BACKUPS: + $this->exportGroupBackups($this->getBackupsBatchSize(), $resources); + break; } } } @@ -194,4 +203,12 @@ abstract class Source extends Target * @param array $resources Resources to export */ abstract protected function exportGroupSites(int $batchSize, array $resources): void; + + /** + * Export Backups Group + * + * @param int $batchSize + * @param array $resources Resources to export + */ + abstract protected function exportGroupBackups(int $batchSize, array $resources): void; } diff --git a/src/Migration/Sources/Appwrite.php b/src/Migration/Sources/Appwrite.php index db59cc9dd7..2c0b8db134 100644 --- a/src/Migration/Sources/Appwrite.php +++ b/src/Migration/Sources/Appwrite.php @@ -5,11 +5,11 @@ namespace Utopia\Migration\Sources; use Appwrite\AppwriteException; use Appwrite\Client; use Appwrite\Query; -use Appwrite\Services\Databases; use Appwrite\Services\Functions; use Appwrite\Services\Messaging; use Appwrite\Services\Sites; use Appwrite\Services\Storage; +use Appwrite\Services\TablesDB; use Appwrite\Services\Teams; use Appwrite\Services\Users; use Utopia\Database\Database as UtopiaDatabase; @@ -128,7 +128,7 @@ class Appwrite extends Source switch ($this->source) { case static::SOURCE_API: - $this->reader = new APIReader(new Databases($this->client)); + $this->reader = new APIReader(new TablesDB($this->client)); break; case static::SOURCE_DATABASE: @@ -145,7 +145,6 @@ class Appwrite extends Source default: throw new \Exception('Unknown source', Exception::CODE_VALIDATION); } - } public static function getName(): string @@ -201,6 +200,9 @@ class Appwrite extends Source Resource::TYPE_SITE_DEPLOYMENT, Resource::TYPE_SITE_VARIABLE, + // Backups + Resource::TYPE_BACKUP_POLICY, + // Settings ]; } @@ -240,6 +242,7 @@ class Appwrite extends Source $this->reportFunctions($resources, $report, $resourceIds); $this->reportMessaging($resources, $report, $resourceIds); $this->reportSites($resources, $report, $resourceIds); + $this->reportBackups($resources, $report, $resourceIds); $report['version'] = $this->call( 'GET', @@ -355,7 +358,6 @@ class Appwrite extends Source */ private function reportStorage(array $resources, array &$report, array $resourceIds = []): void { - if (\in_array(Resource::TYPE_BUCKET, $resources)) { $bucketQueries = $this->buildQueries( resourceType: Resource::TYPE_BUCKET, @@ -870,7 +872,6 @@ class Appwrite extends Source 'enabled' => $database['enabled'] ?? true, ]); $databases[] = $newDatabase; - } } @@ -929,10 +930,12 @@ class Appwrite extends Source $response = $this->reader->listTables($database, $queries); foreach ($response as $table) { + $rowSecurity = $table['rowSecurity'] ?? $table['documentSecurity'] ?? false; $newTable = self::getEntity($databaseName, [ 'id' => $table['$id'], 'name' => $table['name'], - 'documentSecurity' => $table['documentSecurity'], + 'rowSecurity' => $rowSecurity, + 'documentSecurity' => $rowSecurity, 'permissions' => $table['$permissions'], 'createdAt' => $table['$createdAt'], 'updatedAt' => $table['$updatedAt'], @@ -996,7 +999,7 @@ class Appwrite extends Source } /** @var Table $table */ - $col = match($table->getDatabase()->getType()) { + $col = match ($table->getDatabase()->getType()) { Resource::TYPE_DATABASE_VECTORSDB => self::getColumn($table, $column)->getAttribute(), default => self::getColumn($table, $column), }; @@ -1154,10 +1157,11 @@ class Appwrite extends Source unset($row['$id']); unset($row['$permissions']); - unset($row['$collectionId']); unset($row['$databaseId']); unset($row['$sequence']); unset($row['$collection']); + unset($row['$tableId']); + unset($row['$table']); $row = self::getRecord($table->getDatabase()->getType(), [ 'id' => $id, @@ -1422,6 +1426,18 @@ class Appwrite extends Source } } + protected function exportGroupBackups(int $batchSize, array $resources): void + { + // No-op: backup policies are Cloud-only + } + + protected function reportBackups(array $resources, array &$report, array $resourceIds = []): void + { + if (\in_array(Resource::TYPE_BACKUP_POLICY, $resources)) { + $report[Resource::TYPE_BACKUP_POLICY] = 0; + } + } + /** * @throws AppwriteException */ @@ -2509,7 +2525,6 @@ class Appwrite extends Source default => throw new \InvalidArgumentException("Unsupported column type: {$column['type']}"), }; - } /** diff --git a/src/Migration/Sources/Appwrite/Reader.php b/src/Migration/Sources/Appwrite/Reader.php index d7a18027a3..fb6efd98d4 100644 --- a/src/Migration/Sources/Appwrite/Reader.php +++ b/src/Migration/Sources/Appwrite/Reader.php @@ -108,5 +108,4 @@ interface Reader */ public function queryLimit(int $limit): mixed; public function getSupportForAttributes(): bool; - } diff --git a/src/Migration/Sources/Appwrite/Reader/API.php b/src/Migration/Sources/Appwrite/Reader/API.php index b42835bd70..47a52f9dc6 100644 --- a/src/Migration/Sources/Appwrite/Reader/API.php +++ b/src/Migration/Sources/Appwrite/Reader/API.php @@ -4,8 +4,7 @@ namespace Utopia\Migration\Sources\Appwrite\Reader; use Appwrite\AppwriteException; use Appwrite\Query; -use Appwrite\Services\Databases; -/* use Appwrite\Services\Tables; */ +use Appwrite\Services\TablesDB; use Utopia\Migration\Resource; use Utopia\Migration\Resources\Database\Database; use Utopia\Migration\Resources\Database\Table; @@ -17,8 +16,7 @@ use Utopia\Migration\Sources\Appwrite\Reader; class API implements Reader { public function __construct( - private readonly Databases $database, - /* private readonly Tables $table, */ + private readonly TablesDB $database, ) { } @@ -73,13 +71,12 @@ class API implements Reader $lastTable = null; while (true) { - /* $currentTables = $this->tables->list(...); */ - $currentTables = $this->database->listCollections( + $currentTables = $this->database->listTables( $databaseId, $lastTable ? [Query::cursorAfter($lastTable)] : [Query::limit($pageLimit)] - )['collections']; /* ['tables'] */ + )['tables']; $tables = \array_merge($tables, $currentTables); $lastTable = $tables[count($tables) - 1]['$id'] ?? null; @@ -108,8 +105,7 @@ class API implements Reader } if (Resource::isSupported(Resource::TYPE_ROW, $resources)) { - /* $rowsResponse = $this->tables->listRows(...) */ - $rowsResponse = $this->database->listDocuments( + $rowsResponse = $this->database->listRows( $databaseId, $tableId, [Query::limit(1)] @@ -137,11 +133,10 @@ class API implements Reader */ public function listTables(Database $resource, array $queries = []): array { - /* $this->tables->list(...)['tables'] */ - return $this->database->listCollections( + return $this->database->listTables( $resource->getId(), $queries - )['collections']; + )['tables']; } /** @@ -152,12 +147,11 @@ class API implements Reader */ public function listColumns(Table $resource, array $queries = []): array { - /* $this->tables->listColumns(...)['columns'] */ - return $this->database->listAttributes( + return $this->database->listColumns( $resource->getDatabase()->getId(), $resource->getId(), $queries - )['attributes']; + )['columns']; } /** @@ -168,7 +162,6 @@ class API implements Reader */ public function listIndexes(Table $resource, array $queries = []): array { - /* $this->tables->listIndexes(...)['indexes'] */ return $this->database->listIndexes( $resource->getDatabase()->getId(), $resource->getId(), @@ -185,12 +178,11 @@ class API implements Reader */ public function listRows(Table $resource, array $queries = []): array { - /* $this->tables->listRows(...)['rows'] */ - return $this->database->listDocuments( + return $this->database->listRows( $resource->getDatabase()->getId(), $resource->getId(), $queries - )['documents']; + )['rows']; } /** @@ -202,8 +194,7 @@ class API implements Reader */ public function getRow(Table $resource, string $rowId, array $queries = []): array { - /* $this->tables->getRow(...) */ - return $this->database->getDocument( + return $this->database->getRow( $resource->getDatabase()->getId(), $resource->getId(), $rowId, diff --git a/src/Migration/Sources/CSV.php b/src/Migration/Sources/CSV.php index 9b580df2d0..762ed2fb00 100644 --- a/src/Migration/Sources/CSV.php +++ b/src/Migration/Sources/CSV.php @@ -430,6 +430,11 @@ class CSV extends Source throw new \Exception('Not Implemented'); } + protected function exportGroupBackups(int $batchSize, array $resources): void + { + throw new \Exception('Not Implemented'); + } + /** * @param callable(resource $stream, string $delimiter): void $callback * @return void diff --git a/src/Migration/Sources/Firebase.php b/src/Migration/Sources/Firebase.php index 4495fb5ba1..f01b772901 100644 --- a/src/Migration/Sources/Firebase.php +++ b/src/Migration/Sources/Firebase.php @@ -667,7 +667,6 @@ class Firebase extends Source previous: $e )); } - } private function exportBuckets(int $batchsize): void @@ -818,4 +817,9 @@ class Firebase extends Source { throw new \Exception('Not implemented'); } + + protected function exportGroupBackups(int $batchSize, array $resources): void + { + throw new \Exception('Not implemented'); + } } diff --git a/src/Migration/Sources/JSON.php b/src/Migration/Sources/JSON.php index 15e7b6aa3c..8f2a81ae39 100644 --- a/src/Migration/Sources/JSON.php +++ b/src/Migration/Sources/JSON.php @@ -209,6 +209,11 @@ class JSON extends Source throw new \Exception('Not Implemented'); } + protected function exportGroupBackups(int $batchSize, array $resources): void + { + throw new \Exception('Not Implemented'); + } + /** * @throws \Exception */ diff --git a/src/Migration/Sources/NHost.php b/src/Migration/Sources/NHost.php index ada1afb5ff..1a8d70cbae 100644 --- a/src/Migration/Sources/NHost.php +++ b/src/Migration/Sources/NHost.php @@ -952,4 +952,9 @@ class NHost extends Source { throw new \Exception('Not Implemented'); } + + protected function exportGroupBackups(int $batchSize, array $resources): void + { + throw new \Exception('Not Implemented'); + } } diff --git a/src/Migration/Target.php b/src/Migration/Target.php index 8dbc5a87f2..777609f22a 100644 --- a/src/Migration/Target.php +++ b/src/Migration/Target.php @@ -150,7 +150,6 @@ abstract class Target throw new \Exception(\curl_error($ch), Exception::CODE_INTERNAL); } - \curl_close($ch); if ($responseStatus >= 400) { if (\is_array($responseBody)) { diff --git a/src/Migration/Transfer.php b/src/Migration/Transfer.php index 561ff28330..e8c5ee5d10 100644 --- a/src/Migration/Transfer.php +++ b/src/Migration/Transfer.php @@ -26,6 +26,8 @@ class Transfer public const GROUP_MESSAGING = 'messaging'; + public const GROUP_BACKUPS = 'backups'; + public const GROUP_AUTH_RESOURCES = [ Resource::TYPE_USER, Resource::TYPE_TEAM, @@ -88,6 +90,10 @@ class Transfer public const GROUP_SETTINGS_RESOURCES = []; + public const GROUP_BACKUPS_RESOURCES = [ + Resource::TYPE_BACKUP_POLICY, + ]; + public const GROUP_MESSAGING_RESOURCES = [ Resource::TYPE_PROVIDER, Resource::TYPE_TOPIC, @@ -116,6 +122,7 @@ class Transfer Resource::TYPE_TOPIC, Resource::TYPE_SUBSCRIBER, Resource::TYPE_MESSAGE, + Resource::TYPE_BACKUP_POLICY, // legacy Resource::TYPE_DOCUMENT, @@ -399,6 +406,7 @@ class Transfer self::GROUP_DATABASES_VECTOR_DB => array_merge($resources, self::GROUP_VECTORSDB_RESOURCES), self::GROUP_SETTINGS => array_merge($resources, self::GROUP_SETTINGS_RESOURCES), self::GROUP_MESSAGING => array_merge($resources, self::GROUP_MESSAGING_RESOURCES), + self::GROUP_BACKUPS => array_merge($resources, self::GROUP_BACKUPS_RESOURCES), default => throw new \Exception('No service group found'), }; } diff --git a/tests/Migration/E2E/Sources/Base.php b/tests/Migration/E2E/Sources/Base.php index 7b5bd403e8..9563344e3a 100644 --- a/tests/Migration/E2E/Sources/Base.php +++ b/tests/Migration/E2E/Sources/Base.php @@ -124,7 +124,6 @@ abstract class Base extends TestCase throw new \Exception(curl_error($ch)); } - curl_close($ch); if ($responseStatus >= 400) { if (is_array($responseBody)) { diff --git a/tests/Migration/Unit/Adapters/MockSource.php b/tests/Migration/Unit/Adapters/MockSource.php index 889eeb3c68..d4504c88cf 100644 --- a/tests/Migration/Unit/Adapters/MockSource.php +++ b/tests/Migration/Unit/Adapters/MockSource.php @@ -84,6 +84,7 @@ class MockSource extends Source Resource::TYPE_TOPIC, Resource::TYPE_SUBSCRIBER, Resource::TYPE_MESSAGE, + Resource::TYPE_BACKUP_POLICY, // legacy Resource::TYPE_DOCUMENT, @@ -198,4 +199,15 @@ class MockSource extends Source $this->handleResourceTransfer(Transfer::GROUP_SITES, $resource); } } + + protected function exportGroupBackups(int $batchSize, array $resources): void + { + foreach (Transfer::GROUP_BACKUPS_RESOURCES as $resource) { + if (!\in_array($resource, $resources)) { + continue; + } + + $this->handleResourceTransfer(Transfer::GROUP_BACKUPS, $resource); + } + } } diff --git a/tests/Migration/Unit/Destinations/AppwriteAttributeSdkBoundaryTest.php b/tests/Migration/Unit/Destinations/AppwriteAttributeSdkBoundaryTest.php new file mode 100644 index 0000000000..a079ea61fb --- /dev/null +++ b/tests/Migration/Unit/Destinations/AppwriteAttributeSdkBoundaryTest.php @@ -0,0 +1,96 @@ + + */ + private const PARAM_TO_META_FIELD = [ + 'xdefault' => 'default', + 'min' => null, + 'max' => null, + 'elements' => null, + 'onDelete' => null, + ]; + + public function testSdkExposedFieldsAreNotInNonSdkConstant(): void + { + $sdkExposed = $this->collectSdkExposedMetaFields(); + $nonSdk = $this->readNonSdkConstant(); + + $overlap = \array_intersect($sdkExposed, $nonSdk); + $this->assertSame( + [], + \array_values($overlap), + 'ATTRIBUTE_IMMUTABLE_FIELDS marks these fields as non-SDK, but the appwrite/appwrite ' + . 'SDK exposes them via updateXColumn/updateXAttribute: ' . \implode(', ', $overlap) + . '. Either drop these from ATTRIBUTE_IMMUTABLE_FIELDS or update PARAM_TO_META_FIELD ' + . 'in this test if the SDK param doesn\'t correspond to a top-level meta-doc field.', + ); + } + + /** + * @return list meta-doc field names the SDK can mutate + */ + private function collectSdkExposedMetaFields(): array + { + $fields = []; + foreach ([TablesDB::class, Databases::class] as $service) { + $service = new ReflectionClass($service); + foreach ($service->getMethods(ReflectionMethod::IS_PUBLIC) as $method) { + if (!\preg_match('/^update.+(Column|Attribute)$/', $method->getName())) { + continue; + } + foreach ($method->getParameters() as $param) { + $name = $param->getName(); + if (\in_array($name, self::IGNORED_PARAMS, true)) { + continue; + } + $mapped = \array_key_exists($name, self::PARAM_TO_META_FIELD) + ? self::PARAM_TO_META_FIELD[$name] + : $name; + if ($mapped === null) { + continue; + } + $fields[$mapped] = true; + } + } + } + return \array_keys($fields); + } + + /** + * @return list + */ + private function readNonSdkConstant(): array + { + /** @var list $value */ + $value = (new ReflectionClass(AppwriteDestination::class))->getConstant('ATTRIBUTE_IMMUTABLE_FIELDS'); + return $value; + } +} diff --git a/tests/Migration/Unit/General/OnDuplicateTest.php b/tests/Migration/Unit/General/OnDuplicateTest.php new file mode 100644 index 0000000000..3b7e4b1163 --- /dev/null +++ b/tests/Migration/Unit/General/OnDuplicateTest.php @@ -0,0 +1,155 @@ +assertSame( + SchemaAction::Create, + $mode->resolveSchemaAction(exists: false), + "{$mode->value} on non-existing resource must return Create", + ); + } + } + + public function testFailExistsReturnsCreateSoCallerDDLThrows(): void + { + // Fail is routed through Create (not Skip) so the caller's normal + // create flow runs and the library surfaces DuplicateException as + // designed. Returning Skip here would silently hide the error. + $this->assertSame( + SchemaAction::Create, + OnDuplicate::Fail->resolveSchemaAction(exists: true), + ); + } + + public function testSkipAlwaysSkipsExisting(): void + { + // Skip must ignore updatedAt entirely — it's the "don't touch" contract. + $this->assertSame( + SchemaAction::Skip, + OnDuplicate::Skip->resolveSchemaAction( + exists: true, + sourceUpdatedAt: '2026-01-01T00:00:00.000+00:00', + destUpdatedAt: '2020-01-01T00:00:00.000+00:00', + ), + ); + $this->assertSame( + SchemaAction::Skip, + OnDuplicate::Skip->resolveSchemaAction( + exists: true, + sourceUpdatedAt: '2020-01-01T00:00:00.000+00:00', + destUpdatedAt: '2026-01-01T00:00:00.000+00:00', + ), + ); + } + + public function testOverwriteSourceNewerUpdatesInPlace(): void + { + // Source updatedAt strictly newer than dest → Overwrite. The + // caller (DestinationAppwrite) follows up with attribute/index spec + // checks and falls through to drop+recreate when the SDK can't + // express the change. + $this->assertSame( + SchemaAction::Overwrite, + OnDuplicate::Overwrite->resolveSchemaAction( + exists: true, + sourceUpdatedAt: '2026-04-23T10:00:00.000+00:00', + destUpdatedAt: '2026-04-23T09:59:59.000+00:00', + ), + ); + } + + public function testOverwriteSourceEqualSkips(): void + { + $when = '2026-04-23T10:00:00.000+00:00'; + $this->assertSame( + SchemaAction::Skip, + OnDuplicate::Overwrite->resolveSchemaAction( + exists: true, + sourceUpdatedAt: $when, + destUpdatedAt: $when, + ), + ); + } + + public function testOverwriteSourceOlderSkips(): void + { + // Dest is ahead — don't roll back. Avoids overwriting newer + // destination edits with stale source data. + $this->assertSame( + SchemaAction::Skip, + OnDuplicate::Overwrite->resolveSchemaAction( + exists: true, + sourceUpdatedAt: '2026-04-23T09:00:00.000+00:00', + destUpdatedAt: '2026-04-23T10:00:00.000+00:00', + ), + ); + } + + public function testOverwriteNoTimestampsSkips(): void + { + // No timestamps provided at all → no information to act on. Conservative: + // Skip rather than risk a destructive update on uncertain input. + $this->assertSame( + SchemaAction::Skip, + OnDuplicate::Overwrite->resolveSchemaAction(exists: true), + ); + } + + /** + * @return array + */ + public static function unparseableTimestampPairs(): array + { + return [ + 'both empty' => ['', ''], + 'both null' => [null, null], + 'source empty' => ['', '2026-04-23T10:00:00.000+00:00'], + 'dest empty' => ['2026-04-23T10:00:00.000+00:00', ''], + 'source null' => [null, '2026-04-23T10:00:00.000+00:00'], + 'dest null' => ['2026-04-23T10:00:00.000+00:00', null], + 'source zero-date' => ['0000-00-00 00:00:00', '2026-04-23T10:00:00.000+00:00'], + 'dest zero-date' => ['2026-04-23T10:00:00.000+00:00', '0000-00-00 00:00:00'], + 'source garbage' => ['not-a-date', '2026-04-23T10:00:00.000+00:00'], + 'dest garbage' => ['2026-04-23T10:00:00.000+00:00', 'not-a-date'], + ]; + } + + #[DataProvider('unparseableTimestampPairs')] + public function testOverwriteUnparseableUpdatedAtSkips(?string $source, ?string $dest): void + { + // Conservative: unparseable updatedAt preserves existing destination + // rather than risk a destructive update on garbage input. + $this->assertSame( + SchemaAction::Skip, + OnDuplicate::Overwrite->resolveSchemaAction( + exists: true, + sourceUpdatedAt: $source, + destUpdatedAt: $dest, + ), + ); + } + + public function testValuesListsAllCasesInDeclarationOrder(): void + { + // The values() helper is consumed by API/SDK param validators; this + // protects against an accidental case-rename or reorder. + $this->assertSame(['fail', 'skip', 'overwrite'], OnDuplicate::values()); + } +}