diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index b3dabf856..7b9f672af 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -77,6 +77,7 @@ jobs: Postgres, SQLite, MongoDB, + Mirror, SharedTables/MariaDB, SharedTables/MySQL, SharedTables/Postgres, diff --git a/Dockerfile b/Dockerfile index 728090dd3..405656e47 100755 --- a/Dockerfile +++ b/Dockerfile @@ -1,28 +1,39 @@ FROM composer:2.0 AS composer -ARG TESTING=false -ENV TESTING=$TESTING - WORKDIR /usr/local/src/ COPY composer.lock /usr/local/src/ COPY composer.json /usr/local/src/ -RUN composer install --ignore-platform-reqs --optimize-autoloader \ - --no-plugins --no-scripts --prefer-dist - -FROM php:8.3.3-cli-alpine3.19 AS compile +RUN composer install \ + --ignore-platform-reqs \ + --optimize-autoloader \ + --no-plugins \ + --no-scripts \ + --prefer-dist + +FROM php:8.3.10-cli-alpine3.20 AS compile -ENV PHP_REDIS_VERSION=6.0.2 \ - PHP_SWOOLE_VERSION=v5.1.2 \ - PHP_MONGO_VERSION=1.16.1 \ - PHP_XDEBUG_VERSION=3.3.2 +ENV PHP_REDIS_VERSION="6.0.2" \ + PHP_SWOOLE_VERSION="v5.1.3" \ + PHP_MONGO_VERSION="1.16.1" \ + PHP_XDEBUG_VERSION="3.3.2" RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone RUN \ apk update \ - && apk add --no-cache postgresql-libs postgresql-dev make automake autoconf gcc g++ git brotli-dev linux-headers \ + && apk add --no-cache \ + postgresql-libs \ + postgresql-dev \ + make \ + automake \ + autoconf \ + gcc \ + g++ \ + git \ + brotli-dev \ + linux-headers \ && docker-php-ext-install opcache pgsql pdo_mysql pdo_pgsql \ && apk del postgresql-dev \ && rm -rf /var/cache/apk/* @@ -86,6 +97,7 @@ RUN echo extension=redis.so >> /usr/local/etc/php/conf.d/redis.ini RUN echo extension=swoole.so >> /usr/local/etc/php/conf.d/swoole.ini RUN echo extension=mongodb.so >> /usr/local/etc/php/conf.d/mongodb.ini RUN echo extension=pcov.so >> /usr/local/etc/php/conf.d/pcov.ini +RUN echo extension=xdebug.so >> /usr/local/etc/php/conf.d/xdebug.ini RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini" @@ -100,14 +112,13 @@ COPY --from=mongodb /usr/local/lib/php/extensions/no-debug-non-zts-20230831/mong COPY --from=pcov /usr/local/lib/php/extensions/no-debug-non-zts-20230831/pcov.so /usr/local/lib/php/extensions/no-debug-non-zts-20230831/ COPY --from=xdebug /usr/local/lib/php/extensions/no-debug-non-zts-20230831/xdebug.so /usr/local/lib/php/extensions/no-debug-non-zts-20230831/ -# Add Source Code COPY ./bin /usr/src/code/bin COPY ./src /usr/src/code/src COPY ./dev /usr/src/code/dev # Add Debug Configs -RUN if [ "$DEBUG" == "true" ]; then cp /usr/src/code/dev/xdebug.ini /usr/local/etc/php/conf.d/xdebug.ini; fi -RUN if [ "$DEBUG" == "true" ]; then mkdir -p /tmp/xdebug; fi +RUN if [ "$DEBUG" = "true" ]; then cp /usr/src/code/dev/xdebug.ini /usr/local/etc/php/conf.d/xdebug.ini; fi +RUN if [ "$DEBUG" = "true" ]; then mkdir -p /tmp/xdebug; fi RUN if [ "$DEBUG" = "false" ]; then rm -rf /usr/src/code/dev; fi RUN if [ "$DEBUG" = "false" ]; then rm -f /usr/local/lib/php/extensions/no-debug-non-zts-20220829/xdebug.so; fi diff --git a/README.md b/README.md index cccfa1afa..1adf58143 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ A list of the utopia/php concepts and their relevant equivalent using the differ - **Document** - A simple JSON object that will be stored in one of the utopia/database collections. For SQL-based adapters, this will be equivalent to a row. For a No-SQL adapter, this will equivalent to a native document. - **Attribute** - A simple document attribute. For SQL-based adapters, this will be equivalent to a column. For a No-SQL adapter, this will equivalent to a native document field. - **Index** - A simple collection index used to improve the performance of your database queries. -- **Permissions** - Using permissions, you can decide which roles have read, create, update and delete access for a specific document. The special attribute `$permissions` is used to store permission metadata for each document in the collection. A permission role can be any string you want. You can use `$authorization->addRole()` to delegate new roles to your users, once obtained a new role a user would gain read, create, update or delete access to a relevant document. +- **Permissions** - Using permissions, you can decide which roles have read, create, update and delete access for a specific document. The special attribute `$permissions` is used to store permission metadata for each document in the collection. A permission role can be any string you want. You can use `Authorization::setRole()` to delegate new roles to your users, once obtained a new role a user would gain read, create, update or delete access to a relevant document. ### Filters diff --git a/bin/tasks/index.php b/bin/tasks/index.php index c1505cc26..5b43b5920 100644 --- a/bin/tasks/index.php +++ b/bin/tasks/index.php @@ -13,8 +13,8 @@ use Utopia\Database\Adapter\Mongo; use Utopia\Database\Adapter\MySQL; use Utopia\Database\Database; -use Utopia\Http\Validator\Text; use Utopia\Mongo\Client; +use Utopia\Validator\Text; /** * @Example diff --git a/bin/tasks/load.php b/bin/tasks/load.php index e48a4cc55..31deb39dc 100644 --- a/bin/tasks/load.php +++ b/bin/tasks/load.php @@ -21,11 +21,9 @@ use Utopia\Database\Helpers\Permission; use Utopia\Database\Helpers\Role; use Utopia\Database\Validator\Authorization; -use Utopia\Http\Validator\Numeric; -use Utopia\Http\Validator\Text; use Utopia\Mongo\Client; - -$authorization = new Authorization(); +use Utopia\Validator\Numeric; +use Utopia\Validator\Text; /** * @Example @@ -63,7 +61,7 @@ $database->setNamespace($namespace); // Outline collection schema - $createSchema($database); + createSchema($database); // reclaim resources $database = null; @@ -123,7 +121,7 @@ $database->setNamespace($namespace); // Outline collection schema - $createSchema($database); + createSchema($database); // reclaim resources $database = null; @@ -185,7 +183,7 @@ $database->setNamespace($namespace); // Outline collection schema - $createSchema($database); + createSchema($database); // Fill DB $faker = Factory::create(); @@ -228,13 +226,14 @@ }); -$createSchema = function (Database $database) use ($authorization): void { +function createSchema(Database $database): void +{ if ($database->exists($database->getDatabase())) { $database->delete($database->getDatabase()); } $database->create(); - $authorization->addRole(Role::any()->toString()); + Authorization::setRole(Role::any()->toString()); $database->createCollection('articles', permissions: [ Permission::create(Role::any()), @@ -248,7 +247,7 @@ $database->createAttribute('articles', 'views', Database::VAR_INTEGER, 0, true); $database->createAttribute('articles', 'tags', Database::VAR_STRING, 0, true, array: true); $database->createIndex('articles', 'text', Database::INDEX_FULLTEXT, ['text']); -}; +} function createDocument($database, Generator $faker): void { diff --git a/bin/tasks/query.php b/bin/tasks/query.php index 28dc0c431..ed84fd00c 100644 --- a/bin/tasks/query.php +++ b/bin/tasks/query.php @@ -14,9 +14,10 @@ use Utopia\Database\Adapter\MySQL; use Utopia\Database\Database; use Utopia\Database\Query; -use Utopia\Http\Validator\Numeric; -use Utopia\Http\Validator\Text; +use Utopia\Database\Validator\Authorization; use Utopia\Mongo\Client; +use Utopia\Validator\Numeric; +use Utopia\Validator\Text; /** * @Example @@ -83,35 +84,35 @@ $report = []; - $count = $setRoles($faker, 1); + $count = setRoles($faker, 1); Console::info("\n{$count} roles:"); $report[] = [ 'roles' => $count, 'results' => runQueries($database, $limit) ]; - $count = $setRoles($faker, 100); + $count = setRoles($faker, 100); Console::info("\n{$count} roles:"); $report[] = [ 'roles' => $count, 'results' => runQueries($database, $limit) ]; - $count = $setRoles($faker, 400); + $count = setRoles($faker, 400); Console::info("\n{$count} roles:"); $report[] = [ 'roles' => $count, 'results' => runQueries($database, $limit) ]; - $count = $setRoles($faker, 500); + $count = setRoles($faker, 500); Console::info("\n{$count} roles:"); $report[] = [ 'roles' => $count, 'results' => runQueries($database, $limit) ]; - $count = $setRoles($faker, 1000); + $count = setRoles($faker, 1000); Console::info("\n{$count} roles:"); $report[] = [ 'roles' => $count, @@ -135,12 +136,13 @@ Console::error($error->getMessage()); }); -$setRoles = function ($faker, $count) use ($authorization): int { +function setRoles($faker, $count): int +{ for ($i = 0; $i < $count; $i++) { - $authorization->addRole($faker->numerify('user####')); + Authorization::setRole($faker->numerify('user####')); } - return \count($authorization->getRoles()); -}; + return \count(Authorization::getRoles()); +} function runQueries(Database $database, int $limit): array { diff --git a/composer.json b/composer.json index de12d86f6..722e4e5e5 100755 --- a/composer.json +++ b/composer.json @@ -27,27 +27,27 @@ "Composer\\Config::disableProcessTimeout", "docker compose exec tests vendor/bin/phpunit --configuration phpunit.xml" ], - "lint": "./vendor/bin/pint --test", - "format": "./vendor/bin/pint", + "lint": "php -d memory_limit=2G ./vendor/bin/pint --test", + "format": "php -d memory_limit=2G ./vendor/bin/pint", "check": "./vendor/bin/phpstan analyse --level 7 src tests --memory-limit 2G", "coverage": "./vendor/bin/coverage-check ./tmp/clover.xml 90" }, "require": { + "php": ">=8.3", "ext-pdo": "*", "ext-mbstring": "*", - "php": ">=8.0", - "utopia-php/framework": "1.0.*", - "utopia-php/cache": "0.10.*", + "utopia-php/framework": "0.33.*", + "utopia-php/cache": "0.11.*", "utopia-php/mongo": "0.3.*" }, "require-dev": { "fakerphp/faker": "1.23.*", - "phpunit/phpunit": "9.6.*", - "pcov/clobber": "2.0.*", + "phpunit/phpunit": "9.*", + "pcov/clobber": "2.*", "swoole/ide-helper": "5.1.3", - "utopia-php/cli": "0.19.*", - "laravel/pint": "1.17.*", - "phpstan/phpstan": "1.11.*", + "utopia-php/cli": "0.14.*", + "laravel/pint": "1.*", + "phpstan/phpstan": "1.*", "rregeer/phpunit-coverage-check": "0.3.*" }, "suggests": { @@ -55,5 +55,11 @@ "ext-redis": "Needed to support Redis Cache Adapter", "ext-pdo": "Needed to support MariaDB, MySQL or SQLite Database Adapter", "mongodb/mongodb": "Needed to support MongoDB Database Adapter" + }, + "config": { + "allow-plugins": { + "php-http/discovery": true, + "tbachert/spi": true + } } } diff --git a/composer.lock b/composer.lock index 2ad152cc9..6c5cb2f70 100644 --- a/composer.lock +++ b/composer.lock @@ -4,32 +4,217 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "62684826df21956b2d48dc2c42cc3e07", + "content-hash": "0ad14b2121f07c2fe936eaaa82186cbc", "packages": [ + { + "name": "brick/math", + "version": "0.12.1", + "source": { + "type": "git", + "url": "https://github.com/brick/math.git", + "reference": "f510c0a40911935b77b86859eb5223d58d660df1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/brick/math/zipball/f510c0a40911935b77b86859eb5223d58d660df1", + "reference": "f510c0a40911935b77b86859eb5223d58d660df1", + "shasum": "" + }, + "require": { + "php": "^8.1" + }, + "require-dev": { + "php-coveralls/php-coveralls": "^2.2", + "phpunit/phpunit": "^10.1", + "vimeo/psalm": "5.16.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Brick\\Math\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Arbitrary-precision arithmetic library", + "keywords": [ + "Arbitrary-precision", + "BigInteger", + "BigRational", + "arithmetic", + "bigdecimal", + "bignum", + "bignumber", + "brick", + "decimal", + "integer", + "math", + "mathematics", + "rational" + ], + "support": { + "issues": "https://github.com/brick/math/issues", + "source": "https://github.com/brick/math/tree/0.12.1" + }, + "funding": [ + { + "url": "https://github.com/BenMorel", + "type": "github" + } + ], + "time": "2023-11-29T23:19:16+00:00" + }, + { + "name": "composer/semver", + "version": "3.4.3", + "source": { + "type": "git", + "url": "https://github.com/composer/semver.git", + "reference": "4313d26ada5e0c4edfbd1dc481a92ff7bff91f12" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/composer/semver/zipball/4313d26ada5e0c4edfbd1dc481a92ff7bff91f12", + "reference": "4313d26ada5e0c4edfbd1dc481a92ff7bff91f12", + "shasum": "" + }, + "require": { + "php": "^5.3.2 || ^7.0 || ^8.0" + }, + "require-dev": { + "phpstan/phpstan": "^1.11", + "symfony/phpunit-bridge": "^3 || ^7" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "autoload": { + "psr-4": { + "Composer\\Semver\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nils Adermann", + "email": "naderman@naderman.de", + "homepage": "http://www.naderman.de" + }, + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + }, + { + "name": "Rob Bast", + "email": "rob.bast@gmail.com", + "homepage": "http://robbast.nl" + } + ], + "description": "Semver library that offers utilities, version constraint parsing and validation.", + "keywords": [ + "semantic", + "semver", + "validation", + "versioning" + ], + "support": { + "irc": "ircs://irc.libera.chat:6697/composer", + "issues": "https://github.com/composer/semver/issues", + "source": "https://github.com/composer/semver/tree/3.4.3" + }, + "funding": [ + { + "url": "https://packagist.com", + "type": "custom" + }, + { + "url": "https://github.com/composer", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/composer/composer", + "type": "tidelift" + } + ], + "time": "2024-09-19T14:15:21+00:00" + }, + { + "name": "google/protobuf", + "version": "v4.29.3", + "source": { + "type": "git", + "url": "https://github.com/protocolbuffers/protobuf-php.git", + "reference": "ab5077c2cfdd1f415f42d11fdbdf903ba8e3d9b7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/protocolbuffers/protobuf-php/zipball/ab5077c2cfdd1f415f42d11fdbdf903ba8e3d9b7", + "reference": "ab5077c2cfdd1f415f42d11fdbdf903ba8e3d9b7", + "shasum": "" + }, + "require": { + "php": ">=7.0.0" + }, + "require-dev": { + "phpunit/phpunit": ">=5.0.0" + }, + "suggest": { + "ext-bcmath": "Need to support JSON deserialization" + }, + "type": "library", + "autoload": { + "psr-4": { + "Google\\Protobuf\\": "src/Google/Protobuf", + "GPBMetadata\\Google\\Protobuf\\": "src/GPBMetadata/Google/Protobuf" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "description": "proto library for PHP", + "homepage": "https://developers.google.com/protocol-buffers/", + "keywords": [ + "proto" + ], + "support": { + "source": "https://github.com/protocolbuffers/protobuf-php/tree/v4.29.3" + }, + "time": "2025-01-08T21:00:13+00:00" + }, { "name": "jean85/pretty-package-versions", - "version": "2.0.6", + "version": "2.1.0", "source": { "type": "git", "url": "https://github.com/Jean85/pretty-package-versions.git", - "reference": "f9fdd29ad8e6d024f52678b570e5593759b550b4" + "reference": "3c4e5f62ba8d7de1734312e4fff32f67a8daaf10" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Jean85/pretty-package-versions/zipball/f9fdd29ad8e6d024f52678b570e5593759b550b4", - "reference": "f9fdd29ad8e6d024f52678b570e5593759b550b4", + "url": "https://api.github.com/repos/Jean85/pretty-package-versions/zipball/3c4e5f62ba8d7de1734312e4fff32f67a8daaf10", + "reference": "3c4e5f62ba8d7de1734312e4fff32f67a8daaf10", "shasum": "" }, "require": { - "composer-runtime-api": "^2.0.0", - "php": "^7.1|^8.0" + "composer-runtime-api": "^2.1.0", + "php": "^7.4|^8.0" }, "require-dev": { "friendsofphp/php-cs-fixer": "^3.2", "jean85/composer-provided-replaced-stub-package": "^1.0", "phpstan/phpstan": "^1.4", - "phpunit/phpunit": "^7.5|^8.5|^9.4", - "vimeo/psalm": "^4.3" + "phpunit/phpunit": "^7.5|^8.5|^9.6", + "vimeo/psalm": "^4.3 || ^5.0" }, "type": "library", "extra": { @@ -61,9 +246,9 @@ ], "support": { "issues": "https://github.com/Jean85/pretty-package-versions/issues", - "source": "https://github.com/Jean85/pretty-package-versions/tree/2.0.6" + "source": "https://github.com/Jean85/pretty-package-versions/tree/2.1.0" }, - "time": "2024-03-08T09:58:59+00:00" + "time": "2024-11-18T16:19:46+00:00" }, { "name": "mongodb/mongodb", @@ -100,73 +285,1624 @@ }, "autoload": { "files": [ - "src/functions.php" + "src/functions.php" + ], + "psr-4": { + "MongoDB\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "Andreas Braun", + "email": "andreas.braun@mongodb.com" + }, + { + "name": "Jeremy Mikola", + "email": "jmikola@gmail.com" + } + ], + "description": "MongoDB driver library", + "homepage": "https://jira.mongodb.org/browse/PHPLIB", + "keywords": [ + "database", + "driver", + "mongodb", + "persistence" + ], + "support": { + "issues": "https://github.com/mongodb/mongo-php-library/issues", + "source": "https://github.com/mongodb/mongo-php-library/tree/1.10.0" + }, + "time": "2021-10-20T22:22:37+00:00" + }, + { + "name": "nyholm/psr7", + "version": "1.8.2", + "source": { + "type": "git", + "url": "https://github.com/Nyholm/psr7.git", + "reference": "a71f2b11690f4b24d099d6b16690a90ae14fc6f3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Nyholm/psr7/zipball/a71f2b11690f4b24d099d6b16690a90ae14fc6f3", + "reference": "a71f2b11690f4b24d099d6b16690a90ae14fc6f3", + "shasum": "" + }, + "require": { + "php": ">=7.2", + "psr/http-factory": "^1.0", + "psr/http-message": "^1.1 || ^2.0" + }, + "provide": { + "php-http/message-factory-implementation": "1.0", + "psr/http-factory-implementation": "1.0", + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "http-interop/http-factory-tests": "^0.9", + "php-http/message-factory": "^1.0", + "php-http/psr7-integration-tests": "^1.0", + "phpunit/phpunit": "^7.5 || ^8.5 || ^9.4", + "symfony/error-handler": "^4.4" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.8-dev" + } + }, + "autoload": { + "psr-4": { + "Nyholm\\Psr7\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com" + }, + { + "name": "Martijn van der Ven", + "email": "martijn@vanderven.se" + } + ], + "description": "A fast PHP7 implementation of PSR-7", + "homepage": "https://tnyholm.se", + "keywords": [ + "psr-17", + "psr-7" + ], + "support": { + "issues": "https://github.com/Nyholm/psr7/issues", + "source": "https://github.com/Nyholm/psr7/tree/1.8.2" + }, + "funding": [ + { + "url": "https://github.com/Zegnat", + "type": "github" + }, + { + "url": "https://github.com/nyholm", + "type": "github" + } + ], + "time": "2024-09-09T07:06:30+00:00" + }, + { + "name": "nyholm/psr7-server", + "version": "1.1.0", + "source": { + "type": "git", + "url": "https://github.com/Nyholm/psr7-server.git", + "reference": "4335801d851f554ca43fa6e7d2602141538854dc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Nyholm/psr7-server/zipball/4335801d851f554ca43fa6e7d2602141538854dc", + "reference": "4335801d851f554ca43fa6e7d2602141538854dc", + "shasum": "" + }, + "require": { + "php": "^7.1 || ^8.0", + "psr/http-factory": "^1.0", + "psr/http-message": "^1.0 || ^2.0" + }, + "require-dev": { + "nyholm/nsa": "^1.1", + "nyholm/psr7": "^1.3", + "phpunit/phpunit": "^7.0 || ^8.5 || ^9.3" + }, + "type": "library", + "autoload": { + "psr-4": { + "Nyholm\\Psr7Server\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com" + }, + { + "name": "Martijn van der Ven", + "email": "martijn@vanderven.se" + } + ], + "description": "Helper classes to handle PSR-7 server requests", + "homepage": "http://tnyholm.se", + "keywords": [ + "psr-17", + "psr-7" + ], + "support": { + "issues": "https://github.com/Nyholm/psr7-server/issues", + "source": "https://github.com/Nyholm/psr7-server/tree/1.1.0" + }, + "funding": [ + { + "url": "https://github.com/Zegnat", + "type": "github" + }, + { + "url": "https://github.com/nyholm", + "type": "github" + } + ], + "time": "2023-11-08T09:30:43+00:00" + }, + { + "name": "open-telemetry/api", + "version": "1.2.0", + "source": { + "type": "git", + "url": "https://github.com/opentelemetry-php/api.git", + "reference": "351a30baa79699de3de3a814c8ccc7b52ccdfb1d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/opentelemetry-php/api/zipball/351a30baa79699de3de3a814c8ccc7b52ccdfb1d", + "reference": "351a30baa79699de3de3a814c8ccc7b52ccdfb1d", + "shasum": "" + }, + "require": { + "open-telemetry/context": "^1.0", + "php": "^8.1", + "psr/log": "^1.1|^2.0|^3.0", + "symfony/polyfill-php82": "^1.26" + }, + "conflict": { + "open-telemetry/sdk": "<=1.0.8" + }, + "type": "library", + "extra": { + "spi": { + "OpenTelemetry\\API\\Instrumentation\\AutoInstrumentation\\HookManagerInterface": [ + "OpenTelemetry\\API\\Instrumentation\\AutoInstrumentation\\ExtensionHookManager" + ] + }, + "branch-alias": { + "dev-main": "1.1.x-dev" + } + }, + "autoload": { + "files": [ + "Trace/functions.php" + ], + "psr-4": { + "OpenTelemetry\\API\\": "." + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "opentelemetry-php contributors", + "homepage": "https://github.com/open-telemetry/opentelemetry-php/graphs/contributors" + } + ], + "description": "API for OpenTelemetry PHP.", + "keywords": [ + "Metrics", + "api", + "apm", + "logging", + "opentelemetry", + "otel", + "tracing" + ], + "support": { + "chat": "https://app.slack.com/client/T08PSQ7BQ/C01NFPCV44V", + "docs": "https://opentelemetry.io/docs/php", + "issues": "https://github.com/open-telemetry/opentelemetry-php/issues", + "source": "https://github.com/open-telemetry/opentelemetry-php" + }, + "time": "2025-01-08T23:50:34+00:00" + }, + { + "name": "open-telemetry/context", + "version": "1.1.0", + "source": { + "type": "git", + "url": "https://github.com/opentelemetry-php/context.git", + "reference": "0cba875ea1953435f78aec7f1d75afa87bdbf7f3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/opentelemetry-php/context/zipball/0cba875ea1953435f78aec7f1d75afa87bdbf7f3", + "reference": "0cba875ea1953435f78aec7f1d75afa87bdbf7f3", + "shasum": "" + }, + "require": { + "php": "^8.1", + "symfony/polyfill-php82": "^1.26" + }, + "suggest": { + "ext-ffi": "To allow context switching in Fibers" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.0.x-dev" + } + }, + "autoload": { + "files": [ + "fiber/initialize_fiber_handler.php" + ], + "psr-4": { + "OpenTelemetry\\Context\\": "." + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "opentelemetry-php contributors", + "homepage": "https://github.com/open-telemetry/opentelemetry-php/graphs/contributors" + } + ], + "description": "Context implementation for OpenTelemetry PHP.", + "keywords": [ + "Context", + "opentelemetry", + "otel" + ], + "support": { + "chat": "https://app.slack.com/client/T08PSQ7BQ/C01NFPCV44V", + "docs": "https://opentelemetry.io/docs/php", + "issues": "https://github.com/open-telemetry/opentelemetry-php/issues", + "source": "https://github.com/open-telemetry/opentelemetry-php" + }, + "time": "2024-08-21T00:29:20+00:00" + }, + { + "name": "open-telemetry/exporter-otlp", + "version": "1.2.0", + "source": { + "type": "git", + "url": "https://github.com/opentelemetry-php/exporter-otlp.git", + "reference": "243d9657c44a06f740cf384f486afe954c2b725f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/opentelemetry-php/exporter-otlp/zipball/243d9657c44a06f740cf384f486afe954c2b725f", + "reference": "243d9657c44a06f740cf384f486afe954c2b725f", + "shasum": "" + }, + "require": { + "open-telemetry/api": "^1.0", + "open-telemetry/gen-otlp-protobuf": "^1.1", + "open-telemetry/sdk": "^1.0", + "php": "^8.1", + "php-http/discovery": "^1.14" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.0.x-dev" + } + }, + "autoload": { + "files": [ + "_register.php" + ], + "psr-4": { + "OpenTelemetry\\Contrib\\Otlp\\": "." + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "opentelemetry-php contributors", + "homepage": "https://github.com/open-telemetry/opentelemetry-php/graphs/contributors" + } + ], + "description": "OTLP exporter for OpenTelemetry.", + "keywords": [ + "Metrics", + "exporter", + "gRPC", + "http", + "opentelemetry", + "otel", + "otlp", + "tracing" + ], + "support": { + "chat": "https://app.slack.com/client/T08PSQ7BQ/C01NFPCV44V", + "docs": "https://opentelemetry.io/docs/php", + "issues": "https://github.com/open-telemetry/opentelemetry-php/issues", + "source": "https://github.com/open-telemetry/opentelemetry-php" + }, + "time": "2025-01-08T23:50:03+00:00" + }, + { + "name": "open-telemetry/gen-otlp-protobuf", + "version": "1.2.1", + "source": { + "type": "git", + "url": "https://github.com/opentelemetry-php/gen-otlp-protobuf.git", + "reference": "66c3b98e998a726691c92e6405a82e6e7b8b169d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/opentelemetry-php/gen-otlp-protobuf/zipball/66c3b98e998a726691c92e6405a82e6e7b8b169d", + "reference": "66c3b98e998a726691c92e6405a82e6e7b8b169d", + "shasum": "" + }, + "require": { + "google/protobuf": "^3.22 || ^4.0", + "php": "^8.0" + }, + "suggest": { + "ext-protobuf": "For better performance, when dealing with the protobuf format" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.x-dev" + } + }, + "autoload": { + "psr-4": { + "Opentelemetry\\Proto\\": "Opentelemetry/Proto/", + "GPBMetadata\\Opentelemetry\\": "GPBMetadata/Opentelemetry/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "opentelemetry-php contributors", + "homepage": "https://github.com/open-telemetry/opentelemetry-php/graphs/contributors" + } + ], + "description": "PHP protobuf files for communication with OpenTelemetry OTLP collectors/servers.", + "keywords": [ + "Metrics", + "apm", + "gRPC", + "logging", + "opentelemetry", + "otel", + "otlp", + "protobuf", + "tracing" + ], + "support": { + "chat": "https://app.slack.com/client/T08PSQ7BQ/C01NFPCV44V", + "docs": "https://opentelemetry.io/docs/php", + "issues": "https://github.com/open-telemetry/opentelemetry-php/issues", + "source": "https://github.com/open-telemetry/opentelemetry-php" + }, + "time": "2024-10-30T11:49:49+00:00" + }, + { + "name": "open-telemetry/sdk", + "version": "1.2.0", + "source": { + "type": "git", + "url": "https://github.com/opentelemetry-php/sdk.git", + "reference": "9a1c3b866239dbff291e5cc555bb7793eab08127" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/opentelemetry-php/sdk/zipball/9a1c3b866239dbff291e5cc555bb7793eab08127", + "reference": "9a1c3b866239dbff291e5cc555bb7793eab08127", + "shasum": "" + }, + "require": { + "ext-json": "*", + "nyholm/psr7-server": "^1.1", + "open-telemetry/api": "~1.0 || ~1.1", + "open-telemetry/context": "^1.0", + "open-telemetry/sem-conv": "^1.0", + "php": "^8.1", + "php-http/discovery": "^1.14", + "psr/http-client": "^1.0", + "psr/http-client-implementation": "^1.0", + "psr/http-factory-implementation": "^1.0", + "psr/http-message": "^1.0.1|^2.0", + "psr/log": "^1.1|^2.0|^3.0", + "ramsey/uuid": "^3.0 || ^4.0", + "symfony/polyfill-mbstring": "^1.23", + "symfony/polyfill-php82": "^1.26", + "tbachert/spi": "^1.0.1" + }, + "suggest": { + "ext-gmp": "To support unlimited number of synchronous metric readers", + "ext-mbstring": "To increase performance of string operations", + "open-telemetry/sdk-configuration": "File-based OpenTelemetry SDK configuration" + }, + "type": "library", + "extra": { + "spi": { + "OpenTelemetry\\API\\Instrumentation\\AutoInstrumentation\\HookManagerInterface": [ + "OpenTelemetry\\API\\Instrumentation\\AutoInstrumentation\\ExtensionHookManager" + ] + }, + "branch-alias": { + "dev-main": "1.0.x-dev" + } + }, + "autoload": { + "files": [ + "Common/Util/functions.php", + "Logs/Exporter/_register.php", + "Metrics/MetricExporter/_register.php", + "Propagation/_register.php", + "Trace/SpanExporter/_register.php", + "Common/Dev/Compatibility/_load.php", + "_autoload.php" + ], + "psr-4": { + "OpenTelemetry\\SDK\\": "." + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "opentelemetry-php contributors", + "homepage": "https://github.com/open-telemetry/opentelemetry-php/graphs/contributors" + } + ], + "description": "SDK for OpenTelemetry PHP.", + "keywords": [ + "Metrics", + "apm", + "logging", + "opentelemetry", + "otel", + "sdk", + "tracing" + ], + "support": { + "chat": "https://app.slack.com/client/T08PSQ7BQ/C01NFPCV44V", + "docs": "https://opentelemetry.io/docs/php", + "issues": "https://github.com/open-telemetry/opentelemetry-php/issues", + "source": "https://github.com/open-telemetry/opentelemetry-php" + }, + "time": "2025-01-08T23:50:34+00:00" + }, + { + "name": "open-telemetry/sem-conv", + "version": "1.27.1", + "source": { + "type": "git", + "url": "https://github.com/opentelemetry-php/sem-conv.git", + "reference": "1dba705fea74bc0718d04be26090e3697e56f4e6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/opentelemetry-php/sem-conv/zipball/1dba705fea74bc0718d04be26090e3697e56f4e6", + "reference": "1dba705fea74bc0718d04be26090e3697e56f4e6", + "shasum": "" + }, + "require": { + "php": "^8.1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.x-dev" + } + }, + "autoload": { + "psr-4": { + "OpenTelemetry\\SemConv\\": "." + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "opentelemetry-php contributors", + "homepage": "https://github.com/open-telemetry/opentelemetry-php/graphs/contributors" + } + ], + "description": "Semantic conventions for OpenTelemetry PHP.", + "keywords": [ + "Metrics", + "apm", + "logging", + "opentelemetry", + "otel", + "semantic conventions", + "semconv", + "tracing" + ], + "support": { + "chat": "https://app.slack.com/client/T08PSQ7BQ/C01NFPCV44V", + "docs": "https://opentelemetry.io/docs/php", + "issues": "https://github.com/open-telemetry/opentelemetry-php/issues", + "source": "https://github.com/open-telemetry/opentelemetry-php" + }, + "time": "2024-08-28T09:20:31+00:00" + }, + { + "name": "php-http/discovery", + "version": "1.20.0", + "source": { + "type": "git", + "url": "https://github.com/php-http/discovery.git", + "reference": "82fe4c73ef3363caed49ff8dd1539ba06044910d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-http/discovery/zipball/82fe4c73ef3363caed49ff8dd1539ba06044910d", + "reference": "82fe4c73ef3363caed49ff8dd1539ba06044910d", + "shasum": "" + }, + "require": { + "composer-plugin-api": "^1.0|^2.0", + "php": "^7.1 || ^8.0" + }, + "conflict": { + "nyholm/psr7": "<1.0", + "zendframework/zend-diactoros": "*" + }, + "provide": { + "php-http/async-client-implementation": "*", + "php-http/client-implementation": "*", + "psr/http-client-implementation": "*", + "psr/http-factory-implementation": "*", + "psr/http-message-implementation": "*" + }, + "require-dev": { + "composer/composer": "^1.0.2|^2.0", + "graham-campbell/phpspec-skip-example-extension": "^5.0", + "php-http/httplug": "^1.0 || ^2.0", + "php-http/message-factory": "^1.0", + "phpspec/phpspec": "^5.1 || ^6.1 || ^7.3", + "sebastian/comparator": "^3.0.5 || ^4.0.8", + "symfony/phpunit-bridge": "^6.4.4 || ^7.0.1" + }, + "type": "composer-plugin", + "extra": { + "class": "Http\\Discovery\\Composer\\Plugin", + "plugin-optional": true + }, + "autoload": { + "psr-4": { + "Http\\Discovery\\": "src/" + }, + "exclude-from-classmap": [ + "src/Composer/Plugin.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com" + } + ], + "description": "Finds and installs PSR-7, PSR-17, PSR-18 and HTTPlug implementations", + "homepage": "http://php-http.org", + "keywords": [ + "adapter", + "client", + "discovery", + "factory", + "http", + "message", + "psr17", + "psr7" + ], + "support": { + "issues": "https://github.com/php-http/discovery/issues", + "source": "https://github.com/php-http/discovery/tree/1.20.0" + }, + "time": "2024-10-02T11:20:13+00:00" + }, + { + "name": "psr/container", + "version": "2.0.2", + "source": { + "type": "git", + "url": "https://github.com/php-fig/container.git", + "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/container/zipball/c71ecc56dfe541dbd90c5360474fbc405f8d5963", + "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963", + "shasum": "" + }, + "require": { + "php": ">=7.4.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Container\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common Container Interface (PHP FIG PSR-11)", + "homepage": "https://github.com/php-fig/container", + "keywords": [ + "PSR-11", + "container", + "container-interface", + "container-interop", + "psr" + ], + "support": { + "issues": "https://github.com/php-fig/container/issues", + "source": "https://github.com/php-fig/container/tree/2.0.2" + }, + "time": "2021-11-05T16:47:00+00:00" + }, + { + "name": "psr/http-client", + "version": "1.0.3", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-client.git", + "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-client/zipball/bb5906edc1c324c9a05aa0873d40117941e5fa90", + "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90", + "shasum": "" + }, + "require": { + "php": "^7.0 || ^8.0", + "psr/http-message": "^1.0 || ^2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP clients", + "homepage": "https://github.com/php-fig/http-client", + "keywords": [ + "http", + "http-client", + "psr", + "psr-18" + ], + "support": { + "source": "https://github.com/php-fig/http-client" + }, + "time": "2023-09-23T14:17:50+00:00" + }, + { + "name": "psr/http-factory", + "version": "1.1.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-factory.git", + "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-factory/zipball/2b4765fddfe3b508ac62f829e852b1501d3f6e8a", + "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a", + "shasum": "" + }, + "require": { + "php": ">=7.1", + "psr/http-message": "^1.0 || ^2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "PSR-17: Common interfaces for PSR-7 HTTP message factories", + "keywords": [ + "factory", + "http", + "message", + "psr", + "psr-17", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-factory" + }, + "time": "2024-04-15T12:06:14+00:00" + }, + { + "name": "psr/http-message", + "version": "2.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/402d35bcb92c70c026d1a6a9883f06b2ead23d71", + "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-message/tree/2.0" + }, + "time": "2023-04-04T09:54:51+00:00" + }, + { + "name": "psr/log", + "version": "3.0.2", + "source": { + "type": "git", + "url": "https://github.com/php-fig/log.git", + "reference": "f16e1d5863e37f8d8c2a01719f5b34baa2b714d3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/log/zipball/f16e1d5863e37f8d8c2a01719f5b34baa2b714d3", + "reference": "f16e1d5863e37f8d8c2a01719f5b34baa2b714d3", + "shasum": "" + }, + "require": { + "php": ">=8.0.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Log\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for logging libraries", + "homepage": "https://github.com/php-fig/log", + "keywords": [ + "log", + "psr", + "psr-3" + ], + "support": { + "source": "https://github.com/php-fig/log/tree/3.0.2" + }, + "time": "2024-09-11T13:17:53+00:00" + }, + { + "name": "ramsey/collection", + "version": "2.0.0", + "source": { + "type": "git", + "url": "https://github.com/ramsey/collection.git", + "reference": "a4b48764bfbb8f3a6a4d1aeb1a35bb5e9ecac4a5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ramsey/collection/zipball/a4b48764bfbb8f3a6a4d1aeb1a35bb5e9ecac4a5", + "reference": "a4b48764bfbb8f3a6a4d1aeb1a35bb5e9ecac4a5", + "shasum": "" + }, + "require": { + "php": "^8.1" + }, + "require-dev": { + "captainhook/plugin-composer": "^5.3", + "ergebnis/composer-normalize": "^2.28.3", + "fakerphp/faker": "^1.21", + "hamcrest/hamcrest-php": "^2.0", + "jangregor/phpstan-prophecy": "^1.0", + "mockery/mockery": "^1.5", + "php-parallel-lint/php-console-highlighter": "^1.0", + "php-parallel-lint/php-parallel-lint": "^1.3", + "phpcsstandards/phpcsutils": "^1.0.0-rc1", + "phpspec/prophecy-phpunit": "^2.0", + "phpstan/extension-installer": "^1.2", + "phpstan/phpstan": "^1.9", + "phpstan/phpstan-mockery": "^1.1", + "phpstan/phpstan-phpunit": "^1.3", + "phpunit/phpunit": "^9.5", + "psalm/plugin-mockery": "^1.1", + "psalm/plugin-phpunit": "^0.18.4", + "ramsey/coding-standard": "^2.0.3", + "ramsey/conventional-commits": "^1.3", + "vimeo/psalm": "^5.4" + }, + "type": "library", + "extra": { + "captainhook": { + "force-install": true + }, + "ramsey/conventional-commits": { + "configFile": "conventional-commits.json" + } + }, + "autoload": { + "psr-4": { + "Ramsey\\Collection\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ben Ramsey", + "email": "ben@benramsey.com", + "homepage": "https://benramsey.com" + } + ], + "description": "A PHP library for representing and manipulating collections.", + "keywords": [ + "array", + "collection", + "hash", + "map", + "queue", + "set" + ], + "support": { + "issues": "https://github.com/ramsey/collection/issues", + "source": "https://github.com/ramsey/collection/tree/2.0.0" + }, + "funding": [ + { + "url": "https://github.com/ramsey", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/ramsey/collection", + "type": "tidelift" + } + ], + "time": "2022-12-31T21:50:55+00:00" + }, + { + "name": "ramsey/uuid", + "version": "4.7.6", + "source": { + "type": "git", + "url": "https://github.com/ramsey/uuid.git", + "reference": "91039bc1faa45ba123c4328958e620d382ec7088" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ramsey/uuid/zipball/91039bc1faa45ba123c4328958e620d382ec7088", + "reference": "91039bc1faa45ba123c4328958e620d382ec7088", + "shasum": "" + }, + "require": { + "brick/math": "^0.8.8 || ^0.9 || ^0.10 || ^0.11 || ^0.12", + "ext-json": "*", + "php": "^8.0", + "ramsey/collection": "^1.2 || ^2.0" + }, + "replace": { + "rhumsaa/uuid": "self.version" + }, + "require-dev": { + "captainhook/captainhook": "^5.10", + "captainhook/plugin-composer": "^5.3", + "dealerdirect/phpcodesniffer-composer-installer": "^0.7.0", + "doctrine/annotations": "^1.8", + "ergebnis/composer-normalize": "^2.15", + "mockery/mockery": "^1.3", + "paragonie/random-lib": "^2", + "php-mock/php-mock": "^2.2", + "php-mock/php-mock-mockery": "^1.3", + "php-parallel-lint/php-parallel-lint": "^1.1", + "phpbench/phpbench": "^1.0", + "phpstan/extension-installer": "^1.1", + "phpstan/phpstan": "^1.8", + "phpstan/phpstan-mockery": "^1.1", + "phpstan/phpstan-phpunit": "^1.1", + "phpunit/phpunit": "^8.5 || ^9", + "ramsey/composer-repl": "^1.4", + "slevomat/coding-standard": "^8.4", + "squizlabs/php_codesniffer": "^3.5", + "vimeo/psalm": "^4.9" + }, + "suggest": { + "ext-bcmath": "Enables faster math with arbitrary-precision integers using BCMath.", + "ext-gmp": "Enables faster math with arbitrary-precision integers using GMP.", + "ext-uuid": "Enables the use of PeclUuidTimeGenerator and PeclUuidRandomGenerator.", + "paragonie/random-lib": "Provides RandomLib for use with the RandomLibAdapter", + "ramsey/uuid-doctrine": "Allows the use of Ramsey\\Uuid\\Uuid as Doctrine field type." + }, + "type": "library", + "extra": { + "captainhook": { + "force-install": true + } + }, + "autoload": { + "files": [ + "src/functions.php" + ], + "psr-4": { + "Ramsey\\Uuid\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "A PHP library for generating and working with universally unique identifiers (UUIDs).", + "keywords": [ + "guid", + "identifier", + "uuid" + ], + "support": { + "issues": "https://github.com/ramsey/uuid/issues", + "source": "https://github.com/ramsey/uuid/tree/4.7.6" + }, + "funding": [ + { + "url": "https://github.com/ramsey", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/ramsey/uuid", + "type": "tidelift" + } + ], + "time": "2024-04-27T21:32:50+00:00" + }, + { + "name": "symfony/deprecation-contracts", + "version": "v3.5.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/deprecation-contracts.git", + "reference": "74c71c939a79f7d5bf3c1ce9f5ea37ba0114c6f6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/74c71c939a79f7d5bf3c1ce9f5ea37ba0114c6f6", + "reference": "74c71c939a79f7d5bf3c1ce9f5ea37ba0114c6f6", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/contracts", + "name": "symfony/contracts" + }, + "branch-alias": { + "dev-main": "3.5-dev" + } + }, + "autoload": { + "files": [ + "function.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "A generic function and convention to trigger deprecation notices", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/deprecation-contracts/tree/v3.5.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-09-25T14:20:29+00:00" + }, + { + "name": "symfony/http-client", + "version": "v7.2.2", + "source": { + "type": "git", + "url": "https://github.com/symfony/http-client.git", + "reference": "339ba21476eb184290361542f732ad12c97591ec" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/http-client/zipball/339ba21476eb184290361542f732ad12c97591ec", + "reference": "339ba21476eb184290361542f732ad12c97591ec", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "psr/log": "^1|^2|^3", + "symfony/deprecation-contracts": "^2.5|^3", + "symfony/http-client-contracts": "~3.4.4|^3.5.2", + "symfony/service-contracts": "^2.5|^3" + }, + "conflict": { + "amphp/amp": "<2.5", + "php-http/discovery": "<1.15", + "symfony/http-foundation": "<6.4" + }, + "provide": { + "php-http/async-client-implementation": "*", + "php-http/client-implementation": "*", + "psr/http-client-implementation": "1.0", + "symfony/http-client-implementation": "3.0" + }, + "require-dev": { + "amphp/http-client": "^4.2.1|^5.0", + "amphp/http-tunnel": "^1.0|^2.0", + "amphp/socket": "^1.1", + "guzzlehttp/promises": "^1.4|^2.0", + "nyholm/psr7": "^1.0", + "php-http/httplug": "^1.0|^2.0", + "psr/http-client": "^1.0", + "symfony/amphp-http-client-meta": "^1.0|^2.0", + "symfony/dependency-injection": "^6.4|^7.0", + "symfony/http-kernel": "^6.4|^7.0", + "symfony/messenger": "^6.4|^7.0", + "symfony/process": "^6.4|^7.0", + "symfony/rate-limiter": "^6.4|^7.0", + "symfony/stopwatch": "^6.4|^7.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\HttpClient\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides powerful methods to fetch HTTP resources synchronously or asynchronously", + "homepage": "https://symfony.com", + "keywords": [ + "http" + ], + "support": { + "source": "https://github.com/symfony/http-client/tree/v7.2.2" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-12-30T18:35:15+00:00" + }, + { + "name": "symfony/http-client-contracts", + "version": "v3.5.2", + "source": { + "type": "git", + "url": "https://github.com/symfony/http-client-contracts.git", + "reference": "ee8d807ab20fcb51267fdace50fbe3494c31e645" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/http-client-contracts/zipball/ee8d807ab20fcb51267fdace50fbe3494c31e645", + "reference": "ee8d807ab20fcb51267fdace50fbe3494c31e645", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/contracts", + "name": "symfony/contracts" + }, + "branch-alias": { + "dev-main": "3.5-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Contracts\\HttpClient\\": "" + }, + "exclude-from-classmap": [ + "/Test/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to HTTP clients", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https://github.com/symfony/http-client-contracts/tree/v3.5.2" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-12-07T08:49:48+00:00" + }, + { + "name": "symfony/polyfill-mbstring", + "version": "v1.31.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-mbstring.git", + "reference": "85181ba99b2345b0ef10ce42ecac37612d9fd341" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/85181ba99b2345b0ef10ce42ecac37612d9fd341", + "reference": "85181ba99b2345b0ef10ce42ecac37612d9fd341", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "provide": { + "ext-mbstring": "*" + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Mbstring\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for the Mbstring extension", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "mbstring", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.31.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-09-09T11:45:10+00:00" + }, + { + "name": "symfony/polyfill-php80", + "version": "v1.31.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php80.git", + "reference": "60328e362d4c2c802a54fcbf04f9d3fb892b4cf8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/60328e362d4c2c802a54fcbf04f9d3fb892b4cf8", + "reference": "60328e362d4c2c802a54fcbf04f9d3fb892b4cf8", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php80\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ion Bazan", + "email": "ion.bazan@gmail.com" + }, + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php80/tree/v1.31.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-09-09T11:45:10+00:00" + }, + { + "name": "symfony/polyfill-php82", + "version": "v1.31.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php82.git", + "reference": "5d2ed36f7734637dacc025f179698031951b1692" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php82/zipball/5d2ed36f7734637dacc025f179698031951b1692", + "reference": "5d2ed36f7734637dacc025f179698031951b1692", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" ], "psr-4": { - "MongoDB\\": "src/" - } + "Symfony\\Polyfill\\Php82\\": "" + }, + "classmap": [ + "Resources/stubs" + ] }, "notification-url": "https://packagist.org/downloads/", "license": [ - "Apache-2.0" + "MIT" ], "authors": [ { - "name": "Andreas Braun", - "email": "andreas.braun@mongodb.com" + "name": "Nicolas Grekas", + "email": "p@tchwork.com" }, { - "name": "Jeremy Mikola", - "email": "jmikola@gmail.com" + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" } ], - "description": "MongoDB driver library", - "homepage": "https://jira.mongodb.org/browse/PHPLIB", + "description": "Symfony polyfill backporting some PHP 8.2+ features to lower PHP versions", + "homepage": "https://symfony.com", "keywords": [ - "database", - "driver", - "mongodb", - "persistence" + "compatibility", + "polyfill", + "portable", + "shim" ], "support": { - "issues": "https://github.com/mongodb/mongo-php-library/issues", - "source": "https://github.com/mongodb/mongo-php-library/tree/1.10.0" + "source": "https://github.com/symfony/polyfill-php82/tree/v1.31.0" }, - "time": "2021-10-20T22:22:37+00:00" + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2024-09-09T11:45:10+00:00" }, { - "name": "symfony/polyfill-php80", - "version": "v1.31.0", + "name": "symfony/service-contracts", + "version": "v3.5.1", "source": { "type": "git", - "url": "https://github.com/symfony/polyfill-php80.git", - "reference": "60328e362d4c2c802a54fcbf04f9d3fb892b4cf8" + "url": "https://github.com/symfony/service-contracts.git", + "reference": "e53260aabf78fb3d63f8d79d69ece59f80d5eda0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/60328e362d4c2c802a54fcbf04f9d3fb892b4cf8", - "reference": "60328e362d4c2c802a54fcbf04f9d3fb892b4cf8", + "url": "https://api.github.com/repos/symfony/service-contracts/zipball/e53260aabf78fb3d63f8d79d69ece59f80d5eda0", + "reference": "e53260aabf78fb3d63f8d79d69ece59f80d5eda0", "shasum": "" }, "require": { - "php": ">=7.2" + "php": ">=8.1", + "psr/container": "^1.1|^2.0", + "symfony/deprecation-contracts": "^2.5|^3" + }, + "conflict": { + "ext-psr": "<1.1|>=2" }, "type": "library", "extra": { "thanks": { - "name": "symfony/polyfill", - "url": "https://github.com/symfony/polyfill" + "url": "https://github.com/symfony/contracts", + "name": "symfony/contracts" + }, + "branch-alias": { + "dev-main": "3.5-dev" } }, "autoload": { - "files": [ - "bootstrap.php" - ], "psr-4": { - "Symfony\\Polyfill\\Php80\\": "" + "Symfony\\Contracts\\Service\\": "" }, - "classmap": [ - "Resources/stubs" + "exclude-from-classmap": [ + "/Test/" ] }, "notification-url": "https://packagist.org/downloads/", @@ -174,10 +1910,6 @@ "MIT" ], "authors": [ - { - "name": "Ion Bazan", - "email": "ion.bazan@gmail.com" - }, { "name": "Nicolas Grekas", "email": "p@tchwork.com" @@ -187,16 +1919,18 @@ "homepage": "https://symfony.com/contributors" } ], - "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "description": "Generic abstractions related to writing services", "homepage": "https://symfony.com", "keywords": [ - "compatibility", - "polyfill", - "portable", - "shim" + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" ], "support": { - "source": "https://github.com/symfony/polyfill-php80/tree/v1.31.0" + "source": "https://github.com/symfony/service-contracts/tree/v3.5.1" }, "funding": [ { @@ -212,20 +1946,72 @@ "type": "tidelift" } ], - "time": "2024-09-09T11:45:10+00:00" + "time": "2024-09-25T14:20:29+00:00" + }, + { + "name": "tbachert/spi", + "version": "v1.0.2", + "source": { + "type": "git", + "url": "https://github.com/Nevay/spi.git", + "reference": "2ddfaf815dafb45791a61b08170de8d583c16062" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Nevay/spi/zipball/2ddfaf815dafb45791a61b08170de8d583c16062", + "reference": "2ddfaf815dafb45791a61b08170de8d583c16062", + "shasum": "" + }, + "require": { + "composer-plugin-api": "^2.0", + "composer/semver": "^1.0 || ^2.0 || ^3.0", + "php": "^8.1" + }, + "require-dev": { + "composer/composer": "^2.0", + "infection/infection": "^0.27.9", + "phpunit/phpunit": "^10.5", + "psalm/phar": "^5.18" + }, + "type": "composer-plugin", + "extra": { + "class": "Nevay\\SPI\\Composer\\Plugin", + "branch-alias": { + "dev-main": "0.2.x-dev" + }, + "plugin-optional": true + }, + "autoload": { + "psr-4": { + "Nevay\\SPI\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "description": "Service provider loading facility", + "keywords": [ + "service provider" + ], + "support": { + "issues": "https://github.com/Nevay/spi/issues", + "source": "https://github.com/Nevay/spi/tree/v1.0.2" + }, + "time": "2024-10-04T16:36:12+00:00" }, { "name": "utopia-php/cache", - "version": "0.10.2", + "version": "0.11.0", "source": { "type": "git", "url": "https://github.com/utopia-php/cache.git", - "reference": "b22c6eb6d308de246b023efd0fc9758aee8b8247" + "reference": "8ebcab5aac7606331cef69b0081f6c9eff2e58bc" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/cache/zipball/b22c6eb6d308de246b023efd0fc9758aee8b8247", - "reference": "b22c6eb6d308de246b023efd0fc9758aee8b8247", + "url": "https://api.github.com/repos/utopia-php/cache/zipball/8ebcab5aac7606331cef69b0081f6c9eff2e58bc", + "reference": "8ebcab5aac7606331cef69b0081f6c9eff2e58bc", "shasum": "" }, "require": { @@ -236,7 +2022,7 @@ }, "require-dev": { "laravel/pint": "1.2.*", - "phpstan/phpstan": "1.9.x-dev", + "phpstan/phpstan": "^1.12", "phpunit/phpunit": "^9.3", "vimeo/psalm": "4.13.1" }, @@ -260,84 +2046,80 @@ ], "support": { "issues": "https://github.com/utopia-php/cache/issues", - "source": "https://github.com/utopia-php/cache/tree/0.10.2" + "source": "https://github.com/utopia-php/cache/tree/0.11.0" }, - "time": "2024-06-25T20:36:35+00:00" + "time": "2024-11-05T16:53:58+00:00" }, { - "name": "utopia-php/di", - "version": "0.1.0", + "name": "utopia-php/compression", + "version": "0.1.2", "source": { "type": "git", - "url": "https://github.com/utopia-php/di.git", - "reference": "22490c95f7ac3898ed1c33f1b1b5dd577305ee31" + "url": "https://github.com/utopia-php/compression.git", + "reference": "6062f70596415f8d5de40a589367b0eb2a435f98" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/di/zipball/22490c95f7ac3898ed1c33f1b1b5dd577305ee31", - "reference": "22490c95f7ac3898ed1c33f1b1b5dd577305ee31", + "url": "https://api.github.com/repos/utopia-php/compression/zipball/6062f70596415f8d5de40a589367b0eb2a435f98", + "reference": "6062f70596415f8d5de40a589367b0eb2a435f98", "shasum": "" }, "require": { - "php": ">=8.2" + "php": ">=8.0" }, "require-dev": { - "laravel/pint": "^1.2", - "phpbench/phpbench": "^1.2", - "phpstan/phpstan": "^1.10", - "phpunit/phpunit": "^9.5.25", - "swoole/ide-helper": "4.8.3" + "laravel/pint": "1.2.*", + "phpunit/phpunit": "^9.3", + "vimeo/psalm": "4.0.1" }, "type": "library", "autoload": { "psr-4": { - "Utopia\\": "src/", - "Tests\\E2E\\": "tests/e2e" + "Utopia\\Compression\\": "src/Compression" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], - "description": "A simple and lite library for managing dependency injections", + "description": "A simple Compression library to handle file compression", "keywords": [ + "compression", "framework", - "http", "php", - "upf" + "upf", + "utopia" ], "support": { - "issues": "https://github.com/utopia-php/di/issues", - "source": "https://github.com/utopia-php/di/tree/0.1.0" + "issues": "https://github.com/utopia-php/compression/issues", + "source": "https://github.com/utopia-php/compression/tree/0.1.2" }, - "time": "2024-08-08T14:35:19+00:00" + "time": "2024-11-08T14:59:54+00:00" }, { "name": "utopia-php/framework", - "version": "1.0.2", + "version": "0.33.15", "source": { "type": "git", "url": "https://github.com/utopia-php/http.git", - "reference": "fc63ec61c720190a5ea5bb484c615145850951e6" + "reference": "83b0628900c2c53e8c3efbf069f3e13050295edc" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/http/zipball/fc63ec61c720190a5ea5bb484c615145850951e6", - "reference": "fc63ec61c720190a5ea5bb484c615145850951e6", + "url": "https://api.github.com/repos/utopia-php/http/zipball/83b0628900c2c53e8c3efbf069f3e13050295edc", + "reference": "83b0628900c2c53e8c3efbf069f3e13050295edc", "shasum": "" }, "require": { - "ext-swoole": "*", - "php": ">=8.0", - "utopia-php/servers": "0.1.*" + "php": ">=8.1", + "utopia-php/compression": "0.1.*", + "utopia-php/telemetry": "0.1.*" }, "require-dev": { - "ext-xdebug": "*", "laravel/pint": "^1.2", "phpbench/phpbench": "^1.2", "phpstan/phpstan": "^1.10", - "phpunit/phpunit": "^9.5.25", - "swoole/ide-helper": "4.8.3" + "phpunit/phpunit": "^9.5.25" }, "type": "library", "autoload": { @@ -349,18 +2131,17 @@ "license": [ "MIT" ], - "description": "A simple, light and advanced PHP HTTP framework", + "description": "A simple, light and advanced PHP framework", "keywords": [ "framework", - "http", "php", "upf" ], "support": { "issues": "https://github.com/utopia-php/http/issues", - "source": "https://github.com/utopia-php/http/tree/1.0.2" + "source": "https://github.com/utopia-php/http/tree/0.33.15" }, - "time": "2024-09-10T09:04:19+00:00" + "time": "2024-12-10T13:07:04+00:00" }, { "name": "utopia-php/mongo", @@ -423,57 +2204,54 @@ "time": "2023-09-01T17:25:28+00:00" }, { - "name": "utopia-php/servers", - "version": "0.1.1", + "name": "utopia-php/telemetry", + "version": "0.1.0", "source": { "type": "git", - "url": "https://github.com/utopia-php/servers.git", - "reference": "fd5c8d32778f265256c1936372a071b944f5ba8a" + "url": "https://github.com/utopia-php/telemetry.git", + "reference": "d35f2f0632f4ee0be63fb7ace6a94a6adda71a80" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/servers/zipball/fd5c8d32778f265256c1936372a071b944f5ba8a", - "reference": "fd5c8d32778f265256c1936372a071b944f5ba8a", + "url": "https://api.github.com/repos/utopia-php/telemetry/zipball/d35f2f0632f4ee0be63fb7ace6a94a6adda71a80", + "reference": "d35f2f0632f4ee0be63fb7ace6a94a6adda71a80", "shasum": "" }, "require": { + "ext-opentelemetry": "*", + "ext-protobuf": "*", + "nyholm/psr7": "^1.8", + "open-telemetry/exporter-otlp": "^1.1", + "open-telemetry/sdk": "^1.1", "php": ">=8.0", - "utopia-php/di": "0.1.*" + "symfony/http-client": "^7.1" }, "require-dev": { - "laravel/pint": "^0.2.3", - "phpstan/phpstan": "^1.8", - "phpunit/phpunit": "^9.5.5" + "laravel/pint": "^1.2", + "phpbench/phpbench": "^1.2", + "phpstan/phpstan": "^1.10", + "phpunit/phpunit": "^9.5.25" }, "type": "library", "autoload": { "psr-4": { - "Utopia\\Servers\\": "src/Servers" + "Utopia\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], - "authors": [ - { - "name": "Team Appwrite", - "email": "team@appwrite.io" - } - ], - "description": "A base library for building Utopia style servers.", "keywords": [ "framework", "php", - "servers", - "upf", - "utopia" + "upf" ], "support": { - "issues": "https://github.com/utopia-php/servers/issues", - "source": "https://github.com/utopia-php/servers/tree/0.1.1" + "issues": "https://github.com/utopia-php/telemetry/issues", + "source": "https://github.com/utopia-php/telemetry/tree/0.1.0" }, - "time": "2024-09-06T02:25:56+00:00" + "time": "2024-11-13T10:29:53+00:00" } ], "packages-dev": [ @@ -612,16 +2390,16 @@ }, { "name": "laravel/pint", - "version": "v1.17.3", + "version": "v1.19.0", "source": { "type": "git", "url": "https://github.com/laravel/pint.git", - "reference": "9d77be916e145864f10788bb94531d03e1f7b482" + "reference": "8169513746e1bac70c85d6ea1524d9225d4886f0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/pint/zipball/9d77be916e145864f10788bb94531d03e1f7b482", - "reference": "9d77be916e145864f10788bb94531d03e1f7b482", + "url": "https://api.github.com/repos/laravel/pint/zipball/8169513746e1bac70c85d6ea1524d9225d4886f0", + "reference": "8169513746e1bac70c85d6ea1524d9225d4886f0", "shasum": "" }, "require": { @@ -632,13 +2410,13 @@ "php": "^8.1.0" }, "require-dev": { - "friendsofphp/php-cs-fixer": "^3.64.0", - "illuminate/view": "^10.48.20", - "larastan/larastan": "^2.9.8", - "laravel-zero/framework": "^10.4.0", + "friendsofphp/php-cs-fixer": "^3.66.0", + "illuminate/view": "^10.48.25", + "larastan/larastan": "^2.9.12", + "laravel-zero/framework": "^10.48.25", "mockery/mockery": "^1.6.12", - "nunomaduro/termwind": "^1.15.1", - "pestphp/pest": "^2.35.1" + "nunomaduro/termwind": "^1.17.0", + "pestphp/pest": "^2.36.0" }, "bin": [ "builds/pint" @@ -674,20 +2452,20 @@ "issues": "https://github.com/laravel/pint/issues", "source": "https://github.com/laravel/pint" }, - "time": "2024-09-03T15:00:28+00:00" + "time": "2024-12-30T16:20:10+00:00" }, { "name": "myclabs/deep-copy", - "version": "1.12.0", + "version": "1.12.1", "source": { "type": "git", "url": "https://github.com/myclabs/DeepCopy.git", - "reference": "3a6b9a42cd8f8771bd4295d13e1423fa7f3d942c" + "reference": "123267b2c49fbf30d78a7b2d333f6be754b94845" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/3a6b9a42cd8f8771bd4295d13e1423fa7f3d942c", - "reference": "3a6b9a42cd8f8771bd4295d13e1423fa7f3d942c", + "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/123267b2c49fbf30d78a7b2d333f6be754b94845", + "reference": "123267b2c49fbf30d78a7b2d333f6be754b94845", "shasum": "" }, "require": { @@ -726,7 +2504,7 @@ ], "support": { "issues": "https://github.com/myclabs/DeepCopy/issues", - "source": "https://github.com/myclabs/DeepCopy/tree/1.12.0" + "source": "https://github.com/myclabs/DeepCopy/tree/1.12.1" }, "funding": [ { @@ -734,7 +2512,7 @@ "type": "tidelift" } ], - "time": "2024-06-12T14:39:25+00:00" + "time": "2024-11-08T17:47:46+00:00" }, { "name": "nikic/php-parser", @@ -946,16 +2724,16 @@ }, { "name": "phpstan/phpstan", - "version": "1.11.11", + "version": "1.12.15", "source": { "type": "git", "url": "https://github.com/phpstan/phpstan.git", - "reference": "707c2aed5d8d0075666e673a5e71440c1d01a5a3" + "reference": "c91d4e8bc056f46cf653656e6f71004b254574d1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpstan/zipball/707c2aed5d8d0075666e673a5e71440c1d01a5a3", - "reference": "707c2aed5d8d0075666e673a5e71440c1d01a5a3", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/c91d4e8bc056f46cf653656e6f71004b254574d1", + "reference": "c91d4e8bc056f46cf653656e6f71004b254574d1", "shasum": "" }, "require": { @@ -1000,7 +2778,7 @@ "type": "github" } ], - "time": "2024-08-19T14:37:29+00:00" + "time": "2025-01-05T16:40:22+00:00" }, { "name": "phpunit/php-code-coverage", @@ -1323,16 +3101,16 @@ }, { "name": "phpunit/phpunit", - "version": "9.6.21", + "version": "9.6.22", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/phpunit.git", - "reference": "de6abf3b6f8dd955fac3caad3af7a9504e8c2ffa" + "reference": "f80235cb4d3caa59ae09be3adf1ded27521d1a9c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/de6abf3b6f8dd955fac3caad3af7a9504e8c2ffa", - "reference": "de6abf3b6f8dd955fac3caad3af7a9504e8c2ffa", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/f80235cb4d3caa59ae09be3adf1ded27521d1a9c", + "reference": "f80235cb4d3caa59ae09be3adf1ded27521d1a9c", "shasum": "" }, "require": { @@ -1343,7 +3121,7 @@ "ext-mbstring": "*", "ext-xml": "*", "ext-xmlwriter": "*", - "myclabs/deep-copy": "^1.12.0", + "myclabs/deep-copy": "^1.12.1", "phar-io/manifest": "^2.0.4", "phar-io/version": "^3.2.1", "php": ">=7.3", @@ -1406,7 +3184,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/phpunit/issues", "security": "https://github.com/sebastianbergmann/phpunit/security/policy", - "source": "https://github.com/sebastianbergmann/phpunit/tree/9.6.21" + "source": "https://github.com/sebastianbergmann/phpunit/tree/9.6.22" }, "funding": [ { @@ -1422,60 +3200,7 @@ "type": "tidelift" } ], - "time": "2024-09-19T10:50:18+00:00" - }, - { - "name": "psr/container", - "version": "2.0.2", - "source": { - "type": "git", - "url": "https://github.com/php-fig/container.git", - "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/php-fig/container/zipball/c71ecc56dfe541dbd90c5360474fbc405f8d5963", - "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963", - "shasum": "" - }, - "require": { - "php": ">=7.4.0" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "2.0.x-dev" - } - }, - "autoload": { - "psr-4": { - "Psr\\Container\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "PHP-FIG", - "homepage": "https://www.php-fig.org/" - } - ], - "description": "Common Container Interface (PHP FIG PSR-11)", - "homepage": "https://github.com/php-fig/container", - "keywords": [ - "PSR-11", - "container", - "container-interface", - "container-interop", - "psr" - ], - "support": { - "issues": "https://github.com/php-fig/container/issues", - "source": "https://github.com/php-fig/container/tree/2.0.2" - }, - "time": "2021-11-05T16:47:00+00:00" + "time": "2024-12-05T13:48:26+00:00" }, { "name": "rregeer/phpunit-coverage-check", @@ -2518,73 +4243,6 @@ }, "time": "2024-06-17T05:45:20+00:00" }, - { - "name": "symfony/deprecation-contracts", - "version": "v3.5.0", - "source": { - "type": "git", - "url": "https://github.com/symfony/deprecation-contracts.git", - "reference": "0e0d29ce1f20deffb4ab1b016a7257c4f1e789a1" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/0e0d29ce1f20deffb4ab1b016a7257c4f1e789a1", - "reference": "0e0d29ce1f20deffb4ab1b016a7257c4f1e789a1", - "shasum": "" - }, - "require": { - "php": ">=8.1" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-main": "3.5-dev" - }, - "thanks": { - "name": "symfony/contracts", - "url": "https://github.com/symfony/contracts" - } - }, - "autoload": { - "files": [ - "function.php" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Nicolas Grekas", - "email": "p@tchwork.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "A generic function and convention to trigger deprecation notices", - "homepage": "https://symfony.com", - "support": { - "source": "https://github.com/symfony/deprecation-contracts/tree/v3.5.0" - }, - "funding": [ - { - "url": "https://symfony.com/sponsor", - "type": "custom" - }, - { - "url": "https://github.com/fabpot", - "type": "github" - }, - { - "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", - "type": "tidelift" - } - ], - "time": "2024-04-18T09:32:20+00:00" - }, { "name": "theseer/tokenizer", "version": "1.2.3", @@ -2637,29 +4295,25 @@ }, { "name": "utopia-php/cli", - "version": "0.19.0", + "version": "0.14.0", "source": { "type": "git", "url": "https://github.com/utopia-php/cli.git", - "reference": "f8af1d6087f498bc1f0191750a118d357ded9948" + "reference": "c30ef985a4e739758a0d95eb0706b357b6d8c086" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/cli/zipball/f8af1d6087f498bc1f0191750a118d357ded9948", - "reference": "f8af1d6087f498bc1f0191750a118d357ded9948", + "url": "https://api.github.com/repos/utopia-php/cli/zipball/c30ef985a4e739758a0d95eb0706b357b6d8c086", + "reference": "c30ef985a4e739758a0d95eb0706b357b6d8c086", "shasum": "" }, "require": { "php": ">=7.4", - "utopia-php/di": "0.1.*", - "utopia-php/framework": "1.0.*" + "utopia-php/framework": "0.*.*" }, "require-dev": { - "laravel/pint": "1.2.*", - "phpstan/phpstan": "^1.10", "phpunit/phpunit": "^9.3", - "squizlabs/php_codesniffer": "^3.6", - "swoole/ide-helper": "4.8.8" + "squizlabs/php_codesniffer": "^3.6" }, "type": "library", "autoload": { @@ -2671,6 +4325,12 @@ "license": [ "MIT" ], + "authors": [ + { + "name": "Eldad Fux", + "email": "eldad@appwrite.io" + } + ], "description": "A simple CLI library to manage command line applications", "keywords": [ "cli", @@ -2682,9 +4342,9 @@ ], "support": { "issues": "https://github.com/utopia-php/cli/issues", - "source": "https://github.com/utopia-php/cli/tree/0.19.0" + "source": "https://github.com/utopia-php/cli/tree/0.14.0" }, - "time": "2024-09-05T15:46:56+00:00" + "time": "2022-10-09T10:19:07+00:00" } ], "aliases": [], @@ -2693,9 +4353,9 @@ "prefer-stable": false, "prefer-lowest": false, "platform": { + "php": ">=8.3", "ext-pdo": "*", - "ext-mbstring": "*", - "php": ">=8.0" + "ext-mbstring": "*" }, "platform-dev": {}, "plugin-api-version": "2.6.0" diff --git a/dev/xdebug.ini b/dev/xdebug.ini index 8e54265cb..9fdfa2d76 100644 --- a/dev/xdebug.ini +++ b/dev/xdebug.ini @@ -1,8 +1,13 @@ -zend_extension=xdebug +zend_extension = xdebug.so [xdebug] -xdebug.mode=develop,debug,profile +xdebug.mode = develop,debug,profile +xdebug.start_with_request = yes +xdebug.use_compression=false xdebug.client_host=host.docker.internal -xdebug.start_with_request=yes -xdebug.output_dir=/tmp/xdebug -xdebug.use_compression=false \ No newline at end of file +xdebug.client_port = 9003 +xdebug.log = /tmp/xdebug.log + +xdebug.var_display_max_depth = 10 +xdebug.var_display_max_children = 256 +xdebug.var_display_max_data = 4096 diff --git a/docker-compose.yml b/docker-compose.yml index 23b135ba9..953b69838 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -5,7 +5,7 @@ services: build: context: . args: - DEBUG: false + DEBUG: true networks: - database volumes: @@ -14,25 +14,35 @@ services: - ./tests:/usr/src/code/tests - ./dev:/usr/src/code/dev - ./phpunit.xml:/usr/src/code/phpunit.xml - ports: - - "8708:8708" + - ./dev/xdebug.ini:/usr/local/etc/php/conf.d/xdebug.ini adminer: image: adminer container_name: utopia-adminer restart: always ports: - - "8760:8080" + - "8700:8080" networks: - database postgres: - image: postgres:13 + image: postgres:16.4 container_name: utopia-postgres networks: - database ports: - - "8700:5432" + - "8701:5432" + environment: + POSTGRES_USER: root + POSTGRES_PASSWORD: password + + postgres-mirror: + image: postgres:16.4 + container_name: utopia-postgres-mirror + networks: + - database + ports: + - "8702:5432" environment: POSTGRES_USER: root POSTGRES_PASSWORD: password @@ -44,7 +54,18 @@ services: networks: - database ports: - - "8701:3306" + - "8703:3306" + environment: + - MYSQL_ROOT_PASSWORD=password + + mariadb-mirror: + image: mariadb:10.11 + container_name: utopia-mariadb-mirror + command: mariadbd --max_allowed_packet=1G + networks: + - database + ports: + - "8704:3306" environment: - MYSQL_ROOT_PASSWORD=password @@ -54,7 +75,7 @@ services: networks: - database ports: - - "8702:27017" + - "8705:27017" environment: MONGO_INITDB_ROOT_USERNAME: root MONGO_INITDB_ROOT_PASSWORD: example @@ -65,7 +86,23 @@ services: networks: - database ports: - - "8703:3307" + - "8706:3307" + environment: + MYSQL_ROOT_PASSWORD: password + MYSQL_DATABASE: default + MYSQL_USER: user + MYSQL_PASSWORD: password + MYSQL_TCP_PORT: 3307 + cap_add: + - SYS_NICE + + mysql-mirror: + image: mysql:8.0.33 + container_name: utopia-mysql-mirror + networks: + - database + ports: + - "8707:3307" environment: MYSQL_ROOT_PASSWORD: password MYSQL_DATABASE: default @@ -76,10 +113,18 @@ services: - SYS_NICE redis: - image: redis:6.0-alpine + image: redis:7.4.1-alpine3.20 container_name: utopia-redis ports: - - "8706:6379" + - "8708:6379" + networks: + - database + + redis-mirror: + image: redis:7.4.1-alpine3.20 + container_name: utopia-redis-mirror + ports: + - "8709:6379" networks: - database diff --git a/pint.json b/pint.json index e0bbb8026..f5b56a98d 100644 --- a/pint.json +++ b/pint.json @@ -1,5 +1,8 @@ { "preset": "psr12", + "exclude": [ + "vendor" + ], "rules": { "array_indentation": true, "single_import_per_statement": true, diff --git a/src/Database/Adapter.php b/src/Database/Adapter.php index a5cffd444..a21ce60be 100644 --- a/src/Database/Adapter.php +++ b/src/Database/Adapter.php @@ -6,7 +6,7 @@ use Utopia\Database\Exception as DatabaseException; use Utopia\Database\Exception\Duplicate as DuplicateException; use Utopia\Database\Exception\Timeout as TimeoutException; -use Utopia\Database\Validator\Authorization; +use Utopia\Database\Exception\Transaction as TransactionException; abstract class Adapter { @@ -37,42 +37,13 @@ abstract class Adapter */ protected array $metadata = []; - /** - * @var Authorization - */ - protected Authorization $authorization; - - /** - * @param Authorization $authorization - * - * @return $this - */ - public function setAuthorization(Authorization $authorization): self - { - $this->authorization = $authorization; - - return $this; - } - - /** - * @return $this - */ - public function clearTransformations(): self - { - $this->transformations = [ - '*' => [], - ]; - - return $this; - } - /** * @param string $key * @param mixed $value * * @return $this */ - public function setDebug(string $key, mixed $value): self + public function setDebug(string $key, mixed $value): static { $this->debug[$key] = $value; @@ -88,9 +59,9 @@ public function getDebug(): array } /** - * @return self + * @return static */ - public function resetDebug(): self + public function resetDebug(): static { $this->debug = []; @@ -226,7 +197,7 @@ public function getTenant(): ?int * @param mixed $value * @return $this */ - public function setMetadata(string $key, mixed $value): self + public function setMetadata(string $key, mixed $value): static { $this->metadata[$key] = $value; @@ -257,13 +228,42 @@ public function getMetadata(): array * * @return $this */ - public function resetMetadata(): self + public function resetMetadata(): static { $this->metadata = []; return $this; } + /** + * Set a global timeout for database queries in milliseconds. + * + * This function allows you to set a maximum execution time for all database + * queries executed using the library, or a specific event specified by the + * event parameter. Once this timeout is set, any database query that takes + * longer than the specified time will be automatically terminated by the library, + * and an appropriate error or exception will be raised to handle the timeout condition. + * + * @param int $milliseconds The timeout value in milliseconds for database queries. + * @param string $event The event the timeout should fire fore + * @return void + * + * @throws Exception The provided timeout value must be greater than or equal to 0. + */ + abstract public function setTimeout(int $milliseconds, string $event = Database::EVENT_ALL): void; + + /** + * Clears a global timeout for database queries. + * + * @param string $event + * @return void + */ + public function clearTimeout(string $event): void + { + // Clear existing callback + $this->before($event, 'timeout', null); + } + /** * Start a new transaction. * @@ -316,16 +316,36 @@ public function inTransaction(): bool */ public function withTransaction(callable $callback): mixed { - $this->startTransaction(); - - try { - $result = $callback(); - $this->commitTransaction(); - return $result; - } catch (\Throwable $e) { - $this->rollbackTransaction(); - throw $e; + for ($attempts = 0; $attempts < 3; $attempts++) { + try { + $this->startTransaction(); + $result = $callback(); + $this->commitTransaction(); + return $result; + } catch (\Throwable $action) { + try { + $this->rollbackTransaction(); + } catch (\Throwable $rollback) { + if ($attempts < 2) { + \usleep(5000); // 5ms + continue; + } + + $this->inTransaction = 0; + throw $rollback; + } + + if ($attempts < 2) { + \usleep(5000); // 5ms + continue; + } + + $this->inTransaction = 0; + throw $action; + } } + + throw new TransactionException('Failed to execute transaction'); } /** @@ -334,9 +354,9 @@ public function withTransaction(callable $callback): mixed * @param string $event * @param string $name * @param ?callable $callback - * @return self + * @return static */ - public function before(string $event, string $name = '', ?callable $callback = null): self + public function before(string $event, string $name = '', ?callable $callback = null): static { if (!isset($this->transformations[$event])) { $this->transformations[$event] = []; @@ -425,6 +445,14 @@ abstract public function createCollection(string $name, array $attributes = [], */ abstract public function deleteCollection(string $id): bool; + /** + * Analyze a collection updating it's metadata on the database engine + * + * @param string $collection + * @return bool + */ + abstract public function analyzeCollection(string $collection): bool; + /** * Create Attribute * @@ -453,7 +481,7 @@ abstract public function createAttribute(string $collection, string $id, string * * @return bool */ - abstract public function updateAttribute(string $collection, string $id, string $type, int $size, bool $signed = true, bool $array = false, string $newKey = null): bool; + abstract public function updateAttribute(string $collection, string $id, string $type, int $size, bool $signed = true, bool $array = false, ?string $newKey = null): bool; /** * Delete Attribute @@ -717,6 +745,28 @@ abstract public function getLimitForAttributes(): int; */ abstract public function getLimitForIndexes(): int; + /** + * @return int + */ + abstract public function getMaxIndexLength(): int; + + /** + * Get the minimum supported DateTime value + * + * @return \DateTime + */ + abstract public function getMinDateTime(): \DateTime; + + /** + * Get the maximum supported DateTime value + * + * @return \DateTime + */ + public function getMaxDateTime(): \DateTime + { + return new \DateTime('9999-12-31 23:59:59'); + } + /** * Is schemas supported? * @@ -731,6 +781,13 @@ abstract public function getSupportForSchemas(): bool; */ abstract public function getSupportForAttributes(): bool; + /** + * Are schema attributes supported? + * + * @return bool + */ + abstract public function getSupportForSchemaAttributes(): bool; + /** * Is index supported? * @@ -804,6 +861,20 @@ abstract public function getSupportForBatchOperations(): bool; */ abstract public function getSupportForAttributeResizing(): bool; + /** + * Is get connection id supported? + * + * @return bool + */ + abstract public function getSupportForGetConnectionId(): bool; + + /** + * Is cast index as array supported? + * + * @return bool + */ + abstract public function getSupportForCastIndexArray(): bool; + /** * Get current attribute count from collection document * @@ -901,7 +972,7 @@ protected function getAttributeSelections(array $queries): array */ public function filter(string $value): string { - $value = \preg_replace("/[^A-Za-z0-9\_\-]/", '', $value); + $value = \preg_replace("/[^A-Za-z0-9_\-]/", '', $value); if (\is_null($value)) { throw new DatabaseException('Failed to filter key'); @@ -953,45 +1024,25 @@ public function escapeWildcards(string $value): string abstract public function increaseDocumentAttribute(string $collection, string $id, string $attribute, int|float $value, string $updatedAt, int|float|null $min = null, int|float|null $max = null): bool; /** - * @return int - */ - abstract public function getMaxIndexLength(): int; - - - /** - * Set a global timeout for database queries in milliseconds. - * - * This function allows you to set a maximum execution time for all database - * queries executed using the library, or a specific event specified by the - * event parameter. Once this timeout is set, any database query that takes - * longer than the specified time will be automatically terminated by the library, - * and an appropriate error or exception will be raised to handle the timeout condition. - * - * @param int $milliseconds The timeout value in milliseconds for database queries. - * @param string $event The event the timeout should fire fore - * @return void + * Returns the connection ID identifier * - * @throws Exception The provided timeout value must be greater than or equal to 0. + * @return string */ - abstract public function setTimeout(int $milliseconds, string $event = Database::EVENT_ALL): void; + abstract public function getConnectionId(): string; /** - * Clears a global timeout for database queries. + * Get List of internal index keys names * - * @param string $event - * @return void + * @return array */ - public function clearTimeout(string $event): void - { - // Clear existing callback - $this->before($event, 'timeout', null); - } + abstract public function getInternalIndexesKeys(): array; /** - * Analyze a collection updating it's metadata on the database engine + * Get Schema Attributes * * @param string $collection - * @return bool + * @return array + * @throws DatabaseException */ - abstract public function analyzeCollection(string $collection): bool; + abstract public function getSchemaAttributes(string $collection): array; } diff --git a/src/Database/Adapter/MariaDB.php b/src/Database/Adapter/MariaDB.php index e98ba76a1..45d12e6fd 100644 --- a/src/Database/Adapter/MariaDB.php +++ b/src/Database/Adapter/MariaDB.php @@ -9,9 +9,11 @@ use Utopia\Database\Document; use Utopia\Database\Exception as DatabaseException; use Utopia\Database\Exception\Duplicate as DuplicateException; +use Utopia\Database\Exception\NotFound as NotFoundException; use Utopia\Database\Exception\Timeout as TimeoutException; use Utopia\Database\Exception\Truncate as TruncateException; use Utopia\Database\Query; +use Utopia\Database\Validator\Authorization; class MariaDB extends SQL { @@ -91,6 +93,23 @@ public function createCollection(string $name, array $attributes = [], array $in $attribute->getAttribute('array', false) ); + // Ignore relationships with virtual attributes + if ($attribute->getAttribute('type') === Database::VAR_RELATIONSHIP) { + $options = $attribute->getAttribute('options', []); + $relationType = $options['relationType'] ?? null; + $twoWay = $options['twoWay'] ?? false; + $side = $options['side'] ?? null; + + if ( + $relationType === Database::RELATION_MANY_TO_MANY + || ($relationType === Database::RELATION_ONE_TO_ONE && !$twoWay && $side === Database::RELATION_SIDE_CHILD) + || ($relationType === Database::RELATION_ONE_TO_MANY && $side === Database::RELATION_SIDE_PARENT) + || ($relationType === Database::RELATION_MANY_TO_ONE && $side === Database::RELATION_SIDE_CHILD) + ) { + continue; + } + } + $attributeStrings[$key] = "`{$attrId}` {$attrType}, "; } @@ -129,8 +148,8 @@ public function createCollection(string $name, array $attributes = [], array $in $indexStrings[$key] = "{$indexType} `{$indexId}` ({$indexAttributes}),"; } - $sql = " - CREATE TABLE IF NOT EXISTS {$this->getSQLTable($id)} ( + $collection = " + CREATE TABLE {$this->getSQLTable($id)} ( _id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, _uid VARCHAR(255) NOT NULL, _createdAt DATETIME(3) DEFAULT NULL, @@ -142,64 +161,59 @@ public function createCollection(string $name, array $attributes = [], array $in "; if ($this->sharedTables) { - $sql .= " + $collection .= " _tenant INT(11) UNSIGNED DEFAULT NULL, - UNIQUE KEY _uid (_tenant, _uid), + UNIQUE KEY _uid (_uid, _tenant), KEY _created_at (_tenant, _createdAt), KEY _updated_at (_tenant, _updatedAt), KEY _tenant_id (_tenant, _id) "; } else { - $sql .= " + $collection .= " UNIQUE KEY _uid (_uid), KEY _created_at (_createdAt), KEY _updated_at (_updatedAt) "; } - $sql .= ")"; - - $sql = $this->trigger(Database::EVENT_COLLECTION_CREATE, $sql); - - try { - $this->getPDO() - ->prepare($sql) - ->execute(); - - $sql = " - CREATE TABLE IF NOT EXISTS {$this->getSQLTable($id . '_perms')} ( - _id int(11) UNSIGNED NOT NULL AUTO_INCREMENT, - _type VARCHAR(12) NOT NULL, - _permission VARCHAR(255) NOT NULL, - _document VARCHAR(255) NOT NULL, - PRIMARY KEY (_id), - "; + $collection .= ")"; + $collection = $this->trigger(Database::EVENT_COLLECTION_CREATE, $collection); - if ($this->sharedTables) { - $sql .= " - _tenant INT(11) UNSIGNED DEFAULT NULL, - UNIQUE INDEX _index1 (_document, _tenant, _type, _permission), - INDEX _permission (_tenant, _permission, _type) - "; - } else { - $sql .= " - UNIQUE INDEX _index1 (_document, _type, _permission), - INDEX _permission (_permission, _type) - "; - } + $permissions = " + CREATE TABLE {$this->getSQLTable($id . '_perms')} ( + _id int(11) UNSIGNED NOT NULL AUTO_INCREMENT, + _type VARCHAR(12) NOT NULL, + _permission VARCHAR(255) NOT NULL, + _document VARCHAR(255) NOT NULL, + PRIMARY KEY (_id), + "; - $sql .= ")"; + if ($this->sharedTables) { + $permissions .= " + _tenant INT(11) UNSIGNED DEFAULT NULL, + UNIQUE INDEX _index1 (_document, _tenant, _type, _permission), + INDEX _permission (_tenant, _permission, _type) + "; + } else { + $permissions .= " + UNIQUE INDEX _index1 (_document, _type, _permission), + INDEX _permission (_permission, _type) + "; + } - $sql = $this->trigger(Database::EVENT_COLLECTION_CREATE, $sql); + $permissions .= ")"; + $permissions = $this->trigger(Database::EVENT_COLLECTION_CREATE, $permissions); + try { $this->getPDO() - ->prepare($sql) + ->prepare($collection) ->execute(); - } catch (\Exception $th) { + $this->getPDO() - ->prepare("DROP TABLE IF EXISTS {$this->getSQLTable($id)}, {$this->getSQLTable($id . '_perms')};") + ->prepare($permissions) ->execute(); - throw $th; + } catch (PDOException $e) { + throw $this->processException($e); } return true; @@ -311,6 +325,22 @@ public function deleteCollection(string $id): bool ->execute(); } + /** + * Analyze a collection updating it's metadata on the database engine + * + * @param string $collection + * @return bool + */ + public function analyzeCollection(string $collection): bool + { + $name = $this->filter($collection); + + $sql = "ANALYZE TABLE {$this->getSQLTable($name)}"; + + $stmt = $this->getPDO()->prepare($sql); + return $stmt->execute(); + } + /** * Create Attribute * @@ -338,8 +368,7 @@ public function createAttribute(string $collection, string $id, string $type, in ->prepare($sql) ->execute(); } catch (PDOException $e) { - $this->processException($e); - return false; + throw $this->processException($e); } } @@ -357,7 +386,7 @@ public function createAttribute(string $collection, string $id, string $type, in * @throws Exception * @throws PDOException */ - public function updateAttribute(string $collection, string $id, string $type, int $size, bool $signed = true, bool $array = false, string $newKey = null): bool + public function updateAttribute(string $collection, string $id, string $type, int $size, bool $signed = true, bool $array = false, ?string $newKey = null): bool { $name = $this->filter($collection); $id = $this->filter($id); @@ -377,8 +406,7 @@ public function updateAttribute(string $collection, string $id, string $type, in ->prepare($sql) ->execute(); } catch (PDOException $e) { - $this->processException($e); - return false; + throw $this->processException($e); } } @@ -401,9 +429,17 @@ public function deleteAttribute(string $collection, string $id, bool $array = fa $sql = $this->trigger(Database::EVENT_ATTRIBUTE_DELETE, $sql); - return $this->getPDO() - ->prepare($sql) - ->execute(); + try { + return $this->getPDO() + ->prepare($sql) + ->execute(); + } catch (PDOException $e) { + if ($e->getCode() === "42000" && $e->errorInfo[1] === 1091) { + return true; + } + + throw $this->processException($e); + } } /** @@ -426,9 +462,13 @@ public function renameAttribute(string $collection, string $old, string $new): b $sql = $this->trigger(Database::EVENT_ATTRIBUTE_UPDATE, $sql); - return $this->getPDO() - ->prepare($sql) - ->execute(); + try { + return $this->getPDO() + ->prepare($sql) + ->execute(); + } catch (PDOException $e) { + throw $this->processException($e); + } } /** @@ -708,7 +748,7 @@ public function createIndex(string $collection, string $id, string $type, array $collection = $this->getDocument(Database::METADATA, $collection); if ($collection->isEmpty()) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } $collectionAttributes = \json_decode($collection->getAttribute('attributes', []), true); @@ -730,7 +770,7 @@ public function createIndex(string $collection, string $id, string $type, array $attributes[$i] = "`{$attr}`{$length} {$order}"; - if (!empty($collectionAttribute['array']) && $this->castIndexArray()) { + if (!empty($collectionAttribute['array']) && $this->getSupportForCastIndexArray()) { $attributes[$i] = '(CAST(' . $attr . ' AS char(' . Database::ARRAY_INDEX_LENGTH . ') ARRAY))'; } } @@ -762,14 +802,6 @@ public function createIndex(string $collection, string $id, string $type, array } } - /** - * @return bool - */ - public function castIndexArray(): bool - { - return false; - } - /** * Delete Index * @@ -788,9 +820,17 @@ public function deleteIndex(string $collection, string $id): bool $sql = $this->trigger(Database::EVENT_INDEX_DELETE, $sql); - return $this->getPDO() - ->prepare($sql) - ->execute(); + try { + return $this->getPDO() + ->prepare($sql) + ->execute(); + } catch (PDOException $e) { + if ($e->getCode() === "42000" && $e->errorInfo[1] === 1091) { + return true; + } + + throw $e; + } } /** @@ -905,7 +945,6 @@ public function createDocument(string $collection, Document $document): Document } } - $stmt->execute(); $document['$internalId'] = $this->getDocument($collection, $document->getId(), [Query::select(['$internalId'])])->getInternalId(); @@ -913,16 +952,8 @@ public function createDocument(string $collection, Document $document): Document if (isset($stmtPermissions)) { $stmtPermissions->execute(); } - } catch (\Throwable $e) { - if ($e instanceof PDOException) { - switch ($e->getCode()) { - case 1062: - case 23000: - throw new DuplicateException('Duplicated document: ' . $e->getMessage(), previous: $e); - } - } - - throw $e; + } catch (PDOException $e) { + throw $this->processException($e); } return $document; @@ -948,7 +979,8 @@ public function createDocuments(string $collection, array $documents, int $batch try { $name = $this->filter($collection); - $batches = \array_chunk($documents, max(1, $batchSize)); + $batches = \array_chunk($documents, \max(1, $batchSize)); + $internalIds = []; foreach ($batches as $batch) { $bindIndex = 0; @@ -962,7 +994,9 @@ public function createDocuments(string $collection, array $documents, int $batch $attributes['_createdAt'] = $document->getCreatedAt(); $attributes['_updatedAt'] = $document->getUpdatedAt(); $attributes['_permissions'] = \json_encode($document->getPermissions()); + if (!empty($document->getInternalId())) { + $internalIds[$document->getId()] = true; $attributes['_id'] = $document->getInternalId(); } @@ -1041,16 +1075,18 @@ public function createDocuments(string $collection, array $documents, int $batch $stmtPermissions?->execute(); } } - } catch (\Throwable $e) { - if ($e instanceof PDOException) { - switch ($e->getCode()) { - case 1062: - case 23000: - throw new DuplicateException('Duplicated document: ' . $e->getMessage(), previous: $e); - } - } + } catch (PDOException $e) { + throw $this->processException($e); + } - throw $e; + foreach ($documents as $document) { + if (!isset($internalIds[$document->getId()])) { + $document['$internalId'] = $this->getDocument( + $collection, + $document->getId(), + [Query::select(['$internalId'])] + )->getInternalId(); + } } return $documents; @@ -1090,7 +1126,7 @@ public function updateDocument(string $collection, string $id, Document $documen "; if ($this->sharedTables) { - $sql .= ' AND _tenant = :_tenant'; + $sql .= ' AND (_tenant = :_tenant OR _tenant IS NULL)'; } $sql = $this->trigger(Database::EVENT_PERMISSIONS_READ, $sql); @@ -1167,7 +1203,7 @@ public function updateDocument(string $collection, string $id, Document $documen "; if ($this->sharedTables) { - $sql .= ' AND _tenant = :_tenant'; + $sql .= ' AND (_tenant = :_tenant OR _tenant IS NULL)'; } $removeQuery = $sql . $removeQuery; @@ -1254,7 +1290,7 @@ public function updateDocument(string $collection, string $id, Document $documen "; if ($this->sharedTables) { - $sql .= ' AND _tenant = :_tenant'; + $sql .= ' AND (_tenant = :_tenant OR _tenant IS NULL)'; } $sql = $this->trigger(Database::EVENT_DOCUMENT_UPDATE, $sql); @@ -1289,16 +1325,8 @@ public function updateDocument(string $collection, string $id, Document $documen $stmtAddPermissions->execute(); } - } catch (\Throwable $e) { - if ($e instanceof PDOException) { - switch ($e->getCode()) { - case 1062: - case 23000: - throw new DuplicateException('Duplicated document: ' . $e->getMessage(), previous: $e); - } - } - - throw $e; + } catch (PDOException $e) { + throw $this->processException($e); } return $document; @@ -1411,7 +1439,7 @@ public function updateDocuments(string $collection, Document $updates, array $do "; if ($this->sharedTables) { - $sql .= ' AND _tenant = :_tenant'; + $sql .= ' AND (_tenant = :_tenant OR _tenant IS NULL)'; } $sql = $this->trigger(Database::EVENT_PERMISSIONS_READ, $sql); @@ -1425,6 +1453,7 @@ public function updateDocuments(string $collection, Document $updates, array $do $permissionsStmt->execute(); $permissions = $permissionsStmt->fetchAll(); + $permissionsStmt->closeCursor(); $initial = []; foreach (Database::PERMISSIONS as $type) { @@ -1454,7 +1483,7 @@ public function updateDocuments(string $collection, Document $updates, array $do $tenantQuery = ''; if ($this->sharedTables) { - $tenantQuery = ' AND _tenant = :_tenant'; + $tenantQuery = ' AND (_tenant = :_tenant OR _tenant IS NULL)'; } $removeQueries[] = "( @@ -1590,7 +1619,7 @@ public function increaseDocumentAttribute(string $collection, string $id, string "; if ($this->sharedTables) { - $sql .= ' AND _tenant = :_tenant'; + $sql .= ' AND (_tenant = :_tenant OR _tenant IS NULL)'; } $sql .= $sqlMax . $sqlMin; @@ -1625,12 +1654,12 @@ public function deleteDocument(string $collection, string $id): bool $name = $this->filter($collection); $sql = " - DELETE FROM {$this->getSQLTable($name)} - WHERE _uid = :_uid + DELETE FROM {$this->getSQLTable($name)} + WHERE _uid = :_uid "; if ($this->sharedTables) { - $sql .= ' AND _tenant = :_tenant'; + $sql .= ' AND (_tenant = :_tenant OR _tenant IS NULL)'; } $sql = $this->trigger(Database::EVENT_DOCUMENT_DELETE, $sql); @@ -1649,7 +1678,7 @@ public function deleteDocument(string $collection, string $id): bool "; if ($this->sharedTables) { - $sql .= ' AND _tenant = :_tenant'; + $sql .= ' AND (_tenant = :_tenant OR _tenant IS NULL)'; } $sql = $this->trigger(Database::EVENT_PERMISSIONS_DELETE, $sql); @@ -1761,11 +1790,12 @@ public function deleteDocuments(string $collection, array $ids): int * @return array * @throws DatabaseException * @throws TimeoutException + * @throws Exception */ public function find(string $collection, array $queries = [], ?int $limit = 25, ?int $offset = null, array $orderAttributes = [], array $orderTypes = [], array $cursor = [], string $cursorDirection = Database::CURSOR_AFTER, string $forPermission = Database::PERMISSION_READ): array { $name = $this->filter($collection); - $roles = $this->authorization->getRoles(); + $roles = Authorization::getRoles(); $where = []; $orders = []; @@ -1851,12 +1881,12 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, $where[] = $conditions; } - if ($this->authorization->getStatus()) { + if (Authorization::$status) { $where[] = $this->getSQLPermissionsCondition($name, $roles, $forPermission); } if ($this->sharedTables) { - $where[] = "table_main._tenant = :_tenant"; + $where[] = "(table_main._tenant = :_tenant OR table_main._tenant IS NULL)"; } $sqlWhere = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : ''; @@ -1868,7 +1898,7 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, $sql = " SELECT {$this->getAttributeProjection($selections, 'table_main')} - FROM {$this->getSQLTable($name)} as table_main + FROM {$this->getSQLTable($name)} AS table_main {$sqlWhere} {$sqlOrder} {$sqlLimit}; @@ -1913,7 +1943,7 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, try { $stmt->execute(); } catch (PDOException $e) { - $this->processException($e); + throw $this->processException($e); } $results = $stmt->fetchAll(); @@ -1968,7 +1998,7 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, public function count(string $collection, array $queries = [], ?int $max = null): int { $name = $this->filter($collection); - $roles = $this->authorization->getRoles(); + $roles = Authorization::getRoles(); $where = []; $limit = \is_null($max) ? '' : 'LIMIT :max'; @@ -1979,12 +2009,12 @@ public function count(string $collection, array $queries = [], ?int $max = null) $where[] = $conditions; } - if ($this->authorization->getStatus()) { + if (Authorization::$status) { $where[] = $this->getSQLPermissionsCondition($name, $roles); } if ($this->sharedTables) { - $where[] = "table_main._tenant = :_tenant"; + $where[] = "(table_main._tenant = :_tenant OR table_main._tenant IS NULL)"; } $sqlWhere = !empty($where) @@ -2041,7 +2071,7 @@ public function count(string $collection, array $queries = [], ?int $max = null) public function sum(string $collection, string $attribute, array $queries = [], ?int $max = null): int|float { $name = $this->filter($collection); - $roles = $this->authorization->getRoles(); + $roles = Authorization::getRoles(); $where = []; $limit = \is_null($max) ? '' : 'LIMIT :max'; @@ -2051,12 +2081,12 @@ public function sum(string $collection, string $attribute, array $queries = [], $where[] = $this->getSQLCondition($query); } - if ($this->authorization->getStatus()) { + if (Authorization::$status) { $where[] = $this->getSQLPermissionsCondition($name, $roles); } if ($this->sharedTables) { - $where[] = "table_main._tenant = :_tenant"; + $where[] = "(table_main._tenant = :_tenant OR table_main._tenant IS NULL)"; } $sqlWhere = !empty($where) @@ -2283,6 +2313,16 @@ protected function getPDOType(mixed $value): int }; } + public function getMinDateTime(): \DateTime + { + return new \DateTime('1000-01-01 00:00:00'); + } + + public function getMaxDateTime(): \DateTime + { + return new \DateTime('9999-12-31 23:59:59'); + } + /** * Is fulltext Wildcard index supported? * @@ -2337,54 +2377,109 @@ public function setTimeout(int $milliseconds, string $event = Database::EVENT_AL } /** - * @param PDOException $e - * @throws TimeoutException - * @throws DuplicateException + * @return string */ - protected function processException(PDOException $e): void + public function getConnectionId(): string + { + $stmt = $this->getPDO()->query("SELECT CONNECTION_ID();"); + return $stmt->fetchColumn(); + } + + public function getInternalIndexesKeys(): array { - /** - * PDO and Swoole PDOProxy swap error codes and errorInfo - */ + return ['primary', '_created_at', '_updated_at', '_tenant_id']; + } + protected function processException(PDOException $e): \Exception + { // Timeout if ($e->getCode() === '70100' && isset($e->errorInfo[1]) && $e->errorInfo[1] === 1969) { - throw new TimeoutException($e->getMessage(), $e->getCode(), $e); + return new TimeoutException('Query timed out', $e->getCode(), $e); + } + + // Duplicate table + if ($e->getCode() === '42S01' && isset($e->errorInfo[1]) && $e->errorInfo[1] === 1050) { + return new DuplicateException('Collection already exists', $e->getCode(), $e); } // Duplicate column if ($e->getCode() === '42S21' && isset($e->errorInfo[1]) && $e->errorInfo[1] === 1060) { - throw new DuplicateException($e->getMessage(), $e->getCode(), $e); + return new DuplicateException('Attribute already exists', $e->getCode(), $e); + } + + // Duplicate index + if ($e->getCode() === '42000' && isset($e->errorInfo[1]) && $e->errorInfo[1] === 1061) { + return new DuplicateException('Index already exists', $e->getCode(), $e); + } + + // Duplicate row + if ($e->getCode() === '23000' && isset($e->errorInfo[1]) && $e->errorInfo[1] === 1062) { + return new DuplicateException('Document already exists', $e->getCode(), $e); } // Data is too big for column resize if (($e->getCode() === '22001' && isset($e->errorInfo[1]) && $e->errorInfo[1] === 1406) || ($e->getCode() === '01000' && isset($e->errorInfo[1]) && $e->errorInfo[1] === 1265)) { - throw new TruncateException('Resize would result in data truncation', $e->getCode(), $e); + return new TruncateException('Resize would result in data truncation', $e->getCode(), $e); } - // Duplicate index - if ($e->getCode() === '42000' && isset($e->errorInfo[1]) && $e->errorInfo[1] === 1061) { - throw new DuplicateException($e->getMessage(), $e->getCode(), $e); + // Unknown database + if ($e->getCode() === '42000' && isset($e->errorInfo[1]) && $e->errorInfo[1] === 1049) { + return new NotFoundException('Database not found', $e->getCode(), $e); } - throw $e; + return $e; } /** - * Analyze a collection updating it's metadata on the database engine + * Get Schema Attributes * * @param string $collection - * @return bool + * @return array + * @throws DatabaseException */ - public function analyzeCollection(string $collection): bool + public function getSchemaAttributes(string $collection): array { - $name = $this->filter($collection); + $schema = $this->getDatabase(); + $collection = $this->getNamespace().'_'.$this->filter($collection); - $sql = "ANALYZE TABLE {$this->getSQLTable($name)}"; + try { + $stmt = $this->getPDO()->prepare(' + SELECT + COLUMN_NAME as columnName, + COLUMN_DEFAULT as columnDefault, + IS_NULLABLE as isNullable, + DATA_TYPE as dataType, + CHARACTER_MAXIMUM_LENGTH as characterMaximumLength, + NUMERIC_PRECISION as numericPrecision, + NUMERIC_SCALE as numericScale, + DATETIME_PRECISION as datetimePrecision, + COLUMN_TYPE as columnType, + COLUMN_KEY as columnKey, + EXTRA as extra + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = :schema AND TABLE_NAME = :table + '); + $stmt->bindParam(':schema', $schema); + $stmt->bindParam(':table', $collection); + $stmt->execute(); + $results = $stmt->fetchAll(); + $stmt->closeCursor(); - $stmt = $this->getPDO()->prepare($sql); - return $stmt->execute(); + foreach ($results as $index => $document) { + $results[$index] = new Document($document); + } + + return $results; + + } catch (PDOException $e) { + throw new DatabaseException('Failed to get schema attributes', $e->getCode(), $e); + } + } + + public function getSupportForSchemaAttributes(): bool + { + return true; } } diff --git a/src/Database/Adapter/Mongo.php b/src/Database/Adapter/Mongo.php index b88d575cd..5df46e28e 100644 --- a/src/Database/Adapter/Mongo.php +++ b/src/Database/Adapter/Mongo.php @@ -57,6 +57,22 @@ public function __construct(Client $client) $this->client->connect(); } + public function setTimeout(int $milliseconds, string $event = Database::EVENT_ALL): void + { + if (!$this->getSupportForTimeouts()) { + return; + } + + $this->timeout = $milliseconds; + } + + public function clearTimeout(string $event): void + { + parent::clearTimeout($event); + + $this->timeout = null; + } + public function startTransaction(): bool { return true; @@ -106,7 +122,7 @@ public function create(string $name): bool * @return bool * @throws Exception */ - public function exists(string $database, string $collection = null): bool + public function exists(string $database, ?string $collection = null): bool { if (!\is_null($collection)) { $collection = $this->getNamespace() . "_" . $collection; @@ -320,6 +336,17 @@ public function deleteCollection(string $id): bool return (!!$this->getClient()->dropCollection($id)); } + /** + * Analyze a collection updating it's metadata on the database engine + * + * @param string $collection + * @return bool + */ + public function analyzeCollection(string $collection): bool + { + return false; + } + /** * Create Attribute * @@ -980,7 +1007,7 @@ public function deleteDocuments(string $collection, array $ids): int * * @return bool */ - public function updateAttribute(string $collection, string $id, string $type, int $size, bool $signed = true, bool $array = false, string $newKey = null): bool + public function updateAttribute(string $collection, string $id, string $type, int $size, bool $signed = true, bool $array = false, ?string $newKey = null): bool { if (!empty($newKey) && $newKey !== $id) { return $this->renameAttribute($collection, $id, $newKey); @@ -1020,8 +1047,8 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, } // permissions - if ($this->authorization->getStatus()) { // skip if authorization is disabled - $roles = \implode('|', $this->authorization->getRoles()); + if (Authorization::$status) { + $roles = \implode('|', Authorization::getRoles()); $filters['_permissions']['$in'] = [new Regex("{$forPermission}\(\".*(?:{$roles}).*\"\)", 'i')]; } @@ -1135,7 +1162,7 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, try { $results = $this->client->find($name, $filters, $options)->cursor->firstBatch ?? []; } catch (MongoException $e) { - $this->processException($e); + throw $this->processException($e); } if (empty($results)) { @@ -1296,8 +1323,8 @@ public function count(string $collection, array $queries = [], ?int $max = null) $filters = $this->buildFilters($queries); // permissions - if ($this->authorization->getStatus()) { // skip if authorization is disabled - $roles = \implode('|', $this->authorization->getRoles()); + if (Authorization::$status) { // skip if authorization is disabled + $roles = \implode('|', Authorization::getRoles()); $filters['_permissions']['$in'] = [new Regex("read\(\".*(?:{$roles}).*\"\)", 'i')]; } @@ -1324,8 +1351,8 @@ public function sum(string $collection, string $attribute, array $queries = [], $filters = $this->buildFilters($queries); // permissions - if ($this->authorization->getStatus()) { // skip if authorization is disabled - $roles = \implode('|', $this->authorization->getRoles()); + if (Authorization::$status) { // skip if authorization is disabled + $roles = \implode('|', Authorization::getRoles()); $filters['_permissions']['$in'] = [new Regex("read\(\".*(?:{$roles}).*\"\)", 'i')]; } @@ -1640,6 +1667,11 @@ public function getLimitForIndexes(): int return 64; } + public function getMinDateTime(): \DateTime + { + return new \DateTime('-9999-01-01 00:00:00'); + } + /** * Is schemas supported? * @@ -1647,7 +1679,7 @@ public function getLimitForIndexes(): int */ public function getSupportForSchemas(): bool { - return true; + return false; } /** @@ -1745,6 +1777,31 @@ public function getSupportForBatchOperations(): bool return false; } + /** + * Is get connection id supported? + * + * @return bool + */ + public function getSupportForGetConnectionId(): bool + { + return false; + } + + /** + * Is get schema attributes supported? + * + * @return bool + */ + public function getSupportForSchemaAttributes(): bool + { + return false; + } + + public function getSupportForCastIndexArray(): bool + { + return false; + } + /** * Get current attribute count from collection document * @@ -1874,17 +1931,13 @@ public function getKeywords(): array return []; } - /** - * @throws Timeout - * @throws Exception - */ - protected function processException(Exception $e): void + protected function processException(Exception $e): \Exception { if ($e->getCode() === 50) { - throw new Timeout($e->getMessage()); + return new Timeout('Query timed out', $e->getCode(), $e); } - throw $e; + return $e; } /** @@ -1895,31 +1948,19 @@ public function getMaxIndexLength(): int return 0; } - public function setTimeout(int $milliseconds, string $event = Database::EVENT_ALL): void + public function getConnectionId(): string { - if (!$this->getSupportForTimeouts()) { - return; - } - - $this->timeout = $milliseconds; + return '0'; } - public function clearTimeout(string $event): void + public function getInternalIndexesKeys(): array { - parent::clearTimeout($event); - - $this->timeout = null; + return []; } - /** - * Analyze a collection updating it's metadata on the database engine - * - * @param string $collection - * @return bool - */ - public function analyzeCollection(string $collection): bool + public function getSchemaAttributes(string $collection): array { - return false; + return []; } } diff --git a/src/Database/Adapter/MySQL.php b/src/Database/Adapter/MySQL.php index 99c82a647..60cd66ab9 100644 --- a/src/Database/Adapter/MySQL.php +++ b/src/Database/Adapter/MySQL.php @@ -5,9 +5,8 @@ use PDOException; use Utopia\Database\Database; use Utopia\Database\Exception as DatabaseException; -use Utopia\Database\Exception\Duplicate as DuplicateException; +use Utopia\Database\Exception\Dependency as DependencyException; use Utopia\Database\Exception\Timeout as TimeoutException; -use Utopia\Database\Exception\Truncate as TruncateException; class MySQL extends MariaDB { @@ -37,7 +36,7 @@ public function setTimeout(int $milliseconds, string $event = Database::EVENT_AL } /** - * Get Collection Size on disk + * Get size of collection on disk * @param string $collection * @return int * @throws DatabaseException @@ -76,46 +75,23 @@ public function getSizeOfCollectionOnDisk(string $collection): int return $size; } - /** - * @return bool - */ - public function castIndexArray(): bool + public function getSupportForCastIndexArray(): bool { return true; } - /** - * @param PDOException $e - * @throws TimeoutException - * @throws DuplicateException - */ - protected function processException(PDOException $e): void + protected function processException(PDOException $e): \Exception { - /** - * PDO and Swoole PDOProxy swap error codes and errorInfo - */ - // Timeout if ($e->getCode() === 'HY000' && isset($e->errorInfo[1]) && $e->errorInfo[1] === 3024) { - throw new TimeoutException($e->getMessage(), $e->getCode(), $e); - } - - // Duplicate column - if ($e->getCode() === '42S21' && isset($e->errorInfo[1]) && $e->errorInfo[1] === 1060) { - throw new DuplicateException($e->getMessage(), $e->getCode(), $e); - } - - // Duplicate index - if ($e->getCode() === '42000' && isset($e->errorInfo[1]) && $e->errorInfo[1] === 1061) { - throw new DuplicateException($e->getMessage(), $e->getCode(), $e); + return new TimeoutException('Query timed out', $e->getCode(), $e); } - // Data is too big for column resize - if (($e->getCode() === '22001' && isset($e->errorInfo[1]) && $e->errorInfo[1] === 1406) || - ($e->getCode() === '01000' && isset($e->errorInfo[1]) && $e->errorInfo[1] === 1265)) { - throw new TruncateException('Resize would result in data truncation', $e->getCode(), $e); + // Functional index dependency + if ($e->getCode() === 'HY000' && isset($e->errorInfo[1]) && $e->errorInfo[1] === 3837) { + return new DependencyException('Attribute cannot be deleted because it is used in an index', $e->getCode(), $e); } - throw $e; + return parent::processException($e); } } diff --git a/src/Database/Adapter/Postgres.php b/src/Database/Adapter/Postgres.php index 7d1746fa8..b55365961 100644 --- a/src/Database/Adapter/Postgres.php +++ b/src/Database/Adapter/Postgres.php @@ -5,14 +5,15 @@ use Exception; use PDO; use PDOException; -use Throwable; use Utopia\Database\Database; use Utopia\Database\Document; use Utopia\Database\Exception as DatabaseException; -use Utopia\Database\Exception\Duplicate; -use Utopia\Database\Exception\Timeout; +use Utopia\Database\Exception\Duplicate as DuplicateException; +use Utopia\Database\Exception\Timeout as TimeoutException; +use Utopia\Database\Exception\Transaction as TransactionException; use Utopia\Database\Exception\Truncate as TruncateException; use Utopia\Database\Query; +use Utopia\Database\Validator\Authorization; class Postgres extends SQL { @@ -25,6 +26,84 @@ class Postgres extends SQL * 4. Full-text search is different - to_tsvector() and to_tsquery() */ + /** + * @inheritDoc + */ + public function startTransaction(): bool + { + try { + if ($this->inTransaction === 0) { + if ($this->getPDO()->inTransaction()) { + $this->getPDO()->rollBack(); + } else { + // If no active transaction, this has no effect. + $this->getPDO()->prepare('ROLLBACK')->execute(); + } + + $result = $this->getPDO()->beginTransaction(); + } else { + $result = true; + } + } catch (PDOException $e) { + throw new TransactionException('Failed to start transaction: ' . $e->getMessage(), $e->getCode(), $e); + } + + if (!$result) { + throw new TransactionException('Failed to start transaction'); + } + + $this->inTransaction++; + + return $result; + } + + /** + * @inheritDoc + */ + public function rollbackTransaction(): bool + { + if ($this->inTransaction === 0) { + return false; + } + + try { + $result = $this->getPDO()->rollBack(); + $this->inTransaction = 0; + } catch (PDOException $e) { + throw new DatabaseException('Failed to rollback transaction: ' . $e->getMessage(), $e->getCode(), $e); + } + + if (!$result) { + throw new TransactionException('Failed to rollback transaction'); + } + + return $result; + } + + /** + * Returns Max Execution Time + * @param int $milliseconds + * @param string $event + * @return void + * @throws DatabaseException + */ + public function setTimeout(int $milliseconds, string $event = Database::EVENT_ALL): void + { + if (!$this->getSupportForTimeouts()) { + return; + } + if ($milliseconds <= 0) { + throw new DatabaseException('Timeout must be greater than 0'); + } + $this->before($event, 'timeout', function ($sql) use ($milliseconds) { + return " + SET statement_timeout = {$milliseconds}; + {$sql}; + SET statement_timeout = 0; + "; + }); + } + /** * Create Database * @@ -76,6 +155,7 @@ public function delete(string $name): bool * @param array $attributes * @param array $indexes * @return bool + * @throws DuplicateException */ public function createCollection(string $name, array $attributes = [], array $indexes = []): bool { @@ -97,13 +177,30 @@ public function createCollection(string $name, array $attributes = [], array $in $attribute->getAttribute('array', false) ); + // Ignore relationships with virtual attributes + if ($attribute->getAttribute('type') === Database::VAR_RELATIONSHIP) { + $options = $attribute->getAttribute('options', []); + $relationType = $options['relationType'] ?? null; + $twoWay = $options['twoWay'] ?? false; + $side = $options['side'] ?? null; + + if ( + $relationType === Database::RELATION_MANY_TO_MANY + || ($relationType === Database::RELATION_ONE_TO_ONE && !$twoWay && $side === Database::RELATION_SIDE_CHILD) + || ($relationType === Database::RELATION_ONE_TO_MANY && $side === Database::RELATION_SIDE_PARENT) + || ($relationType === Database::RELATION_MANY_TO_ONE && $side === Database::RELATION_SIDE_CHILD) + ) { + continue; + } + } + $attributeStrings[] = "\"{$attrId}\" {$attrType}, "; } $sqlTenant = $this->sharedTables ? '_tenant INTEGER DEFAULT NULL,' : ''; - $sql = " - CREATE TABLE IF NOT EXISTS {$this->getSQLTable($id)} ( + $collection = " + CREATE TABLE {$this->getSQLTable($id)} ( _id SERIAL NOT NULL, _uid VARCHAR(255) NOT NULL, ". $sqlTenant ." @@ -114,59 +211,60 @@ public function createCollection(string $name, array $attributes = [], array $in PRIMARY KEY (_id) ); "; + if ($this->sharedTables) { - $sql .= " + $collection .= " CREATE UNIQUE INDEX \"{$namespace}_{$this->tenant}_{$id}_uid\" ON {$this->getSQLTable($id)} (LOWER(_uid), _tenant); CREATE INDEX \"{$namespace}_{$this->tenant}_{$id}_created\" ON {$this->getSQLTable($id)} (_tenant, \"_createdAt\"); CREATE INDEX \"{$namespace}_{$this->tenant}_{$id}_updated\" ON {$this->getSQLTable($id)} (_tenant, \"_updatedAt\"); CREATE INDEX \"{$namespace}_{$this->tenant}_{$id}_tenant_id\" ON {$this->getSQLTable($id)} (_tenant, _id); "; } else { - $sql .= " + $collection .= " CREATE UNIQUE INDEX \"{$namespace}_{$id}_uid\" ON {$this->getSQLTable($id)} (LOWER(_uid)); CREATE INDEX \"{$namespace}_{$id}_created\" ON {$this->getSQLTable($id)} (\"_createdAt\"); CREATE INDEX \"{$namespace}_{$id}_updated\" ON {$this->getSQLTable($id)} (\"_updatedAt\"); "; } - $sql = $this->trigger(Database::EVENT_COLLECTION_CREATE, $sql); + $collection = $this->trigger(Database::EVENT_COLLECTION_CREATE, $collection); - $stmt = $this->getPDO()->prepare($sql); - - try { - $stmt->execute(); + $permissions = " + CREATE TABLE {$this->getSQLTable($id . '_perms')} ( + _id SERIAL NOT NULL, + _tenant INTEGER DEFAULT NULL, + _type VARCHAR(12) NOT NULL, + _permission VARCHAR(255) NOT NULL, + _document VARCHAR(255) NOT NULL, + PRIMARY KEY (_id) + ); + "; - $sql = " - CREATE TABLE IF NOT EXISTS {$this->getSQLTable($id . '_perms')} ( - _id SERIAL NOT NULL, - _tenant INTEGER DEFAULT NULL, - _type VARCHAR(12) NOT NULL, - _permission VARCHAR(255) NOT NULL, - _document VARCHAR(255) NOT NULL, - PRIMARY KEY (_id) - ); - "; + if ($this->sharedTables) { + $permissions .= " + CREATE UNIQUE INDEX \"{$namespace}_{$this->tenant}_{$id}_ukey\" + ON {$this->getSQLTable($id. '_perms')} USING btree (_tenant,_document,_type,_permission); + CREATE INDEX \"{$namespace}_{$this->tenant}_{$id}_permission\" + ON {$this->getSQLTable($id. '_perms')} USING btree (_tenant,_permission,_type); + "; + } else { + $permissions .= " + CREATE UNIQUE INDEX \"{$namespace}_{$id}_ukey\" + ON {$this->getSQLTable($id. '_perms')} USING btree (_document,_type,_permission); + CREATE INDEX \"{$namespace}_{$id}_permission\" + ON {$this->getSQLTable($id. '_perms')} USING btree (_permission,_type); + "; + } - if ($this->sharedTables) { - $sql .= " - CREATE UNIQUE INDEX \"{$namespace}_{$this->tenant}_{$id}_ukey\" - ON {$this->getSQLTable($id. '_perms')} USING btree (_tenant,_document,_type,_permission); - CREATE INDEX \"{$namespace}_{$this->tenant}_{$id}_permission\" - ON {$this->getSQLTable($id. '_perms')} USING btree (_tenant,_permission,_type); - "; - } else { - $sql .= " - CREATE UNIQUE INDEX \"{$namespace}_{$id}_ukey\" - ON {$this->getSQLTable($id. '_perms')} USING btree (_document,_type,_permission); - CREATE INDEX \"{$namespace}_{$id}_permission\" - ON {$this->getSQLTable($id. '_perms')} USING btree (_permission,_type); - "; - } + $permissions = $this->trigger(Database::EVENT_COLLECTION_CREATE, $permissions); - $sql = $this->trigger(Database::EVENT_COLLECTION_CREATE, $sql); + try { + $this->getPDO() + ->prepare($collection) + ->execute(); $this->getPDO() - ->prepare($sql) + ->prepare($permissions) ->execute(); foreach ($indexes as $index) { @@ -184,8 +282,16 @@ public function createCollection(string $name, array $attributes = [], array $in $indexOrders ); } - } catch (Exception $e) { - throw new DatabaseException('Failed to create collection: ' . $e->getMessage()); + } catch (PDOException $e) { + $e = $this->processException($e); + + if (!($e instanceof DuplicateException)) { + $this->getPDO() + ->prepare("DROP TABLE IF EXISTS {$this->getSQLTable($id)}, {$this->getSQLTable($id . '_perms')};") + ->execute(); + } + + throw $e; } return true; @@ -278,6 +384,17 @@ public function deleteCollection(string $id): bool ->execute(); } + /** + * Analyze a collection updating it's metadata on the database engine + * + * @param string $collection + * @return bool + */ + public function analyzeCollection(string $collection): bool + { + return false; + } + /** * Create Attribute * @@ -288,6 +405,7 @@ public function deleteCollection(string $id): bool * @param bool $array * * @return bool + * @throws Exception */ public function createAttribute(string $collection, string $id, string $type, int $size, bool $signed = true, bool $array = false): bool { @@ -307,8 +425,7 @@ public function createAttribute(string $collection, string $id, string $type, in ->prepare($sql) ->execute(); } catch (PDOException $e) { - $this->processException($e); - return false; + throw $this->processException($e); } } @@ -320,6 +437,7 @@ public function createAttribute(string $collection, string $id, string $type, in * @param bool $array * * @return bool + * @throws DatabaseException */ public function deleteAttribute(string $collection, string $id, bool $array = false): bool { @@ -333,9 +451,17 @@ public function deleteAttribute(string $collection, string $id, bool $array = fa $sql = $this->trigger(Database::EVENT_ATTRIBUTE_DELETE, $sql); - return $this->getPDO() - ->prepare($sql) - ->execute(); + try { + return $this->getPDO() + ->prepare($sql) + ->execute(); + } catch (PDOException $e) { + if ($e->getCode() === "42703" && $e->errorInfo[1] === 7) { + return true; + } + + throw $e; + } } /** @@ -375,12 +501,12 @@ public function renameAttribute(string $collection, string $old, string $new): b * @param int $size * @param bool $signed * @param bool $array - * @param string $newKey + * @param string|null $newKey * @return bool * @throws Exception * @throws PDOException */ - public function updateAttribute(string $collection, string $id, string $type, int $size, bool $signed = true, bool $array = false, string $newKey = null): bool + public function updateAttribute(string $collection, string $id, string $type, int $size, bool $signed = true, bool $array = false, ?string $newKey = null): bool { $name = $this->filter($collection); $id = $this->filter($id); @@ -426,8 +552,7 @@ public function updateAttribute(string $collection, string $id, string $type, in return $result; } catch (PDOException $e) { - $this->processException($e); - return false; + throw $this->processException($e); } } @@ -888,13 +1013,8 @@ public function createDocument(string $collection, Document $document): Document if (isset($stmtPermissions)) { $stmtPermissions->execute(); } - } catch (Throwable $e) { - switch ($e->getCode()) { - case 23505: - throw new Duplicate('Duplicated document: ' . $e->getMessage()); - default: - throw $e; - } + } catch (PDOException $e) { + throw $this->processException($e); } return $document; @@ -909,7 +1029,7 @@ public function createDocument(string $collection, Document $document): Document * * @return array * - * @throws Duplicate + * @throws DuplicateException */ public function createDocuments(string $collection, array $documents, int $batchSize = Database::INSERT_BATCH_SIZE): array { @@ -920,6 +1040,7 @@ public function createDocuments(string $collection, array $documents, int $batch try { $name = $this->filter($collection); $batches = \array_chunk($documents, max(1, $batchSize)); + $internalIds = []; foreach ($batches as $batch) { $bindIndex = 0; @@ -934,6 +1055,11 @@ public function createDocuments(string $collection, array $documents, int $batch $attributes['_updatedAt'] = $document->getUpdatedAt(); $attributes['_permissions'] = \json_encode($document->getPermissions()); + if (!empty($document->getInternalId())) { + $internalIds[$document->getId()] = true; + $attributes['_id'] = $document->getInternalId(); + } + if ($this->sharedTables) { $attributes['_tenant'] = $this->tenant; } @@ -989,15 +1115,21 @@ public function createDocuments(string $collection, array $documents, int $batch $stmtPermissions?->execute(); } } - - return $documents; - } catch (PDOException $e) { - throw match ($e->getCode()) { - 1062, 23000 => new Duplicate('Duplicated document: ' . $e->getMessage()), - default => $e, - }; + throw $this->processException($e); + } + + foreach ($documents as $document) { + if (!isset($internalIds[$document->getId()])) { + $document['$internalId'] = $this->getDocument( + $collection, + $document->getId(), + [Query::select(['$internalId'])] + )->getInternalId(); + } } + + return $documents; } /** @@ -1008,6 +1140,8 @@ public function createDocuments(string $collection, array $documents, int $batch * @param Document $document * * @return Document + * @throws DatabaseException + * @throws DuplicateException */ public function updateDocument(string $collection, string $id, Document $document): Document { @@ -1030,7 +1164,7 @@ public function updateDocument(string $collection, string $id, Document $documen "; if ($this->sharedTables) { - $sql .= ' AND _tenant = :_tenant'; + $sql .= ' AND (_tenant = :_tenant OR _tenant IS NULL)'; } $sql = $this->trigger(Database::EVENT_PERMISSIONS_READ, $sql); @@ -1108,7 +1242,7 @@ public function updateDocument(string $collection, string $id, Document $documen "; if ($this->sharedTables) { - $sql .= ' AND _tenant = :_tenant'; + $sql .= ' AND (_tenant = :_tenant OR _tenant IS NULL)'; } $removeQuery = $sql . $removeQuery; @@ -1180,7 +1314,7 @@ public function updateDocument(string $collection, string $id, Document $documen "; if ($this->sharedTables) { - $sql .= ' AND _tenant = :_tenant'; + $sql .= ' AND (_tenant = :_tenant OR _tenant IS NULL)'; } $sql = $this->trigger(Database::EVENT_DOCUMENT_UPDATE, $sql); @@ -1215,13 +1349,8 @@ public function updateDocument(string $collection, string $id, Document $documen $stmtAddPermissions->execute(); } } catch (PDOException $e) { - switch ($e->getCode()) { - case 1062: - case 23505: - throw new Duplicate('Duplicated document: ' . $e->getMessage()); - default: - throw $e; - } + throw $this->processException($e); + } return $document; @@ -1266,7 +1395,7 @@ public function updateDocuments(string $collection, Document $updates, array $do $where[] = "_uid IN (" . \implode(', ', \array_map(fn ($index) => ":_id_{$index}", \array_keys($ids))) . ")"; if ($this->sharedTables) { - $where[] = "_tenant = :_tenant"; + $where[] = "(_tenant = :_tenant OR _tenant IS NULL)"; } $sqlWhere = 'WHERE ' . implode(' AND ', $where); @@ -1377,14 +1506,14 @@ public function updateDocuments(string $collection, Document $updates, array $do $tenantQuery = ''; if ($this->sharedTables) { - $tenantQuery = ' AND _tenant = :_tenant'; + $tenantQuery = ' AND (_tenant = :_tenant OR _tenant IS NULL)'; } $removeQueries[] = "( - _document = :uid_{$index} - {$tenantQuery} - AND _type = '{$type}' - AND _permission IN (" . \implode(', ', \array_map(function (string $i) use ($permissionsToRemove, $index, $type, &$removeBindKeys, &$removeBindValues) { + _document = :uid_{$index} + {$tenantQuery} + AND _type = '{$type}' + AND _permission IN (" . \implode(', ', \array_map(function (string $i) use ($permissionsToRemove, $index, $type, &$removeBindKeys, &$removeBindValues) { $bindKey = 'remove_' . $type . '_' . $index . '_' . $i; $removeBindKeys[] = ':' . $bindKey; $removeBindValues[$bindKey] = $permissionsToRemove[$i]; @@ -1392,7 +1521,7 @@ public function updateDocuments(string $collection, Document $updates, array $do return ':' . $bindKey; }, \array_keys($permissionsToRemove))) . ") - )"; + )"; } } @@ -1446,6 +1575,7 @@ public function updateDocuments(string $collection, Document $updates, array $do foreach ($removeBindValues as $key => $value) { $stmtRemovePermissions->bindValue($key, $value, $this->getPDOType($value)); } + if ($this->sharedTables) { $stmtRemovePermissions->bindValue(':_tenant', $this->tenant); } @@ -1512,7 +1642,7 @@ public function increaseDocumentAttribute(string $collection, string $id, string "; if ($this->sharedTables) { - $sql .= ' AND _tenant = :_tenant'; + $sql .= ' AND (_tenant = :_tenant OR _tenant IS NULL)'; } $sql .= $sqlMax . $sqlMin; @@ -1550,7 +1680,7 @@ public function deleteDocument(string $collection, string $id): bool "; if ($this->sharedTables) { - $sql .= ' AND _tenant = :_tenant'; + $sql .= ' AND (_tenant = :_tenant OR _tenant IS NULL)'; } $sql = $this->trigger(Database::EVENT_DOCUMENT_DELETE, $sql); @@ -1567,7 +1697,7 @@ public function deleteDocument(string $collection, string $id): bool "; if ($this->sharedTables) { - $sql .= ' AND _tenant = :_tenant'; + $sql .= ' AND (_tenant = :_tenant OR _tenant IS NULL)'; } $sql = $this->trigger(Database::EVENT_PERMISSIONS_DELETE, $sql); @@ -1684,14 +1814,15 @@ public function deleteDocuments(string $collection, array $ids): int * @param string $forPermission * * @return array - * @throws Exception - * @throws PDOException - * @throws Timeout + * @throws DatabaseException + * @throws TimeoutException + + * @throws TimeoutException */ public function find(string $collection, array $queries = [], ?int $limit = 25, ?int $offset = null, array $orderAttributes = [], array $orderTypes = [], array $cursor = [], string $cursorDirection = Database::CURSOR_AFTER, string $forPermission = Database::PERMISSION_READ): array { $name = $this->filter($collection); - $roles = $this->authorization->getRoles(); + $roles = Authorization::getRoles(); $where = []; $orders = []; @@ -1772,10 +1903,10 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, } if ($this->sharedTables) { - $where[] = "table_main._tenant = :_tenant"; + $where[] = "(table_main._tenant = :_tenant OR table_main._tenant IS NULL)"; } - if ($this->authorization->getStatus()) { + if (Authorization::$status) { $where[] = $this->getSQLPermissionsCondition($name, $roles, $forPermission); } @@ -1832,7 +1963,7 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, try { $stmt->execute(); } catch (PDOException $e) { - $this->processException($e); + throw $this->processException($e); } $results = $stmt->fetchAll(); @@ -1888,7 +2019,7 @@ public function find(string $collection, array $queries = [], ?int $limit = 25, public function count(string $collection, array $queries = [], ?int $max = null): int { $name = $this->filter($collection); - $roles = $this->authorization->getRoles(); + $roles = Authorization::getRoles(); $where = []; $limit = \is_null($max) ? '' : 'LIMIT :max'; @@ -1900,10 +2031,10 @@ public function count(string $collection, array $queries = [], ?int $max = null) } if ($this->sharedTables) { - $where[] = "table_main._tenant = :_tenant"; + $where[] = "(table_main._tenant = :_tenant OR table_main._tenant IS NULL)"; } - if ($this->authorization->getStatus()) { + if (Authorization::$status) { $where[] = $this->getSQLPermissionsCondition($name, $roles); } @@ -1954,7 +2085,7 @@ public function count(string $collection, array $queries = [], ?int $max = null) public function sum(string $collection, string $attribute, array $queries = [], ?int $max = null): int|float { $name = $this->filter($collection); - $roles = $this->authorization->getRoles(); + $roles = Authorization::getRoles(); $where = []; $limit = \is_null($max) ? '' : 'LIMIT :max'; @@ -1965,10 +2096,10 @@ public function sum(string $collection, string $attribute, array $queries = [], } if ($this->sharedTables) { - $where[] = "table_main._tenant = :_tenant"; + $where[] = "(table_main._tenant = :_tenant OR table_main._tenant IS NULL)"; } - if ($this->authorization->getStatus()) { + if (Authorization::$status) { $where[] = $this->getSQLPermissionsCondition($name, $roles); } @@ -2254,12 +2385,16 @@ protected function decodeArray(array $value): string return '{' . implode(",", $value) . '}'; } + public function getMinDateTime(): \DateTime + { + return new \DateTime('-4713-01-01 00:00:00'); + } + /** * Is fulltext Wildcard index supported? * * @return bool */ - // TODO: Fix full-text search logic for postgres and MariaDB public function getSupportForFulltextWildcardIndex(): bool { return false; @@ -2286,73 +2421,61 @@ public function getSupportForJSONOverlaps(): bool } /** - * Returns Max Execution Time - * @param int $milliseconds - * @param string $event - * @return void - * @throws DatabaseException + * Is get schema attributes supported? + * + * @return bool */ - public function setTimeout(int $milliseconds, string $event = Database::EVENT_ALL): void + public function getSupportForSchemaAttributes(): bool { - if (!$this->getSupportForTimeouts()) { - return; - } - if ($milliseconds <= 0) { - throw new DatabaseException('Timeout must be greater than 0'); - } - $this->before($event, 'timeout', function ($sql) use ($milliseconds) { - return " - SET statement_timeout = {$milliseconds}; - {$sql}; - SET statement_timeout = 0; - "; - }); + return false; } /** - * @param PDOException $e - * @throws Timeout - * @throws Duplicate + * @return string */ - protected function processException(PDOException $e): void + public function getLikeOperator(): string { - /** - * PDO and Swoole PDOProxy swap error codes and errorInfo - */ + return 'ILIKE'; + } + + + protected function processException(PDOException $e): \Exception + { + // Timeout if ($e->getCode() === '57014' && isset($e->errorInfo[1]) && $e->errorInfo[1] === 7) { - throw new Timeout($e->getMessage(), $e->getCode(), $e); + return new TimeoutException('Query timed out', $e->getCode(), $e); + } + + // Duplicate table + if ($e->getCode() === '42P07' && isset($e->errorInfo[1]) && $e->errorInfo[1] === 7) { + return new DuplicateException('Collection already exists', $e->getCode(), $e); } + // Duplicate column if ($e->getCode() === '42701' && isset($e->errorInfo[1]) && $e->errorInfo[1] === 7) { - throw new Duplicate($e->getMessage(), $e->getCode(), $e); + return new DuplicateException('Attribute already exists', $e->getCode(), $e); + } + + // Duplicate row + if ($e->getCode() === '23505' && isset($e->errorInfo[1]) && $e->errorInfo[1] === 7) { + return new DuplicateException('Document already exists', $e->getCode(), $e); } // Data is too big for column resize if ($e->getCode() === '22001' && isset($e->errorInfo[1]) && $e->errorInfo[1] === 7) { - throw new TruncateException('Resize would result in data truncation', $e->getCode(), $e); + return new TruncateException('Resize would result in data truncation', $e->getCode(), $e); } - throw $e; + return $e; } /** * @return string */ - public function getLikeOperator(): string + public function getConnectionId(): string { - return 'ILIKE'; - } - - - /** - * Analyze a collection updating it's metadata on the database engine - * - * @param string $collection - * @return bool - */ - public function analyzeCollection(string $collection): bool - { - return false; + $stmt = $this->getPDO()->query("SELECT pg_backend_pid();"); + return $stmt->fetchColumn(); } } diff --git a/src/Database/Adapter/SQL.php b/src/Database/Adapter/SQL.php index b06492f3f..725a91a50 100644 --- a/src/Database/Adapter/SQL.php +++ b/src/Database/Adapter/SQL.php @@ -9,6 +9,8 @@ use Utopia\Database\Database; use Utopia\Database\Document; use Utopia\Database\Exception as DatabaseException; +use Utopia\Database\Exception\NotFound as NotFoundException; +use Utopia\Database\Exception\Transaction as TransactionException; use Utopia\Database\Query; abstract class SQL extends Adapter @@ -34,20 +36,26 @@ public function startTransaction(): bool { try { if ($this->inTransaction === 0) { + if ($this->getPDO()->inTransaction()) { + $this->getPDO()->rollBack(); + } else { + // If no active transaction, this has no effect. + $this->getPDO()->prepare('ROLLBACK')->execute(); + } + $result = $this->getPDO()->beginTransaction(); } else { - $result = true; + $result = $this->getPDO()->exec('SAVEPOINT transaction' . $this->inTransaction); } } catch (PDOException $e) { - throw new DatabaseException('Failed to start transaction: ' . $e->getMessage(), $e->getCode(), $e); + throw new TransactionException('Failed to start transaction: ' . $e->getMessage(), $e->getCode(), $e); } if (!$result) { - throw new DatabaseException('Failed to start transaction'); + throw new TransactionException('Failed to start transaction'); } $this->inTransaction++; - return $result; } @@ -63,16 +71,20 @@ public function commitTransaction(): bool return true; } + if (!$this->getPDO()->inTransaction()) { + $this->inTransaction = 0; + return false; + } + try { $result = $this->getPDO()->commit(); + $this->inTransaction = 0; } catch (PDOException $e) { - throw new DatabaseException('Failed to commit transaction: ' . $e->getMessage(), $e->getCode(), $e); - } finally { - $this->inTransaction--; + throw new TransactionException('Failed to commit transaction: ' . $e->getMessage(), $e->getCode(), $e); } if (!$result) { - throw new DatabaseException('Failed to commit transaction'); + throw new TransactionException('Failed to commit transaction'); } return $result; @@ -88,15 +100,19 @@ public function rollbackTransaction(): bool } try { - $result = $this->getPDO()->rollBack(); + if ($this->inTransaction > 1) { + $result = $this->getPDO()->exec('ROLLBACK TO transaction' . ($this->inTransaction - 1)); + $this->inTransaction--; + } else { + $result = $this->getPDO()->rollBack(); + $this->inTransaction = 0; + } } catch (PDOException $e) { throw new DatabaseException('Failed to rollback transaction: ' . $e->getMessage(), $e->getCode(), $e); - } finally { - $this->inTransaction = 0; } if (!$result) { - throw new DatabaseException('Failed to rollback transaction'); + throw new TransactionException('Failed to rollback transaction'); } return $result; @@ -148,10 +164,19 @@ public function exists(string $database, ?string $collection = null): bool $stmt->bindValue(':schema', $database, PDO::PARAM_STR); } - $stmt->execute(); + try { + $stmt->execute(); + $document = $stmt->fetchAll(); + $stmt->closeCursor(); + } catch (PDOException $e) { + $e = $this->processException($e); - $document = $stmt->fetchAll(); - $stmt->closeCursor(); + if ($e instanceof NotFoundException) { + return false; + } + + throw $e; + } if (empty($document)) { return false; @@ -194,7 +219,7 @@ public function getDocument(string $collection, string $id, array $queries = [], "; if ($this->sharedTables) { - $sql .= "AND _tenant = :_tenant"; + $sql .= "AND (_tenant = :_tenant OR _tenant IS NULL)"; } if ($this->getSupportForUpdateLock()) { @@ -371,6 +396,16 @@ public function getSupportForBatchOperations(): bool return true; } + /** + * Is get connection id supported? + * + * @return bool + */ + public function getSupportForGetConnectionId(): bool + { + return true; + } + /** * Get current attribute count from collection document * @@ -811,6 +846,11 @@ public function getSupportForQueryContains(): bool */ abstract public function getSupportForJSONOverlaps(): bool; + public function getSupportForCastIndexArray(): bool + { + return false; + } + public function getSupportForRelationships(): bool { return true; @@ -988,7 +1028,7 @@ protected function getSQLPermissionsCondition(string $collection, array $roles, $tenantQuery = ''; if ($this->sharedTables) { - $tenantQuery = 'AND _tenant = :_tenant'; + $tenantQuery = 'AND (_tenant = :_tenant OR _tenant IS NULL)'; } return "table_main._uid IN ( @@ -1060,7 +1100,10 @@ public function getMaxVarcharLength(): int */ public function getMaxIndexLength(): int { - return 768; + /** + * $tenant int = 1 + */ + return $this->sharedTables ? 767 : 768; } /** @@ -1104,4 +1147,18 @@ public function getLikeOperator(): string return 'LIKE'; } + public function getInternalIndexesKeys(): array + { + return []; + } + + protected function processException(PDOException $e): \Exception + { + return $e; + } + + public function getSchemaAttributes(string $collection): array + { + return []; + } } diff --git a/src/Database/Adapter/SQLite.php b/src/Database/Adapter/SQLite.php index 55494fa55..07cad6999 100644 --- a/src/Database/Adapter/SQLite.php +++ b/src/Database/Adapter/SQLite.php @@ -10,7 +10,9 @@ use Utopia\Database\Exception as DatabaseException; use Utopia\Database\Exception\Duplicate; use Utopia\Database\Exception\Duplicate as DuplicateException; +use Utopia\Database\Exception\NotFound as NotFoundException; use Utopia\Database\Exception\Timeout as TimeoutException; +use Utopia\Database\Exception\Transaction as TransactionException; use Utopia\Database\Helpers\ID; /** @@ -29,6 +31,36 @@ */ class SQLite extends MariaDB { + /** + * @inheritDoc + */ + public function startTransaction(): bool + { + try { + if ($this->inTransaction === 0) { + if ($this->getPDO()->inTransaction()) { + $this->getPDO()->rollBack(); + } + + $result = $this->getPDO()->beginTransaction(); + } else { + $result = $this->getPDO() + ->prepare('SAVEPOINT transaction' . $this->inTransaction) + ->execute(); + } + } catch (PDOException $e) { + throw new TransactionException('Failed to start transaction: ' . $e->getMessage(), $e->getCode(), $e); + } + + if (!$result) { + throw new TransactionException('Failed to start transaction'); + } + + $this->inTransaction++; + + return $result; + } + /** * Check if Database exists * Optionally check if collection exists in Database @@ -128,8 +160,8 @@ public function createCollection(string $name, array $attributes = [], array $in $tenantQuery = $this->sharedTables ? '`_tenant` INTEGER DEFAULT NULL,' : ''; - $sql = " - CREATE TABLE IF NOT EXISTS `{$this->getSQLTable($id)}` ( + $collection = " + CREATE TABLE {$this->getSQLTable($id)} ( `_id` INTEGER PRIMARY KEY AUTOINCREMENT, `_uid` VARCHAR(36) NOT NULL, {$tenantQuery} @@ -140,32 +172,10 @@ public function createCollection(string $name, array $attributes = [], array $in ) "; - $sql = $this->trigger(Database::EVENT_COLLECTION_CREATE, $sql); - - $this->getPDO()->prepare($sql)->execute(); - - $this->createIndex($id, '_index1', Database::INDEX_UNIQUE, ['_uid'], [], []); - $this->createIndex($id, '_created_at', Database::INDEX_KEY, [ '_createdAt'], [], []); - $this->createIndex($id, '_updated_at', Database::INDEX_KEY, [ '_updatedAt'], [], []); - - if ($this->sharedTables) { - $this->createIndex($id, '_tenant_id', Database::INDEX_KEY, [ '_id'], [], []); - } - - foreach ($indexes as $index) { - $indexId = $this->filter($index->getId()); - $indexType = $index->getAttribute('type'); - $indexAttributes = $index->getAttribute('attributes', []); - $indexLengths = $index->getAttribute('lengths', []); - $indexOrders = $index->getAttribute('orders', []); - - $this->createIndex($id, $indexId, $indexType, $indexAttributes, $indexLengths, $indexOrders); - } - - $tenantQuery = $this->sharedTables ? '`_tenant` INTEGER DEFAULT NULL,' : ''; + $collection = $this->trigger(Database::EVENT_COLLECTION_CREATE, $collection); - $sql = " - CREATE TABLE IF NOT EXISTS `{$this->getSQLTable($id)}_perms` ( + $permissions = " + CREATE TABLE {$this->getSQLTable($id . '_perms')} ( `_id` INTEGER PRIMARY KEY AUTOINCREMENT, {$tenantQuery} `_type` VARCHAR(12) NOT NULL, @@ -174,16 +184,52 @@ public function createCollection(string $name, array $attributes = [], array $in ) "; - $sql = $this->trigger(Database::EVENT_COLLECTION_CREATE, $sql); + $permissions = $this->trigger(Database::EVENT_COLLECTION_CREATE, $permissions); - $this->getPDO() - ->prepare($sql) - ->execute(); + try { + $this->getPDO() + ->prepare($collection) + ->execute(); + + $this->getPDO() + ->prepare($permissions) + ->execute(); + + $this->createIndex($id, '_index1', Database::INDEX_UNIQUE, ['_uid'], [], []); + $this->createIndex($id, '_created_at', Database::INDEX_KEY, [ '_createdAt'], [], []); + $this->createIndex($id, '_updated_at', Database::INDEX_KEY, [ '_updatedAt'], [], []); + + $this->createIndex("{$id}_perms", '_index_1', Database::INDEX_UNIQUE, ['_document', '_type', '_permission'], [], []); + $this->createIndex("{$id}_perms", '_index_2', Database::INDEX_KEY, ['_permission', '_type'], [], []); + + if ($this->sharedTables) { + $this->createIndex($id, '_tenant_id', Database::INDEX_KEY, [ '_id'], [], []); + } + + foreach ($indexes as $index) { + $indexId = $this->filter($index->getId()); + $indexType = $index->getAttribute('type'); + $indexAttributes = $index->getAttribute('attributes', []); + $indexLengths = $index->getAttribute('lengths', []); + $indexOrders = $index->getAttribute('orders', []); + + $this->createIndex($id, $indexId, $indexType, $indexAttributes, $indexLengths, $indexOrders); + } - $this->createIndex("{$id}_perms", '_index_1', Database::INDEX_UNIQUE, ['_document', '_type', '_permission'], [], []); - $this->createIndex("{$id}_perms", '_index_2', Database::INDEX_KEY, ['_permission', '_type'], [], []); + $this->createIndex("{$id}_perms", '_index_1', Database::INDEX_UNIQUE, ['_document', '_type', '_permission'], [], []); + $this->createIndex("{$id}_perms", '_index_2', Database::INDEX_KEY, ['_permission', '_type'], [], []); - // Update $this->getCountOfIndexes when adding another default index + } catch (PDOException $e) { + $e = $this->processException($e); + + if (!($e instanceof Duplicate)) { + $this->getPDO() + ->prepare("DROP TABLE IF EXISTS {$this->getSQLTable($id)}, {$this->getSQLTable($id . '_perms')};") + ->execute(); + } + + throw $e; + } return true; } @@ -250,14 +296,14 @@ public function deleteCollection(string $id): bool { $id = $this->filter($id); - $sql = "DROP TABLE IF EXISTS `{$this->getSQLTable($id)}`"; + $sql = "DROP TABLE IF EXISTS {$this->getSQLTable($id)}"; $sql = $this->trigger(Database::EVENT_COLLECTION_DELETE, $sql); $this->getPDO() ->prepare($sql) ->execute(); - $sql = "DROP TABLE IF EXISTS `{$this->getSQLTable($id)}_perms`"; + $sql = "DROP TABLE IF EXISTS {$this->getSQLTable($id . '_perms')}"; $sql = $this->trigger(Database::EVENT_COLLECTION_DELETE, $sql); $this->getPDO() @@ -267,6 +313,17 @@ public function deleteCollection(string $id): bool return true; } + /** + * Analyze a collection updating it's metadata on the database engine + * + * @param string $collection + * @return bool + */ + public function analyzeCollection(string $collection): bool + { + return false; + } + /** * Update Attribute * @@ -276,12 +333,12 @@ public function deleteCollection(string $id): bool * @param int $size * @param bool $signed * @param bool $array - * @param string $newKey + * @param string|null $newKey * @return bool * @throws Exception * @throws PDOException */ - public function updateAttribute(string $collection, string $id, string $type, int $size, bool $signed = true, bool $array = false, string $newKey = null): bool + public function updateAttribute(string $collection, string $id, string $type, int $size, bool $signed = true, bool $array = false, ?string $newKey = null): bool { if (!empty($newKey) && $newKey !== $id) { return $this->renameAttribute($collection, $id, $newKey); @@ -308,7 +365,7 @@ public function deleteAttribute(string $collection, string $id, bool $array = fa $collection = $this->getDocument(Database::METADATA, $name); if ($collection->isEmpty()) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } $indexes = \json_decode($collection->getAttribute('indexes', []), true); @@ -323,16 +380,21 @@ public function deleteAttribute(string $collection, string $id, bool $array = fa } } - $sql = " - ALTER TABLE {$this->getSQLTable($name)} - DROP COLUMN `{$id}` - "; + $sql = "ALTER TABLE {$this->getSQLTable($name)} DROP COLUMN `{$id}`"; $sql = $this->trigger(Database::EVENT_COLLECTION_DELETE, $sql); - return $this->getPDO() - ->prepare($sql) - ->execute(); + try { + return $this->getPDO() + ->prepare($sql) + ->execute(); + } catch (PDOException $e) { + if (str_contains($e->getMessage(), 'no such column')) { + return true; + } + + throw $e; + } } /** @@ -350,7 +412,7 @@ public function renameIndex(string $collection, string $old, string $new): bool $collection = $this->getDocument(Database::METADATA, $collection); if ($collection->isEmpty()) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } $old = $this->filter($old); @@ -438,9 +500,17 @@ public function deleteIndex(string $collection, string $id): bool $sql = "DROP INDEX `{$this->getNamespace()}_{$this->tenant}_{$name}_{$id}`"; $sql = $this->trigger(Database::EVENT_INDEX_DELETE, $sql); - return $this->getPDO() - ->prepare($sql) - ->execute(); + try { + return $this->getPDO() + ->prepare($sql) + ->execute(); + } catch (PDOException $e) { + if (str_contains($e->getMessage(), 'no such index')) { + return true; + } + + throw $e; + } } /** @@ -593,7 +663,7 @@ public function updateDocument(string $collection, string $id, Document $documen "; if ($this->sharedTables) { - $sql .= " AND _tenant = :_tenant"; + $sql .= " AND (_tenant = :_tenant OR _tenant IS NULL)"; } $sql = $this->trigger(Database::EVENT_PERMISSIONS_READ, $sql); @@ -670,7 +740,7 @@ public function updateDocument(string $collection, string $id, Document $documen "; if ($this->sharedTables) { - $sql .= " AND _tenant = :_tenant"; + $sql .= " AND (_tenant = :_tenant OR _tenant IS NULL)"; } $removeQuery = $sql . $removeQuery; @@ -742,7 +812,7 @@ public function updateDocument(string $collection, string $id, Document $documen "; if ($this->sharedTables) { - $sql .= " AND _tenant = :_tenant"; + $sql .= " AND (_tenant = :_tenant OR _tenant IS NULL)"; } $sql = $this->trigger(Database::EVENT_DOCUMENT_UPDATE, $sql); @@ -855,6 +925,26 @@ public function getSupportForAttributeResizing(): bool return false; } + /** + * Is get connection id supported? + * + * @return bool + */ + public function getSupportForGetConnectionId(): bool + { + return false; + } + + /** + * Is get schema attributes supported? + * + * @return bool + */ + public function getSupportForSchemaAttributes(): bool + { + return false; + } + /** * Get SQL Index Type * @@ -955,7 +1045,7 @@ protected function getSQLPermissionsCondition(string $collection, array $roles, */ protected function getSQLTable(string $name): string { - return "{$this->getNamespace()}_{$name}"; + return "`{$this->getNamespace()}_{$name}`"; } /** @@ -1117,38 +1207,18 @@ public function getKeywords(): array ]; } - /** - * @param PDOException $e - * @throws TimeoutException - * @throws DuplicateException - */ - protected function processException(PDOException $e): void + protected function processException(PDOException $e): \Exception { - /** - * PDO and Swoole PDOProxy swap error codes and errorInfo - */ - // Timeout if ($e->getCode() === 'HY000' && isset($e->errorInfo[1]) && $e->errorInfo[1] === 3024) { - throw new TimeoutException($e->getMessage(), $e->getCode(), $e); + return new TimeoutException('Query timed out', $e->getCode(), $e); } // Duplicate if ($e->getCode() === 'HY000' && isset($e->errorInfo[1]) && $e->errorInfo[1] === 1) { - throw new DuplicateException($e->getMessage(), $e->getCode(), $e); + return new DuplicateException('Document already exists', $e->getCode(), $e); } - throw $e; - } - - /** - * Analyze a collection updating it's metadata on the database engine - * - * @param string $collection - * @return bool - */ - public function analyzeCollection(string $collection): bool - { - return false; + return $e; } } diff --git a/src/Database/Database.php b/src/Database/Database.php index 89170c484..b8a66c16d 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -9,6 +9,7 @@ use Utopia\Database\Exception\Conflict as ConflictException; use Utopia\Database\Exception\Duplicate as DuplicateException; use Utopia\Database\Exception\Limit as LimitException; +use Utopia\Database\Exception\NotFound as NotFoundException; use Utopia\Database\Exception\Query as QueryException; use Utopia\Database\Exception\Relationship as RelationshipException; use Utopia\Database\Exception\Restricted as RestrictedException; @@ -18,7 +19,6 @@ use Utopia\Database\Helpers\Permission; use Utopia\Database\Helpers\Role; use Utopia\Database\Validator\Authorization; -use Utopia\Database\Validator\Authorization\Input; use Utopia\Database\Validator\Index as IndexValidator; use Utopia\Database\Validator\PartialStructure; use Utopia\Database\Validator\Permissions; @@ -140,17 +140,6 @@ class Database public const INSERT_BATCH_SIZE = 100; public const DELETE_BATCH_SIZE = 100; - protected Adapter $adapter; - - protected Cache $cache; - - protected string $cacheName = 'default'; - - /** - * @var array - */ - protected array $map = []; - /** * List of Internal attributes * @@ -292,6 +281,17 @@ class Database 'indexes' => [], ]; + protected Adapter $adapter; + + protected Cache $cache; + + protected string $cacheName = 'default'; + + /** + * @var array + */ + protected array $map = []; + /** * @var array */ @@ -303,14 +303,14 @@ class Database protected array $instanceFilters = []; /** - * @var array + * @var array> */ protected array $listeners = [ '*' => [], ]; /** - * Array in which the keys are the names of databse listeners that + * Array in which the keys are the names of database listeners that * should be skipped when dispatching events. null $silentListeners * will skip all listeners. * @@ -322,6 +322,8 @@ class Database protected bool $resolveRelationships = true; + protected bool $checkRelationshipsExist = true; + protected int $relationshipFetchDepth = 1; protected bool $filter = true; @@ -330,6 +332,10 @@ class Database protected bool $preserveDates = false; + protected int $maxQueryValues = 100; + + protected bool $migrating = false; + /** * Stack of collection IDs when creating or updating related documents * @var array @@ -346,24 +352,20 @@ class Database */ protected array $relationshipDeleteStack = []; - /** - * @var Authorization - */ - private Authorization $authorization; - /** * @param Adapter $adapter * @param Cache $cache * @param array $filters */ - public function __construct(Adapter $adapter, Cache $cache, array $filters = []) - { + public function __construct( + Adapter $adapter, + Cache $cache, + array $filters = [] + ) { $this->adapter = $adapter; $this->cache = $cache; $this->instanceFilters = $filters; - $this->setAuthorization(new Authorization()); - self::addFilter( 'json', /** @@ -409,13 +411,12 @@ function (mixed $value) { self::addFilter( 'datetime', /** - * @param string|null $value - * @return string|null - * @throws Exception + * @param mixed $value + * @return mixed */ - function (?string $value) { + function (mixed $value) { if (is_null($value)) { - return null; + return; } try { $value = new \DateTime($value); @@ -435,38 +436,15 @@ function (?string $value) { ); } - /** - * Sets instance of authorization for permission checks - * - * @param Authorization $authorization - * @return self - */ - public function setAuthorization(Authorization $authorization): self - { - $this->adapter->setAuthorization($authorization); - $this->authorization = $authorization; - return $this; - } - - /** - * Get instance of authorization - * - * @return Authorization - */ - public function getAuthorization(): Authorization - { - return $this->authorization; - } - /** * Add listener to events * * @param string $event * @param string $name * @param callable $callback - * @return self + * @return static */ - public function on(string $event, string $name, callable $callback): self + public function on(string $event, string $name, callable $callback): static { if (!isset($this->listeners[$event])) { $this->listeners[$event] = []; @@ -484,7 +462,7 @@ public function on(string $event, string $name, callable $callback): self * @param callable $callback * @return $this */ - public function before(string $event, string $name, callable $callback): self + public function before(string $event, string $name, callable $callback): static { $this->adapter->before($event, $name, $callback); @@ -499,7 +477,7 @@ public function before(string $event, string $name, callable $callback): self * @param array|null $listeners List of listeners to silence; if null, all listeners will be silenced * @return T */ - public function silent(callable $callback, array $listeners = null): mixed + public function silent(callable $callback, ?array $listeners = null): mixed { $previous = $this->silentListeners; @@ -520,6 +498,17 @@ public function silent(callable $callback, array $listeners = null): mixed } } + /** + * Get getConnection Id + * + * @return string + * @throws Exception + */ + public function getConnectionId(): string + { + return $this->adapter->getConnectionId(); + } + /** * Skip relationships for all the calls inside the callback * @@ -539,6 +528,18 @@ public function skipRelationships(callable $callback): mixed } } + public function skipRelationshipsExistCheck(callable $callback): mixed + { + $previous = $this->checkRelationshipsExist; + $this->checkRelationshipsExist = false; + + try { + return $callback(); + } finally { + $this->checkRelationshipsExist = $previous; + } + } + /** * Trigger callback for events * @@ -597,7 +598,7 @@ public function withRequestTimestamp(?\DateTime $requestTimestamp, callable $cal * * @throws DatabaseException */ - public function setNamespace(string $namespace): self + public function setNamespace(string $namespace): static { $this->adapter->setNamespace($namespace); @@ -621,10 +622,10 @@ public function getNamespace(): string * * @param string $name * - * @return self + * @return static * @throws DatabaseException */ - public function setDatabase(string $name): self + public function setDatabase(string $name): static { $this->adapter->setDatabase($name); @@ -651,7 +652,7 @@ public function getDatabase(): string * * @return $this */ - public function setCache(Cache $cache): self + public function setCache(Cache $cache): static { $this->cache = $cache; return $this; @@ -673,7 +674,7 @@ public function getCache(): Cache * @param string $name * @return $this */ - public function setCacheName(string $name): self + public function setCacheName(string $name): static { $this->cacheName = $name; @@ -695,9 +696,9 @@ public function getCacheName(): string * * @param string $key * @param mixed $value - * @return self + * @return static */ - public function setMetadata(string $key, mixed $value): self + public function setMetadata(string $key, mixed $value): static { $this->adapter->setMetadata($key, $value); @@ -729,10 +730,10 @@ public function resetMetadata(): void * * @param int $milliseconds * @param string $event - * @return self + * @return static * @throws Exception */ - public function setTimeout(int $milliseconds, string $event = Database::EVENT_ALL): self + public function setTimeout(int $milliseconds, string $event = Database::EVENT_ALL): static { $this->adapter->setTimeout($milliseconds, $event); @@ -755,10 +756,9 @@ public function clearTimeout(string $event = Database::EVENT_ALL): void * * @return $this */ - public function enableFilters(): self + public function enableFilters(): static { $this->filter = true; - return $this; } @@ -767,13 +767,33 @@ public function enableFilters(): self * * @return $this */ - public function disableFilters(): self + public function disableFilters(): static { $this->filter = false; - return $this; } + /** + * Skip filters + * + * Execute a callback without filters + * + * @template T + * @param callable(): T $callback + * @return T + */ + public function skipFilters(callable $callback): mixed + { + $initial = $this->filter; + $this->disableFilters(); + + try { + return $callback(); + } finally { + $this->filter = $initial; + } + } + /** * Get instance filters * @@ -789,7 +809,7 @@ public function getInstanceFilters(): array * * @return $this */ - public function enableValidation(): self + public function enableValidation(): static { $this->validate = true; @@ -801,7 +821,7 @@ public function enableValidation(): self * * @return $this */ - public function disableValidation(): self + public function disableValidation(): static { $this->validate = false; @@ -811,7 +831,7 @@ public function disableValidation(): self /** * Skip Validation * - * Skips validation for the code to be executed inside the callback + * Execute a callback without validation * * @template T * @param callable(): T $callback @@ -830,14 +850,25 @@ public function skipValidation(callable $callback): mixed } /** - * Set Share Tables + * Get shared tables + * + * Get whether to share tables between tenants + * @return bool + */ + public function getSharedTables(): bool + { + return $this->adapter->getSharedTables(); + } + + /** + * Set shard tables * * Set whether to share tables between tenants * * @param bool $sharedTables - * @return self + * @return static */ - public function setSharedTables(bool $sharedTables): self + public function setSharedTables(bool $sharedTables): static { $this->adapter->setSharedTables($sharedTables); @@ -850,22 +881,96 @@ public function setSharedTables(bool $sharedTables): self * Set tenant to use if tables are shared * * @param ?int $tenant - * @return self + * @return static */ - public function setTenant(?int $tenant): self + public function setTenant(?int $tenant): static { $this->adapter->setTenant($tenant); return $this; } - public function setPreserveDates(bool $preserve): self + /** + * Get Tenant + * + * Get tenant to use if tables are shared + * + * @return ?int + */ + public function getTenant(): ?int + { + return $this->adapter->getTenant(); + } + + /** + * With Tenant + * + * Execute a callback with a specific tenant + * + * @param int|null $tenant + * @param callable $callback + * @return mixed + */ + public function withTenant(?int $tenant, callable $callback): mixed + { + $previous = $this->adapter->getTenant(); + $this->adapter->setTenant($tenant); + + try { + return $callback(); + } finally { + $this->adapter->setTenant($previous); + } + } + + public function getPreserveDates(): bool + { + return $this->preserveDates; + } + + public function setPreserveDates(bool $preserve): static { $this->preserveDates = $preserve; return $this; } + public function setMigrating(bool $migrating): self + { + $this->migrating = $migrating; + + return $this; + } + + public function isMigrating(): bool + { + return $this->migrating; + } + + public function withPreserveDates(callable $callback): mixed + { + $previous = $this->preserveDates; + $this->preserveDates = true; + + try { + return $callback(); + } finally { + $this->preserveDates = $previous; + } + } + + public function setMaxQueryValues(int $max): self + { + $this->maxQueryValues = $max; + + return $this; + } + + public function getMaxQueryValues(): int + { + return$this->maxQueryValues; + } + /** * Get list of keywords that cannot be used * @@ -952,17 +1057,16 @@ public function ping(): bool /** * Create the database * - * @throws DatabaseException - * + * @param string|null $database * @return bool + * @throws DuplicateException + * @throws LimitException + * @throws Exception */ public function create(?string $database = null): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } + $database ??= $this->adapter->getDatabase(); - $database = $database ?? $this->adapter->getDatabase(); $this->adapter->create($database); /** @@ -991,11 +1095,7 @@ public function create(?string $database = null): bool */ public function exists(?string $database = null, ?string $collection = null): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - - $database = $database ?? $this->adapter->getDatabase(); + $database ??= $this->adapter->getDatabase(); return $this->adapter->exists($database, $collection); } @@ -1007,10 +1107,6 @@ public function exists(?string $database = null, ?string $collection = null): bo */ public function list(): array { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $databases = $this->adapter->list(); $this->trigger(self::EVENT_DATABASE_LIST, $databases); @@ -1023,13 +1119,10 @@ public function list(): array * * @param string|null $database * @return bool + * @throws DatabaseException */ public function delete(?string $database = null): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $database = $database ?? $this->adapter->getDatabase(); $deleted = $this->adapter->delete($database); @@ -1039,6 +1132,8 @@ public function delete(?string $database = null): bool 'deleted' => $deleted ]); + $this->cache->flush(); + return $deleted; } @@ -1048,19 +1143,15 @@ public function delete(?string $database = null): bool * @param string $id * @param array $attributes * @param array $indexes - * @param array $permissions + * @param array|null $permissions * @param bool $documentSecurity * @return Document * @throws DatabaseException * @throws DuplicateException * @throws LimitException */ - public function createCollection(string $id, array $attributes = [], array $indexes = [], array $permissions = null, bool $documentSecurity = true): Document + public function createCollection(string $id, array $attributes = [], array $indexes = [], ?array $permissions = null, bool $documentSecurity = true): Document { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $permissions ??= [ Permission::create(Role::any()), ]; @@ -1090,7 +1181,8 @@ public function createCollection(string $id, array $attributes = [], array $inde if ($this->validate) { $validator = new IndexValidator( $attributes, - $this->adapter->getMaxIndexLength() + $this->adapter->getMaxIndexLength(), + $this->adapter->getInternalIndexesKeys() ); foreach ($indexes as $index) { if (!$validator->isValid($index)) { @@ -1099,12 +1191,6 @@ public function createCollection(string $id, array $attributes = [], array $inde } } - $this->adapter->createCollection($id, $attributes, $indexes); - - if ($id === self::METADATA) { - return new Document(self::COLLECTION); - } - // Check index limits, if given if ($indexes && $this->adapter->getCountOfIndexes($collection) > $this->adapter->getLimitForIndexes()) { throw new LimitException('Index limit of ' . $this->adapter->getLimitForIndexes() . ' exceeded. Cannot create collection.'); @@ -1116,17 +1202,23 @@ public function createCollection(string $id, array $attributes = [], array $inde $this->adapter->getLimitForAttributes() > 0 && $this->adapter->getCountOfAttributes($collection) > $this->adapter->getLimitForAttributes() ) { - throw new LimitException('Column limit of ' . $this->adapter->getLimitForAttributes() . ' exceeded. Cannot create collection.'); + throw new LimitException('Attribute limit of ' . $this->adapter->getLimitForAttributes() . ' exceeded. Cannot create collection.'); } if ( $this->adapter->getDocumentSizeLimit() > 0 && $this->adapter->getAttributeWidth($collection) > $this->adapter->getDocumentSizeLimit() ) { - throw new LimitException('Row width limit of ' . $this->adapter->getDocumentSizeLimit() . ' exceeded. Cannot create collection.'); + throw new LimitException('Document size limit of ' . $this->adapter->getDocumentSizeLimit() . ' exceeded. Cannot create collection.'); } } + $this->adapter->createCollection($id, $attributes, $indexes); + + if ($id === self::METADATA) { + return new Document(self::COLLECTION); + } + $createdCollection = $this->silent(fn () => $this->createDocument(self::METADATA, $collection)); $this->trigger(self::EVENT_COLLECTION_CREATE, $createdCollection); @@ -1147,10 +1239,6 @@ public function createCollection(string $id, array $attributes = [], array $inde */ public function updateCollection(string $id, array $permissions, bool $documentSecurity): Document { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - if ($this->validate) { $validator = new Permissions(); if (!$validator->isValid($permissions)) { @@ -1161,14 +1249,14 @@ public function updateCollection(string $id, array $permissions, bool $documentS $collection = $this->silent(fn () => $this->getCollection($id)); if ($collection->isEmpty()) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } if ( $this->adapter->getSharedTables() && $collection->getAttribute('$tenant') != $this->adapter->getTenant() ) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } $collection @@ -1192,16 +1280,15 @@ public function updateCollection(string $id, array $permissions, bool $documentS */ public function getCollection(string $id): Document { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getDocument(self::METADATA, $id)); + $tenant = $collection->getAttribute('$tenant'); + if ( $id !== self::METADATA && $this->adapter->getSharedTables() - && $collection->getAttribute('$tenant') != $this->adapter->getTenant() + && $tenant !== null + && $tenant != $this->adapter->getTenant() ) { return new Document(); } @@ -1222,60 +1309,47 @@ public function getCollection(string $id): Document */ public function listCollections(int $limit = 25, int $offset = 0): array { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $result = $this->silent(fn () => $this->find(self::METADATA, [ Query::limit($limit), Query::offset($offset) ])); - if ($this->adapter->getSharedTables()) { - $result = \array_filter($result, function ($collection) { - return $collection->getAttribute('$tenant') == $this->adapter->getTenant(); - }); - } - $this->trigger(self::EVENT_COLLECTION_LIST, $result); return $result; } /** - * Get Collection Size on disk + * Get Collection Size * * @param string $collection * * @return int + * @throws Exception */ - public function getSizeOfCollectionOnDisk(string $collection): int + public function getSizeOfCollection(string $collection): int { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); if ($collection->isEmpty()) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } if ($this->adapter->getSharedTables() && $collection->getAttribute('$tenant') != $this->adapter->getTenant()) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } - return $this->adapter->getSizeOfCollectionOnDisk($collection->getId()); + return $this->adapter->getSizeOfCollection($collection->getId()); } /** - * Get Collection Size of Data + * Get Collection Size on disk * * @param string $collection * * @return int */ - public function getSizeOfCollection(string $collection): int + public function getSizeOfCollectionOnDisk(string $collection): int { if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); @@ -1284,14 +1358,14 @@ public function getSizeOfCollection(string $collection): int $collection = $this->silent(fn () => $this->getCollection($collection)); if ($collection->isEmpty()) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } if ($this->adapter->getSharedTables() && $collection->getAttribute('$tenant') != $this->adapter->getTenant()) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } - return $this->adapter->getSizeOfCollection($collection->getId()); + return $this->adapter->getSizeOfCollectionOnDisk($collection->getId()); } /** @@ -1304,24 +1378,20 @@ public function getSizeOfCollection(string $collection): int */ public function deleteCollection(string $id): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getDocument(self::METADATA, $id)); if ($collection->isEmpty()) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } if ($this->adapter->getSharedTables() && $collection->getAttribute('$tenant') != $this->adapter->getTenant()) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } $relationships = \array_filter( $collection->getAttribute('attributes'), fn ($attribute) => - $attribute->getAttribute('type') === Database::VAR_RELATIONSHIP + $attribute->getAttribute('type') === Database::VAR_RELATIONSHIP ); foreach ($relationships as $relationship) { @@ -1340,6 +1410,8 @@ public function deleteCollection(string $id): bool $this->trigger(self::EVENT_COLLECTION_DELETE, $collection); } + $this->purgeCachedCollection($id); + return $deleted; } @@ -1365,24 +1437,17 @@ public function deleteCollection(string $id): bool * @throws DuplicateException * @throws LimitException * @throws StructureException + * @throws Exception */ - public function createAttribute(string $collection, string $id, string $type, int $size, bool $required, mixed $default = null, bool $signed = true, bool $array = false, string $format = null, array $formatOptions = [], array $filters = []): bool + public function createAttribute(string $collection, string $id, string $type, int $size, bool $required, mixed $default = null, bool $signed = true, bool $array = false, ?string $format = null, array $formatOptions = [], array $filters = []): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); if ($collection->isEmpty()) { - throw new DatabaseException('Collection not found'); - } - - if ($this->adapter->getSharedTables() && $collection->getAttribute('$tenant') != $this->adapter->getTenant()) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } - // Attribute IDs are case insensitive + // Attribute IDs are case-insensitive $attributes = $collection->getAttribute('attributes', []); /** @var array $attributes */ foreach ($attributes as $attribute) { @@ -1391,9 +1456,9 @@ public function createAttribute(string $collection, string $id, string $type, in } } - /** Ensure required filters for the attribute are passed */ + // Ensure required filters for the attribute are passed $requiredFilters = $this->getRequiredFilters($type); - if (!empty(array_diff($requiredFilters, $filters))) { + if (!empty(\array_diff($requiredFilters, $filters))) { throw new DatabaseException("Attribute of type: $type requires the following filters: " . implode(",", $requiredFilters)); } @@ -1455,10 +1520,10 @@ public function createAttribute(string $collection, string $id, string $type, in throw new DatabaseException('Unknown attribute type: ' . $type . '. Must be one of ' . self::VAR_STRING . ', ' . self::VAR_INTEGER . ', ' . self::VAR_FLOAT . ', ' . self::VAR_BOOLEAN . ', ' . self::VAR_DATETIME . ', ' . self::VAR_RELATIONSHIP); } - // only execute when $default is given + // Only execute when $default is given if (!\is_null($default)) { if ($required === true) { - throw new DatabaseException('Cannot set a default value on a required attribute'); + throw new DatabaseException('Cannot set a default value for a required attribute'); } $this->validateDefaultTypes($type, $default); @@ -1472,7 +1537,7 @@ public function createAttribute(string $collection, string $id, string $type, in } } catch (DuplicateException $e) { // HACK: Metadata should still be updated, can be removed when null tenant collections are supported. - if (!$this->adapter->getSharedTables()) { + if (!$this->adapter->getSharedTables() || !$this->isMigrating()) { throw $e; } } @@ -1510,7 +1575,7 @@ protected function getRequiredFilters(?string $type): array * @param string $type Type of the attribute * @param mixed $default Default value of the attribute * - * @throws Exception + * @throws DatabaseException * @return void */ protected function validateDefaultTypes(string $type, mixed $default): void @@ -1561,10 +1626,6 @@ protected function validateDefaultTypes(string $type, mixed $default): void */ protected function updateIndexMeta(string $collection, string $id, callable $updateCallback): Document { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); if ($collection->getId() === self::METADATA) { @@ -1575,7 +1636,7 @@ protected function updateIndexMeta(string $collection, string $id, callable $upd $index = \array_search($id, \array_map(fn ($index) => $index['$id'], $indexes)); if ($index === false) { - throw new DatabaseException('Index not found'); + throw new NotFoundException('Index not found'); } // Execute update from callback @@ -1604,10 +1665,6 @@ protected function updateIndexMeta(string $collection, string $id, callable $upd */ protected function updateAttributeMeta(string $collection, string $id, callable $updateCallback): Document { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); if ($collection->getId() === self::METADATA) { @@ -1618,14 +1675,14 @@ protected function updateAttributeMeta(string $collection, string $id, callable $index = \array_search($id, \array_map(fn ($attribute) => $attribute['$id'], $attributes)); if ($index === false) { - throw new DatabaseException('Attribute not found'); + throw new NotFoundException('Attribute not found'); } // Execute update from callback $updateCallback($attributes[$index], $collection, $index); // Save - $collection->setAttribute('attributes', $attributes, Document::SET_TYPE_ASSIGN); + $collection->setAttribute('attributes', $attributes); $this->silent(fn () => $this->updateDocument(self::METADATA, $collection->getId(), $collection)); @@ -1731,7 +1788,7 @@ public function updateAttributeDefault(string $collection, string $id, mixed $de /** * Update Attribute. This method is for updating data that causes underlying structure to change. Check out other updateAttribute methods if you are looking for metadata adjustments. - * To update attribute key (ID), use renameAttribute instead. + * * @param string $collection * @param string $id * @param string|null $type @@ -1747,7 +1804,7 @@ public function updateAttributeDefault(string $collection, string $id, mixed $de * @return Document * @throws Exception */ - public function updateAttribute(string $collection, string $id, string $type = null, int $size = null, bool $required = null, mixed $default = null, bool $signed = null, bool $array = null, string $format = null, ?array $formatOptions = null, ?array $filters = null, ?string $newKey = null): Document + public function updateAttribute(string $collection, string $id, ?string $type = null, ?int $size = null, ?bool $required = null, mixed $default = null, ?bool $signed = null, ?bool $array = null, ?string $format = null, ?array $formatOptions = null, ?array $filters = null, ?string $newKey = null): Document { return $this->updateAttributeMeta($collection, $id, function ($attribute, $collectionDoc, $attributeIndex) use ($collection, $id, $type, $size, $required, $default, $signed, $array, $format, $formatOptions, $filters, $newKey) { $altering = !\is_null($type) @@ -1838,15 +1895,13 @@ public function updateAttribute(string $collection, string $id, string $type = n $this->adapter->getDocumentSizeLimit() > 0 && $this->adapter->getAttributeWidth($collectionDoc) >= $this->adapter->getDocumentSizeLimit() ) { - throw new LimitException('Row width limit reached. Cannot create new attribute.'); + throw new LimitException('Row width limit reached. Cannot update attribute.'); } if ($altering) { - $updated = $this->adapter->updateAttribute($collection, $id, $type, $size, $signed, $array, $newKey); - - if ($id !== $newKey) { - $indexes = $collectionDoc->getAttribute('indexes'); + $indexes = $collectionDoc->getAttribute('indexes'); + if (!\is_null($newKey) && $id !== $newKey) { foreach ($indexes as $index) { if (in_array($id, $index['attributes'])) { $index['attributes'] = array_map(function ($attribute) use ($id, $newKey) { @@ -1856,6 +1911,25 @@ public function updateAttribute(string $collection, string $id, string $type = n } } + /** + * Since we allow changing type & size we need to validate index length + */ + if ($this->validate) { + $validator = new IndexValidator( + $attributes, + $this->adapter->getMaxIndexLength(), + $this->adapter->getInternalIndexesKeys() + ); + + foreach ($indexes as $index) { + if (!$validator->isValid($index)) { + throw new DatabaseException($validator->getDescription()); + } + } + } + + $updated = $this->adapter->updateAttribute($collection, $id, $type, $size, $signed, $array, $newKey); + if (!$updated) { throw new DatabaseException('Failed to update attribute'); } @@ -1880,10 +1954,6 @@ public function updateAttribute(string $collection, string $id, string $type = n */ public function checkAttribute(Document $collection, Document $attribute): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = clone $collection; $collection->setAttribute('attributes', $attribute, Document::SET_TYPE_APPEND); @@ -1917,10 +1987,6 @@ public function checkAttribute(Document $collection, Document $attribute): bool */ public function deleteAttribute(string $collection, string $id): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); $attributes = $collection->getAttribute('attributes', []); $indexes = $collection->getAttribute('indexes', []); @@ -1936,7 +2002,7 @@ public function deleteAttribute(string $collection, string $id): bool } if (\is_null($attribute)) { - throw new DatabaseException('Attribute not found'); + throw new NotFoundException('Attribute not found'); } if ($attribute['type'] === self::VAR_RELATIONSHIP) { @@ -1991,43 +2057,47 @@ public function deleteAttribute(string $collection, string $id): bool */ public function renameAttribute(string $collection, string $old, string $new): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); + + /** + * @var array $attributes + */ $attributes = $collection->getAttribute('attributes', []); - $indexes = $collection->getAttribute('indexes', []); - $attribute = \in_array($old, \array_map(fn ($attribute) => $attribute['$id'], $attributes)); + /** + * @var array $indexes + */ + $indexes = $collection->getAttribute('indexes', []); - if ($attribute === false) { - throw new DatabaseException('Attribute not found'); - } + $attribute = new Document(); - $attributeNew = \in_array($new, \array_map(fn ($attribute) => $attribute['$id'], $attributes)); + foreach ($attributes as $value) { + if ($value->getId() === $old) { + $attribute = $value; + } - if ($attributeNew !== false) { - throw new DuplicateException('Attribute name already used'); + if ($value->getId() === $new) { + throw new DuplicateException('Attribute name already used'); + } } - foreach ($attributes as $key => $value) { - if (isset($value['$id']) && $value['$id'] === $old) { - $attributes[$key]['key'] = $new; - $attributes[$key]['$id'] = $new; - $attributeNew = $attributes[$key]; - break; - } + if ($attribute->isEmpty()) { + throw new NotFoundException('Attribute not found'); } + $attribute->setAttribute('$id', $new); + $attribute->setAttribute('key', $new); + foreach ($indexes as $index) { $indexAttributes = $index->getAttribute('attributes', []); - $indexAttributes = \array_map(fn ($attribute) => ($attribute === $old) ? $new : $attribute, $indexAttributes); + $indexAttributes = \array_map(fn ($attr) => ($attr === $old) ? $new : $attr, $indexAttributes); $index->setAttribute('attributes', $indexAttributes); } + $renamed = $this->adapter->renameAttribute($collection->getId(), $old, $new); + $collection->setAttribute('attributes', $attributes); $collection->setAttribute('indexes', $indexes); @@ -2035,9 +2105,7 @@ public function renameAttribute(string $collection, string $old, string $new): b $this->silent(fn () => $this->updateDocument(self::METADATA, $collection->getId(), $collection)); } - $renamed = $this->adapter->renameAttribute($collection->getId(), $old, $new); - - $this->trigger(self::EVENT_ATTRIBUTE_UPDATE, $attributeNew); + $this->trigger(self::EVENT_ATTRIBUTE_UPDATE, $attribute); return $renamed; } @@ -2069,20 +2137,16 @@ public function createRelationship( ?string $twoWayKey = null, string $onDelete = Database::RELATION_MUTATE_RESTRICT ): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); if ($collection->isEmpty()) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } $relatedCollection = $this->silent(fn () => $this->getCollection($relatedCollection)); if ($relatedCollection->isEmpty()) { - throw new DatabaseException('Related collection not found'); + throw new NotFoundException('Related collection not found'); } $id ??= $relatedCollection->getId(); @@ -2261,10 +2325,6 @@ public function updateRelationship( ?bool $twoWay = null, ?string $onDelete = null ): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - if ( \is_null($newKey) && \is_null($newTwoWayKey) @@ -2284,7 +2344,20 @@ public function updateRelationship( throw new DuplicateException('Attribute already exists'); } - $this->updateAttributeMeta($collection->getId(), $id, function ($attribute) use ($collection, $id, $newKey, $newTwoWayKey, $twoWay, $onDelete) { + $attributeIndex = array_search($id, array_map(fn ($attribute) => $attribute['$id'], $attributes)); + + if ($attributeIndex === false) { + throw new NotFoundException('Attribute not found'); + } + + $attribute = $attributes[$attributeIndex]; + $type = $attribute['options']['relationType']; + $side = $attribute['options']['side']; + + $relatedCollectionId = $attribute['options']['relatedCollection']; + $relatedCollection = $this->getCollection($relatedCollectionId); + + $this->updateAttributeMeta($collection->getId(), $id, function ($attribute) use ($collection, $id, $newKey, $newTwoWayKey, $twoWay, $onDelete, $type, $side) { $altering = (!\is_null($newKey) && $newKey !== $id) || (!\is_null($newTwoWayKey) && $newTwoWayKey !== $attribute['options']['twoWayKey']); @@ -2299,9 +2372,6 @@ public function updateRelationship( throw new DuplicateException('Related attribute already exists'); } - $type = $attribute['options']['relationType']; - $side = $attribute['options']['side']; - $newKey ??= $attribute['key']; $twoWayKey = $attribute['options']['twoWayKey']; $newTwoWayKey ??= $attribute['options']['twoWayKey']; @@ -2363,68 +2433,76 @@ public function updateRelationship( throw new DatabaseException('Failed to update relationship'); } } + }); - $this->purgeCachedCollection($collection->getId()); - $this->purgeCachedCollection($relatedCollection->getId()); + // Update Indexes + $renameIndex = function (string $collection, string $key, string $newKey) { + $this->updateIndexMeta( + $collection, + '_index_' . $key, + function ($index) use ($newKey) { + $index->setAttribute('attributes', [$newKey]); + } + ); + $this->silent( + fn () => + $this->renameIndex($collection, '_index_' . $key, '_index_' . $newKey) + ); + }; - $renameIndex = function (string $collection, string $key, string $newKey) { - $this->updateIndexMeta( - $collection, - '_index_' . $key, - fn ($index) => - $index->setAttribute('attributes', [$newKey]) - ); - $this->silent( - fn () => - $this->renameIndex($collection, '_index_' . $key, '_index_' . $newKey) - ); - }; + $newKey ??= $attribute['key']; + $twoWayKey = $attribute['options']['twoWayKey']; + $newTwoWayKey ??= $attribute['options']['twoWayKey']; + $twoWay ??= $attribute['options']['twoWay']; + $onDelete ??= $attribute['options']['onDelete']; - switch ($type) { - case self::RELATION_ONE_TO_ONE: - if ($id !== $newKey) { - $renameIndex($collection->getId(), $id, $newKey); - } - if ($twoWay && $twoWayKey !== $newTwoWayKey) { + switch ($type) { + case self::RELATION_ONE_TO_ONE: + if ($id !== $newKey) { + $renameIndex($collection->getId(), $id, $newKey); + } + if ($twoWay && $twoWayKey !== $newTwoWayKey) { + $renameIndex($relatedCollection->getId(), $twoWayKey, $newTwoWayKey); + } + break; + case self::RELATION_ONE_TO_MANY: + if ($side === Database::RELATION_SIDE_PARENT) { + if ($twoWayKey !== $newTwoWayKey) { $renameIndex($relatedCollection->getId(), $twoWayKey, $newTwoWayKey); } - break; - case self::RELATION_ONE_TO_MANY: - if ($side === Database::RELATION_SIDE_PARENT) { - if ($twoWayKey !== $newTwoWayKey) { - $renameIndex($relatedCollection->getId(), $twoWayKey, $newTwoWayKey); - } - } else { - if ($id !== $newKey) { - $renameIndex($collection->getId(), $id, $newKey); - } - } - break; - case self::RELATION_MANY_TO_ONE: - if ($side === Database::RELATION_SIDE_PARENT) { - if ($id !== $newKey) { - $renameIndex($collection->getId(), $id, $newKey); - } - } else { - if ($twoWayKey !== $newTwoWayKey) { - $renameIndex($relatedCollection->getId(), $twoWayKey, $newTwoWayKey); - } + } else { + if ($id !== $newKey) { + $renameIndex($collection->getId(), $id, $newKey); } - break; - case self::RELATION_MANY_TO_MANY: - $junction = $this->getJunctionCollection($collection, $relatedCollection, $side); - + } + break; + case self::RELATION_MANY_TO_ONE: + if ($side === Database::RELATION_SIDE_PARENT) { if ($id !== $newKey) { - $renameIndex($junction, $id, $newKey); + $renameIndex($collection->getId(), $id, $newKey); } + } else { if ($twoWayKey !== $newTwoWayKey) { - $renameIndex($junction, $twoWayKey, $newTwoWayKey); + $renameIndex($relatedCollection->getId(), $twoWayKey, $newTwoWayKey); } - break; - default: - throw new RelationshipException('Invalid relationship type.'); - } - }); + } + break; + case self::RELATION_MANY_TO_MANY: + $junction = $this->getJunctionCollection($collection, $relatedCollection, $side); + + if ($id !== $newKey) { + $renameIndex($junction, $id, $newKey); + } + if ($twoWayKey !== $newTwoWayKey) { + $renameIndex($junction, $twoWayKey, $newTwoWayKey); + } + break; + default: + throw new RelationshipException('Invalid relationship type.'); + } + + $this->purgeCachedCollection($collection->getId()); + $this->purgeCachedCollection($relatedCollection->getId()); return true; } @@ -2443,10 +2521,6 @@ public function updateRelationship( */ public function deleteRelationship(string $collection, string $id): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); $attributes = $collection->getAttribute('attributes', []); $relationship = null; @@ -2460,7 +2534,7 @@ public function deleteRelationship(string $collection, string $id): bool } if (\is_null($relationship)) { - throw new DatabaseException('Attribute not found'); + throw new NotFoundException('Attribute not found'); } $collection->setAttribute('attributes', \array_values($attributes)); @@ -2571,10 +2645,6 @@ public function deleteRelationship(string $collection, string $id): bool */ public function renameIndex(string $collection, string $old, string $new): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); $indexes = $collection->getAttribute('indexes', []); @@ -2582,7 +2652,7 @@ public function renameIndex(string $collection, string $old, string $new): bool $index = \in_array($old, \array_map(fn ($index) => $index['$id'], $indexes)); if ($index === false) { - throw new DatabaseException('Index not found'); + throw new NotFoundException('Index not found'); } $indexNew = \in_array($new, \array_map(fn ($index) => $index['$id'], $indexes)); @@ -2634,10 +2704,6 @@ public function renameIndex(string $collection, string $old, string $new): bool */ public function createIndex(string $collection, string $id, string $type, array $attributes, array $lengths = [], array $orders = []): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - if (empty($attributes)) { throw new DatabaseException('Missing attributes'); } @@ -2687,6 +2753,16 @@ public function createIndex(string $collection, string $id, string $type, array foreach ($attributes as $i => $attr) { foreach ($collectionAttributes as $collectionAttribute) { if ($collectionAttribute->getAttribute('key') === $attr) { + + /** + * mysql does not save length in collection when length = attributes size + */ + if ($collectionAttribute->getAttribute('type') === Database::VAR_STRING) { + if (!empty($lengths[$i]) && $lengths[$i] === $collectionAttribute->getAttribute('size') && $this->adapter->getMaxIndexLength() > 0) { + $lengths[$i] = null; + } + } + $isArray = $collectionAttribute->getAttribute('array', false); if ($isArray) { if ($this->adapter->getMaxIndexLength() > 0) { @@ -2713,7 +2789,8 @@ public function createIndex(string $collection, string $id, string $type, array if ($this->validate) { $validator = new IndexValidator( $collection->getAttribute('attributes', []), - $this->adapter->getMaxIndexLength() + $this->adapter->getMaxIndexLength(), + $this->adapter->getInternalIndexesKeys() ); if (!$validator->isValid($index)) { throw new DatabaseException($validator->getDescription()); @@ -2728,7 +2805,8 @@ public function createIndex(string $collection, string $id, string $type, array } } catch (DuplicateException $e) { // HACK: Metadata should still be updated, can be removed when null tenant collections are supported. - if (!$this->adapter->getSharedTables()) { + + if (!$this->adapter->getSharedTables() || !$this->isMigrating()) { throw $e; } } @@ -2756,10 +2834,6 @@ public function createIndex(string $collection, string $id, string $type, array */ public function deleteIndex(string $collection, string $id): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); $indexes = $collection->getAttribute('indexes', []); @@ -2772,14 +2846,14 @@ public function deleteIndex(string $collection, string $id): bool } } + $deleted = $this->adapter->deleteIndex($collection->getId(), $id); + $collection->setAttribute('indexes', \array_values($indexes)); if ($collection->getId() !== self::METADATA) { $this->silent(fn () => $this->updateDocument(self::METADATA, $collection->getId(), $collection)); } - $deleted = $this->adapter->deleteIndex($collection->getId(), $id); - $this->trigger(self::EVENT_INDEX_DELETE, $indexDeleted); return $deleted; @@ -2798,16 +2872,12 @@ public function deleteIndex(string $collection, string $id): bool */ public function getDocument(string $collection, string $id, array $queries = [], bool $forUpdate = false): Document { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - if ($collection === self::METADATA && $id === self::METADATA) { return new Document(self::COLLECTION); } if (empty($collection)) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } if (empty($id)) { @@ -2817,7 +2887,7 @@ public function getDocument(string $collection, string $id, array $queries = [], $collection = $this->silent(fn () => $this->getCollection($collection)); if ($collection->isEmpty()) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } $attributes = $collection->getAttribute('attributes', []); @@ -2874,6 +2944,7 @@ public function getDocument(string $collection, string $id, array $queries = [], $queries = \array_values($queries); + $validator = new Authorization(self::PERMISSION_READ); $documentSecurity = $collection->getAttribute('documentSecurity', false); /** @@ -2890,12 +2961,10 @@ public function getDocument(string $collection, string $id, array $queries = [], $document = new Document($cache); if ($collection->getId() !== self::METADATA) { - $isValid = $this->authorization->isValid(new Input(self::PERMISSION_READ, [ + if (!$validator->isValid([ ...$collection->getRead(), ...($documentSecurity ? $document->getRead() : []) - ])); - - if (!$isValid) { + ])) { return new Document(); } } @@ -2914,12 +2983,10 @@ public function getDocument(string $collection, string $id, array $queries = [], $document->setAttribute('$collection', $collection->getId()); if ($collection->getId() !== self::METADATA) { - $isValid = $this->authorization->isValid(new Input(self::PERMISSION_READ, [ + if (!$validator->isValid([ ...$collection->getRead(), ...($documentSecurity ? $document->getRead() : []) - ])); - - if (!$isValid) { + ])) { return new Document(); } } @@ -2935,7 +3002,7 @@ public function getDocument(string $collection, string $id, array $queries = [], $relationships = \array_filter( $collection->getAttribute('attributes', []), fn ($attribute) => - $attribute['type'] === Database::VAR_RELATIONSHIP + $attribute['type'] === Database::VAR_RELATIONSHIP ); $hasTwoWayRelationship = false; @@ -2948,7 +3015,6 @@ public function getDocument(string $collection, string $id, array $queries = [], /** * Bug with function purity in PHPStan means it thinks $this->map is always empty - * * @phpstan-ignore-next-line */ foreach ($this->map as $key => $value) { @@ -2964,10 +3030,10 @@ public function getDocument(string $collection, string $id, array $queries = [], } } - // Don't save to cache if it's part of a two-way relationship or a relationship at all + // Don't save to cache if it's part of a relationship if (!$hasTwoWayRelationship && empty($relationships)) { $this->cache->save($documentCacheKey, $document->getArrayCopy(), $documentCacheHash); - //add document reference to the collection key + // Add document reference to the collection key $this->cache->save($collectionCacheKey, 'empty', $documentCacheKey); } @@ -2978,7 +3044,7 @@ public function getDocument(string $collection, string $id, array $queries = [], if ($query->getMethod() === Query::TYPE_SELECT) { $values = $query->getValues(); foreach ($this->getInternalAttributes() as $internalAttribute) { - if (!in_array($internalAttribute['$id'], $values)) { + if (!\in_array($internalAttribute['$id'], $values)) { $document->removeAttribute($internalAttribute['$id']); } } @@ -3052,8 +3118,8 @@ private function populateDocumentRelationships(Document $collection, Document $d // collection as an existing relationship, but a different two-way key (the third condition), // or the same two-way key as an existing relationship, but a different key (the fourth condition). $transitive = (($existingKey === $twoWayKey - && $existingCollection === $relatedCollection->getId() - && $existingSide !== $side) + && $existingCollection === $relatedCollection->getId() + && $existingSide !== $side) || ($existingTwoWayKey === $key && $existingRelatedCollection === $collection->getId() && $existingSide !== $side) @@ -3237,16 +3303,20 @@ private function populateDocumentRelationships(Document $collection, Document $d */ public function createDocument(string $collection, Document $document): Document { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { + if ( + $collection !== self::METADATA + && $this->adapter->getSharedTables() + && empty($this->adapter->getTenant()) + ) { throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); } $collection = $this->silent(fn () => $this->getCollection($collection)); if ($collection->getId() !== self::METADATA) { - $isValid = $this->authorization->isValid(new Input(self::PERMISSION_CREATE, $collection->getCreate())); - if (!$isValid) { - throw new AuthorizationException($this->authorization->getDescription()); + $authorization = new Authorization(self::PERMISSION_CREATE); + if (!$authorization->isValid($collection->getCreate())) { + throw new AuthorizationException($authorization->getDescription()); } } @@ -3274,7 +3344,11 @@ public function createDocument(string $collection, Document $document): Document } } - $structure = new Structure($collection); + $structure = new Structure( + $collection, + $this->adapter->getMinDateTime(), + $this->adapter->getMaxDateTime(), + ); if (!$structure->isValid($document)) { throw new StructureException($structure->getDescription()); } @@ -3294,6 +3368,7 @@ public function createDocument(string $collection, Document $document): Document $document = $this->decode($collection, $document); $this->trigger(self::EVENT_DOCUMENT_CREATE, $document); + return $document; } @@ -3312,10 +3387,6 @@ public function createDocument(string $collection, Document $document): Document */ public function createDocuments(string $collection, array $documents, int $batchSize = self::INSERT_BATCH_SIZE): array { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - if (empty($documents)) { return []; } @@ -3336,7 +3407,11 @@ public function createDocuments(string $collection, array $documents, int $batch $document = $this->encode($collection, $document); - $validator = new Structure($collection); + $validator = new Structure( + $collection, + $this->adapter->getMinDateTime(), + $this->adapter->getMaxDateTime(), + ); if (!$validator->isValid($document)) { throw new StructureException($validator->getDescription()); } @@ -3360,7 +3435,10 @@ public function createDocuments(string $collection, array $documents, int $batch $documents[$key] = $this->decode($collection, $document); } - $this->trigger(self::EVENT_DOCUMENTS_CREATE, $documents); + $this->trigger(self::EVENT_DOCUMENTS_CREATE, new Document([ + '$collection' => $collection->getId(), + 'modified' => count($documents) + ])); return $documents; } @@ -3378,7 +3456,7 @@ private function createDocumentRelationships(Document $collection, Document $doc $relationships = \array_filter( $attributes, fn ($attribute) => - $attribute['type'] === Database::VAR_RELATIONSHIP + $attribute['type'] === Database::VAR_RELATIONSHIP ); $stackCount = count($this->relationshipWriteStack); @@ -3647,7 +3725,7 @@ private function relateDocumentsById( // Get the related document, will be empty on permissions failure $related = $this->skipRelationships(fn () => $this->getDocument($relatedCollection->getId(), $relationId)); - if ($related->isEmpty()) { + if ($related->isEmpty() && $this->checkRelationshipsExist) { return; } @@ -3676,7 +3754,7 @@ private function relateDocumentsById( $junction = $this->getJunctionCollection($collection, $relatedCollection, $side); $this->skipRelationships(fn () => $this->createDocument($junction, new Document([ - $key => $related->getId(), + $key => $relationId, $twoWayKey => $documentId, '$permissions' => [ Permission::read(Role::any()), @@ -3703,10 +3781,6 @@ private function relateDocumentsById( */ public function updateDocument(string $collection, string $id, Document $document): Document { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - if (!$id) { throw new DatabaseException('Must define $id attribute'); } @@ -3715,7 +3789,7 @@ public function updateDocument(string $collection, string $id, Document $documen $document = $this->withTransaction(function () use ($collection, $id, $document) { $time = DateTime::now(); - $old = $this->authorization->skip(fn () => $this->silent( + $old = Authorization::skip(fn () => $this->silent( fn () => $this->getDocument($collection->getId(), $id, forUpdate: true) )); @@ -3734,6 +3808,8 @@ public function updateDocument(string $collection, string $id, Document $documen return $attribute['type'] === Database::VAR_RELATIONSHIP; }); + $updateValidator = new Authorization(self::PERMISSION_UPDATE); + $readValidator = new Authorization(self::PERMISSION_READ); $shouldUpdate = false; if ($collection->getId() !== self::METADATA) { @@ -3827,19 +3903,20 @@ public function updateDocument(string $collection, string $id, Document $documen } } - $updateValidator = new Input(self::PERMISSION_UPDATE, [ + $updatePermissions = [ ...$collection->getUpdate(), ...($documentSecurity ? $old->getUpdate() : []) - ]); + ]; - $readValidator = new Input(self::PERMISSION_READ, [ + $readPermissions = [ ...$collection->getRead(), ...($documentSecurity ? $old->getRead() : []) - ]); + ]; - if (($shouldUpdate && !$this->authorization->isValid($updateValidator)) - || (!$shouldUpdate && !$this->authorization->isValid($readValidator))) { - throw new AuthorizationException($this->authorization->getDescription()); + if ($shouldUpdate && !$updateValidator->isValid($updatePermissions)) { + throw new AuthorizationException($updateValidator->getDescription()); + } elseif (!$shouldUpdate && !$readValidator->isValid($readPermissions)) { + throw new AuthorizationException($readValidator->getDescription()); } } @@ -3860,7 +3937,11 @@ public function updateDocument(string $collection, string $id, Document $documen $document = $this->encode($collection, $document); - $structureValidator = new Structure($collection); + $structureValidator = new Structure( + $collection, + $this->adapter->getMinDateTime(), + $this->adapter->getMaxDateTime(), + ); if (!$structureValidator->isValid($document)) { // Make sure updated structure still apply collection rules (if any) throw new StructureException($structureValidator->getDescription()); } @@ -3897,24 +3978,48 @@ public function updateDocument(string $collection, string $id, Document $documen * @param array $queries * @param int $batchSize * - * @return int + * @return array * * @throws AuthorizationException * @throws DatabaseException */ - public function updateDocuments(string $collection, Document $updates, array $queries = [], int $batchSize = self::INSERT_BATCH_SIZE): int + public function updateDocuments(string $collection, Document $updates, array $queries = [], int $batchSize = self::INSERT_BATCH_SIZE): array { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - if ($updates->isEmpty()) { - return 0; + return []; } - $queries = Query::groupByType($queries)['filters']; $collection = $this->silent(fn () => $this->getCollection($collection)); + if ($collection->isEmpty()) { + throw new DatabaseException('Collection not found'); + } + + $attributes = $collection->getAttribute('attributes', []); + $indexes = $collection->getAttribute('indexes', []); + + if ($this->validate) { + $validator = new DocumentsValidator( + $attributes, + $indexes, + $this->maxQueryValues, + $this->adapter->getMinDateTime(), + $this->adapter->getMaxDateTime(), + ); + + if (!$validator->isValid($queries)) { + throw new QueryException($validator->getDescription()); + } + } + + $grouped = Query::groupByType($queries); + $limit = $grouped['limit']; + $cursor = $grouped['cursor']; + + if (!empty($cursor) && $cursor->getCollection() !== $collection->getId()) { + throw new DatabaseException("cursor Document must be from the same Collection."); + } + unset($updates['$id']); unset($updates['$createdAt']); unset($updates['$tenant']); @@ -3926,35 +4031,49 @@ public function updateDocuments(string $collection, Document $updates, array $qu $updates = $this->encode($collection, $updates); // Check new document structure - $validator = new PartialStructure($collection); + $validator = new PartialStructure( + $collection, + $this->adapter->getMinDateTime(), + $this->adapter->getMaxDateTime(), + ); + if (!$validator->isValid($updates)) { throw new StructureException($validator->getDescription()); } - $affected = $this->withTransaction(function () use ($collection, $queries, $batchSize, $updates) { + $documents = $this->withTransaction(function () use ($collection, $queries, $batchSize, $updates, $limit, $cursor) { $lastDocument = null; - $totalModified = 0; - $affectedDocumentIds = []; + $documents = []; $documentSecurity = $collection->getAttribute('documentSecurity', false); - $skipAuth = $this->authorization->isValid(new Input(self::PERMISSION_UPDATE, $collection->getUpdate())); + $authorization = new Authorization(self::PERMISSION_UPDATE); + $skipAuth = $authorization->isValid($collection->getUpdate()); if (!$skipAuth && !$documentSecurity && $collection->getId() !== self::METADATA) { - throw new AuthorizationException($this->authorization->getDescription()); + throw new AuthorizationException($authorization->getDescription()); } + $originalLimit = $limit; + $lastDocument = $cursor; + // Resolve and update relationships while (true) { - $affectedDocuments = $this->find($collection->getId(), array_merge( + if ($limit && $limit < $batchSize) { + $batchSize = $limit; + } elseif (!empty($limit)) { + $limit -= $batchSize; + } + + $affectedDocuments = $this->silent(fn () => $this->find($collection->getId(), array_merge( + $queries, empty($lastDocument) ? [ Query::limit($batchSize), ] : [ Query::limit($batchSize), Query::cursorAfter($lastDocument), - ], - $queries, - ), forPermission: Database::PERMISSION_UPDATE); + ] + ), forPermission: Database::PERMISSION_UPDATE)); if (empty($affectedDocuments)) { break; @@ -3962,12 +4081,21 @@ public function updateDocuments(string $collection, Document $updates, array $qu foreach ($affectedDocuments as $document) { if ($this->resolveRelationships) { - $newDocument = array_merge($document->getArrayCopy(), $updates->getArrayCopy()); + $newDocument = new Document(array_merge($document->getArrayCopy(), $updates->getArrayCopy())); + $this->silent(fn () => $this->updateDocumentRelationships($collection, $document, $newDocument)); + $documents[] = $newDocument; + } - $this->silent(fn () => $this->updateDocumentRelationships($collection, $document, new Document($newDocument))); + // Check if document was updated after the request timestamp + try { + $oldUpdatedAt = new \DateTime($document->getUpdatedAt()); + } catch (Exception $e) { + throw new DatabaseException($e->getMessage(), $e->getCode(), $e); } - $affectedDocumentIds[] = $document->getId(); + if (!is_null($this->timestamp) && $oldUpdatedAt > $this->timestamp) { + throw new ConflictException('Document was updated after the request timestamp'); + } } $getResults = fn () => $this->adapter->updateDocuments( @@ -3976,28 +4104,31 @@ public function updateDocuments(string $collection, Document $updates, array $qu $affectedDocuments ); - $result = $skipAuth ? $this->authorization->skip($getResults) : $getResults(); - - $totalModified += $result; + $skipAuth ? $authorization->skip($getResults) : $getResults(); if (count($affectedDocuments) < $batchSize) { break; - } else { - $lastDocument = end($affectedDocuments); + } elseif ($originalLimit && count($documents) == $originalLimit) { + break; } - } - $this->trigger(self::EVENT_DOCUMENTS_UPDATE, $affectedDocumentIds); + $lastDocument = end($affectedDocuments); + } - foreach ($affectedDocumentIds as $id) { - $this->purgeRelatedDocuments($collection, $id); - $this->purgeCachedDocument($collection->getId(), $id); + foreach ($documents as $document) { + $this->purgeRelatedDocuments($collection, $document->getId()); + $this->purgeCachedDocument($collection->getId(), $document->getId()); } - return $totalModified; + $this->trigger(self::EVENT_DOCUMENTS_UPDATE, new Document([ + '$collection' => $collection->getId(), + 'modified' => count($documents) + ])); + + return $documents; }); - return $affected; + return $documents; } /** @@ -4196,7 +4327,7 @@ private function updateDocumentRelationships(Document $collection, Document $old $removedDocuments = \array_diff($oldIds, $newIds); foreach ($removedDocuments as $relation) { - $this->authorization->skip(fn () => $this->skipRelationships(fn () => $this->updateDocument( + Authorization::skip(fn () => $this->skipRelationships(fn () => $this->updateDocument( $relatedCollection->getId(), $relation, new Document([$twoWayKey => null]) @@ -4326,7 +4457,7 @@ private function updateDocumentRelationships(Document $collection, Document $old ]); foreach ($junctions as $junction) { - $this->authorization->skip(fn () => $this->deleteDocument($junction->getCollection(), $junction->getId())); + Authorization::skip(fn () => $this->deleteDocument($junction->getCollection(), $junction->getId())); } } @@ -4411,16 +4542,14 @@ private function getJunctionCollection(Document $collection, Document $relatedCo */ public function increaseDocumentAttribute(string $collection, string $id, string $attribute, int|float $value = 1, int|float|null $max = null): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - if ($value <= 0) { // Can be a float throw new DatabaseException('Value must be numeric and greater than 0'); } + $validator = new Authorization(self::PERMISSION_UPDATE); + /* @var $document Document */ - $document = $this->authorization->skip(fn () => $this->silent(fn () => $this->getDocument($collection, $id))); // Skip ensures user does not need read permission for this + $document = Authorization::skip(fn () => $this->silent(fn () => $this->getDocument($collection, $id))); // Skip ensures user does not need read permission for this if ($document->isEmpty()) { return false; @@ -4430,12 +4559,11 @@ public function increaseDocumentAttribute(string $collection, string $id, string if ($collection->getId() !== self::METADATA) { $documentSecurity = $collection->getAttribute('documentSecurity', false); - $isValid = $this->authorization->isValid(new Input(self::PERMISSION_UPDATE, [ + if (!$validator->isValid([ ...$collection->getUpdate(), ...($documentSecurity ? $document->getUpdate() : []) - ])); - if (!$isValid) { - throw new AuthorizationException($this->authorization->getDescription()); + ])) { + throw new AuthorizationException($validator->getDescription()); } } @@ -4444,7 +4572,7 @@ public function increaseDocumentAttribute(string $collection, string $id, string }); if (empty($attr)) { - throw new DatabaseException('Attribute not found'); + throw new NotFoundException('Attribute not found'); } $whiteList = [self::VAR_INTEGER, self::VAR_FLOAT]; @@ -4505,15 +4633,14 @@ public function increaseDocumentAttribute(string $collection, string $id, string */ public function decreaseDocumentAttribute(string $collection, string $id, string $attribute, int|float $value = 1, int|float|null $min = null): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - if ($value <= 0) { // Can be a float throw new DatabaseException('Value must be numeric and greater than 0'); } + + $validator = new Authorization(self::PERMISSION_UPDATE); + /* @var $document Document */ - $document = $this->authorization->skip(fn () => $this->silent(fn () => $this->getDocument($collection, $id))); // Skip ensures user does not need read permission for this + $document = Authorization::skip(fn () => $this->silent(fn () => $this->getDocument($collection, $id))); // Skip ensures user does not need read permission for this if ($document->isEmpty()) { return false; @@ -4523,12 +4650,11 @@ public function decreaseDocumentAttribute(string $collection, string $id, string if ($collection->getId() !== self::METADATA) { $documentSecurity = $collection->getAttribute('documentSecurity', false); - $isValid = $this->authorization->isValid(new Input(self::PERMISSION_UPDATE, [ + if (!$validator->isValid([ ...$collection->getUpdate(), ...($documentSecurity ? $document->getUpdate() : []) - ])); - if (!$isValid) { - throw new AuthorizationException($this->authorization->getDescription()); + ])) { + throw new AuthorizationException($validator->getDescription()); } } @@ -4537,7 +4663,7 @@ public function decreaseDocumentAttribute(string $collection, string $id, string }); if (empty($attr)) { - throw new DatabaseException('Attribute not found'); + throw new NotFoundException('Attribute not found'); } $whiteList = [self::VAR_INTEGER, self::VAR_FLOAT]; @@ -4594,19 +4720,13 @@ public function decreaseDocumentAttribute(string $collection, string $id, string * @throws ConflictException * @throws DatabaseException * @throws RestrictedException - * @throws StructureException */ public function deleteDocument(string $collection, string $id): bool { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); $deleted = $this->withTransaction(function () use ($collection, $id, &$document) { - /* @var $document Document */ - $document = $this->authorization->skip(fn () => $this->silent( + $document = Authorization::skip(fn () => $this->silent( fn () => $this->getDocument($collection->getId(), $id, forUpdate: true) )); @@ -4615,14 +4735,15 @@ public function deleteDocument(string $collection, string $id): bool return false; } + $validator = new Authorization(self::PERMISSION_DELETE); + if ($collection->getId() !== self::METADATA) { $documentSecurity = $collection->getAttribute('documentSecurity', false); - $isValid = $this->authorization->isValid(new Input(self::PERMISSION_DELETE, [ + if (!$validator->isValid([ ...$collection->getDelete(), ...($documentSecurity ? $document->getDelete() : []) - ])); - if (!$isValid) { - throw new AuthorizationException($this->authorization->getDescription()); + ])) { + throw new AuthorizationException($validator->getDescription()); } } @@ -4633,7 +4754,7 @@ public function deleteDocument(string $collection, string $id): bool throw new DatabaseException($e->getMessage(), $e->getCode(), $e); } - if (!is_null($this->timestamp) && $oldUpdatedAt > $this->timestamp) { + if (!\is_null($this->timestamp) && $oldUpdatedAt > $this->timestamp) { throw new ConflictException('Document was updated after the request timestamp'); } @@ -4717,8 +4838,8 @@ private function deleteDocumentRelationships(Document $collection, Document $doc // collection as an existing relationship, but a different two-way key (the third condition), // or the same two-way key as an existing relationship, but a different key (the fourth condition). $transitive = (($existingKey === $twoWayKey - && $existingCollection === $relatedCollection->getId() - && $existingSide !== $side) + && $existingCollection === $relatedCollection->getId() + && $existingSide !== $side) || ($existingTwoWayKey === $key && $existingRelatedCollection === $collection->getId() && $existingSide !== $side) @@ -4783,7 +4904,7 @@ private function deleteRestrict( && $side === Database::RELATION_SIDE_CHILD && !$twoWay ) { - $this->authorization->skip(function () use ($document, $relatedCollection, $twoWayKey) { + Authorization::skip(function () use ($document, $relatedCollection, $twoWayKey) { $related = $this->findOne($relatedCollection->getId(), [ Query::select(['$id']), Query::equal($twoWayKey, [$document->getId()]) @@ -4807,7 +4928,7 @@ private function deleteRestrict( $relationType === Database::RELATION_MANY_TO_ONE && $side === Database::RELATION_SIDE_CHILD ) { - $related = $this->authorization->skip(fn () => $this->findOne($relatedCollection->getId(), [ + $related = Authorization::skip(fn () => $this->findOne($relatedCollection->getId(), [ Query::select(['$id']), Query::equal($twoWayKey, [$document->getId()]) ])); @@ -4843,7 +4964,7 @@ private function deleteSetNull(Document $collection, Document $relatedCollection } // Shouldn't need read or update permission to delete - $this->authorization->skip(function () use ($document, $value, $relatedCollection, $twoWay, $twoWayKey, $side) { + Authorization::skip(function () use ($document, $value, $relatedCollection, $twoWay, $twoWayKey, $side) { if (!$twoWay && $side === Database::RELATION_SIDE_CHILD) { $related = $this->findOne($relatedCollection->getId(), [ Query::select(['$id']), @@ -4875,7 +4996,7 @@ private function deleteSetNull(Document $collection, Document $relatedCollection break; } foreach ($value as $relation) { - $this->authorization->skip(function () use ($relatedCollection, $twoWayKey, $relation) { + Authorization::skip(function () use ($relatedCollection, $twoWayKey, $relation) { $this->skipRelationships(fn () => $this->updateDocument( $relatedCollection->getId(), $relation->getId(), @@ -4901,7 +5022,7 @@ private function deleteSetNull(Document $collection, Document $relatedCollection } foreach ($value as $relation) { - $this->authorization->skip(function () use ($relatedCollection, $twoWayKey, $relation) { + Authorization::skip(function () use ($relatedCollection, $twoWayKey, $relation) { $this->skipRelationships(fn () => $this->updateDocument( $relatedCollection->getId(), $relation->getId(), @@ -5042,48 +5163,84 @@ private function deleteCascade(Document $collection, Document $relatedCollection * @param array $queries * @param int $batchSize * - * @return int + * @return array * * @throws AuthorizationException * @throws DatabaseException * @throws RestrictedException */ - public function deleteDocuments(string $collection, array $queries = [], int $batchSize = self::DELETE_BATCH_SIZE): int + public function deleteDocuments(string $collection, array $queries = [], int $batchSize = self::DELETE_BATCH_SIZE): array { if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); } - $queries = Query::groupByType($queries)['filters']; $collection = $this->silent(fn () => $this->getCollection($collection)); - $affectedDocumentIds = []; - $deleted = $this->withTransaction(function () use ($collection, $queries, $batchSize, $affectedDocumentIds) { - $lastDocument = null; + if ($collection->isEmpty()) { + throw new DatabaseException('Collection not found'); + } + + $attributes = $collection->getAttribute('attributes', []); + $indexes = $collection->getAttribute('indexes', []); + + if ($this->validate) { + $validator = new DocumentsValidator( + $attributes, + $indexes, + $this->maxQueryValues, + $this->adapter->getMinDateTime(), + $this->adapter->getMaxDateTime() + ); + if (!$validator->isValid($queries)) { + throw new QueryException($validator->getDescription()); + } + } + + $grouped = Query::groupByType($queries); + $limit = $grouped['limit']; + $cursor = $grouped['cursor']; + + if (!empty($cursor) && $cursor->getCollection() !== $collection->getId()) { + throw new DatabaseException("cursor Document must be from the same Collection."); + } + + $documents = $this->withTransaction(function () use ($collection, $queries, $batchSize, $limit, $cursor) { $documentSecurity = $collection->getAttribute('documentSecurity', false); - $skipAuth = $this->authorization->isValid(new Input(self::PERMISSION_DELETE, $collection->getDelete())); + $authorization = new Authorization(self::PERMISSION_DELETE); + $skipAuth = $authorization->isValid($collection->getDelete()); + $documents = []; if (!$skipAuth && !$documentSecurity && $collection->getId() !== self::METADATA) { - throw new AuthorizationException($this->authorization->getDescription()); + throw new AuthorizationException($authorization->getDescription()); } + $originalLimit = $limit; + $lastDocument = $cursor; + while (true) { - $affectedDocuments = $this->find($collection->getId(), array_merge( + if ($limit && $limit < $batchSize) { + $batchSize = $limit; + } elseif (!empty($limit)) { + $limit -= $batchSize; + } + + $affectedDocuments = $this->silent(fn () => $this->find($collection->getId(), array_merge( + $queries, empty($lastDocument) ? [ Query::limit($batchSize), ] : [ Query::limit($batchSize), Query::cursorAfter($lastDocument), - ], - $queries, - ), forPermission: Database::PERMISSION_DELETE); + ] + ), forPermission: Database::PERMISSION_DELETE)); if (empty($affectedDocuments)) { break; } - $affectedDocumentIds = array_merge($affectedDocumentIds, array_map(fn ($document) => $document->getId(), $affectedDocuments)); + $documents = array_merge($affectedDocuments, $documents); foreach ($affectedDocuments as $document) { // Delete Relationships @@ -5091,28 +5248,45 @@ public function deleteDocuments(string $collection, array $queries = [], int $ba $document = $this->silent(fn () => $this->deleteDocumentRelationships($collection, $document)); } + // Check if document was updated after the request timestamp + try { + $oldUpdatedAt = new \DateTime($document->getUpdatedAt()); + } catch (Exception $e) { + throw new DatabaseException($e->getMessage(), $e->getCode(), $e); + } + + if (!\is_null($this->timestamp) && $oldUpdatedAt > $this->timestamp) { + throw new ConflictException('Document was updated after the request timestamp'); + } + $this->purgeRelatedDocuments($collection, $document->getId()); $this->purgeCachedDocument($collection->getId(), $document->getId()); } if (count($affectedDocuments) < $batchSize) { break; - } else { - $lastDocument = end($affectedDocuments); + } elseif ($originalLimit && count($documents) == $originalLimit) { + break; } + + $lastDocument = end($affectedDocuments); } - if (empty($affectedDocumentIds)) { - return 0; + if (empty($documents)) { + return []; } - $this->trigger(self::EVENT_DOCUMENTS_DELETE, $affectedDocumentIds); + $this->trigger(self::EVENT_DOCUMENTS_DELETE, new Document([ + '$collection' => $collection->getId(), + 'modified' => count($documents) + ])); + + $this->adapter->deleteDocuments($collection->getId(), array_map(fn ($document) => $document->getId(), $documents)); - // Mass delete using adapter with query - return $this->adapter->deleteDocuments($collection->getId(), $affectedDocumentIds); + return $documents; }); - return $deleted; + return $documents; } /** @@ -5165,35 +5339,38 @@ public function purgeCachedDocument(string $collectionId, string $id): bool * @throws DatabaseException * @throws QueryException * @throws TimeoutException + * @throws Exception */ public function find(string $collection, array $queries = [], string $forPermission = Database::PERMISSION_READ): array { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); if ($collection->isEmpty()) { - throw new DatabaseException('Collection not found'); + throw new NotFoundException('Collection not found'); } $attributes = $collection->getAttribute('attributes', []); $indexes = $collection->getAttribute('indexes', []); if ($this->validate) { - $validator = new DocumentsValidator($attributes, $indexes); + $validator = new DocumentsValidator( + $attributes, + $indexes, + $this->maxQueryValues, + $this->adapter->getMinDateTime(), + $this->adapter->getMaxDateTime(), + ); if (!$validator->isValid($queries)) { throw new QueryException($validator->getDescription()); } } + $authorization = new Authorization(self::PERMISSION_READ); $documentSecurity = $collection->getAttribute('documentSecurity', false); - - $skipAuth = $this->authorization->isValid(new Input($forPermission, $collection->getPermissionsByType($forPermission))); + $skipAuth = $authorization->isValid($collection->getPermissionsByType($forPermission)); if (!$skipAuth && !$documentSecurity && $collection->getId() !== self::METADATA) { - throw new AuthorizationException($this->authorization->getDescription()); + throw new AuthorizationException($authorization->getDescription()); } $relationships = \array_filter( @@ -5281,7 +5458,7 @@ public function find(string $collection, array $queries = [], string $forPermiss $forPermission ); - $results = $skipAuth ? $this->authorization->skip($getResults) : $getResults(); + $results = $skipAuth ? Authorization::skip($getResults) : $getResults(); foreach ($results as &$node) { if ($this->resolveRelationships && (empty($selects) || !empty($nestedSelections))) { @@ -5353,28 +5530,33 @@ public function findOne(string $collection, array $queries = []): Document */ public function count(string $collection, array $queries = [], ?int $max = null): int { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); $attributes = $collection->getAttribute('attributes', []); $indexes = $collection->getAttribute('indexes', []); if ($this->validate) { - $validator = new DocumentsValidator($attributes, $indexes); + $validator = new DocumentsValidator( + $attributes, + $indexes, + $this->maxQueryValues, + $this->adapter->getMinDateTime(), + $this->adapter->getMaxDateTime(), + ); if (!$validator->isValid($queries)) { throw new QueryException($validator->getDescription()); } } - $skipAuth = $this->authorization->isValid(new Input(self::PERMISSION_READ, $collection->getRead())); + $authorization = new Authorization(self::PERMISSION_READ); + if ($authorization->isValid($collection->getRead())) { + $skipAuth = true; + } $queries = Query::groupByType($queries)['filters']; $queries = self::convertQueries($collection, $queries); $getCount = fn () => $this->adapter->count($collection->getId(), $queries, $max); - $count = $skipAuth ? $this->authorization->skip($getCount) : $getCount(); + $count = $skipAuth ?? false ? Authorization::skip($getCount) : $getCount(); $this->trigger(self::EVENT_DOCUMENT_COUNT, $count); @@ -5396,16 +5578,18 @@ public function count(string $collection, array $queries = [], ?int $max = null) */ public function sum(string $collection, string $attribute, array $queries = [], ?int $max = null): float|int { - if ($this->adapter->getSharedTables() && empty($this->adapter->getTenant())) { - throw new DatabaseException('Missing tenant. Tenant must be set when table sharing is enabled.'); - } - $collection = $this->silent(fn () => $this->getCollection($collection)); $attributes = $collection->getAttribute('attributes', []); $indexes = $collection->getAttribute('indexes', []); if ($this->validate) { - $validator = new DocumentsValidator($attributes, $indexes); + $validator = new DocumentsValidator( + $attributes, + $indexes, + $this->maxQueryValues, + $this->adapter->getMinDateTime(), + $this->adapter->getMaxDateTime(), + ); if (!$validator->isValid($queries)) { throw new QueryException($validator->getDescription()); } @@ -5464,12 +5648,12 @@ public function encode(Document $collection, Document $document): Document $filters = $attribute['filters'] ?? []; $value = $document->getAttribute($key); - // continue on optional param with no default + // Continue on optional param with no default if (is_null($value) && is_null($default)) { continue; } - // assign default only if no value provided + // Assign default only if no value provided // False positive "Call to function is_null() with mixed will always evaluate to false" // @phpstan-ignore-next-line if (is_null($value) && !is_null($default)) { @@ -5510,13 +5694,13 @@ public function decode(Document $collection, Document $document, array $selectio $attributes = \array_filter( $collection->getAttribute('attributes', []), fn ($attribute) => - $attribute['type'] !== self::VAR_RELATIONSHIP + $attribute['type'] !== self::VAR_RELATIONSHIP ); $relationships = \array_filter( $collection->getAttribute('attributes', []), fn ($attribute) => - $attribute['type'] === self::VAR_RELATIONSHIP + $attribute['type'] === self::VAR_RELATIONSHIP ); foreach ($relationships as $relationship) { @@ -5649,11 +5833,11 @@ public function casting(Document $collection, Document $document): Document protected function encodeAttribute(string $name, mixed $value, Document $document): mixed { if (!array_key_exists($name, self::$filters) && !array_key_exists($name, $this->instanceFilters)) { - throw new DatabaseException("Filter: {$name} not found"); + throw new NotFoundException("Filter: {$name} not found"); } try { - if (array_key_exists($name, $this->instanceFilters)) { + if (\array_key_exists($name, $this->instanceFilters)) { $value = $this->instanceFilters[$name]['encode']($value, $document, $this); } else { $value = self::$filters[$name]['encode']($value, $document, $this); @@ -5685,7 +5869,7 @@ protected function decodeAttribute(string $name, mixed $value, Document $documen } if (!array_key_exists($name, self::$filters) && !array_key_exists($name, $this->instanceFilters)) { - throw new DatabaseException('Filter not found'); + throw new NotFoundException('Filter not found'); } if (array_key_exists($name, $this->instanceFilters)) { @@ -5784,11 +5968,16 @@ public function getLimitForIndexes(): int * @param array $queries * @return array * @throws QueryException + * @throws Exception */ public static function convertQueries(Document $collection, array $queries): array { $attributes = $collection->getAttribute('attributes', []); + foreach (Database::INTERNAL_ATTRIBUTES as $attribute) { + $attributes[] = new Document($attribute); + } + foreach ($attributes as $attribute) { foreach ($queries as $query) { if ($query->getAttribute() === $attribute->getId()) { @@ -5832,7 +6021,7 @@ private function purgeRelatedDocuments(Document $collection, string $id): void $relationships = \array_filter( $collection->getAttribute('attributes', []), fn ($attribute) => - $attribute['type'] === Database::VAR_RELATIONSHIP + $attribute['type'] === Database::VAR_RELATIONSHIP ); if (empty($relationships)) { @@ -5876,4 +6065,16 @@ public function analyzeCollection(string $collection): bool { return $this->adapter->analyzeCollection($collection); } + + /** + * Get Schema Attributes + * + * @param string $collection + * @return array + * @throws DatabaseException + */ + public function getSchemaAttributes(string $collection): array + { + return $this->adapter->getSchemaAttributes($collection); + } } diff --git a/src/Database/Document.php b/src/Database/Document.php index 7afddc25f..f605f615f 100644 --- a/src/Database/Document.php +++ b/src/Database/Document.php @@ -210,9 +210,9 @@ public function getAttribute(string $name, mixed $default = null): mixed * @param mixed $value * @param string $type * - * @return self + * @return static */ - public function setAttribute(string $key, mixed $value, string $type = self::SET_TYPE_ASSIGN): self + public function setAttribute(string $key, mixed $value, string $type = self::SET_TYPE_ASSIGN): static { switch ($type) { case self::SET_TYPE_ASSIGN: @@ -235,9 +235,9 @@ public function setAttribute(string $key, mixed $value, string $type = self::SET * Set Attributes. * * @param array $attributes - * @return self + * @return static */ - public function setAttributes(array $attributes): self + public function setAttributes(array $attributes): static { foreach ($attributes as $key => $value) { $this->setAttribute($key, $value); @@ -253,14 +253,15 @@ public function setAttributes(array $attributes): self * * @param string $key * - * @return self + * @return static */ - public function removeAttribute(string $key): self + public function removeAttribute(string $key): static { if (\array_key_exists($key, (array)$this)) { unset($this[$key]); } + /* @phpstan-ignore-next-line */ return $this; } diff --git a/src/Database/Exception.php b/src/Database/Exception.php index 94099c6ae..d86e94c2b 100644 --- a/src/Database/Exception.php +++ b/src/Database/Exception.php @@ -6,7 +6,7 @@ class Exception extends \Exception { - public function __construct(string $message, int|string $code = 0, Throwable $previous = null) + public function __construct(string $message, int|string $code = 0, ?Throwable $previous = null) { if (\is_string($code)) { if (\is_numeric($code)) { diff --git a/src/Database/Exception/Dependency.php b/src/Database/Exception/Dependency.php new file mode 100644 index 000000000..5c58ef63c --- /dev/null +++ b/src/Database/Exception/Dependency.php @@ -0,0 +1,9 @@ + + */ + protected array $writeFilters = []; + + /** + * Callbacks to run when an error occurs on the destination database + * + * @var array + */ + protected array $errorCallbacks = []; + + /** + * Collections that should only be present in the source database + */ + protected const SOURCE_ONLY_COLLECTIONS = [ + 'upgrades', + ]; + + /** + * @param Database $source + * @param ?Database $destination + * @param array $filters + */ + public function __construct( + Database $source, + ?Database $destination = null, + array $filters = [], + ) { + parent::__construct( + $source->getAdapter(), + $source->getCache() + ); + $this->source = $source; + $this->destination = $destination; + $this->writeFilters = $filters; + } + + public function getSource(): Database + { + return $this->source; + } + + public function getDestination(): ?Database + { + return $this->destination; + } + + /** + * @return array + */ + public function getWriteFilters(): array + { + return $this->writeFilters; + } + + /** + * @param callable(string, \Throwable): void $callback + * @return void + */ + public function onError(callable $callback): void + { + $this->errorCallbacks[] = $callback; + } + + /** + * @param string $method + * @param array $args + * @return mixed + */ + protected function delegate(string $method, array $args = []): mixed + { + $result = $this->source->{$method}(...$args); + + if ($this->destination === null) { + return $result; + } + + try { + $result = $this->destination->{$method}(...$args); + } catch (\Throwable $err) { + $this->logError($method, $err); + } + + return $result; + } + + public function setDatabase(string $name): static + { + $this->delegate(__FUNCTION__, \func_get_args()); + + return $this; + } + + public function setNamespace(string $namespace): static + { + $this->delegate(__FUNCTION__, \func_get_args()); + + return $this; + } + + public function setSharedTables(bool $sharedTables): static + { + $this->delegate(__FUNCTION__, \func_get_args()); + + return $this; + } + + public function setTenant(?int $tenant): static + { + $this->delegate(__FUNCTION__, \func_get_args()); + + return $this; + } + + public function setPreserveDates(bool $preserve): static + { + $this->delegate(__FUNCTION__, \func_get_args()); + + $this->preserveDates = $preserve; + + return $this; + } + + public function enableValidation(): static + { + $this->delegate(__FUNCTION__); + + $this->validate = true; + + return $this; + } + + public function disableValidation(): static + { + $this->delegate(__FUNCTION__); + + $this->validate = false; + + return $this; + } + + public function on(string $event, string $name, callable $callback): static + { + $this->source->on($event, $name, $callback); + + return $this; + } + + protected function trigger(string $event, mixed $args = null): void + { + $this->source->trigger($event, $args); + } + + public function silent(callable $callback, ?array $listeners = null): mixed + { + return $this->source->silent($callback, $listeners); + } + + public function withRequestTimestamp(?\DateTime $requestTimestamp, callable $callback): mixed + { + return $this->delegate(__FUNCTION__, \func_get_args()); + } + + public function exists(?string $database = null, ?string $collection = null): bool + { + return $this->delegate(__FUNCTION__, \func_get_args()); + } + + public function create(?string $database = null): bool + { + return $this->delegate(__FUNCTION__, \func_get_args()); + } + + public function delete(?string $database = null): bool + { + return $this->delegate(__FUNCTION__, \func_get_args()); + } + + public function createCollection(string $id, array $attributes = [], array $indexes = [], ?array $permissions = null, bool $documentSecurity = true): Document + { + $result = $this->source->createCollection( + $id, + $attributes, + $indexes, + $permissions, + $documentSecurity + ); + + if ($this->destination === null) { + return $result; + } + + try { + foreach ($this->writeFilters as $filter) { + $result = $filter->beforeCreateCollection( + source: $this->source, + destination: $this->destination, + collectionId: $id, + collection: $result, + ); + } + + $this->destination->createCollection( + $id, + $attributes, + $indexes, + $permissions, + $documentSecurity + ); + + $this->silent(function () use ($id) { + $this->createUpgrades(); + + $this->source->createDocument('upgrades', new Document([ + '$id' => $id, + 'collectionId' => $id, + 'status' => 'upgraded' + ])); + }); + } catch (\Throwable $err) { + $this->logError('createCollection', $err); + } + return $result; + } + + public function updateCollection(string $id, array $permissions, bool $documentSecurity): Document + { + $result = $this->source->updateCollection($id, $permissions, $documentSecurity); + + if ($this->destination === null) { + return $result; + } + + try { + foreach ($this->writeFilters as $filter) { + $result = $filter->beforeUpdateCollection( + source: $this->source, + destination: $this->destination, + collectionId: $id, + collection: $result, + ); + } + + $this->destination->updateCollection($id, $permissions, $documentSecurity); + } catch (\Throwable $err) { + $this->logError('updateCollection', $err); + } + + return $result; + } + + public function deleteCollection(string $id): bool + { + $result = $this->source->deleteCollection($id); + + if ($this->destination === null) { + return $result; + } + + try { + $this->destination->deleteCollection($id); + + foreach ($this->writeFilters as $filter) { + $filter->beforeDeleteCollection( + source: $this->source, + destination: $this->destination, + collectionId: $id, + ); + } + } catch (\Throwable $err) { + $this->logError('deleteCollection', $err); + } + + return $result; + } + + public function createAttribute(string $collection, string $id, string $type, int $size, bool $required, $default = null, bool $signed = true, bool $array = false, ?string $format = null, array $formatOptions = [], array $filters = []): bool + { + $result = $this->source->createAttribute( + $collection, + $id, + $type, + $size, + $required, + $default, + $signed, + $array, + $format, + $formatOptions, + $filters + ); + + if ($this->destination === null) { + return $result; + } + + try { + $document = new Document([ + '$id' => $id, + 'type' => $type, + 'size' => $size, + 'required' => $required, + 'default' => $default, + 'signed' => $signed, + 'array' => $array, + 'format' => $format, + 'formatOptions' => $formatOptions, + 'filters' => $filters, + ]); + + foreach ($this->writeFilters as $filter) { + $document = $filter->beforeCreateAttribute( + source: $this->source, + destination: $this->destination, + collectionId: $collection, + attributeId: $id, + attribute: $document, + ); + } + + $result = $this->destination->createAttribute( + $collection, + $document->getId(), + $document->getAttribute('type'), + $document->getAttribute('size'), + $document->getAttribute('required'), + $document->getAttribute('default'), + $document->getAttribute('signed'), + $document->getAttribute('array'), + $document->getAttribute('format'), + $document->getAttribute('formatOptions'), + $document->getAttribute('filters'), + ); + } catch (\Throwable $err) { + $this->logError('createAttribute', $err); + } + + return $result; + } + + public function updateAttribute(string $collection, string $id, ?string $type = null, ?int $size = null, ?bool $required = null, mixed $default = null, ?bool $signed = null, ?bool $array = null, ?string $format = null, ?array $formatOptions = null, ?array $filters = null, ?string $newKey = null): Document + { + $document = $this->source->updateAttribute( + $collection, + $id, + $type, + $size, + $required, + $default, + $signed, + $array, + $format, + $formatOptions, + $filters, + $newKey, + ); + + if ($this->destination === null) { + return $document; + } + + try { + foreach ($this->writeFilters as $filter) { + $document = $filter->beforeUpdateAttribute( + source: $this->source, + destination: $this->destination, + collectionId: $collection, + attributeId: $id, + attribute: $document, + ); + } + + $this->destination->updateAttribute( + $collection, + $id, + $document->getAttribute('type'), + $document->getAttribute('size'), + $document->getAttribute('required'), + $document->getAttribute('default'), + $document->getAttribute('signed'), + $document->getAttribute('array'), + $document->getAttribute('format'), + $document->getAttribute('formatOptions'), + $document->getAttribute('filters'), + $newKey, + ); + } catch (\Throwable $err) { + $this->logError('updateAttribute', $err); + } + + return $document; + } + + public function deleteAttribute(string $collection, string $id): bool + { + $result = $this->source->deleteAttribute($collection, $id); + + if ($this->destination === null) { + return $result; + } + + try { + foreach ($this->writeFilters as $filter) { + $filter->beforeDeleteAttribute( + source: $this->source, + destination: $this->destination, + collectionId: $collection, + attributeId: $id, + ); + } + + $this->destination->deleteAttribute($collection, $id); + } catch (\Throwable $err) { + $this->logError('deleteAttribute', $err); + } + + return $result; + } + + public function createIndex(string $collection, string $id, string $type, array $attributes, array $lengths = [], array $orders = []): bool + { + $result = $this->source->createIndex($collection, $id, $type, $attributes, $lengths, $orders); + + if ($this->destination === null) { + return $result; + } + + try { + $document = new Document([ + '$id' => $id, + 'type' => $type, + 'attributes' => $attributes, + 'lengths' => $lengths, + 'orders' => $orders, + ]); + + foreach ($this->writeFilters as $filter) { + $document = $filter->beforeCreateIndex( + source: $this->source, + destination: $this->destination, + collectionId: $collection, + indexId: $id, + index: $document, + ); + } + + $result = $this->destination->createIndex( + $collection, + $document->getId(), + $document->getAttribute('type'), + $document->getAttribute('attributes'), + $document->getAttribute('lengths'), + $document->getAttribute('orders') + ); + } catch (\Throwable $err) { + $this->logError('createIndex', $err); + } + + return $result; + } + + public function deleteIndex(string $collection, string $id): bool + { + $result = $this->source->deleteIndex($collection, $id); + + if ($this->destination === null) { + return $result; + } + + try { + $this->destination->deleteIndex($collection, $id); + + foreach ($this->writeFilters as $filter) { + $filter->beforeDeleteIndex( + source: $this->source, + destination: $this->destination, + collectionId: $collection, + indexId: $id, + ); + } + } catch (\Throwable $err) { + $this->logError('deleteIndex', $err); + } + + return $result; + } + + public function createDocument(string $collection, Document $document): Document + { + $document = $this->source->createDocument($collection, $document); + + if ( + \in_array($collection, self::SOURCE_ONLY_COLLECTIONS) + || $this->destination === null + ) { + return $document; + } + + $upgrade = $this->silent(fn () => $this->getUpgradeStatus($collection)); + if ($upgrade === null || $upgrade->getAttribute('status', '') !== 'upgraded') { + return $document; + } + + try { + $clone = clone $document; + + foreach ($this->writeFilters as $filter) { + $clone = $filter->beforeCreateDocument( + source: $this->source, + destination: $this->destination, + collectionId: $collection, + document: $clone, + ); + } + + $this->destination->setPreserveDates(true); + $document = $this->destination->createDocument($collection, $clone); + $this->destination->setPreserveDates(false); + + foreach ($this->writeFilters as $filter) { + $filter->afterCreateDocument( + source: $this->source, + destination: $this->destination, + collectionId: $collection, + document: $clone, + ); + } + } catch (\Throwable $err) { + $this->logError('createDocument', $err); + } + + return $document; + } + + public function createDocuments( + string $collection, + array $documents, + int $batchSize = self::INSERT_BATCH_SIZE + ): array { + $documents = $this->source->createDocuments($collection, $documents, $batchSize); + + if ( + \in_array($collection, self::SOURCE_ONLY_COLLECTIONS) + || $this->destination === null + ) { + return $documents; + } + + $upgrade = $this->silent(fn () => $this->getUpgradeStatus($collection)); + if ($upgrade === null || $upgrade->getAttribute('status', '') !== 'upgraded') { + return $documents; + } + + try { + $clones = []; + + foreach ($documents as $document) { + $clone = clone $document; + + foreach ($this->writeFilters as $filter) { + $clone = $filter->beforeCreateDocument( + source: $this->source, + destination: $this->destination, + collectionId: $collection, + document: $clone, + ); + } + + $clones[] = $clone; + } + + $this->destination->setPreserveDates(true); + $this->destination->createDocuments($collection, $clones, $batchSize); + $this->destination->setPreserveDates(false); + + foreach ($clones as $clone) { + foreach ($this->writeFilters as $filter) { + $filter->afterCreateDocument( + source: $this->source, + destination: $this->destination, + collectionId: $collection, + document: $clone, + ); + } + } + + } catch (\Throwable $err) { + $this->logError('createDocuments', $err); + } + + return $documents; + } + + public function updateDocument(string $collection, string $id, Document $document): Document + { + $document = $this->source->updateDocument($collection, $id, $document); + + if ( + \in_array($collection, self::SOURCE_ONLY_COLLECTIONS) + || $this->destination === null + ) { + return $document; + } + + $upgrade = $this->silent(fn () => $this->getUpgradeStatus($collection)); + + if ($upgrade === null || $upgrade->getAttribute('status', '') !== 'upgraded') { + return $document; + } + + try { + $clone = clone $document; + + foreach ($this->writeFilters as $filter) { + $clone = $filter->beforeUpdateDocument( + source: $this->source, + destination: $this->destination, + collectionId: $collection, + document: $clone, + ); + } + + $this->destination->setPreserveDates(true); + $this->destination->updateDocument($collection, $id, $clone); + $this->destination->setPreserveDates(false); + + foreach ($this->writeFilters as $filter) { + $filter->afterUpdateDocument( + source: $this->source, + destination: $this->destination, + collectionId: $collection, + document: $clone, + ); + } + } catch (\Throwable $err) { + $this->logError('updateDocument', $err); + } + + return $document; + } + + public function updateDocuments( + string $collection, + Document $updates, + array $queries = [], + int $batchSize = self::INSERT_BATCH_SIZE + ): array { + $documents = $this->source->updateDocuments($collection, $updates, $queries, $batchSize); + + if ( + \in_array($collection, self::SOURCE_ONLY_COLLECTIONS) + || $this->destination === null + ) { + return $documents; + } + + $upgrade = $this->silent(fn () => $this->getUpgradeStatus($collection)); + if ($upgrade === null || $upgrade->getAttribute('status', '') !== 'upgraded') { + return $documents; + } + + try { + $clone = clone $updates; + + foreach ($this->writeFilters as $filter) { + $clone = $filter->beforeUpdateDocuments( + source: $this->source, + destination: $this->destination, + collectionId: $collection, + updates: $clone, + queries: $queries, + ); + } + + $this->destination->setPreserveDates(true); + $this->destination->updateDocuments($collection, $clone, $queries, $batchSize); + $this->destination->setPreserveDates(false); + + foreach ($this->writeFilters as $filter) { + $filter->afterUpdateDocuments( + source: $this->source, + destination: $this->destination, + collectionId: $collection, + updates: $clone, + queries: $queries, + ); + } + } catch (\Throwable $err) { + $this->logError('updateDocuments', $err); + } + + return $documents; + } + + public function deleteDocument(string $collection, string $id): bool + { + $result = $this->source->deleteDocument($collection, $id); + + if ( + \in_array($collection, self::SOURCE_ONLY_COLLECTIONS) + || $this->destination === null + ) { + return $result; + } + + $upgrade = $this->silent(fn () => $this->getUpgradeStatus($collection)); + if ($upgrade === null || $upgrade->getAttribute('status', '') !== 'upgraded') { + return $result; + } + + try { + foreach ($this->writeFilters as $filter) { + $filter->beforeDeleteDocument( + source: $this->source, + destination: $this->destination, + collectionId: $collection, + documentId: $id, + ); + } + + $this->destination->deleteDocument($collection, $id); + + foreach ($this->writeFilters as $filter) { + $filter->afterDeleteDocument( + source: $this->source, + destination: $this->destination, + collectionId: $collection, + documentId: $id, + ); + } + } catch (\Throwable $err) { + $this->logError('deleteDocument', $err); + } + + return $result; + } + + public function deleteDocuments(string $collection, array $queries = [], int $batchSize = self::DELETE_BATCH_SIZE): array + { + $documents = $this->source->deleteDocuments($collection, $queries, $batchSize); + + if ( + \in_array($collection, self::SOURCE_ONLY_COLLECTIONS) + || $this->destination === null + ) { + return $documents; + } + + $upgrade = $this->silent(fn () => $this->getUpgradeStatus($collection)); + if ($upgrade === null || $upgrade->getAttribute('status', '') !== 'upgraded') { + return $documents; + } + + try { + foreach ($this->writeFilters as $filter) { + $filter->beforeDeleteDocuments( + source: $this->source, + destination: $this->destination, + collectionId: $collection, + queries: $queries, + ); + } + + $this->destination->deleteDocuments($collection, $queries, $batchSize); + + foreach ($this->writeFilters as $filter) { + $filter->afterDeleteDocuments( + source: $this->source, + destination: $this->destination, + collectionId: $collection, + queries: $queries, + ); + } + } catch (\Throwable $err) { + $this->logError('deleteDocuments', $err); + } + + return $documents; + } + + public function updateAttributeRequired(string $collection, string $id, bool $required): Document + { + return $this->delegate(__FUNCTION__, \func_get_args()); + } + + public function updateAttributeFormat(string $collection, string $id, string $format): Document + { + return $this->delegate(__FUNCTION__, \func_get_args()); + } + + public function updateAttributeFormatOptions(string $collection, string $id, array $formatOptions): Document + { + return $this->delegate(__FUNCTION__, [$collection, $id, $formatOptions]); + } + + public function updateAttributeFilters(string $collection, string $id, array $filters): Document + { + return $this->delegate(__FUNCTION__, \func_get_args()); + } + + public function updateAttributeDefault(string $collection, string $id, mixed $default = null): Document + { + return $this->delegate(__FUNCTION__, \func_get_args()); + } + + public function renameAttribute(string $collection, string $old, string $new): bool + { + return $this->delegate(__FUNCTION__, \func_get_args()); + } + + public function createRelationship( + string $collection, + string $relatedCollection, + string $type, + bool $twoWay = false, + ?string $id = null, + ?string $twoWayKey = null, + string $onDelete = Database::RELATION_MUTATE_RESTRICT + ): bool { + return $this->delegate(__FUNCTION__, \func_get_args()); + } + + public function updateRelationship( + string $collection, + string $id, + ?string $newKey = null, + ?string $newTwoWayKey = null, + ?bool $twoWay = null, + ?string $onDelete = null + ): bool { + return $this->delegate(__FUNCTION__, \func_get_args()); + } + + public function deleteRelationship(string $collection, string $id): bool + { + return $this->delegate(__FUNCTION__, \func_get_args()); + } + + + public function renameIndex(string $collection, string $old, string $new): bool + { + return $this->delegate(__FUNCTION__, \func_get_args()); + } + + public function increaseDocumentAttribute(string $collection, string $id, string $attribute, int|float $value = 1, int|float|null $max = null): bool + { + return $this->delegate(__FUNCTION__, \func_get_args()); + } + + public function decreaseDocumentAttribute(string $collection, string $id, string $attribute, int|float $value = 1, int|float|null $min = null): bool + { + return $this->delegate(__FUNCTION__, \func_get_args()); + } + + /** + * @throws Limit + * @throws DuplicateException + * @throws Exception + */ + public function createUpgrades(): void + { + $collection = $this->source->getCollection('upgrades'); + + if (!$collection->isEmpty()) { + return; + } + + $this->source->createCollection( + id: 'upgrades', + attributes: [ + new Document([ + '$id' => ID::custom('collectionId'), + 'type' => Database::VAR_STRING, + 'size' => Database::LENGTH_KEY, + 'required' => true, + 'signed' => true, + 'array' => false, + 'filters' => [], + 'default' => null, + 'format' => '' + ]), + new Document([ + '$id' => ID::custom('status'), + 'type' => Database::VAR_STRING, + 'size' => Database::LENGTH_KEY, + 'required' => false, + 'signed' => true, + 'array' => false, + 'filters' => [], + 'default' => null, + 'format' => '' + ]), + ], + indexes: [ + new Document([ + '$id' => ID::custom('_unique_collection'), + 'type' => Database::INDEX_UNIQUE, + 'attributes' => ['collectionId'], + 'lengths' => [Database::LENGTH_KEY], + 'orders' => [], + ]), + new Document([ + '$id' => ID::custom('_status_index'), + 'type' => Database::INDEX_KEY, + 'attributes' => ['status'], + 'lengths' => [Database::LENGTH_KEY], + 'orders' => [Database::ORDER_ASC], + ]), + ], + ); + } + + /** + * @throws Exception + */ + protected function getUpgradeStatus(string $collection): ?Document + { + if ($collection === 'upgrades' || $collection === Database::METADATA) { + return new Document(); + } + + return Authorization::skip(function () use ($collection) { + try { + return $this->source->getDocument('upgrades', $collection); + } catch (\Throwable) { + return; + } + }); + } + + protected function logError(string $action, \Throwable $err): void + { + foreach ($this->errorCallbacks as $callback) { + $callback($action, $err); + } + } +} diff --git a/src/Database/Mirroring/Filter.php b/src/Database/Mirroring/Filter.php new file mode 100644 index 000000000..c440ea4b6 --- /dev/null +++ b/src/Database/Mirroring/Filter.php @@ -0,0 +1,362 @@ + $queries + * @return Document + */ + public function beforeUpdateDocuments( + Database $source, + Database $destination, + string $collectionId, + Document $updates, + array $queries + ): Document { + return $updates; + } + + /** + * @param Database $source + * @param Database $destination + * @param string $collectionId + * @param Document $updates + * @param array $queries + * @return void + */ + public function afterUpdateDocuments( + Database $source, + Database $destination, + string $collectionId, + Document $updates, + array $queries + ): void { + } + + /** + * Called before document is deleted in the destination database + * + * @param Database $source + * @param Database $destination + * @param string $collectionId + * @param string $documentId + * @return void + */ + public function beforeDeleteDocument( + Database $source, + Database $destination, + string $collectionId, + string $documentId, + ): void { + } + + /** + * Called after document is deleted in the destination database + * + * @param Database $source + * @param Database $destination + * @param string $collectionId + * @param string $documentId + * @return void + */ + public function afterDeleteDocument( + Database $source, + Database $destination, + string $collectionId, + string $documentId, + ): void { + } + + /** + * @param Database $source + * @param Database $destination + * @param string $collectionId + * @param array $queries + * @return void + */ + public function beforeDeleteDocuments( + Database $source, + Database $destination, + string $collectionId, + array $queries + ): void { + } + + /** + * @param Database $source + * @param Database $destination + * @param string $collectionId + * @param array $queries + * @return void + */ + public function afterDeleteDocuments( + Database $source, + Database $destination, + string $collectionId, + array $queries + ): void { + } +} diff --git a/src/Database/Query.php b/src/Database/Query.php index aab17c195..7388453b2 100644 --- a/src/Database/Query.php +++ b/src/Database/Query.php @@ -254,6 +254,10 @@ public static function parseQuery(array $query): self $attribute = $query['attribute'] ?? ''; $values = $query['values'] ?? []; + if (!\is_string($method)) { + throw new QueryException('Invalid query method. Must be a string, got ' . \gettype($method)); + } + if (!self::isMethod($method)) { throw new QueryException('Invalid query method: ' . $method); } @@ -262,6 +266,10 @@ public static function parseQuery(array $query): self throw new QueryException('Invalid query attribute. Must be a string, got ' . \gettype($attribute)); } + if (!\is_array($values)) { + throw new QueryException('Invalid query values. Must be an array, got ' . \gettype($values)); + } + if (\in_array($method, self::LOGICAL_TYPES)) { foreach ($values as $index => $value) { $values[$index] = self::parseQuery($value); diff --git a/src/Database/Validator/Authorization.php b/src/Database/Validator/Authorization.php index 22d0ebc5c..2dd645ba7 100644 --- a/src/Database/Validator/Authorization.php +++ b/src/Database/Validator/Authorization.php @@ -2,35 +2,34 @@ namespace Utopia\Database\Validator; -use Utopia\Database\Validator\Authorization\Input; -use Utopia\Http\Validator; +use Utopia\Validator; class Authorization extends Validator { /** - * @var bool + * @var array */ - protected bool $status = true; + private static array $roles = [ + 'any' => true + ]; /** - * Default value in case we need - * to reset Authorization status - * - * @var bool + * @var string */ - protected bool $statusDefault = true; + protected string $action = ''; /** - * @var array + * @var string */ - private array $roles = [ - 'any' => true - ]; + protected string $message = 'Authorization Error'; /** - * @var string + * @param string $action */ - protected string $message = 'Authorization Error'; + public function __construct(string $action) + { + $this->action = $action; + } /** * Get Description. @@ -44,43 +43,36 @@ public function getDescription(): string return $this->message; } - /* - * Validation + /** + * Is valid. * * Returns true if valid or false if not. - */ - public function isValid(mixed $input): bool // any, CREATE + * + * @param mixed $permissions + * + * @return bool + */ + public function isValid($permissions): bool { - if (!($input instanceof Input)) { - $this->message = 'Invalid input provided'; - return false; - } - - /** - * @var Input $input - */ - - $permissions = $input->getPermissions(); - $action = $input->getAction(); - - if (!$this->status) { + if (!self::$status) { return true; } if (empty($permissions)) { - $this->message = 'No permissions provided for action \''.$action.'\''; + $this->message = 'No permissions provided for action \''.$this->action.'\''; return false; } $permission = '-'; foreach ($permissions as $permission) { - if (\array_key_exists($permission, $this->roles)) { + if (\array_key_exists($permission, self::$roles)) { return true; } } - $this->message = 'Missing "'.$action.'" permission for role "'.$permission.'". Only "'.\json_encode($this->getRoles()).'" scopes are allowed and "'.\json_encode($permissions).'" was given.'; + $this->message = 'Missing "'.$this->action.'" permission for role "'.$permission.'". Only "'.\json_encode(self::getRoles()).'" scopes are allowed and "'.\json_encode($permissions).'" was given.'; + return false; } @@ -88,9 +80,9 @@ public function isValid(mixed $input): bool // any, CREATE * @param string $role * @return void */ - public function addRole(string $role): void // user:meldiron, users, any + public static function setRole(string $role): void { - $this->roles[$role] = true; + self::$roles[$role] = true; } /** @@ -98,25 +90,25 @@ public function addRole(string $role): void // user:meldiron, users, any * * @return void */ - public function removeRole(string $role): void + public static function unsetRole(string $role): void { - unset($this->roles[$role]); + unset(self::$roles[$role]); } /** * @return array */ - public function getRoles(): array + public static function getRoles(): array { - return \array_keys($this->roles); + return \array_keys(self::$roles); } /** * @return void */ - public function cleanRoles(): void + public static function cleanRoles(): void { - $this->roles = []; + self::$roles = []; } /** @@ -124,53 +116,36 @@ public function cleanRoles(): void * * @return bool */ - public function isRole(string $role): bool + public static function isRole(string $role): bool { - return (\array_key_exists($role, $this->roles)); + return (\array_key_exists($role, self::$roles)); } /** - * Change default status. - * This will be used for the - * value set on the $this->reset() method - * @param bool $status - * @return void + * @var bool */ - public function setDefaultStatus(bool $status): void - { - $this->statusDefault = $status; - $this->status = $status; - } + public static bool $status = true; /** - * Change status - * - * @param bool $status - * @return void - */ - public function setStatus(bool $status): void - { - $this->status = $status; - } - - /** - * Get status + * Default value in case we need + * to reset Authorization status * - * @return bool + * @var bool */ - public function getStatus(): bool - { - return $this->status; - } + public static bool $statusDefault = true; /** - * Get default status + * Change default status. + * This will be used for the + * value set on the self::reset() method * - * @return bool + * @param bool $status + * @return void */ - public function getStatusDefault(): bool + public static function setDefaultStatus(bool $status): void { - return $this->statusDefault; + self::$statusDefault = $status; + self::$status = $status; } /** @@ -182,15 +157,15 @@ public function getStatusDefault(): bool * @param callable(): T $callback * @return T */ - public function skip(callable $callback): mixed + public static function skip(callable $callback): mixed { - $initialStatus = $this->status; - $this->disable(); + $initialStatus = self::$status; + self::disable(); try { return $callback(); } finally { - $this->status = $initialStatus; + self::$status = $initialStatus; } } @@ -199,9 +174,9 @@ public function skip(callable $callback): mixed * * @return void */ - public function enable(): void + public static function enable(): void { - $this->status = true; + self::$status = true; } /** @@ -209,9 +184,9 @@ public function enable(): void * * @return void */ - public function disable(): void + public static function disable(): void { - $this->status = false; + self::$status = false; } /** @@ -219,9 +194,9 @@ public function disable(): void * * @return void */ - public function reset(): void + public static function reset(): void { - $this->status = $this->statusDefault; + self::$status = self::$statusDefault; } /** diff --git a/src/Database/Validator/Authorization/Input.php b/src/Database/Validator/Authorization/Input.php deleted file mode 100644 index 4c2387097..000000000 --- a/src/Database/Validator/Authorization/Input.php +++ /dev/null @@ -1,49 +0,0 @@ -permissions = $permissions; - $this->action = $action; - } - - /** - * @param string[] $permissions - */ - public function setPermissions(array $permissions): self - { - $this->permissions = $permissions; - return $this; - } - - public function setAction(string $action): self - { - $this->action = $action; - return $this; - } - - /** - * @return string[] - */ - public function getPermissions(): array - { - return $this->permissions; - } - - public function getAction(): string - { - return $this->action; - } -} diff --git a/src/Database/Validator/Datetime.php b/src/Database/Validator/Datetime.php index 1d8c9dfd2..7950b1e07 100644 --- a/src/Database/Validator/Datetime.php +++ b/src/Database/Validator/Datetime.php @@ -2,7 +2,7 @@ namespace Utopia\Database\Validator; -use Utopia\Http\Validator; +use Utopia\Validator; class Datetime extends Validator { @@ -13,33 +13,18 @@ class Datetime extends Validator public const PRECISION_ANY = 'any'; /** - * @var string + * @throws \Exception */ - protected string $precision = self::PRECISION_ANY; - - /** - * @var bool - */ - protected bool $requireDateInFuture = false; - - - /** - * @var int minimum offset from now in seconds - */ - protected int $offset = 0; - - /** - * @param int $offset minimum offset from now in seconds - */ - public function __construct(bool $requireDateInFuture = false, string $precision = self::PRECISION_ANY, int $offset = 0) - { + public function __construct( + private readonly \DateTime $min = new \DateTime('0000-01-01'), + private readonly \DateTime $max = new \DateTime('9999-12-31'), + private readonly bool $requireDateInFuture = false, + private readonly string $precision = self::PRECISION_ANY, + private readonly int $offset = 0, + ) { if ($offset < 0) { - throw new \Exception('Offset must be a positive number.'); + throw new \Exception('Offset must be a positive integer.'); } - - $this->requireDateInFuture = $requireDateInFuture; - $this->offset = $offset; - $this->precision = $precision; } /** @@ -51,16 +36,19 @@ public function getDescription(): string $message = 'Value must be valid date'; if ($this->offset > 0) { - $message .= " at least " . $this->offset . " seconds in future"; + $message .= " at least " . $this->offset . " seconds in the future and"; } elseif ($this->requireDateInFuture) { - $message .= " in future"; + $message .= " in the future and"; } if ($this->precision !== self::PRECISION_ANY) { $message .= " with " . $this->precision . " precision"; } - $message .= '.'; + $min = $this->min->format('Y-m-d H:i:s'); + $max = $this->max->format('Y-m-d H:i:s'); + + $message .= " between {$min} and {$max}."; return $message; } @@ -72,7 +60,7 @@ public function getDescription(): string */ public function isValid($value): bool { - if (empty($value)) { + if (empty($value) || ! is_string($value)) { return false; } @@ -114,13 +102,24 @@ public function isValid($value): bool return false; } } - } catch (\Exception $e) { + } catch (\Exception) { return false; } - [$year] = explode('-', $value); + // Custom year validation to account for PHP allowing year overflow + $matches = []; + if (preg_match('/(?min->format('Y'); + $maxYear = (int)$this->max->format('Y'); + if ($year < $minYear || $year > $maxYear) { + return false; + } + } else { + return false; + } - if ((int)$year > 9999) { + if ($date < $this->min || $date > $this->max) { return false; } diff --git a/src/Database/Validator/Index.php b/src/Database/Validator/Index.php index d7f1beba4..2270a6e0f 100644 --- a/src/Database/Validator/Index.php +++ b/src/Database/Validator/Index.php @@ -5,7 +5,7 @@ use Utopia\Database\Database; use Utopia\Database\Document; use Utopia\Database\Exception as DatabaseException; -use Utopia\Http\Validator; +use Utopia\Validator; class Index extends Validator { @@ -17,14 +17,21 @@ class Index extends Validator */ protected array $attributes; + /** + * @var array $reservedKeys + */ + protected array $reservedKeys; + /** * @param array $attributes * @param int $maxLength + * @param array $reservedKeys * @throws DatabaseException */ - public function __construct(array $attributes, int $maxLength) + public function __construct(array $attributes, int $maxLength, array $reservedKeys = []) { $this->maxLength = $maxLength; + $this->reservedKeys = $reservedKeys; foreach ($attributes as $attribute) { $key = \strtolower($attribute->getAttribute('key', $attribute->getAttribute('$id'))); @@ -80,15 +87,15 @@ public function checkEmptyIndexAttributes(Document $index): bool public function checkDuplicatedAttributes(Document $index): bool { $attributes = $index->getAttribute('attributes', []); - $orders = $index->getAttribute('orders', []); $stack = []; - foreach ($attributes as $key => $attribute) { - $direction = $orders[$key] ?? 'ASC'; - $value = \strtolower($attribute . '|' . $direction); + foreach ($attributes as $attribute) { + $value = \strtolower($attribute); + if (\in_array($value, $stack)) { $this->message = 'Duplicate attributes provided'; return false; } + $stack[] = $value; } return true; @@ -209,6 +216,24 @@ public function checkIndexLength(Document $index): bool return true; } + /** + * @param Document $index + * @return bool + */ + public function checkReservedNames(Document $index): bool + { + $key = $index->getAttribute('key', $index->getAttribute('$id')); + + foreach ($this->reservedKeys as $reserved) { + if (\strtolower($key) === \strtolower($reserved)) { + $this->message = 'Index key name is reserved'; + return false; + } + } + + return true; + } + /** * Is valid. * @@ -243,6 +268,10 @@ public function isValid($value): bool return false; } + if (!$this->checkReservedNames($value)) { + return false; + } + return true; } diff --git a/src/Database/Validator/IndexedQueries.php b/src/Database/Validator/IndexedQueries.php index 24846460e..cb727c0fb 100644 --- a/src/Database/Validator/IndexedQueries.php +++ b/src/Database/Validator/IndexedQueries.php @@ -68,8 +68,20 @@ public function isValid($value): bool } $queries = []; foreach ($value as $query) { - if (!$query instanceof Query) { - $query = Query::parse($query); + if (! $query instanceof Query) { + try { + $query = Query::parse($query); + } catch (\Throwable $e) { + $this->message = 'Invalid query: '.$e->getMessage(); + + return false; + } + } + + if ($query->isNested()) { + if (! self::isValid($query->getValues())) { + return false; + } } $queries[] = $query; diff --git a/src/Database/Validator/Key.php b/src/Database/Validator/Key.php index 74f175f59..ad1c5df4e 100644 --- a/src/Database/Validator/Key.php +++ b/src/Database/Validator/Key.php @@ -2,7 +2,7 @@ namespace Utopia\Database\Validator; -use Utopia\Http\Validator; +use Utopia\Validator; class Key extends Validator { diff --git a/src/Database/Validator/Queries.php b/src/Database/Validator/Queries.php index cc5ae3f5a..b1d67aad0 100644 --- a/src/Database/Validator/Queries.php +++ b/src/Database/Validator/Queries.php @@ -4,7 +4,7 @@ use Utopia\Database\Query; use Utopia\Database\Validator\Query\Base; -use Utopia\Http\Validator; +use Utopia\Validator; class Queries extends Validator { diff --git a/src/Database/Validator/Queries/Documents.php b/src/Database/Validator/Queries/Documents.php index 0d1dc2384..abce8694f 100644 --- a/src/Database/Validator/Queries/Documents.php +++ b/src/Database/Validator/Queries/Documents.php @@ -22,8 +22,13 @@ class Documents extends IndexedQueries * @param array $indexes * @throws Exception */ - public function __construct(array $attributes, array $indexes) - { + public function __construct( + array $attributes, + array $indexes, + int $maxValuesCount = 100, + \DateTime $minAllowedDate = new \DateTime('0000-01-01'), + \DateTime $maxAllowedDate = new \DateTime('9999-12-31'), + ) { $attributes[] = new Document([ '$id' => '$id', 'key' => '$id', @@ -53,7 +58,12 @@ public function __construct(array $attributes, array $indexes) new Limit(), new Offset(), new Cursor(), - new Filter($attributes), + new Filter( + $attributes, + $maxValuesCount, + $minAllowedDate, + $maxAllowedDate, + ), new Order($attributes), new Select($attributes), ]; diff --git a/src/Database/Validator/Query/Base.php b/src/Database/Validator/Query/Base.php index fa96b5a69..a37fdd65a 100644 --- a/src/Database/Validator/Query/Base.php +++ b/src/Database/Validator/Query/Base.php @@ -2,7 +2,7 @@ namespace Utopia\Database\Validator\Query; -use Utopia\Http\Validator; +use Utopia\Validator; abstract class Base extends Validator { diff --git a/src/Database/Validator/Query/Filter.php b/src/Database/Validator/Query/Filter.php index 697c87ee9..0bb4fa90a 100644 --- a/src/Database/Validator/Query/Filter.php +++ b/src/Database/Validator/Query/Filter.php @@ -6,10 +6,10 @@ use Utopia\Database\Document; use Utopia\Database\Query; use Utopia\Database\Validator\Datetime as DatetimeValidator; -use Utopia\Http\Validator\Boolean; -use Utopia\Http\Validator\FloatValidator; -use Utopia\Http\Validator\Integer; -use Utopia\Http\Validator\Text; +use Utopia\Validator\Boolean; +use Utopia\Validator\FloatValidator; +use Utopia\Validator\Integer; +use Utopia\Validator\Text; class Filter extends Base { @@ -18,19 +18,21 @@ class Filter extends Base */ protected array $schema = []; - private int $maxValuesCount; - /** * @param array $attributes * @param int $maxValuesCount + * @param \DateTime $minAllowedDate + * @param \DateTime $maxAllowedDate */ - public function __construct(array $attributes = [], int $maxValuesCount = 100) - { + public function __construct( + array $attributes = [], + private readonly int $maxValuesCount = 100, + private readonly \DateTime $minAllowedDate = new \DateTime('0000-01-01'), + private readonly \DateTime $maxAllowedDate = new \DateTime('9999-12-31'), + ) { foreach ($attributes as $attribute) { $this->schema[$attribute->getAttribute('key', $attribute->getAttribute('$id'))] = $attribute->getArrayCopy(); } - - $this->maxValuesCount = $maxValuesCount; } /** @@ -67,6 +69,7 @@ protected function isValidAttribute(string $attribute): bool /** * @param string $attribute * @param array $values + * @param string $method * @return bool */ protected function isValidAttributeAndValues(string $attribute, array $values, string $method): bool @@ -93,7 +96,6 @@ protected function isValidAttributeAndValues(string $attribute, array $values, s $attributeType = $attributeSchema['type']; foreach ($values as $value) { - $validator = null; switch ($attributeType) { @@ -114,7 +116,10 @@ protected function isValidAttributeAndValues(string $attribute, array $values, s break; case Database::VAR_DATETIME: - $validator = new DatetimeValidator(); + $validator = new DatetimeValidator( + min: $this->minAllowedDate, + max: $this->maxAllowedDate + ); break; case Database::VAR_RELATIONSHIP: diff --git a/src/Database/Validator/Query/Limit.php b/src/Database/Validator/Query/Limit.php index affe0bc89..facc266d7 100644 --- a/src/Database/Validator/Query/Limit.php +++ b/src/Database/Validator/Query/Limit.php @@ -3,8 +3,8 @@ namespace Utopia\Database\Validator\Query; use Utopia\Database\Query; -use Utopia\Http\Validator\Numeric; -use Utopia\Http\Validator\Range; +use Utopia\Validator\Numeric; +use Utopia\Validator\Range; class Limit extends Base { diff --git a/src/Database/Validator/Query/Offset.php b/src/Database/Validator/Query/Offset.php index 6fc7c9564..8d59be4d0 100644 --- a/src/Database/Validator/Query/Offset.php +++ b/src/Database/Validator/Query/Offset.php @@ -3,8 +3,8 @@ namespace Utopia\Database\Validator\Query; use Utopia\Database\Query; -use Utopia\Http\Validator\Numeric; -use Utopia\Http\Validator\Range; +use Utopia\Validator\Numeric; +use Utopia\Validator\Range; class Offset extends Base { diff --git a/src/Database/Validator/Roles.php b/src/Database/Validator/Roles.php index 2db3e8cc7..0306118e7 100644 --- a/src/Database/Validator/Roles.php +++ b/src/Database/Validator/Roles.php @@ -3,7 +3,7 @@ namespace Utopia\Database\Validator; use Utopia\Database\Helpers\Role; -use Utopia\Http\Validator; +use Utopia\Validator; class Roles extends Validator { diff --git a/src/Database/Validator/Structure.php b/src/Database/Validator/Structure.php index 20388a94c..7b2e8b6f5 100644 --- a/src/Database/Validator/Structure.php +++ b/src/Database/Validator/Structure.php @@ -8,20 +8,15 @@ use Utopia\Database\Document; use Utopia\Database\Exception as DatabaseException; use Utopia\Database\Validator\Datetime as DatetimeValidator; -use Utopia\Http\Validator; -use Utopia\Http\Validator\Boolean; -use Utopia\Http\Validator\FloatValidator; -use Utopia\Http\Validator\Integer; -use Utopia\Http\Validator\Range; -use Utopia\Http\Validator\Text; +use Utopia\Validator; +use Utopia\Validator\Boolean; +use Utopia\Validator\FloatValidator; +use Utopia\Validator\Integer; +use Utopia\Validator\Range; +use Utopia\Validator\Text; class Structure extends Validator { - /** - * @var Document - */ - protected Document $collection; - /** * @var array> */ @@ -106,9 +101,11 @@ class Structure extends Validator * Structure constructor. * */ - public function __construct(Document $collection) - { - $this->collection = $collection; + public function __construct( + protected readonly Document $collection, + private readonly \DateTime $minAllowedDate = new \DateTime('0000-01-01'), + private readonly \DateTime $maxAllowedDate = new \DateTime('9999-12-31'), + ) { } /** @@ -126,7 +123,7 @@ public static function getFormats(): array * Stores a callback and required params to create Validator * * @param string $name - * @param Closure $callback Callback that accepts $params in order and returns \Utopia\Http\Validator + * @param Closure $callback Callback that accepts $params in order and returns \Utopia\Validator * @param string $type Primitive data type for validation */ public static function addFormat(string $name, Closure $callback, string $type): void @@ -342,7 +339,10 @@ protected function checkForInvalidAttributeValues(array $structure, array $keys) break; case Database::VAR_DATETIME: - $validators[] = new DatetimeValidator(); + $validators[] = new DatetimeValidator( + min: $this->minAllowedDate, + max: $this->maxAllowedDate + ); break; default: diff --git a/tests/e2e/Adapter/Base.php b/tests/e2e/Adapter/Base.php index f3c4b7b79..3a80da72c 100644 --- a/tests/e2e/Adapter/Base.php +++ b/tests/e2e/Adapter/Base.php @@ -12,6 +12,7 @@ use Utopia\Database\Exception as DatabaseException; use Utopia\Database\Exception\Authorization as AuthorizationException; use Utopia\Database\Exception\Conflict as ConflictException; +use Utopia\Database\Exception\Dependency as DependencyException; use Utopia\Database\Exception\Duplicate as DuplicateException; use Utopia\Database\Exception\Limit as LimitException; use Utopia\Database\Exception\Query as QueryException; @@ -28,7 +29,7 @@ use Utopia\Database\Validator\Datetime as DatetimeValidator; use Utopia\Database\Validator\Index; use Utopia\Database\Validator\Structure; -use Utopia\Http\Validator\Range; +use Utopia\Validator\Range; ini_set('memory_limit', '2048M'); @@ -37,14 +38,25 @@ abstract class Base extends TestCase protected static string $namespace; /** - * @var Authorization + * @return Database */ - protected static ?Authorization $authorization = null; + abstract protected static function getDatabase(): Database; /** - * @return Database + * @param string $collection + * @param string $column + * + * @return bool */ - abstract protected function getDatabase(): Database; + abstract protected static function deleteColumn(string $collection, string $column): bool; + + /** + * @param string $collection + * @param string $index + * + * @return bool + */ + abstract protected static function deleteIndex(string $collection, string $index): bool; /** * @return string @@ -53,42 +65,55 @@ abstract protected static function getAdapterName(): string; public function setUp(): void { - if (is_null(self::$authorization)) { - self::$authorization = new Authorization(); - } - - self::$authorization->addRole('any'); + Authorization::setRole('any'); } public function tearDown(): void { - self::$authorization->setDefaultStatus(true); + Authorization::setDefaultStatus(true); } protected string $testDatabase = 'utopiaTests'; public function testPing(): void { - $this->assertEquals(true, $this->getDatabase()->ping()); + $this->assertEquals(true, static::getDatabase()->ping()); } public function testCreateExistsDelete(): void { - $schemaSupport = $this->getDatabase()->getAdapter()->getSupportForSchemas(); - if (!$schemaSupport) { - $this->assertEquals($this->getDatabase(), $this->getDatabase()->setDatabase($this->testDatabase)); - $this->assertEquals(true, $this->getDatabase()->create()); + if (!static::getDatabase()->getAdapter()->getSupportForSchemas()) { + $this->expectNotToPerformAssertions(); return; } - if (!$this->getDatabase()->exists($this->testDatabase)) { - $this->assertEquals(true, $this->getDatabase()->create()); + $this->assertEquals(true, static::getDatabase()->exists($this->testDatabase)); + $this->assertEquals(true, static::getDatabase()->delete($this->testDatabase)); + $this->assertEquals(false, static::getDatabase()->exists($this->testDatabase)); + $this->assertEquals(true, static::getDatabase()->create()); + } + + /** + * @throws LimitException + * @throws DuplicateException + * @throws DatabaseException + */ + public function testCreateDuplicates(): void + { + static::getDatabase()->createCollection('duplicates', permissions: [ + Permission::read(Role::any()) + ]); + + try { + static::getDatabase()->createCollection('duplicates'); + $this->fail('Failed to throw exception'); + } catch (Exception $e) { + $this->assertInstanceOf(DuplicateException::class, $e); } - $this->assertEquals(true, $this->getDatabase()->exists($this->testDatabase)); - $this->assertEquals(true, $this->getDatabase()->delete($this->testDatabase)); - $this->assertEquals(false, $this->getDatabase()->exists($this->testDatabase)); - $this->assertEquals($this->getDatabase(), $this->getDatabase()->setDatabase($this->testDatabase)); - $this->assertEquals(true, $this->getDatabase()->create()); + + $this->assertNotEmpty(static::getDatabase()->listCollections()); + + static::getDatabase()->deleteCollection('duplicates'); } public function testUpdateDeleteCollectionNotFound(): void @@ -108,165 +133,175 @@ public function testUpdateDeleteCollectionNotFound(): void } } + public function testGetCollectionId(): void + { + if (!static::getDatabase()->getAdapter()->getSupportForGetConnectionId()) { + $this->expectNotToPerformAssertions(); + return; + } + + $this->assertIsString(static::getDatabase()->getConnectionId()); + } + public function testDeleteRelatedCollection(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('c1'); - $this->getDatabase()->createCollection('c2'); + static::getDatabase()->createCollection('c1'); + static::getDatabase()->createCollection('c2'); // ONE_TO_ONE - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'c1', relatedCollection: 'c2', type: Database::RELATION_ONE_TO_ONE, ); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('c1')); - $collection = $this->getDatabase()->getCollection('c2'); + $this->assertEquals(true, static::getDatabase()->deleteCollection('c1')); + $collection = static::getDatabase()->getCollection('c2'); $this->assertCount(0, $collection->getAttribute('attributes')); $this->assertCount(0, $collection->getAttribute('indexes')); - $this->getDatabase()->createCollection('c1'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createCollection('c1'); + static::getDatabase()->createRelationship( collection: 'c1', relatedCollection: 'c2', type: Database::RELATION_ONE_TO_ONE, ); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('c2')); - $collection = $this->getDatabase()->getCollection('c1'); + $this->assertEquals(true, static::getDatabase()->deleteCollection('c2')); + $collection = static::getDatabase()->getCollection('c1'); $this->assertCount(0, $collection->getAttribute('attributes')); $this->assertCount(0, $collection->getAttribute('indexes')); - $this->getDatabase()->createCollection('c2'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createCollection('c2'); + static::getDatabase()->createRelationship( collection: 'c1', relatedCollection: 'c2', type: Database::RELATION_ONE_TO_ONE, twoWay: true ); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('c1')); - $collection = $this->getDatabase()->getCollection('c2'); + $this->assertEquals(true, static::getDatabase()->deleteCollection('c1')); + $collection = static::getDatabase()->getCollection('c2'); $this->assertCount(0, $collection->getAttribute('attributes')); $this->assertCount(0, $collection->getAttribute('indexes')); - $this->getDatabase()->createCollection('c1'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createCollection('c1'); + static::getDatabase()->createRelationship( collection: 'c1', relatedCollection: 'c2', type: Database::RELATION_ONE_TO_ONE, twoWay: true ); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('c2')); - $collection = $this->getDatabase()->getCollection('c1'); + $this->assertEquals(true, static::getDatabase()->deleteCollection('c2')); + $collection = static::getDatabase()->getCollection('c1'); $this->assertCount(0, $collection->getAttribute('attributes')); $this->assertCount(0, $collection->getAttribute('indexes')); // ONE_TO_MANY - $this->getDatabase()->createCollection('c2'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createCollection('c2'); + static::getDatabase()->createRelationship( collection: 'c1', relatedCollection: 'c2', type: Database::RELATION_ONE_TO_MANY, ); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('c1')); - $collection = $this->getDatabase()->getCollection('c2'); + $this->assertEquals(true, static::getDatabase()->deleteCollection('c1')); + $collection = static::getDatabase()->getCollection('c2'); $this->assertCount(0, $collection->getAttribute('attributes')); $this->assertCount(0, $collection->getAttribute('indexes')); - $this->getDatabase()->createCollection('c1'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createCollection('c1'); + static::getDatabase()->createRelationship( collection: 'c1', relatedCollection: 'c2', type: Database::RELATION_ONE_TO_MANY, ); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('c2')); - $collection = $this->getDatabase()->getCollection('c1'); + $this->assertEquals(true, static::getDatabase()->deleteCollection('c2')); + $collection = static::getDatabase()->getCollection('c1'); $this->assertCount(0, $collection->getAttribute('attributes')); $this->assertCount(0, $collection->getAttribute('indexes')); - $this->getDatabase()->createCollection('c2'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createCollection('c2'); + static::getDatabase()->createRelationship( collection: 'c1', relatedCollection: 'c2', type: Database::RELATION_ONE_TO_MANY, twoWay: true ); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('c1')); - $collection = $this->getDatabase()->getCollection('c2'); + $this->assertEquals(true, static::getDatabase()->deleteCollection('c1')); + $collection = static::getDatabase()->getCollection('c2'); $this->assertCount(0, $collection->getAttribute('attributes')); $this->assertCount(0, $collection->getAttribute('indexes')); - $this->getDatabase()->createCollection('c1'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createCollection('c1'); + static::getDatabase()->createRelationship( collection: 'c1', relatedCollection: 'c2', type: Database::RELATION_ONE_TO_MANY, twoWay: true ); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('c2')); - $collection = $this->getDatabase()->getCollection('c1'); + $this->assertEquals(true, static::getDatabase()->deleteCollection('c2')); + $collection = static::getDatabase()->getCollection('c1'); $this->assertCount(0, $collection->getAttribute('attributes')); $this->assertCount(0, $collection->getAttribute('indexes')); // RELATION_MANY_TO_ONE - $this->getDatabase()->createCollection('c2'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createCollection('c2'); + static::getDatabase()->createRelationship( collection: 'c1', relatedCollection: 'c2', type: Database::RELATION_MANY_TO_ONE, ); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('c1')); - $collection = $this->getDatabase()->getCollection('c2'); + $this->assertEquals(true, static::getDatabase()->deleteCollection('c1')); + $collection = static::getDatabase()->getCollection('c2'); $this->assertCount(0, $collection->getAttribute('attributes')); $this->assertCount(0, $collection->getAttribute('indexes')); - $this->getDatabase()->createCollection('c1'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createCollection('c1'); + static::getDatabase()->createRelationship( collection: 'c1', relatedCollection: 'c2', type: Database::RELATION_MANY_TO_ONE, ); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('c2')); - $collection = $this->getDatabase()->getCollection('c1'); + $this->assertEquals(true, static::getDatabase()->deleteCollection('c2')); + $collection = static::getDatabase()->getCollection('c1'); $this->assertCount(0, $collection->getAttribute('attributes')); $this->assertCount(0, $collection->getAttribute('indexes')); - $this->getDatabase()->createCollection('c2'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createCollection('c2'); + static::getDatabase()->createRelationship( collection: 'c1', relatedCollection: 'c2', type: Database::RELATION_MANY_TO_ONE, twoWay: true ); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('c1')); - $collection = $this->getDatabase()->getCollection('c2'); + $this->assertEquals(true, static::getDatabase()->deleteCollection('c1')); + $collection = static::getDatabase()->getCollection('c2'); $this->assertCount(0, $collection->getAttribute('attributes')); $this->assertCount(0, $collection->getAttribute('indexes')); - $this->getDatabase()->createCollection('c1'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createCollection('c1'); + static::getDatabase()->createRelationship( collection: 'c1', relatedCollection: 'c2', type: Database::RELATION_MANY_TO_ONE, twoWay: true ); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('c2')); - $collection = $this->getDatabase()->getCollection('c1'); + $this->assertEquals(true, static::getDatabase()->deleteCollection('c2')); + $collection = static::getDatabase()->getCollection('c1'); $this->assertCount(0, $collection->getAttribute('attributes')); $this->assertCount(0, $collection->getAttribute('indexes')); } @@ -329,7 +364,6 @@ public function testVirtualRelationsAttributes(): void /** * Success for later test update */ - $doc = static::getDatabase()->createDocument('v1', new Document([ '$id' => 'man', '$permissions' => [ @@ -357,7 +391,7 @@ public function testVirtualRelationsAttributes(): void ])); $this->fail('Failed to throw exception'); } catch (Exception $e) { - $this->assertTrue($e instanceof RelationshipException); + $this->assertInstanceOf(RelationshipException::class, $e); } static::getDatabase()->deleteRelationship('v1', 'v2'); @@ -727,27 +761,27 @@ public function testVirtualRelationsAttributes(): void public function testPreserveDatesUpdate(): void { - self::$authorization->disable(); + Authorization::disable(); - $this->getDatabase()->setPreserveDates(true); + static::getDatabase()->setPreserveDates(true); - $this->getDatabase()->createCollection('preserve_update_dates'); + static::getDatabase()->createCollection('preserve_update_dates'); - $this->getDatabase()->createAttribute('preserve_update_dates', 'attr1', Database::VAR_STRING, 10, false); + static::getDatabase()->createAttribute('preserve_update_dates', 'attr1', Database::VAR_STRING, 10, false); - $doc1 = $this->getDatabase()->createDocument('preserve_update_dates', new Document([ + $doc1 = static::getDatabase()->createDocument('preserve_update_dates', new Document([ '$id' => 'doc1', '$permissions' => [], 'attr1' => 'value1', ])); - $doc2 = $this->getDatabase()->createDocument('preserve_update_dates', new Document([ + $doc2 = static::getDatabase()->createDocument('preserve_update_dates', new Document([ '$id' => 'doc2', '$permissions' => [], 'attr1' => 'value2', ])); - $doc3 = $this->getDatabase()->createDocument('preserve_update_dates', new Document([ + $doc3 = static::getDatabase()->createDocument('preserve_update_dates', new Document([ '$id' => 'doc3', '$permissions' => [], 'attr1' => 'value3', @@ -756,8 +790,9 @@ public function testPreserveDatesUpdate(): void $newDate = '2000-01-01T10:00:00.000+00:00'; $doc1->setAttribute('$updatedAt', $newDate); - $this->getDatabase()->updateDocument('preserve_update_dates', 'doc1', $doc1); - $doc1 = $this->getDatabase()->getDocument('preserve_update_dates', 'doc1'); + $doc1 = static::getDatabase()->updateDocument('preserve_update_dates', 'doc1', $doc1); + $this->assertEquals($newDate, $doc1->getAttribute('$updatedAt')); + $doc1 = static::getDatabase()->getDocument('preserve_update_dates', 'doc1'); $this->assertEquals($newDate, $doc1->getAttribute('$updatedAt')); $this->getDatabase()->updateDocuments( @@ -773,38 +808,38 @@ public function testPreserveDatesUpdate(): void ] ); - $doc2 = $this->getDatabase()->getDocument('preserve_update_dates', 'doc2'); - $doc3 = $this->getDatabase()->getDocument('preserve_update_dates', 'doc3'); + $doc2 = static::getDatabase()->getDocument('preserve_update_dates', 'doc2'); + $doc3 = static::getDatabase()->getDocument('preserve_update_dates', 'doc3'); $this->assertEquals($newDate, $doc2->getAttribute('$updatedAt')); $this->assertEquals($newDate, $doc3->getAttribute('$updatedAt')); - $this->getDatabase()->deleteCollection('preserve_update_dates'); + static::getDatabase()->deleteCollection('preserve_update_dates'); - $this->getDatabase()->setPreserveDates(false); + static::getDatabase()->setPreserveDates(false); - self::$authorization->reset(); + Authorization::reset(); } public function testPreserveDatesCreate(): void { - self::$authorization->disable(); + Authorization::disable(); - $this->getDatabase()->setPreserveDates(true); + static::getDatabase()->setPreserveDates(true); - $this->getDatabase()->createCollection('preserve_create_dates'); + static::getDatabase()->createCollection('preserve_create_dates'); - $this->getDatabase()->createAttribute('preserve_create_dates', 'attr1', Database::VAR_STRING, 10, false); + static::getDatabase()->createAttribute('preserve_create_dates', 'attr1', Database::VAR_STRING, 10, false); $date = '2000-01-01T10:00:00.000+00:00'; - $this->getDatabase()->createDocument('preserve_create_dates', new Document([ + static::getDatabase()->createDocument('preserve_create_dates', new Document([ '$id' => 'doc1', '$permissions' => [], 'attr1' => 'value1', '$createdAt' => $date ])); - $this->getDatabase()->createDocuments('preserve_create_dates', [ + static::getDatabase()->createDocuments('preserve_create_dates', [ new Document([ '$id' => 'doc2', '$permissions' => [], @@ -819,18 +854,18 @@ public function testPreserveDatesCreate(): void ]), ], 2); - $doc1 = $this->getDatabase()->getDocument('preserve_create_dates', 'doc1'); - $doc2 = $this->getDatabase()->getDocument('preserve_create_dates', 'doc2'); - $doc3 = $this->getDatabase()->getDocument('preserve_create_dates', 'doc3'); + $doc1 = static::getDatabase()->getDocument('preserve_create_dates', 'doc1'); + $doc2 = static::getDatabase()->getDocument('preserve_create_dates', 'doc2'); + $doc3 = static::getDatabase()->getDocument('preserve_create_dates', 'doc3'); $this->assertEquals($date, $doc1->getAttribute('$createdAt')); $this->assertEquals($date, $doc2->getAttribute('$createdAt')); $this->assertEquals($date, $doc3->getAttribute('$createdAt')); - $this->getDatabase()->deleteCollection('preserve_create_dates'); + static::getDatabase()->deleteCollection('preserve_create_dates'); - $this->getDatabase()->setPreserveDates(false); + static::getDatabase()->setPreserveDates(false); - self::$authorization->reset(); + Authorization::reset(); } /** @@ -880,14 +915,18 @@ public function testIndexValidation(): void 'indexes' => $indexes ]); - $validator = new Index($attributes, $this->getDatabase()->getAdapter()->getMaxIndexLength()); + $validator = new Index( + $attributes, + static::getDatabase()->getAdapter()->getMaxIndexLength(), + static::getDatabase()->getAdapter()->getInternalIndexesKeys() + ); $errorMessage = 'Index length 701 is larger than the size for title1: 700"'; $this->assertFalse($validator->isValid($indexes[0])); $this->assertEquals($errorMessage, $validator->getDescription()); try { - $this->getDatabase()->createCollection($collection->getId(), $attributes, $indexes, [ + static::getDatabase()->createCollection($collection->getId(), $attributes, $indexes, [ Permission::read(Role::any()), Permission::create(Role::any()), ]); @@ -908,13 +947,13 @@ public function testIndexValidation(): void $collection->setAttribute('indexes', $indexes); - if ($this->getDatabase()->getAdapter()->getMaxIndexLength() > 0) { - $errorMessage = 'Index length is longer than the maximum: ' . $this->getDatabase()->getAdapter()->getMaxIndexLength(); + if (static::getDatabase()->getAdapter()->getMaxIndexLength() > 0) { + $errorMessage = 'Index length is longer than the maximum: ' . static::getDatabase()->getAdapter()->getMaxIndexLength(); $this->assertFalse($validator->isValid($indexes[0])); $this->assertEquals($errorMessage, $validator->getDescription()); try { - $this->getDatabase()->createCollection($collection->getId(), $attributes, $indexes); + static::getDatabase()->createCollection($collection->getId(), $attributes, $indexes); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals($errorMessage, $e->getMessage()); @@ -950,13 +989,17 @@ public function testIndexValidation(): void 'indexes' => $indexes ]); - $validator = new Index($attributes, $this->getDatabase()->getAdapter()->getMaxIndexLength()); + $validator = new Index( + $attributes, + static::getDatabase()->getAdapter()->getMaxIndexLength(), + static::getDatabase()->getAdapter()->getInternalIndexesKeys() + ); $errorMessage = 'Attribute "integer" cannot be part of a FULLTEXT index, must be of type string'; $this->assertFalse($validator->isValid($indexes[0])); $this->assertEquals($errorMessage, $validator->getDescription()); try { - $this->getDatabase()->createCollection($collection->getId(), $attributes, $indexes); + static::getDatabase()->createCollection($collection->getId(), $attributes, $indexes); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals($errorMessage, $e->getMessage()); @@ -965,9 +1008,9 @@ public function testIndexValidation(): void public function testCreatedAtUpdatedAt(): void { - $this->assertInstanceOf('Utopia\Database\Document', $this->getDatabase()->createCollection('created_at')); - $this->getDatabase()->createAttribute('created_at', 'title', Database::VAR_STRING, 100, false); - $document = $this->getDatabase()->createDocument('created_at', new Document([ + $this->assertInstanceOf('Utopia\Database\Document', static::getDatabase()->createCollection('created_at')); + static::getDatabase()->createAttribute('created_at', 'title', Database::VAR_STRING, 100, false); + $document = static::getDatabase()->createDocument('created_at', new Document([ '$id' => ID::custom('uid123'), '$permissions' => [ @@ -983,6 +1026,14 @@ public function testCreatedAtUpdatedAt(): void } + /** + * @throws AuthorizationException + * @throws DuplicateException + * @throws ConflictException + * @throws LimitException + * @throws StructureException + * @throws DatabaseException + */ public function testQueryTimeout(): void { if (!$this->getDatabase()->getAdapter()->getSupportForTimeouts()) { @@ -991,10 +1042,20 @@ public function testQueryTimeout(): void } static::getDatabase()->createCollection('global-timeouts'); - $this->assertEquals(true, static::getDatabase()->createAttribute('global-timeouts', 'longtext', Database::VAR_STRING, 100000000, true)); - for ($i = 0 ; $i <= 20 ; $i++) { - $this->getDatabase()->createDocument('global-timeouts', new Document([ + $this->assertEquals( + true, + static::getDatabase()->createAttribute( + collection: 'global-timeouts', + id: 'longtext', + type: Database::VAR_STRING, + size: 100000000, + required: true + ) + ); + + for ($i = 0; $i < 20; $i++) { + static::getDatabase()->createDocument('global-timeouts', new Document([ 'longtext' => file_get_contents(__DIR__ . '/../../resources/longtext.txt'), '$permissions' => [ Permission::read(Role::any()), @@ -1007,13 +1068,14 @@ public function testQueryTimeout(): void static::getDatabase()->setTimeout(1); try { - $this->getDatabase()->find('global-timeouts', [ + static::getDatabase()->find('global-timeouts', [ Query::notEqual('longtext', 'appwrite'), ]); $this->fail('Failed to throw exception'); - } catch (TimeoutException $ex) { + } catch (\Exception $e) { static::getDatabase()->clearTimeout(); static::getDatabase()->deleteCollection('global-timeouts'); + $this->assertInstanceOf(TimeoutException::class, $e); } } @@ -1022,34 +1084,60 @@ public function testQueryTimeout(): void */ public function testCreateListExistsDeleteCollection(): void { - $this->assertInstanceOf('Utopia\Database\Document', $this->getDatabase()->createCollection('actors', permissions: [ + $this->assertInstanceOf('Utopia\Database\Document', static::getDatabase()->createCollection('actors', permissions: [ Permission::create(Role::any()), Permission::read(Role::any()), ])); - $this->assertCount(1, $this->getDatabase()->listCollections()); - $this->assertEquals(true, $this->getDatabase()->exists($this->testDatabase, 'actors')); + $this->assertCount(1, static::getDatabase()->listCollections()); + $this->assertEquals(true, static::getDatabase()->exists($this->testDatabase, 'actors')); // Collection names should not be unique - $this->assertInstanceOf('Utopia\Database\Document', $this->getDatabase()->createCollection('actors2', permissions: [ + $this->assertInstanceOf('Utopia\Database\Document', static::getDatabase()->createCollection('actors2', permissions: [ Permission::create(Role::any()), Permission::read(Role::any()), ])); - $this->assertCount(2, $this->getDatabase()->listCollections()); - $this->assertEquals(true, $this->getDatabase()->exists($this->testDatabase, 'actors2')); - $collection = $this->getDatabase()->getCollection('actors2'); + $this->assertCount(2, static::getDatabase()->listCollections()); + $this->assertEquals(true, static::getDatabase()->exists($this->testDatabase, 'actors2')); + $collection = static::getDatabase()->getCollection('actors2'); $collection->setAttribute('name', 'actors'); // change name to one that exists - $this->assertInstanceOf('Utopia\Database\Document', $this->getDatabase()->updateDocument( + $this->assertInstanceOf('Utopia\Database\Document', static::getDatabase()->updateDocument( $collection->getCollection(), $collection->getId(), $collection )); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('actors2')); // Delete collection when finished - $this->assertCount(1, $this->getDatabase()->listCollections()); + $this->assertEquals(true, static::getDatabase()->deleteCollection('actors2')); // Delete collection when finished + $this->assertCount(1, static::getDatabase()->listCollections()); - $this->assertEquals(false, $this->getDatabase()->getCollection('actors')->isEmpty()); - $this->assertEquals(true, $this->getDatabase()->deleteCollection('actors')); - $this->assertEquals(true, $this->getDatabase()->getCollection('actors')->isEmpty()); - $this->assertEquals(false, $this->getDatabase()->exists($this->testDatabase, 'actors')); + $this->assertEquals(false, static::getDatabase()->getCollection('actors')->isEmpty()); + $this->assertEquals(true, static::getDatabase()->deleteCollection('actors')); + $this->assertEquals(true, static::getDatabase()->getCollection('actors')->isEmpty()); + $this->assertEquals(false, static::getDatabase()->exists($this->testDatabase, 'actors')); + } + + public function testCreateIndex(): void + { + $database = $this->getDatabase(); + + $database->createCollection('indexes'); + $database->createAttribute('indexes', 'name', Database::VAR_STRING, 10, false); + + $database->createIndex('indexes', 'index_1', Database::INDEX_KEY, ['name']); + + try { + $database->createIndex('indexes', 'index3', Database::INDEX_KEY, ['$id', '$id']); + } catch (Throwable $e) { + self::assertTrue($e instanceof DatabaseException); + self::assertEquals($e->getMessage(), 'Duplicate attributes provided'); + } + + try { + $database->createIndex('indexes', 'index4', Database::INDEX_KEY, ['name', 'Name']); + } catch (Throwable $e) { + self::assertTrue($e instanceof DatabaseException); + self::assertEquals($e->getMessage(), 'Duplicate attributes provided'); + } + + $database->deleteCollection('indexes'); } public function testSizeCollection(): void @@ -1076,7 +1164,6 @@ public function testSizeCollection(): void static::getDatabase()->createAttribute('sizeTest2', 'string3', Database::VAR_STRING, 254 + 1, true); static::getDatabase()->createIndex('sizeTest2', 'index', Database::INDEX_KEY, ['string1', 'string2', 'string3'], [128, 128, 128]); - $loopCount = 100; for ($i = 0; $i < $loopCount; $i++) { @@ -1094,7 +1181,7 @@ public function testSizeCollection(): void $this->assertGreaterThan($size1, $size2); - self::$authorization->skip(function () use ($loopCount) { + Authorization::skip(function () use ($loopCount) { for ($i = 0; $i < $loopCount; $i++) { $this->getDatabase()->deleteDocument('sizeTest2', 'doc' . $i); } @@ -1145,49 +1232,49 @@ public function testSizeCollectionOnDisk(): void public function testSizeFullText(): void { // SQLite does not support fulltext indexes - if (!$this->getDatabase()->getAdapter()->getSupportForFulltextIndex()) { + if (!static::getDatabase()->getAdapter()->getSupportForFulltextIndex()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('fullTextSizeTest'); + static::getDatabase()->createCollection('fullTextSizeTest'); - $size1 = $this->getDatabase()->getSizeOfCollectionOnDisk('fullTextSizeTest'); + $size1 = static::getDatabase()->getSizeOfCollection('fullTextSizeTest'); - $this->getDatabase()->createAttribute('fullTextSizeTest', 'string1', Database::VAR_STRING, 128, true); - $this->getDatabase()->createAttribute('fullTextSizeTest', 'string2', Database::VAR_STRING, 254, true); - $this->getDatabase()->createAttribute('fullTextSizeTest', 'string3', Database::VAR_STRING, 254, true); - $this->getDatabase()->createIndex('fullTextSizeTest', 'index', Database::INDEX_KEY, ['string1', 'string2', 'string3'], [128, 128, 128]); + static::getDatabase()->createAttribute('fullTextSizeTest', 'string1', Database::VAR_STRING, 128, true); + static::getDatabase()->createAttribute('fullTextSizeTest', 'string2', Database::VAR_STRING, 254, true); + static::getDatabase()->createAttribute('fullTextSizeTest', 'string3', Database::VAR_STRING, 254, true); + static::getDatabase()->createIndex('fullTextSizeTest', 'index', Database::INDEX_KEY, ['string1', 'string2', 'string3'], [128, 128, 128]); $loopCount = 10; for ($i = 0; $i < $loopCount; $i++) { - $this->getDatabase()->createDocument('fullTextSizeTest', new Document([ + static::getDatabase()->createDocument('fullTextSizeTest', new Document([ 'string1' => 'string1' . $i, 'string2' => 'string2' . $i, 'string3' => 'string3' . $i, ])); } - $size2 = $this->getDatabase()->getSizeOfCollectionOnDisk('fullTextSizeTest'); + $size2 = static::getDatabase()->getSizeOfCollectionOnDisk('fullTextSizeTest'); $this->assertGreaterThan($size1, $size2); - $this->getDatabase()->createIndex('fullTextSizeTest', 'fulltext_index', Database::INDEX_FULLTEXT, ['string1']); + static::getDatabase()->createIndex('fullTextSizeTest', 'fulltext_index', Database::INDEX_FULLTEXT, ['string1']); - $size3 = $this->getDatabase()->getSizeOfCollectionOnDisk('fullTextSizeTest'); + $size3 = static::getDatabase()->getSizeOfCollectionOnDisk('fullTextSizeTest'); $this->assertGreaterThan($size2, $size3); } public function testPurgeCollectionCache(): void { - $this->getDatabase()->createCollection('redis'); + static::getDatabase()->createCollection('redis'); - $this->assertEquals(true, $this->getDatabase()->createAttribute('redis', 'name', Database::VAR_STRING, 128, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('redis', 'age', Database::VAR_INTEGER, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('redis', 'name', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('redis', 'age', Database::VAR_INTEGER, 0, true)); - $this->getDatabase()->createDocument('redis', new Document([ + static::getDatabase()->createDocument('redis', new Document([ '$id' => 'doc1', 'name' => 'Richard', 'age' => 15, @@ -1196,106 +1283,169 @@ public function testPurgeCollectionCache(): void ] ])); - $document = $this->getDatabase()->getDocument('redis', 'doc1'); + $document = static::getDatabase()->getDocument('redis', 'doc1'); $this->assertEquals('Richard', $document->getAttribute('name')); $this->assertEquals(15, $document->getAttribute('age')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('redis', 'age')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('redis', 'age')); - $document = $this->getDatabase()->getDocument('redis', 'doc1'); + $document = static::getDatabase()->getDocument('redis', 'doc1'); $this->assertEquals('Richard', $document->getAttribute('name')); $this->assertArrayNotHasKey('age', $document); - $this->assertEquals(true, $this->getDatabase()->createAttribute('redis', 'age', Database::VAR_INTEGER, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('redis', 'age', Database::VAR_INTEGER, 0, true)); - $document = $this->getDatabase()->getDocument('redis', 'doc1'); + $document = static::getDatabase()->getDocument('redis', 'doc1'); $this->assertEquals('Richard', $document->getAttribute('name')); $this->assertArrayHasKey('age', $document); } + public function testSchemaAttributes(): void + { + if (!$this->getDatabase()->getAdapter()->getSupportForSchemaAttributes()) { + $this->expectNotToPerformAssertions(); + return; + } + + $collection = 'schema_attributes'; + $db = static::getDatabase(); + + $this->assertEmpty($db->getSchemaAttributes('no_such_collection')); + + $db->createCollection($collection); + + $db->createAttribute($collection, 'username', Database::VAR_STRING, 128, true); + $db->createAttribute($collection, 'story', Database::VAR_STRING, 20000, true); + $db->createAttribute($collection, 'string_list', Database::VAR_STRING, 128, true, null, true, true); + $db->createAttribute($collection, 'dob', Database::VAR_DATETIME, 0, false, '2000-06-12T14:12:55.000+00:00', true, false, null, [], ['datetime']); + + $attributes = []; + foreach ($db->getSchemaAttributes($collection) as $attribute) { + /** + * @var Document $attribute + */ + $attributes[$attribute->getAttribute('columnName')] = $attribute; + } + + $attribute = $attributes['username']; + $this->assertEquals('username', $attribute['columnName']); + $this->assertEquals('varchar', $attribute['dataType']); + $this->assertEquals('varchar(128)', $attribute['columnType']); + $this->assertEquals('128', $attribute['characterMaximumLength']); + $this->assertEquals('YES', $attribute['isNullable']); + + $attribute = $attributes['story']; + $this->assertEquals('story', $attribute['columnName']); + $this->assertEquals('text', $attribute['dataType']); + $this->assertEquals('text', $attribute['columnType']); + $this->assertEquals('65535', $attribute['characterMaximumLength']); + + $attribute = $attributes['string_list']; + $this->assertEquals('string_list', $attribute['columnName']); + $this->assertTrue(in_array($attribute['dataType'], ['json', 'longtext'])); // mysql vs maria + $this->assertTrue(in_array($attribute['columnType'], ['json', 'longtext'])); + $this->assertTrue(in_array($attribute['characterMaximumLength'], [null, '4294967295'])); + $this->assertEquals('YES', $attribute['isNullable']); + + $attribute = $attributes['dob']; + $this->assertEquals('dob', $attribute['columnName']); + $this->assertEquals('datetime', $attribute['dataType']); + $this->assertEquals('datetime(3)', $attribute['columnType']); + $this->assertEquals(null, $attribute['characterMaximumLength']); + $this->assertEquals('3', $attribute['datetimePrecision']); + + if ($db->getSharedTables()) { + $attribute = $attributes['_tenant']; + $this->assertEquals('_tenant', $attribute['columnName']); + $this->assertEquals('int', $attribute['dataType']); + $this->assertEquals('10', $attribute['numericPrecision']); + $this->assertTrue(in_array($attribute['columnType'], ['int unsigned', 'int(11) unsigned'])); + } + } + public function testCreateDeleteAttribute(): void { - $this->getDatabase()->createCollection('attributes'); + static::getDatabase()->createCollection('attributes'); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'string1', Database::VAR_STRING, 128, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'string2', Database::VAR_STRING, 16382 + 1, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'string3', Database::VAR_STRING, 65535 + 1, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'string4', Database::VAR_STRING, 16777215 + 1, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'integer', Database::VAR_INTEGER, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'bigint', Database::VAR_INTEGER, 8, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'float', Database::VAR_FLOAT, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'boolean', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'string1', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'string2', Database::VAR_STRING, 16382 + 1, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'string3', Database::VAR_STRING, 65535 + 1, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'string4', Database::VAR_STRING, 16777215 + 1, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'integer', Database::VAR_INTEGER, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'bigint', Database::VAR_INTEGER, 8, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'float', Database::VAR_FLOAT, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'boolean', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createIndex('attributes', 'string1_index', Database::INDEX_KEY, ['string1'])); - $this->assertEquals(true, $this->getDatabase()->createIndex('attributes', 'string2_index', Database::INDEX_KEY, ['string2'], [255])); - $this->assertEquals(true, $this->getDatabase()->createIndex('attributes', 'multi_index', Database::INDEX_KEY, ['string1', 'string2', 'string3'], [128, 128, 128])); + $this->assertEquals(true, static::getDatabase()->createIndex('attributes', 'string1_index', Database::INDEX_KEY, ['string1'])); + $this->assertEquals(true, static::getDatabase()->createIndex('attributes', 'string2_index', Database::INDEX_KEY, ['string2'], [255])); + $this->assertEquals(true, static::getDatabase()->createIndex('attributes', 'multi_index', Database::INDEX_KEY, ['string1', 'string2', 'string3'], [128, 128, 128])); - $collection = $this->getDatabase()->getCollection('attributes'); + $collection = static::getDatabase()->getCollection('attributes'); $this->assertCount(8, $collection->getAttribute('attributes')); $this->assertCount(3, $collection->getAttribute('indexes')); // Array - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'string_list', Database::VAR_STRING, 128, true, null, true, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'integer_list', Database::VAR_INTEGER, 0, true, null, true, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'float_list', Database::VAR_FLOAT, 0, true, null, true, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'boolean_list', Database::VAR_BOOLEAN, 0, true, null, true, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'string_list', Database::VAR_STRING, 128, true, null, true, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'integer_list', Database::VAR_INTEGER, 0, true, null, true, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'float_list', Database::VAR_FLOAT, 0, true, null, true, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'boolean_list', Database::VAR_BOOLEAN, 0, true, null, true, true)); - $collection = $this->getDatabase()->getCollection('attributes'); + $collection = static::getDatabase()->getCollection('attributes'); $this->assertCount(12, $collection->getAttribute('attributes')); // Default values - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'string_default', Database::VAR_STRING, 256, false, 'test')); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'integer_default', Database::VAR_INTEGER, 0, false, 1)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'float_default', Database::VAR_FLOAT, 0, false, 1.5)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'boolean_default', Database::VAR_BOOLEAN, 0, false, false)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'datetime_default', Database::VAR_DATETIME, 0, false, '2000-06-12T14:12:55.000+00:00', true, false, null, [], ['datetime'])); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'string_default', Database::VAR_STRING, 256, false, 'test')); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'integer_default', Database::VAR_INTEGER, 0, false, 1)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'float_default', Database::VAR_FLOAT, 0, false, 1.5)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'boolean_default', Database::VAR_BOOLEAN, 0, false, false)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'datetime_default', Database::VAR_DATETIME, 0, false, '2000-06-12T14:12:55.000+00:00', true, false, null, [], ['datetime'])); - $collection = $this->getDatabase()->getCollection('attributes'); + $collection = static::getDatabase()->getCollection('attributes'); $this->assertCount(17, $collection->getAttribute('attributes')); // Delete - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'string1')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'string2')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'string3')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'string4')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'integer')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'bigint')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'float')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'boolean')); - - $collection = $this->getDatabase()->getCollection('attributes'); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'string1')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'string2')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'string3')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'string4')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'integer')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'bigint')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'float')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'boolean')); + + $collection = static::getDatabase()->getCollection('attributes'); $this->assertCount(9, $collection->getAttribute('attributes')); $this->assertCount(0, $collection->getAttribute('indexes')); // Delete Array - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'string_list')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'integer_list')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'float_list')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'boolean_list')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'string_list')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'integer_list')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'float_list')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'boolean_list')); - $collection = $this->getDatabase()->getCollection('attributes'); + $collection = static::getDatabase()->getCollection('attributes'); $this->assertCount(5, $collection->getAttribute('attributes')); // Delete default - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'string_default')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'integer_default')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'float_default')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'boolean_default')); - $this->assertEquals(true, $this->getDatabase()->deleteAttribute('attributes', 'datetime_default')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'string_default')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'integer_default')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'float_default')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'boolean_default')); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'datetime_default')); - $collection = $this->getDatabase()->getCollection('attributes'); + $collection = static::getDatabase()->getCollection('attributes'); $this->assertCount(0, $collection->getAttribute('attributes')); // Test for custom chars in ID - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'as_5dasdasdas', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'as5dasdasdas_', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', '.as5dasdasdas', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', '-as5dasdasdas', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'as-5dasdasdas', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'as5dasdasdas-', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'socialAccountForYoutubeSubscribersss', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', '5f058a89258075f058a89258075f058t9214', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'as_5dasdasdas', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'as5dasdasdas_', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', '.as5dasdasdas', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', '-as5dasdasdas', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'as-5dasdasdas', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'as5dasdasdas-', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'socialAccountForYoutubeSubscribersss', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', '5f058a89258075f058a89258075f058t9214', Database::VAR_BOOLEAN, 0, true)); // Test non-shared tables duplicates throw duplicate static::getDatabase()->createAttribute('attributes', 'duplicate', Database::VAR_STRING, 128, true); @@ -1305,6 +1455,26 @@ public function testCreateDeleteAttribute(): void } catch (Exception $e) { $this->assertInstanceOf(DuplicateException::class, $e); } + + // Test delete attribute when column does not exist + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'string1', Database::VAR_STRING, 128, true)); + sleep(1); + + $this->assertEquals(true, static::deleteColumn('attributes', 'string1')); + + $collection = static::getDatabase()->getCollection('attributes'); + $attributes = $collection->getAttribute('attributes'); + $attribute = end($attributes); + $this->assertEquals('string1', $attribute->getId()); + + $this->assertEquals(true, static::getDatabase()->deleteAttribute('attributes', 'string1')); + + $collection = static::getDatabase()->getCollection('attributes'); + $attributes = $collection->getAttribute('attributes'); + $attribute = end($attributes); + $this->assertNotEquals('string1', $attribute->getId()); + + $collection = static::getDatabase()->getCollection('attributes'); } /** @@ -1338,7 +1508,7 @@ public function invalidDefaultValues(): array public function testInvalidDefaultValues(string $type, mixed $default): void { $this->expectException(\Exception::class); - $this->assertEquals(false, $this->getDatabase()->createAttribute('attributes', 'bad_default', $type, 256, true, $default)); + $this->assertEquals(false, static::getDatabase()->createAttribute('attributes', 'bad_default', $type, 256, true, $default)); } /** @@ -1346,18 +1516,19 @@ public function testInvalidDefaultValues(string $type, mixed $default): void */ public function testAttributeCaseInsensitivity(): void { + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'caseSensitive', Database::VAR_STRING, 128, true)); $this->expectException(DuplicateException::class); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributes', 'CaseSensitive', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributes', 'CaseSensitive', Database::VAR_STRING, 128, true)); } public function testAttributeKeyWithSymbols(): void { - $this->getDatabase()->createCollection('attributesWithKeys'); + static::getDatabase()->createCollection('attributesWithKeys'); - $this->assertEquals(true, $this->getDatabase()->createAttribute('attributesWithKeys', 'key_with.sym$bols', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('attributesWithKeys', 'key_with.sym$bols', Database::VAR_STRING, 128, true)); - $document = $this->getDatabase()->createDocument('attributesWithKeys', new Document([ + $document = static::getDatabase()->createDocument('attributesWithKeys', new Document([ 'key_with.sym$bols' => 'value', '$permissions' => [ Permission::read(Role::any()), @@ -1366,7 +1537,7 @@ public function testAttributeKeyWithSymbols(): void $this->assertEquals('value', $document->getAttribute('key_with.sym$bols')); - $document = $this->getDatabase()->getDocument('attributesWithKeys', $document->getId()); + $document = static::getDatabase()->getDocument('attributesWithKeys', $document->getId()); $this->assertEquals('value', $document->getAttribute('key_with.sym$bols')); } @@ -1374,7 +1545,7 @@ public function testAttributeKeyWithSymbols(): void public function testCollectionNotFound(): void { try { - $this->getDatabase()->find('not_exist', []); + static::getDatabase()->find('not_exist', []); $this->fail('Failed to throw Exception'); } catch (Exception $e) { $this->assertEquals('Collection not found', $e->getMessage()); @@ -1383,9 +1554,9 @@ public function testCollectionNotFound(): void public function testAttributeNamesWithDots(): void { - $this->getDatabase()->createCollection('dots.parent'); + static::getDatabase()->createCollection('dots.parent'); - $this->assertTrue($this->getDatabase()->createAttribute( + $this->assertTrue(static::getDatabase()->createAttribute( collection: 'dots.parent', id: 'dots.name', type: Database::VAR_STRING, @@ -1393,14 +1564,14 @@ public function testAttributeNamesWithDots(): void required: false )); - $document = $this->getDatabase()->find('dots.parent', [ + $document = static::getDatabase()->find('dots.parent', [ Query::select(['dots.name']), ]); $this->assertEmpty($document); - $this->getDatabase()->createCollection('dots'); + static::getDatabase()->createCollection('dots'); - $this->assertTrue($this->getDatabase()->createAttribute( + $this->assertTrue(static::getDatabase()->createAttribute( collection: 'dots', id: 'name', type: Database::VAR_STRING, @@ -1408,13 +1579,13 @@ public function testAttributeNamesWithDots(): void required: false )); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'dots.parent', relatedCollection: 'dots', type: Database::RELATION_ONE_TO_ONE ); - $this->getDatabase()->createDocument('dots.parent', new Document([ + static::getDatabase()->createDocument('dots.parent', new Document([ '$id' => ID::custom('father'), 'dots.name' => 'Bill clinton', '$permissions' => [ @@ -1434,7 +1605,7 @@ public function testAttributeNamesWithDots(): void ] ])); - $documents = $this->getDatabase()->find('dots.parent', [ + $documents = static::getDatabase()->find('dots.parent', [ Query::select(['*']), ]); @@ -1446,9 +1617,13 @@ public function testAttributeNamesWithDots(): void */ public function testIndexCaseInsensitivity(): void { - $this->assertEquals(true, $this->getDatabase()->createIndex('attributes', 'key_caseSensitive', Database::INDEX_KEY, ['caseSensitive'], [128])); - $this->expectException(DuplicateException::class); - $this->assertEquals(true, $this->getDatabase()->createIndex('attributes', 'key_CaseSensitive', Database::INDEX_KEY, ['caseSensitive'], [128])); + $this->assertEquals(true, static::getDatabase()->createIndex('attributes', 'key_caseSensitive', Database::INDEX_KEY, ['caseSensitive'], [128])); + + try { + $this->assertEquals(true, static::getDatabase()->createIndex('attributes', 'key_CaseSensitive', Database::INDEX_KEY, ['caseSensitive'], [128])); + } catch (Throwable $e) { + self::assertTrue($e instanceof DuplicateException); + } } /** @@ -1458,7 +1633,7 @@ public function testIndexCaseInsensitivity(): void */ public function testCleanupAttributeTests(): void { - $this->getDatabase()->deleteCollection('attributes'); + static::getDatabase()->deleteCollection('attributes'); $this->assertEquals(1, 1); } @@ -1469,39 +1644,39 @@ public function testCleanupAttributeTests(): void public function testUnknownFormat(): void { $this->expectException(\Exception::class); - $this->assertEquals(false, $this->getDatabase()->createAttribute('attributes', 'bad_format', Database::VAR_STRING, 256, true, null, true, false, 'url')); + $this->assertEquals(false, static::getDatabase()->createAttribute('attributes', 'bad_format', Database::VAR_STRING, 256, true, null, true, false, 'url')); } public function testCreateDeleteIndex(): void { - $this->getDatabase()->createCollection('indexes'); + static::getDatabase()->createCollection('indexes'); - $this->assertEquals(true, $this->getDatabase()->createAttribute('indexes', 'string', Database::VAR_STRING, 128, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('indexes', 'order', Database::VAR_STRING, 128, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('indexes', 'integer', Database::VAR_INTEGER, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('indexes', 'float', Database::VAR_FLOAT, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('indexes', 'boolean', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('indexes', 'string', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('indexes', 'order', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('indexes', 'integer', Database::VAR_INTEGER, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('indexes', 'float', Database::VAR_FLOAT, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('indexes', 'boolean', Database::VAR_BOOLEAN, 0, true)); // Indexes - $this->assertEquals(true, $this->getDatabase()->createIndex('indexes', 'index1', Database::INDEX_KEY, ['string', 'integer'], [128], [Database::ORDER_ASC])); - $this->assertEquals(true, $this->getDatabase()->createIndex('indexes', 'index2', Database::INDEX_KEY, ['float', 'integer'], [], [Database::ORDER_ASC, Database::ORDER_DESC])); - $this->assertEquals(true, $this->getDatabase()->createIndex('indexes', 'index3', Database::INDEX_KEY, ['integer', 'boolean'], [], [Database::ORDER_ASC, Database::ORDER_DESC, Database::ORDER_DESC])); - $this->assertEquals(true, $this->getDatabase()->createIndex('indexes', 'index4', Database::INDEX_UNIQUE, ['string'], [128], [Database::ORDER_ASC])); - $this->assertEquals(true, $this->getDatabase()->createIndex('indexes', 'index5', Database::INDEX_UNIQUE, ['$id', 'string'], [128], [Database::ORDER_ASC])); - $this->assertEquals(true, $this->getDatabase()->createIndex('indexes', 'order', Database::INDEX_UNIQUE, ['order'], [128], [Database::ORDER_ASC])); - - $collection = $this->getDatabase()->getCollection('indexes'); + $this->assertEquals(true, static::getDatabase()->createIndex('indexes', 'index1', Database::INDEX_KEY, ['string', 'integer'], [128], [Database::ORDER_ASC])); + $this->assertEquals(true, static::getDatabase()->createIndex('indexes', 'index2', Database::INDEX_KEY, ['float', 'integer'], [], [Database::ORDER_ASC, Database::ORDER_DESC])); + $this->assertEquals(true, static::getDatabase()->createIndex('indexes', 'index3', Database::INDEX_KEY, ['integer', 'boolean'], [], [Database::ORDER_ASC, Database::ORDER_DESC, Database::ORDER_DESC])); + $this->assertEquals(true, static::getDatabase()->createIndex('indexes', 'index4', Database::INDEX_UNIQUE, ['string'], [128], [Database::ORDER_ASC])); + $this->assertEquals(true, static::getDatabase()->createIndex('indexes', 'index5', Database::INDEX_UNIQUE, ['$id', 'string'], [128], [Database::ORDER_ASC])); + $this->assertEquals(true, static::getDatabase()->createIndex('indexes', 'order', Database::INDEX_UNIQUE, ['order'], [128], [Database::ORDER_ASC])); + + $collection = static::getDatabase()->getCollection('indexes'); $this->assertCount(6, $collection->getAttribute('indexes')); // Delete Indexes - $this->assertEquals(true, $this->getDatabase()->deleteIndex('indexes', 'index1')); - $this->assertEquals(true, $this->getDatabase()->deleteIndex('indexes', 'index2')); - $this->assertEquals(true, $this->getDatabase()->deleteIndex('indexes', 'index3')); - $this->assertEquals(true, $this->getDatabase()->deleteIndex('indexes', 'index4')); - $this->assertEquals(true, $this->getDatabase()->deleteIndex('indexes', 'index5')); - $this->assertEquals(true, $this->getDatabase()->deleteIndex('indexes', 'order')); - - $collection = $this->getDatabase()->getCollection('indexes'); + $this->assertEquals(true, static::getDatabase()->deleteIndex('indexes', 'index1')); + $this->assertEquals(true, static::getDatabase()->deleteIndex('indexes', 'index2')); + $this->assertEquals(true, static::getDatabase()->deleteIndex('indexes', 'index3')); + $this->assertEquals(true, static::getDatabase()->deleteIndex('indexes', 'index4')); + $this->assertEquals(true, static::getDatabase()->deleteIndex('indexes', 'index5')); + $this->assertEquals(true, static::getDatabase()->deleteIndex('indexes', 'order')); + + $collection = static::getDatabase()->getCollection('indexes'); $this->assertCount(0, $collection->getAttribute('indexes')); // Test non-shared tables duplicates throw duplicate @@ -1513,6 +1688,16 @@ public function testCreateDeleteIndex(): void $this->assertInstanceOf(DuplicateException::class, $e); } + // Test delete index when index does not exist + $this->assertEquals(true, static::getDatabase()->createIndex('indexes', 'index1', Database::INDEX_KEY, ['string', 'integer'], [128], [Database::ORDER_ASC])); + $this->assertEquals(true, static::deleteIndex('indexes', 'index1')); + $this->assertEquals(true, static::getDatabase()->deleteIndex('indexes', 'index1')); + + // Test delete index when attribute does not exist + $this->assertEquals(true, static::getDatabase()->createIndex('indexes', 'index1', Database::INDEX_KEY, ['string', 'integer'], [128], [Database::ORDER_ASC])); + $this->assertEquals(true, static::getDatabase()->deleteAttribute('indexes', 'string')); + $this->assertEquals(true, static::getDatabase()->deleteIndex('indexes', 'index1')); + static::getDatabase()->deleteCollection('indexes'); } @@ -1572,7 +1757,7 @@ public function testCreateCollectionWithSchema(): void ]), ]; - $collection = $this->getDatabase()->createCollection('withSchema', $attributes, $indexes); + $collection = static::getDatabase()->createCollection('withSchema', $attributes, $indexes); $this->assertEquals(false, $collection->isEmpty()); $this->assertEquals('withSchema', $collection->getId()); @@ -1595,10 +1780,10 @@ public function testCreateCollectionWithSchema(): void $this->assertEquals('index3', $collection->getAttribute('indexes')[2]['$id']); $this->assertEquals(Database::INDEX_KEY, $collection->getAttribute('indexes')[2]['type']); - $this->getDatabase()->deleteCollection('withSchema'); + static::getDatabase()->deleteCollection('withSchema'); // Test collection with dash (+attribute +index) - $collection2 = $this->getDatabase()->createCollection('with-dash', [ + $collection2 = static::getDatabase()->createCollection('with-dash', [ new Document([ '$id' => ID::custom('attribute-one'), 'type' => Database::VAR_STRING, @@ -1628,7 +1813,7 @@ public function testCreateCollectionWithSchema(): void $this->assertCount(1, $collection2->getAttribute('indexes')); $this->assertEquals('index-one', $collection2->getAttribute('indexes')[0]['$id']); $this->assertEquals(Database::INDEX_KEY, $collection2->getAttribute('indexes')[0]['type']); - $this->getDatabase()->deleteCollection('with-dash'); + static::getDatabase()->deleteCollection('with-dash'); } public function testCreateCollectionValidator(): void @@ -1727,7 +1912,7 @@ public function testCreateCollectionValidator(): void ]; foreach ($collections as $id) { - $collection = $this->getDatabase()->createCollection($id, $attributes, $indexes); + $collection = static::getDatabase()->createCollection($id, $attributes, $indexes); $this->assertEquals(false, $collection->isEmpty()); $this->assertEquals($id, $collection->getId()); @@ -1754,27 +1939,27 @@ public function testCreateCollectionValidator(): void $this->assertEquals('index.4', $collection->getAttribute('indexes')[3]['$id']); $this->assertEquals(Database::INDEX_KEY, $collection->getAttribute('indexes')[3]['type']); - $this->getDatabase()->deleteCollection($id); + static::getDatabase()->deleteCollection($id); } } public function testCreateDocument(): Document { - $this->getDatabase()->createCollection('documents'); - - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'string', Database::VAR_STRING, 128, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'integer_signed', Database::VAR_INTEGER, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'integer_unsigned', Database::VAR_INTEGER, 4, true, signed: false)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'bigint_signed', Database::VAR_INTEGER, 8, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'bigint_unsigned', Database::VAR_INTEGER, 9, true, signed: false)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'float_signed', Database::VAR_FLOAT, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'float_unsigned', Database::VAR_FLOAT, 0, true, signed: false)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'boolean', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'colors', Database::VAR_STRING, 32, true, null, true, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'empty', Database::VAR_STRING, 32, false, null, true, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents', 'with-dash', Database::VAR_STRING, 128, false, null)); - - $document = $this->getDatabase()->createDocument('documents', new Document([ + static::getDatabase()->createCollection('documents'); + + $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'string', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'integer_signed', Database::VAR_INTEGER, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'integer_unsigned', Database::VAR_INTEGER, 4, true, signed: false)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'bigint_signed', Database::VAR_INTEGER, 8, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'bigint_unsigned', Database::VAR_INTEGER, 9, true, signed: false)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'float_signed', Database::VAR_FLOAT, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'float_unsigned', Database::VAR_FLOAT, 0, true, signed: false)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'boolean', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'colors', Database::VAR_STRING, 32, true, null, true, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'empty', Database::VAR_STRING, 32, false, null, true, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents', 'with-dash', Database::VAR_STRING, 128, false, null)); + + $document = static::getDatabase()->createDocument('documents', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::read(Role::user(ID::custom('1'))), @@ -1825,7 +2010,7 @@ public function testCreateDocument(): Document $this->assertEquals('Works', $document->getAttribute('with-dash')); // Test create document with manual internal id - $manualIdDocument = $this->getDatabase()->createDocument('documents', new Document([ + $manualIdDocument = static::getDatabase()->createDocument('documents', new Document([ '$id' => '56000', '$internalId' => '56000', '$permissions' => [ @@ -1878,7 +2063,7 @@ public function testCreateDocument(): Document $this->assertEquals([], $manualIdDocument->getAttribute('empty')); $this->assertEquals('Works', $manualIdDocument->getAttribute('with-dash')); - $manualIdDocument = $this->getDatabase()->getDocument('documents', '56000'); + $manualIdDocument = static::getDatabase()->getDocument('documents', '56000'); $this->assertEquals('56000', $manualIdDocument->getInternalId()); $this->assertNotEmpty(true, $manualIdDocument->getId()); @@ -1952,11 +2137,11 @@ public function testCreateDocuments(): array $count = 3; $collection = 'testCreateDocuments'; - $this->getDatabase()->createCollection($collection); + static::getDatabase()->createCollection($collection); - $this->assertEquals(true, $this->getDatabase()->createAttribute($collection, 'string', Database::VAR_STRING, 128, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute($collection, 'integer', Database::VAR_INTEGER, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute($collection, 'bigint', Database::VAR_INTEGER, 8, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute($collection, 'string', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute($collection, 'integer', Database::VAR_INTEGER, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute($collection, 'bigint', Database::VAR_INTEGER, 8, true)); // Create an array of documents with random attributes. Don't use the createDocument function $documents = []; @@ -1975,7 +2160,7 @@ public function testCreateDocuments(): array ]); } - $documents = $this->getDatabase()->createDocuments($collection, $documents, 3); + $documents = static::getDatabase()->createDocuments($collection, $documents, 3); $this->assertEquals($count, count($documents)); @@ -1994,15 +2179,15 @@ public function testCreateDocuments(): array public function testRespectNulls(): Document { - $this->getDatabase()->createCollection('documents_nulls'); + static::getDatabase()->createCollection('documents_nulls'); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents_nulls', 'string', Database::VAR_STRING, 128, false)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents_nulls', 'integer', Database::VAR_INTEGER, 0, false)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents_nulls', 'bigint', Database::VAR_INTEGER, 8, false)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents_nulls', 'float', Database::VAR_FLOAT, 0, false)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('documents_nulls', 'boolean', Database::VAR_BOOLEAN, 0, false)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents_nulls', 'string', Database::VAR_STRING, 128, false)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents_nulls', 'integer', Database::VAR_INTEGER, 0, false)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents_nulls', 'bigint', Database::VAR_INTEGER, 8, false)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents_nulls', 'float', Database::VAR_FLOAT, 0, false)); + $this->assertEquals(true, static::getDatabase()->createAttribute('documents_nulls', 'boolean', Database::VAR_BOOLEAN, 0, false)); - $document = $this->getDatabase()->createDocument('documents_nulls', new Document([ + $document = static::getDatabase()->createDocument('documents_nulls', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::read(Role::user('1')), @@ -2030,16 +2215,16 @@ public function testRespectNulls(): Document public function testCreateDocumentDefaults(): void { - $this->getDatabase()->createCollection('defaults'); + static::getDatabase()->createCollection('defaults'); - $this->assertEquals(true, $this->getDatabase()->createAttribute('defaults', 'string', Database::VAR_STRING, 128, false, 'default')); - $this->assertEquals(true, $this->getDatabase()->createAttribute('defaults', 'integer', Database::VAR_INTEGER, 0, false, 1)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('defaults', 'float', Database::VAR_FLOAT, 0, false, 1.5)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('defaults', 'boolean', Database::VAR_BOOLEAN, 0, false, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('defaults', 'colors', Database::VAR_STRING, 32, false, ['red', 'green', 'blue'], true, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('defaults', 'datetime', Database::VAR_DATETIME, 0, false, '2000-06-12T14:12:55.000+00:00', true, false, null, [], ['datetime'])); + $this->assertEquals(true, static::getDatabase()->createAttribute('defaults', 'string', Database::VAR_STRING, 128, false, 'default')); + $this->assertEquals(true, static::getDatabase()->createAttribute('defaults', 'integer', Database::VAR_INTEGER, 0, false, 1)); + $this->assertEquals(true, static::getDatabase()->createAttribute('defaults', 'float', Database::VAR_FLOAT, 0, false, 1.5)); + $this->assertEquals(true, static::getDatabase()->createAttribute('defaults', 'boolean', Database::VAR_BOOLEAN, 0, false, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('defaults', 'colors', Database::VAR_STRING, 32, false, ['red', 'green', 'blue'], true, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('defaults', 'datetime', Database::VAR_DATETIME, 0, false, '2000-06-12T14:12:55.000+00:00', true, false, null, [], ['datetime'])); - $document = $this->getDatabase()->createDocument('defaults', new Document([ + $document = static::getDatabase()->createDocument('defaults', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::create(Role::any()), @@ -2048,7 +2233,7 @@ public function testCreateDocumentDefaults(): void ], ])); - $document2 = $this->getDatabase()->getDocument('defaults', $document->getId()); + $document2 = static::getDatabase()->getDocument('defaults', $document->getId()); $this->assertCount(4, $document2->getPermissions()); $this->assertEquals('read("any")', $document2->getPermissions()[0]); $this->assertEquals('create("any")', $document2->getPermissions()[1]); @@ -2070,7 +2255,7 @@ public function testCreateDocumentDefaults(): void $this->assertEquals('2000-06-12T14:12:55.000+00:00', $document->getAttribute('datetime')); // cleanup collection - $this->getDatabase()->deleteCollection('defaults'); + static::getDatabase()->deleteCollection('defaults'); } /** @@ -2079,14 +2264,14 @@ public function testCreateDocumentDefaults(): void public function testIncreaseDecrease(): Document { $collection = 'increase_decrease'; - $this->getDatabase()->createCollection($collection); + static::getDatabase()->createCollection($collection); - $this->assertEquals(true, $this->getDatabase()->createAttribute($collection, 'increase', Database::VAR_INTEGER, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute($collection, 'decrease', Database::VAR_INTEGER, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute($collection, 'increase_text', Database::VAR_STRING, 255, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute($collection, 'increase_float', Database::VAR_FLOAT, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute($collection, 'increase', Database::VAR_INTEGER, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute($collection, 'decrease', Database::VAR_INTEGER, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute($collection, 'increase_text', Database::VAR_STRING, 255, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute($collection, 'increase_float', Database::VAR_FLOAT, 0, true)); - $document = $this->getDatabase()->createDocument($collection, new Document([ + $document = static::getDatabase()->createDocument($collection, new Document([ 'increase' => 100, 'decrease' => 100, 'increase_float' => 100, @@ -2103,20 +2288,20 @@ public function testIncreaseDecrease(): Document $this->assertEquals(true, static::getDatabase()->increaseDocumentAttribute($collection, $document->getId(), 'increase', 1, 101)); - $document = $this->getDatabase()->getDocument($collection, $document->getId()); + $document = static::getDatabase()->getDocument($collection, $document->getId()); $this->assertEquals(101, $document->getAttribute('increase')); $this->assertNotEquals($updatedAt, $document->getUpdatedAt()); - $this->assertEquals(true, $this->getDatabase()->decreaseDocumentAttribute($collection, $document->getId(), 'decrease', 1, 98)); - $document = $this->getDatabase()->getDocument($collection, $document->getId()); + $this->assertEquals(true, static::getDatabase()->decreaseDocumentAttribute($collection, $document->getId(), 'decrease', 1, 98)); + $document = static::getDatabase()->getDocument($collection, $document->getId()); $this->assertEquals(99, $document->getAttribute('decrease')); - $this->assertEquals(true, $this->getDatabase()->increaseDocumentAttribute($collection, $document->getId(), 'increase_float', 5.5, 110)); - $document = $this->getDatabase()->getDocument($collection, $document->getId()); + $this->assertEquals(true, static::getDatabase()->increaseDocumentAttribute($collection, $document->getId(), 'increase_float', 5.5, 110)); + $document = static::getDatabase()->getDocument($collection, $document->getId()); $this->assertEquals(105.5, $document->getAttribute('increase_float')); - $this->assertEquals(true, $this->getDatabase()->decreaseDocumentAttribute($collection, $document->getId(), 'increase_float', 1.1, 100)); - $document = $this->getDatabase()->getDocument($collection, $document->getId()); + $this->assertEquals(true, static::getDatabase()->decreaseDocumentAttribute($collection, $document->getId(), 'increase_float', 1.1, 100)); + $document = static::getDatabase()->getDocument($collection, $document->getId()); $this->assertEquals(104.4, $document->getAttribute('increase_float')); return $document; @@ -2128,7 +2313,7 @@ public function testIncreaseDecrease(): Document public function testIncreaseLimitMax(Document $document): void { $this->expectException(Exception::class); - $this->assertEquals(true, $this->getDatabase()->increaseDocumentAttribute('increase_decrease', $document->getId(), 'increase', 10.5, 102.4)); + $this->assertEquals(true, static::getDatabase()->increaseDocumentAttribute('increase_decrease', $document->getId(), 'increase', 10.5, 102.4)); } /** @@ -2137,7 +2322,7 @@ public function testIncreaseLimitMax(Document $document): void public function testDecreaseLimitMin(Document $document): void { $this->expectException(Exception::class); - $this->assertEquals(false, $this->getDatabase()->decreaseDocumentAttribute('increase_decrease', $document->getId(), 'decrease', 10, 99)); + $this->assertEquals(false, static::getDatabase()->decreaseDocumentAttribute('increase_decrease', $document->getId(), 'decrease', 10, 99)); } /** @@ -2146,7 +2331,7 @@ public function testDecreaseLimitMin(Document $document): void public function testIncreaseTextAttribute(Document $document): void { $this->expectException(Exception::class); - $this->assertEquals(false, $this->getDatabase()->increaseDocumentAttribute('increase_decrease', $document->getId(), 'increase_text')); + $this->assertEquals(false, static::getDatabase()->increaseDocumentAttribute('increase_decrease', $document->getId(), 'increase_text')); } /** @@ -2154,7 +2339,7 @@ public function testIncreaseTextAttribute(Document $document): void */ public function testGetDocument(Document $document): Document { - $document = $this->getDatabase()->getDocument('documents', $document->getId()); + $document = static::getDatabase()->getDocument('documents', $document->getId()); $this->assertNotEmpty(true, $document->getId()); $this->assertIsString($document->getAttribute('string')); @@ -2181,7 +2366,7 @@ public function testGetDocumentSelect(Document $document): Document { $documentId = $document->getId(); - $document = $this->getDatabase()->getDocument('documents', $documentId, [ + $document = static::getDatabase()->getDocument('documents', $documentId, [ Query::select(['string', 'integer_signed']), ]); @@ -2202,7 +2387,7 @@ public function testGetDocumentSelect(Document $document): Document $this->assertArrayNotHasKey('$permissions', $document); $this->assertArrayNotHasKey('$collection', $document); - $document = $this->getDatabase()->getDocument('documents', $documentId, [ + $document = static::getDatabase()->getDocument('documents', $documentId, [ Query::select(['string', 'integer_signed', '$id']), ]); @@ -2213,7 +2398,7 @@ public function testGetDocumentSelect(Document $document): Document $this->assertArrayNotHasKey('$permissions', $document); $this->assertArrayNotHasKey('$collection', $document); - $document = $this->getDatabase()->getDocument('documents', $documentId, [ + $document = static::getDatabase()->getDocument('documents', $documentId, [ Query::select(['string', 'integer_signed', '$permissions']), ]); @@ -2224,7 +2409,7 @@ public function testGetDocumentSelect(Document $document): Document $this->assertArrayHasKey('$permissions', $document); $this->assertArrayNotHasKey('$collection', $document); - $document = $this->getDatabase()->getDocument('documents', $documentId, [ + $document = static::getDatabase()->getDocument('documents', $documentId, [ Query::select(['string', 'integer_signed', '$internalId']), ]); @@ -2235,7 +2420,7 @@ public function testGetDocumentSelect(Document $document): Document $this->assertArrayNotHasKey('$permissions', $document); $this->assertArrayNotHasKey('$collection', $document); - $document = $this->getDatabase()->getDocument('documents', $documentId, [ + $document = static::getDatabase()->getDocument('documents', $documentId, [ Query::select(['string', 'integer_signed', '$collection']), ]); @@ -2246,7 +2431,7 @@ public function testGetDocumentSelect(Document $document): Document $this->assertArrayNotHasKey('$permissions', $document); $this->assertArrayHasKey('$collection', $document); - $document = $this->getDatabase()->getDocument('documents', $documentId, [ + $document = static::getDatabase()->getDocument('documents', $documentId, [ Query::select(['string', 'integer_signed', '$createdAt']), ]); @@ -2257,7 +2442,7 @@ public function testGetDocumentSelect(Document $document): Document $this->assertArrayNotHasKey('$permissions', $document); $this->assertArrayNotHasKey('$collection', $document); - $document = $this->getDatabase()->getDocument('documents', $documentId, [ + $document = static::getDatabase()->getDocument('documents', $documentId, [ Query::select(['string', 'integer_signed', '$updatedAt']), ]); @@ -2284,7 +2469,7 @@ public function testFulltextIndexWithInteger(): void $this->expectExceptionMessage('Attribute "integer_signed" cannot be part of a FULLTEXT index, must be of type string'); } - $this->getDatabase()->createIndex('documents', 'fulltext_integer', Database::INDEX_FULLTEXT, ['string','integer_signed']); + static::getDatabase()->createIndex('documents', 'fulltext_integer', Database::INDEX_FULLTEXT, ['string','integer_signed']); } public function testListDocumentSearch(): void @@ -2295,8 +2480,8 @@ public function testListDocumentSearch(): void return; } - $this->getDatabase()->createIndex('documents', 'string', Database::INDEX_FULLTEXT, ['string']); - $this->getDatabase()->createDocument('documents', new Document([ + static::getDatabase()->createIndex('documents', 'string', Database::INDEX_FULLTEXT, ['string']); + static::getDatabase()->createDocument('documents', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::create(Role::any()), @@ -2318,13 +2503,33 @@ public function testListDocumentSearch(): void /** * Allow reserved keywords for search */ - $documents = $this->getDatabase()->find('documents', [ + $documents = static::getDatabase()->find('documents', [ Query::search('string', '*test+alias@email-provider.com'), ]); $this->assertEquals(1, count($documents)); } + public function testMaxQueriesValues(): void + { + $max = static::getDatabase()->getMaxQueryValues(); + + static::getDatabase()->setMaxQueryValues(5); + + try { + static::getDatabase()->find( + 'documents', + [Query::equal('$id', [1, 2, 3, 4, 5, 6])] + ); + $this->fail('Failed to throw exception'); + } catch (Throwable $e) { + $this->assertTrue($e instanceof QueryException); + $this->assertEquals('Invalid query: Query on attribute has greater than 5 values: $id', $e->getMessage()); + } + + static::getDatabase()->setMaxQueryValues($max); + } + public function testEmptyTenant(): void { if (static::getDatabase()->getAdapter()->getSharedTables()) { @@ -2358,17 +2563,17 @@ public function testEmptySearch(): void return; } - $documents = $this->getDatabase()->find('documents', [ + $documents = static::getDatabase()->find('documents', [ Query::search('string', ''), ]); $this->assertEquals(0, count($documents)); - $documents = $this->getDatabase()->find('documents', [ + $documents = static::getDatabase()->find('documents', [ Query::search('string', '*'), ]); $this->assertEquals(0, count($documents)); - $documents = $this->getDatabase()->find('documents', [ + $documents = static::getDatabase()->find('documents', [ Query::search('string', '<>'), ]); $this->assertEquals(0, count($documents)); @@ -2534,9 +2739,9 @@ public function testDeleteDocument(Document $document): void */ public function testArrayAttribute(): void { - self::$authorization->addRole(Role::any()->toString()); + Authorization::setRole(Role::any()->toString()); - $database = $this->getDatabase(); + $database = static::getDatabase(); $collection = 'json'; $permissions = [Permission::read(Role::any())]; @@ -2562,6 +2767,15 @@ public function testArrayAttribute(): void array: true )); + $this->assertEquals(true, $database->createAttribute( + $collection, + 'cards', + Database::VAR_STRING, + size: 5000, + required: false, + array: true + )); + $this->assertEquals(true, $database->createAttribute( $collection, 'numbers', @@ -2685,6 +2899,32 @@ public function testArrayAttribute(): void $this->assertEquals('Antony', $document->getAttribute('names')[1]); $this->assertEquals(100, $document->getAttribute('numbers')[1]); + /** + * functional index dependency cannot be dropped or rename + */ + $database->createIndex($collection, 'idx_cards', Database::INDEX_KEY, ['cards'], [100]); + + if ($this->getDatabase()->getAdapter()->getSupportForCastIndexArray()) { + try { + $database->deleteAttribute($collection, 'cards'); + $this->fail('Failed to throw exception'); + } catch (Throwable $e) { + $this->assertInstanceOf(DependencyException::class, $e); + $this->assertEquals('Attribute cannot be deleted because it is used in an index', $e->getMessage()); + } + + try { + $database->renameAttribute($collection, 'cards', 'cards_new'); + $this->fail('Failed to throw exception'); + } catch (Throwable $e) { + $this->assertInstanceOf(DependencyException::class, $e); + $this->assertEquals('Attribute cannot be deleted because it is used in an index', $e->getMessage()); + } + } else { + $this->assertTrue($database->renameAttribute($collection, 'cards', 'cards_new')); + $this->assertTrue($database->deleteAttribute($collection, 'cards_new')); + } + try { $database->createIndex($collection, 'indx', Database::INDEX_FULLTEXT, ['names']); $this->fail('Failed to throw exception'); @@ -2721,7 +2961,7 @@ public function testArrayAttribute(): void $database->createIndex($collection, 'indx_numbers', Database::INDEX_KEY, ['tv_show', 'numbers'], [], []); // [700, 255] $this->fail('Failed to throw exception'); } catch (Throwable $e) { - $this->assertEquals('Index length is longer than the maximum: 768', $e->getMessage()); + $this->assertEquals('Index length is longer than the maximum: ' . $database->getAdapter()->getMaxIndexLength(), $e->getMessage()); } } @@ -2795,23 +3035,23 @@ public function testArrayAttribute(): void */ public function testFind(): array { - self::$authorization->addRole(Role::any()->toString()); + Authorization::setRole(Role::any()->toString()); - $this->getDatabase()->createCollection('movies', permissions: [ + static::getDatabase()->createCollection('movies', permissions: [ Permission::create(Role::any()), Permission::update(Role::users()) ]); - $this->assertEquals(true, $this->getDatabase()->createAttribute('movies', 'name', Database::VAR_STRING, 128, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('movies', 'director', Database::VAR_STRING, 128, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('movies', 'year', Database::VAR_INTEGER, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('movies', 'price', Database::VAR_FLOAT, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('movies', 'active', Database::VAR_BOOLEAN, 0, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('movies', 'genres', Database::VAR_STRING, 32, true, null, true, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('movies', 'with-dash', Database::VAR_STRING, 128, true)); - $this->assertEquals(true, $this->getDatabase()->createAttribute('movies', 'nullable', Database::VAR_STRING, 128, false)); + $this->assertEquals(true, static::getDatabase()->createAttribute('movies', 'name', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('movies', 'director', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('movies', 'year', Database::VAR_INTEGER, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('movies', 'price', Database::VAR_FLOAT, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('movies', 'active', Database::VAR_BOOLEAN, 0, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('movies', 'genres', Database::VAR_STRING, 32, true, null, true, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('movies', 'with-dash', Database::VAR_STRING, 128, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('movies', 'nullable', Database::VAR_STRING, 128, false)); - $document = $this->getDatabase()->createDocument('movies', new Document([ + $document = static::getDatabase()->createDocument('movies', new Document([ '$id' => ID::custom('frozen'), '$permissions' => [ Permission::read(Role::any()), @@ -2836,7 +3076,7 @@ public function testFind(): array 'with-dash' => 'Works' ])); - $this->getDatabase()->createDocument('movies', new Document([ + static::getDatabase()->createDocument('movies', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::read(Role::user('1')), @@ -2860,7 +3100,7 @@ public function testFind(): array 'with-dash' => 'Works' ])); - $this->getDatabase()->createDocument('movies', new Document([ + static::getDatabase()->createDocument('movies', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::read(Role::user('1')), @@ -2884,7 +3124,7 @@ public function testFind(): array 'with-dash' => 'Works2' ])); - $this->getDatabase()->createDocument('movies', new Document([ + static::getDatabase()->createDocument('movies', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::read(Role::user('1')), @@ -2908,7 +3148,7 @@ public function testFind(): array 'with-dash' => 'Works2' ])); - $this->getDatabase()->createDocument('movies', new Document([ + static::getDatabase()->createDocument('movies', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::read(Role::user('1')), @@ -2932,7 +3172,7 @@ public function testFind(): array 'with-dash' => 'Works3' ])); - $this->getDatabase()->createDocument('movies', new Document([ + static::getDatabase()->createDocument('movies', new Document([ '$permissions' => [ Permission::read(Role::user('x')), Permission::create(Role::any()), @@ -2962,7 +3202,7 @@ public function testFind(): array public function testFindBasicChecks(): void { - $documents = $this->getDatabase()->find('movies'); + $documents = static::getDatabase()->find('movies'); $movieDocuments = $documents; $this->assertEquals(5, count($documents)); @@ -2995,13 +3235,13 @@ public function testFindBasicChecks(): void /** * Check $id: Notice, this orders ID names alphabetically, not by internal numeric ID */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc('$id'), ]); $this->assertEquals($lastDocumentId, $documents[0]->getId()); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderAsc('$id'), @@ -3011,13 +3251,13 @@ public function testFindBasicChecks(): void /** * Check internal numeric ID sorting */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc(''), ]); $this->assertEquals($movieDocuments[\count($movieDocuments) - 1]->getId(), $documents[0]->getId()); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderAsc(''), @@ -3030,8 +3270,8 @@ public function testFindCheckPermissions(): void /** * Check Permissions */ - self::$authorization->addRole('user:x'); - $documents = $this->getDatabase()->find('movies'); + Authorization::setRole('user:x'); + $documents = static::getDatabase()->find('movies'); $this->assertEquals(6, count($documents)); } @@ -3041,13 +3281,13 @@ public function testFindCheckInteger(): void /** * Query with dash attribute */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::equal('with-dash', ['Works']), ]); $this->assertEquals(2, count($documents)); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::equal('with-dash', ['Works2', 'Works3']), ]); @@ -3056,7 +3296,7 @@ public function testFindCheckInteger(): void /** * Check an Integer condition */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::equal('year', [2019]), ]); @@ -3070,7 +3310,7 @@ public function testFindBoolean(): void /** * Boolean condition */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::equal('active', [true]), ]); @@ -3082,7 +3322,7 @@ public function testFindStringQueryEqual(): void /** * String condition */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::equal('director', ['TBD']), ]); @@ -3100,7 +3340,7 @@ public function testFindNotEqual(): void /** * Not Equal query */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::notEqual('director', 'TBD'), ]); @@ -3122,22 +3362,22 @@ public function testFindNotEqual(): void public function testFindBetween(): void { - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::between('price', 25.94, 25.99), ]); $this->assertEquals(2, count($documents)); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::between('price', 30, 35), ]); $this->assertEquals(0, count($documents)); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::between('$createdAt', '1975-12-06', '2050-12-06'), ]); $this->assertEquals(6, count($documents)); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::between('$updatedAt', '1975-12-06T07:08:49.733+02:00', '2050-02-05T10:15:21.825+00:00'), ]); $this->assertEquals(6, count($documents)); @@ -3148,7 +3388,7 @@ public function testFindFloat(): void /** * Float condition */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::lessThan('price', 26.00), Query::greaterThan('price', 25.98), ]); @@ -3163,7 +3403,7 @@ public function testFindContains(): void return; } - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::contains('genres', ['comics']) ]); @@ -3172,20 +3412,20 @@ public function testFindContains(): void /** * Array contains OR condition */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::contains('genres', ['comics', 'kids']), ]); $this->assertEquals(4, count($documents)); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::contains('genres', ['non-existent']), ]); $this->assertEquals(0, count($documents)); try { - $this->getDatabase()->find('movies', [ + static::getDatabase()->find('movies', [ Query::contains('price', [10.5]), ]); $this->fail('Failed to throw exception'); @@ -3201,10 +3441,10 @@ public function testFindFulltext(): void * Fulltext search */ if ($this->getDatabase()->getAdapter()->getSupportForFulltextIndex()) { - $success = $this->getDatabase()->createIndex('movies', 'name', Database::INDEX_FULLTEXT, ['name']); + $success = static::getDatabase()->createIndex('movies', 'name', Database::INDEX_FULLTEXT, ['name']); $this->assertEquals(true, $success); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::search('name', 'captain'), ]); @@ -3218,7 +3458,7 @@ public function testFindFulltext(): void // TODO: I think this needs a changes? how do we distinguish between regular full text and wildcard? if ($this->getDatabase()->getAdapter()->getSupportForFulltextWildCardIndex()) { - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::search('name', 'cap'), ]); @@ -3231,62 +3471,62 @@ public function testFindFulltext(): void public function testFindFulltextSpecialChars(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForFulltextIndex()) { + if (!static::getDatabase()->getAdapter()->getSupportForFulltextIndex()) { $this->expectNotToPerformAssertions(); return; } $collection = 'full_text'; - $this->getDatabase()->createCollection($collection, permissions: [ + static::getDatabase()->createCollection($collection, permissions: [ Permission::create(Role::any()), Permission::update(Role::users()) ]); - $this->assertTrue($this->getDatabase()->createAttribute($collection, 'ft', Database::VAR_STRING, 128, true)); - $this->assertTrue($this->getDatabase()->createIndex($collection, 'ft-index', Database::INDEX_FULLTEXT, ['ft'])); + $this->assertTrue(static::getDatabase()->createAttribute($collection, 'ft', Database::VAR_STRING, 128, true)); + $this->assertTrue(static::getDatabase()->createIndex($collection, 'ft-index', Database::INDEX_FULLTEXT, ['ft'])); - $this->getDatabase()->createDocument($collection, new Document([ + static::getDatabase()->createDocument($collection, new Document([ '$permissions' => [Permission::read(Role::any())], 'ft' => 'Alf: chapter_4@nasa.com' ])); - $documents = $this->getDatabase()->find($collection, [ + $documents = static::getDatabase()->find($collection, [ Query::search('ft', 'chapter_4'), ]); $this->assertEquals(1, count($documents)); - $this->getDatabase()->createDocument($collection, new Document([ + static::getDatabase()->createDocument($collection, new Document([ '$permissions' => [Permission::read(Role::any())], 'ft' => 'al@ba.io +-*)(<>~' ])); - $documents = $this->getDatabase()->find($collection, [ + $documents = static::getDatabase()->find($collection, [ Query::search('ft', 'al@ba.io'), // === al ba io* ]); - if ($this->getDatabase()->getAdapter()->getSupportForFulltextWildcardIndex()) { + if (static::getDatabase()->getAdapter()->getSupportForFulltextWildcardIndex()) { $this->assertEquals(0, count($documents)); } else { $this->assertEquals(1, count($documents)); } - $this->getDatabase()->createDocument($collection, new Document([ + static::getDatabase()->createDocument($collection, new Document([ '$permissions' => [Permission::read(Role::any())], 'ft' => 'donald duck' ])); - $this->getDatabase()->createDocument($collection, new Document([ + static::getDatabase()->createDocument($collection, new Document([ '$permissions' => [Permission::read(Role::any())], 'ft' => 'donald trump' ])); - $documents = $this->getDatabase()->find($collection, [ + $documents = static::getDatabase()->find($collection, [ Query::search('ft', 'donald trump'), Query::orderAsc('ft'), ]); $this->assertEquals(2, count($documents)); - $documents = $this->getDatabase()->find($collection, [ + $documents = static::getDatabase()->find($collection, [ Query::search('ft', '"donald trump"'), // Exact match ]); @@ -3298,7 +3538,7 @@ public function testFindMultipleConditions(): void /** * Multiple conditions */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::equal('director', ['TBD']), Query::equal('year', [2026]), ]); @@ -3308,7 +3548,7 @@ public function testFindMultipleConditions(): void /** * Multiple conditions and OR values */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::equal('name', ['Frozen II', 'Captain Marvel']), ]); @@ -3322,7 +3562,7 @@ public function testFindByID(): void /** * $id condition */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::equal('$id', ['frozen']), ]); @@ -3342,7 +3582,7 @@ public function testFindByInternalID(array $data): void /** * Test that internal ID queries are handled correctly */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::equal('$internalId', [$data['$internalId']]), ]); @@ -3355,7 +3595,7 @@ public function testFindByInternalID(array $data): void */ public function testSelectInternalID(): void { - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::select(['$internalId', '$id']), Query::orderAsc(''), Query::limit(1), @@ -3366,7 +3606,7 @@ public function testSelectInternalID(): void $this->assertArrayHasKey('$internalId', $document); $this->assertCount(2, $document); - $document = $this->getDatabase()->getDocument('movies', $document->getId(), [ + $document = static::getDatabase()->getDocument('movies', $document->getId(), [ Query::select(['$internalId']), ]); @@ -3379,7 +3619,7 @@ public function testFindOrderBy(): void /** * ORDER BY */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc('price'), @@ -3400,11 +3640,11 @@ public function testFindOrderByNatural(): void /** * ORDER BY natural */ - $base = array_reverse($this->getDatabase()->find('movies', [ + $base = array_reverse(static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), ])); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc(''), @@ -3424,7 +3664,7 @@ public function testFindOrderByMultipleAttributes(): void /** * ORDER BY - Multiple attributes */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc('price'), @@ -3445,12 +3685,12 @@ public function testFindOrderByCursorAfter(): void /** * ORDER BY - After */ - $movies = $this->getDatabase()->find('movies', [ + $movies = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), ]); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorAfter($movies[1]) @@ -3459,7 +3699,7 @@ public function testFindOrderByCursorAfter(): void $this->assertEquals($movies[2]['name'], $documents[0]['name']); $this->assertEquals($movies[3]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorAfter($movies[3]) @@ -3468,7 +3708,7 @@ public function testFindOrderByCursorAfter(): void $this->assertEquals($movies[4]['name'], $documents[0]['name']); $this->assertEquals($movies[5]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorAfter($movies[4]) @@ -3476,7 +3716,7 @@ public function testFindOrderByCursorAfter(): void $this->assertEquals(1, count($documents)); $this->assertEquals($movies[5]['name'], $documents[0]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorAfter($movies[5]) @@ -3490,12 +3730,12 @@ public function testFindOrderByCursorBefore(): void /** * ORDER BY - Before */ - $movies = $this->getDatabase()->find('movies', [ + $movies = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), ]); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorBefore($movies[5]) @@ -3504,7 +3744,7 @@ public function testFindOrderByCursorBefore(): void $this->assertEquals($movies[3]['name'], $documents[0]['name']); $this->assertEquals($movies[4]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorBefore($movies[3]) @@ -3513,7 +3753,7 @@ public function testFindOrderByCursorBefore(): void $this->assertEquals($movies[1]['name'], $documents[0]['name']); $this->assertEquals($movies[2]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorBefore($movies[2]) @@ -3522,7 +3762,7 @@ public function testFindOrderByCursorBefore(): void $this->assertEquals($movies[0]['name'], $documents[0]['name']); $this->assertEquals($movies[1]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorBefore($movies[1]) @@ -3530,7 +3770,7 @@ public function testFindOrderByCursorBefore(): void $this->assertEquals(1, count($documents)); $this->assertEquals($movies[0]['name'], $documents[0]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorBefore($movies[0]) @@ -3543,12 +3783,12 @@ public function testFindOrderByAfterNaturalOrder(): void /** * ORDER BY - After by natural order */ - $movies = array_reverse($this->getDatabase()->find('movies', [ + $movies = array_reverse(static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), ])); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc(''), @@ -3558,7 +3798,7 @@ public function testFindOrderByAfterNaturalOrder(): void $this->assertEquals($movies[2]['name'], $documents[0]['name']); $this->assertEquals($movies[3]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc(''), @@ -3568,7 +3808,7 @@ public function testFindOrderByAfterNaturalOrder(): void $this->assertEquals($movies[4]['name'], $documents[0]['name']); $this->assertEquals($movies[5]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc(''), @@ -3577,7 +3817,7 @@ public function testFindOrderByAfterNaturalOrder(): void $this->assertEquals(1, count($documents)); $this->assertEquals($movies[5]['name'], $documents[0]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc(''), @@ -3591,13 +3831,13 @@ public function testFindOrderByBeforeNaturalOrder(): void /** * ORDER BY - Before by natural order */ - $movies = $this->getDatabase()->find('movies', [ + $movies = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc(''), ]); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc(''), @@ -3607,7 +3847,7 @@ public function testFindOrderByBeforeNaturalOrder(): void $this->assertEquals($movies[3]['name'], $documents[0]['name']); $this->assertEquals($movies[4]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc(''), @@ -3617,7 +3857,7 @@ public function testFindOrderByBeforeNaturalOrder(): void $this->assertEquals($movies[1]['name'], $documents[0]['name']); $this->assertEquals($movies[2]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc(''), @@ -3627,7 +3867,7 @@ public function testFindOrderByBeforeNaturalOrder(): void $this->assertEquals($movies[0]['name'], $documents[0]['name']); $this->assertEquals($movies[1]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc(''), @@ -3636,7 +3876,7 @@ public function testFindOrderByBeforeNaturalOrder(): void $this->assertEquals(1, count($documents)); $this->assertEquals($movies[0]['name'], $documents[0]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc(''), @@ -3650,13 +3890,13 @@ public function testFindOrderBySingleAttributeAfter(): void /** * ORDER BY - Single Attribute After */ - $movies = $this->getDatabase()->find('movies', [ + $movies = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc('year') ]); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('year'), @@ -3667,7 +3907,7 @@ public function testFindOrderBySingleAttributeAfter(): void $this->assertEquals($movies[2]['name'], $documents[0]['name']); $this->assertEquals($movies[3]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('year'), @@ -3677,7 +3917,7 @@ public function testFindOrderBySingleAttributeAfter(): void $this->assertEquals($movies[4]['name'], $documents[0]['name']); $this->assertEquals($movies[5]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('year'), @@ -3686,7 +3926,7 @@ public function testFindOrderBySingleAttributeAfter(): void $this->assertEquals(1, count($documents)); $this->assertEquals($movies[5]['name'], $documents[0]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('year'), @@ -3700,13 +3940,13 @@ public function testFindOrderBySingleAttributeBefore(): void /** * ORDER BY - Single Attribute Before */ - $movies = $this->getDatabase()->find('movies', [ + $movies = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc('year') ]); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('year'), @@ -3716,7 +3956,7 @@ public function testFindOrderBySingleAttributeBefore(): void $this->assertEquals($movies[3]['name'], $documents[0]['name']); $this->assertEquals($movies[4]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('year'), @@ -3726,7 +3966,7 @@ public function testFindOrderBySingleAttributeBefore(): void $this->assertEquals($movies[1]['name'], $documents[0]['name']); $this->assertEquals($movies[2]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('year'), @@ -3736,7 +3976,7 @@ public function testFindOrderBySingleAttributeBefore(): void $this->assertEquals($movies[0]['name'], $documents[0]['name']); $this->assertEquals($movies[1]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('year'), @@ -3745,7 +3985,7 @@ public function testFindOrderBySingleAttributeBefore(): void $this->assertEquals(1, count($documents)); $this->assertEquals($movies[0]['name'], $documents[0]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('year'), @@ -3759,14 +3999,14 @@ public function testFindOrderByMultipleAttributeAfter(): void /** * ORDER BY - Multiple Attribute After */ - $movies = $this->getDatabase()->find('movies', [ + $movies = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc('price'), Query::orderAsc('year') ]); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), @@ -3777,7 +4017,7 @@ public function testFindOrderByMultipleAttributeAfter(): void $this->assertEquals($movies[2]['name'], $documents[0]['name']); $this->assertEquals($movies[3]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), @@ -3788,7 +4028,7 @@ public function testFindOrderByMultipleAttributeAfter(): void $this->assertEquals($movies[4]['name'], $documents[0]['name']); $this->assertEquals($movies[5]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), @@ -3798,7 +4038,7 @@ public function testFindOrderByMultipleAttributeAfter(): void $this->assertEquals(1, count($documents)); $this->assertEquals($movies[5]['name'], $documents[0]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), @@ -3813,14 +4053,14 @@ public function testFindOrderByMultipleAttributeBefore(): void /** * ORDER BY - Multiple Attribute Before */ - $movies = $this->getDatabase()->find('movies', [ + $movies = static::getDatabase()->find('movies', [ Query::limit(25), Query::offset(0), Query::orderDesc('price'), Query::orderAsc('year') ]); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), @@ -3832,7 +4072,7 @@ public function testFindOrderByMultipleAttributeBefore(): void $this->assertEquals($movies[3]['name'], $documents[0]['name']); $this->assertEquals($movies[4]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), @@ -3843,7 +4083,7 @@ public function testFindOrderByMultipleAttributeBefore(): void $this->assertEquals($movies[2]['name'], $documents[0]['name']); $this->assertEquals($movies[3]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), @@ -3854,7 +4094,7 @@ public function testFindOrderByMultipleAttributeBefore(): void $this->assertEquals($movies[0]['name'], $documents[0]['name']); $this->assertEquals($movies[1]['name'], $documents[1]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), @@ -3864,7 +4104,7 @@ public function testFindOrderByMultipleAttributeBefore(): void $this->assertEquals(1, count($documents)); $this->assertEquals($movies[0]['name'], $documents[0]['name']); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), @@ -3879,12 +4119,12 @@ public function testFindOrderByAndCursor(): void /** * ORDER BY + CURSOR */ - $documentsTest = $this->getDatabase()->find('movies', [ + $documentsTest = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('price'), ]); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(1), Query::offset(0), Query::orderDesc('price'), @@ -3899,12 +4139,12 @@ public function testFindOrderByIdAndCursor(): void /** * ORDER BY ID + CURSOR */ - $documentsTest = $this->getDatabase()->find('movies', [ + $documentsTest = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('$id'), ]); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(1), Query::offset(0), Query::orderDesc('$id'), @@ -3919,13 +4159,13 @@ public function testFindOrderByCreateDateAndCursor(): void /** * ORDER BY CREATE DATE + CURSOR */ - $documentsTest = $this->getDatabase()->find('movies', [ + $documentsTest = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('$createdAt'), ]); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(1), Query::offset(0), Query::orderDesc('$createdAt'), @@ -3940,12 +4180,12 @@ public function testFindOrderByUpdateDateAndCursor(): void /** * ORDER BY UPDATE DATE + CURSOR */ - $documentsTest = $this->getDatabase()->find('movies', [ + $documentsTest = static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::orderDesc('$updatedAt'), ]); - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(1), Query::offset(0), Query::orderDesc('$updatedAt'), @@ -3960,7 +4200,7 @@ public function testFindLimit(): void /** * Limit */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(4), Query::offset(0), Query::orderAsc('name') @@ -3978,7 +4218,7 @@ public function testFindLimitAndOffset(): void /** * Limit + Offset */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::limit(4), Query::offset(2), Query::orderAsc('name') @@ -3996,7 +4236,7 @@ public function testFindOrQueries(): void /** * Test that OR queries are handled correctly */ - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::equal('director', ['TBD', 'Joe Johnston']), Query::equal('year', [2025]), ]); @@ -4014,7 +4254,7 @@ public function testFindOrderByAfterException(): void ]); $this->expectException(Exception::class); - $this->getDatabase()->find('movies', [ + static::getDatabase()->find('movies', [ Query::limit(2), Query::offset(0), Query::cursorAfter($document) @@ -4028,9 +4268,9 @@ public function testFindEdgeCases(Document $document): void { $collection = 'edgeCases'; - $this->getDatabase()->createCollection($collection); + static::getDatabase()->createCollection($collection); - $this->assertEquals(true, $this->getDatabase()->createAttribute($collection, 'value', Database::VAR_STRING, 256, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute($collection, 'value', Database::VAR_STRING, 256, true)); $values = [ 'NormalString', @@ -4049,7 +4289,7 @@ public function testFindEdgeCases(Document $document): void ]; foreach ($values as $value) { - $this->getDatabase()->createDocument($collection, new Document([ + static::getDatabase()->createDocument($collection, new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::any()), @@ -4063,7 +4303,7 @@ public function testFindEdgeCases(Document $document): void /** * Check Basic */ - $documents = $this->getDatabase()->find($collection); + $documents = static::getDatabase()->find($collection); $this->assertEquals(count($values), count($documents)); $this->assertNotEmpty($documents[0]->getId()); @@ -4077,7 +4317,7 @@ public function testFindEdgeCases(Document $document): void * Check `equals` query */ foreach ($values as $value) { - $documents = $this->getDatabase()->find($collection, [ + $documents = static::getDatabase()->find($collection, [ Query::limit(25), Query::equal('value', [$value]) ]); @@ -4090,7 +4330,7 @@ public function testFindEdgeCases(Document $document): void public function testOrSingleQuery(): void { try { - $this->getDatabase()->find('movies', [ + static::getDatabase()->find('movies', [ Query::or([ Query::equal('active', [true]) ]) @@ -4109,8 +4349,8 @@ public function testOrMultipleQueries(): void Query::equal('name', ['Frozen II']) ]) ]; - $this->assertCount(4, $this->getDatabase()->find('movies', $queries)); - $this->assertEquals(4, $this->getDatabase()->count('movies', $queries)); + $this->assertCount(4, static::getDatabase()->find('movies', $queries)); + $this->assertEquals(4, static::getDatabase()->count('movies', $queries)); $queries = [ Query::equal('active', [true]), @@ -4121,8 +4361,8 @@ public function testOrMultipleQueries(): void ]) ]; - $this->assertCount(3, $this->getDatabase()->find('movies', $queries)); - $this->assertEquals(3, $this->getDatabase()->count('movies', $queries)); + $this->assertCount(3, static::getDatabase()->find('movies', $queries)); + $this->assertEquals(3, static::getDatabase()->count('movies', $queries)); } public function testOrNested(): void @@ -4139,18 +4379,18 @@ public function testOrNested(): void ]) ]; - $documents = $this->getDatabase()->find('movies', $queries); + $documents = static::getDatabase()->find('movies', $queries); $this->assertCount(1, $documents); $this->assertArrayNotHasKey('name', $documents[0]); - $count = $this->getDatabase()->count('movies', $queries); + $count = static::getDatabase()->count('movies', $queries); $this->assertEquals(1, $count); } public function testAndSingleQuery(): void { try { - $this->getDatabase()->find('movies', [ + static::getDatabase()->find('movies', [ Query::and([ Query::equal('active', [true]) ]) @@ -4169,8 +4409,8 @@ public function testAndMultipleQueries(): void Query::equal('name', ['Frozen II']) ]) ]; - $this->assertCount(1, $this->getDatabase()->find('movies', $queries)); - $this->assertEquals(1, $this->getDatabase()->count('movies', $queries)); + $this->assertCount(1, static::getDatabase()->find('movies', $queries)); + $this->assertEquals(1, static::getDatabase()->count('movies', $queries)); } public function testAndNested(): void @@ -4185,16 +4425,16 @@ public function testAndNested(): void ]) ]; - $documents = $this->getDatabase()->find('movies', $queries); + $documents = static::getDatabase()->find('movies', $queries); $this->assertCount(3, $documents); - $count = $this->getDatabase()->count('movies', $queries); + $count = static::getDatabase()->count('movies', $queries); $this->assertEquals(3, $count); } public function testNestedIDQueries(): void { - self::$authorization->addRole(Role::any()->toString()); + Authorization::setRole(Role::any()->toString()); static::getDatabase()->createCollection('movies_nested_id', permissions: [ Permission::create(Role::any()), @@ -4258,7 +4498,7 @@ public function testNestedIDQueries(): void */ public function testFindOne(): void { - $document = $this->getDatabase()->findOne('movies', [ + $document = static::getDatabase()->findOne('movies', [ Query::offset(2), Query::orderAsc('name') ]); @@ -4266,7 +4506,7 @@ public function testFindOne(): void $this->assertFalse($document->isEmpty()); $this->assertEquals('Frozen', $document->getAttribute('name')); - $document = $this->getDatabase()->findOne('movies', [ + $document = static::getDatabase()->findOne('movies', [ Query::offset(10) ]); $this->assertTrue($document->isEmpty()); @@ -4274,7 +4514,7 @@ public function testFindOne(): void public function testFindNull(): void { - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::isNull('nullable'), ]); @@ -4283,7 +4523,7 @@ public function testFindNull(): void public function testFindNotNull(): void { - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::isNotNull('nullable'), ]); @@ -4292,18 +4532,18 @@ public function testFindNotNull(): void public function testFindStartsWith(): void { - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::startsWith('name', 'Work'), ]); $this->assertEquals(2, count($documents)); if ($this->getDatabase()->getAdapter() instanceof SQL) { - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::startsWith('name', '%ork'), ]); } else { - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::startsWith('name', '.*ork'), ]); } @@ -4313,7 +4553,7 @@ public function testFindStartsWith(): void public function testFindStartsWithWords(): void { - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::startsWith('name', 'Work in Progress'), ]); @@ -4322,7 +4562,7 @@ public function testFindStartsWithWords(): void public function testFindEndsWith(): void { - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::endsWith('name', 'Marvel'), ]); @@ -4331,7 +4571,7 @@ public function testFindEndsWith(): void public function testFindSelect(): void { - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::select(['name', 'year']) ]); @@ -4349,7 +4589,7 @@ public function testFindSelect(): void $this->assertArrayNotHasKey('$permissions', $document); } - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::select(['name', 'year', '$id']) ]); @@ -4367,7 +4607,7 @@ public function testFindSelect(): void $this->assertArrayNotHasKey('$permissions', $document); } - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::select(['name', 'year', '$internalId']) ]); @@ -4385,7 +4625,7 @@ public function testFindSelect(): void $this->assertArrayNotHasKey('$permissions', $document); } - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::select(['name', 'year', '$collection']) ]); @@ -4403,7 +4643,7 @@ public function testFindSelect(): void $this->assertArrayNotHasKey('$permissions', $document); } - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::select(['name', 'year', '$createdAt']) ]); @@ -4421,7 +4661,7 @@ public function testFindSelect(): void $this->assertArrayNotHasKey('$permissions', $document); } - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::select(['name', 'year', '$updatedAt']) ]); @@ -4439,7 +4679,7 @@ public function testFindSelect(): void $this->assertArrayNotHasKey('$permissions', $document); } - $documents = $this->getDatabase()->find('movies', [ + $documents = static::getDatabase()->find('movies', [ Query::select(['name', 'year', '$permissions']) ]); @@ -4463,39 +4703,40 @@ public function testFindSelect(): void */ public function testCount(): void { - $count = $this->getDatabase()->count('movies'); + $count = static::getDatabase()->count('movies'); $this->assertEquals(6, $count); - $count = $this->getDatabase()->count('movies', [Query::equal('year', [2019])]); + $count = static::getDatabase()->count('movies', [Query::equal('year', [2019])]); + $this->assertEquals(2, $count); - $count = $this->getDatabase()->count('movies', [Query::equal('with-dash', ['Works'])]); + $count = static::getDatabase()->count('movies', [Query::equal('with-dash', ['Works'])]); $this->assertEquals(2, $count); - $count = $this->getDatabase()->count('movies', [Query::equal('with-dash', ['Works2', 'Works3'])]); + $count = static::getDatabase()->count('movies', [Query::equal('with-dash', ['Works2', 'Works3'])]); $this->assertEquals(4, $count); - self::$authorization->removeRole('user:x'); - $count = $this->getDatabase()->count('movies'); + Authorization::unsetRole('user:x'); + $count = static::getDatabase()->count('movies'); $this->assertEquals(5, $count); - self::$authorization->disable(); - $count = $this->getDatabase()->count('movies'); + Authorization::disable(); + $count = static::getDatabase()->count('movies'); $this->assertEquals(6, $count); - self::$authorization->reset(); + Authorization::reset(); - self::$authorization->disable(); - $count = $this->getDatabase()->count('movies', [], 3); + Authorization::disable(); + $count = static::getDatabase()->count('movies', [], 3); $this->assertEquals(3, $count); - self::$authorization->reset(); + Authorization::reset(); /** * Test that OR queries are handled correctly */ - self::$authorization->disable(); - $count = $this->getDatabase()->count('movies', [ + Authorization::disable(); + $count = static::getDatabase()->count('movies', [ Query::equal('director', ['TBD', 'Joe Johnston']), Query::equal('year', [2025]), ]); $this->assertEquals(1, $count); - self::$authorization->reset(); + Authorization::reset(); } /** @@ -4503,28 +4744,29 @@ public function testCount(): void */ public function testSum(): void { - self::$authorization->addRole('user:x'); - $sum = $this->getDatabase()->sum('movies', 'year', [Query::equal('year', [2019]),]); + Authorization::setRole('user:x'); + + $sum = static::getDatabase()->sum('movies', 'year', [Query::equal('year', [2019]),]); $this->assertEquals(2019 + 2019, $sum); - $sum = $this->getDatabase()->sum('movies', 'year'); + $sum = static::getDatabase()->sum('movies', 'year'); $this->assertEquals(2013 + 2019 + 2011 + 2019 + 2025 + 2026, $sum); - $sum = $this->getDatabase()->sum('movies', 'price', [Query::equal('year', [2019]),]); + $sum = static::getDatabase()->sum('movies', 'price', [Query::equal('year', [2019]),]); $this->assertEquals(round(39.50 + 25.99, 2), round($sum, 2)); - $sum = $this->getDatabase()->sum('movies', 'price', [Query::equal('year', [2019]),]); + $sum = static::getDatabase()->sum('movies', 'price', [Query::equal('year', [2019]),]); $this->assertEquals(round(39.50 + 25.99, 2), round($sum, 2)); - $sum = $this->getDatabase()->sum('movies', 'year', [Query::equal('year', [2019])], 1); + $sum = static::getDatabase()->sum('movies', 'year', [Query::equal('year', [2019])], 1); $this->assertEquals(2019, $sum); - self::$authorization->removeRole('user:x'); - self::$authorization->removeRole('userx'); - $sum = $this->getDatabase()->sum('movies', 'year', [Query::equal('year', [2019]),]); + Authorization::unsetRole('user:x'); + Authorization::unsetRole('userx'); + $sum = static::getDatabase()->sum('movies', 'year', [Query::equal('year', [2019]),]); $this->assertEquals(2019 + 2019, $sum); - $sum = $this->getDatabase()->sum('movies', 'year'); + $sum = static::getDatabase()->sum('movies', 'year'); $this->assertEquals(2013 + 2019 + 2011 + 2019 + 2025, $sum); - $sum = $this->getDatabase()->sum('movies', 'price', [Query::equal('year', [2019]),]); + $sum = static::getDatabase()->sum('movies', 'price', [Query::equal('year', [2019]),]); $this->assertEquals(round(39.50 + 25.99, 2), round($sum, 2)); - $sum = $this->getDatabase()->sum('movies', 'price', [Query::equal('year', [2019]),]); + $sum = static::getDatabase()->sum('movies', 'price', [Query::equal('year', [2019]),]); $this->assertEquals(round(39.50 + 25.99, 2), round($sum, 2)); } @@ -4719,7 +4961,7 @@ public function testEncodeDecode(): void ], ]); - $result = $this->getDatabase()->encode($collection, $document); + $result = static::getDatabase()->encode($collection, $document); $this->assertEquals('608fdbe51361a', $result->getAttribute('$id')); $this->assertContains('read("any")', $result->getAttribute('$permissions')); @@ -4743,7 +4985,7 @@ public function testEncodeDecode(): void $this->assertEquals(['admin', 'developer', 'tester',], $result->getAttribute('roles')); $this->assertEquals(['{"$id":"1","label":"x"}', '{"$id":"2","label":"y"}', '{"$id":"3","label":"z"}',], $result->getAttribute('tags')); - $result = $this->getDatabase()->decode($collection, $document); + $result = static::getDatabase()->decode($collection, $document); $this->assertEquals('608fdbe51361a', $result->getAttribute('$id')); $this->assertContains('read("any")', $result->getAttribute('$permissions')); @@ -4777,10 +5019,10 @@ public function testEncodeDecode(): void */ public function testReadPermissionsSuccess(Document $document): Document { - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); - $document = $this->getDatabase()->createDocument('documents', new Document([ + $document = static::getDatabase()->createDocument('documents', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::create(Role::any()), @@ -4800,22 +5042,22 @@ public function testReadPermissionsSuccess(Document $document): Document $this->assertEquals(false, $document->isEmpty()); - self::$authorization->cleanRoles(); + Authorization::cleanRoles(); - $document = $this->getDatabase()->getDocument($document->getCollection(), $document->getId()); + $document = static::getDatabase()->getDocument($document->getCollection(), $document->getId()); $this->assertEquals(true, $document->isEmpty()); - self::$authorization->addRole(Role::any()->toString()); + Authorization::setRole(Role::any()->toString()); return $document; } public function testReadPermissionsFailure(): Document { - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); - $document = $this->getDatabase()->createDocument('documents', new Document([ + $document = static::getDatabase()->createDocument('documents', new Document([ '$permissions' => [ Permission::read(Role::user('1')), Permission::create(Role::user('1')), @@ -4833,13 +5075,13 @@ public function testReadPermissionsFailure(): Document 'colors' => ['pink', 'green', 'blue'], ])); - self::$authorization->cleanRoles(); + Authorization::cleanRoles(); - $document = $this->getDatabase()->getDocument($document->getCollection(), $document->getId()); + $document = static::getDatabase()->getDocument($document->getCollection(), $document->getId()); $this->assertEquals(true, $document->isEmpty()); - self::$authorization->addRole(Role::any()->toString()); + Authorization::setRole(Role::any()->toString()); return $document; } @@ -4849,10 +5091,10 @@ public function testReadPermissionsFailure(): Document */ public function testWritePermissionsSuccess(Document $document): void { - self::$authorization->cleanRoles(); + Authorization::cleanRoles(); $this->expectException(AuthorizationException::class); - $this->getDatabase()->createDocument('documents', new Document([ + static::getDatabase()->createDocument('documents', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::create(Role::any()), @@ -4878,10 +5120,10 @@ public function testWritePermissionsUpdateFailure(Document $document): Document { $this->expectException(AuthorizationException::class); - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); - $document = $this->getDatabase()->createDocument('documents', new Document([ + $document = static::getDatabase()->createDocument('documents', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::create(Role::any()), @@ -4899,9 +5141,9 @@ public function testWritePermissionsUpdateFailure(Document $document): Document 'colors' => ['pink', 'green', 'blue'], ])); - self::$authorization->cleanRoles(); + Authorization::cleanRoles(); - $document = $this->getDatabase()->updateDocument('documents', $document->getId(), new Document([ + $document = static::getDatabase()->updateDocument('documents', $document->getId(), new Document([ '$id' => ID::custom($document->getId()), '$permissions' => [ Permission::read(Role::any()), @@ -4923,7 +5165,7 @@ public function testWritePermissionsUpdateFailure(Document $document): Document public function testNoChangeUpdateDocumentWithoutPermission(): Document { - $document = $this->getDatabase()->createDocument('documents', new Document([ + $document = static::getDatabase()->createDocument('documents', new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::any()) @@ -4939,7 +5181,7 @@ public function testNoChangeUpdateDocumentWithoutPermission(): Document 'colors' => ['pink', 'green', 'blue'], ])); - $updatedDocument = $this->getDatabase()->updateDocument( + $updatedDocument = static::getDatabase()->updateDocument( 'documents', $document->getId(), $document @@ -4949,7 +5191,7 @@ public function testNoChangeUpdateDocumentWithoutPermission(): Document // It should also not throw any authorization exception without any permission because of no change. $this->assertEquals($updatedDocument->getUpdatedAt(), $document->getUpdatedAt()); - $document = $this->getDatabase()->createDocument('documents', new Document([ + $document = static::getDatabase()->createDocument('documents', new Document([ '$id' => ID::unique(), '$permissions' => [], 'string' => 'text📝', @@ -4965,7 +5207,7 @@ public function testNoChangeUpdateDocumentWithoutPermission(): Document // Should throw exception, because nothing was updated, but there was no read permission try { - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'documents', $document->getId(), $document @@ -4979,22 +5221,22 @@ public function testNoChangeUpdateDocumentWithoutPermission(): Document public function testStructureValidationAfterRelationsAttribute(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection("structure_1", [], [], [Permission::create(Role::any())]); - $this->getDatabase()->createCollection("structure_2", [], [], [Permission::create(Role::any())]); + static::getDatabase()->createCollection("structure_1", [], [], [Permission::create(Role::any())]); + static::getDatabase()->createCollection("structure_2", [], [], [Permission::create(Role::any())]); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: "structure_1", relatedCollection: "structure_2", type: Database::RELATION_ONE_TO_ONE, ); try { - $this->getDatabase()->createDocument('structure_1', new Document([ + static::getDatabase()->createDocument('structure_1', new Document([ '$permissions' => [ Permission::read(Role::any()), ], @@ -5009,7 +5251,7 @@ public function testStructureValidationAfterRelationsAttribute(): void public function testNoChangeUpdateDocumentWithRelationWithoutPermission(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -5030,13 +5272,13 @@ public function testNoChangeUpdateDocumentWithRelationWithoutPermission(): void Permission::delete(Role::any()), ]; for ($i = 1; $i < 6; $i++) { - $this->getDatabase()->createCollection("level{$i}", [$attribute], [], $permissions); + static::getDatabase()->createCollection("level{$i}", [$attribute], [], $permissions); } for ($i = 1; $i < 5; $i++) { $collectionId = $i; $relatedCollectionId = $i + 1; - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: "level{$collectionId}", relatedCollection: "level{$relatedCollectionId}", type: Database::RELATION_ONE_TO_ONE, @@ -5045,7 +5287,7 @@ public function testNoChangeUpdateDocumentWithRelationWithoutPermission(): void } // Create document with relationship with nested data - $level1 = $this->getDatabase()->createDocument('level1', new Document([ + $level1 = static::getDatabase()->createDocument('level1', new Document([ '$id' => 'level1', '$permissions' => [], 'name' => 'Level 1', @@ -5070,18 +5312,18 @@ public function testNoChangeUpdateDocumentWithRelationWithoutPermission(): void ], ], ])); - $this->getDatabase()->updateDocument('level1', $level1->getId(), new Document($level1->getArrayCopy())); - $updatedLevel1 = $this->getDatabase()->getDocument('level1', $level1->getId()); + static::getDatabase()->updateDocument('level1', $level1->getId(), new Document($level1->getArrayCopy())); + $updatedLevel1 = static::getDatabase()->getDocument('level1', $level1->getId()); $this->assertEquals($level1, $updatedLevel1); try { - $this->getDatabase()->updateDocument('level1', $level1->getId(), $level1->setAttribute('name', 'haha')); + static::getDatabase()->updateDocument('level1', $level1->getId(), $level1->setAttribute('name', 'haha')); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertInstanceOf(AuthorizationException::class, $e); } $level1->setAttribute('name', 'Level 1'); - $this->getDatabase()->updateCollection('level3', [ + static::getDatabase()->updateCollection('level3', [ Permission::read(Role::any()), Permission::create(Role::any()), Permission::update(Role::any()), @@ -5094,11 +5336,11 @@ public function testNoChangeUpdateDocumentWithRelationWithoutPermission(): void $level2->setAttribute('level3', $level3); $level1->setAttribute('level2', $level2); - $level1 = $this->getDatabase()->updateDocument('level1', $level1->getId(), $level1); + $level1 = static::getDatabase()->updateDocument('level1', $level1->getId(), $level1); $this->assertEquals('updated value', $level1['level2']['level3']['name']); for ($i = 1; $i < 6; $i++) { - $this->getDatabase()->deleteCollection("level{$i}"); + static::getDatabase()->deleteCollection("level{$i}"); } } @@ -5120,10 +5362,10 @@ public function testExceptionAttributeLimit(): void ]); } - $this->getDatabase()->createCollection('attributeLimit', $attributes); + static::getDatabase()->createCollection('attributeLimit', $attributes); $this->expectException(LimitException::class); - $this->assertEquals(false, $this->getDatabase()->createAttribute('attributeLimit', "breaking", Database::VAR_INTEGER, 0, true)); + $this->assertEquals(false, static::getDatabase()->createAttribute('attributeLimit', "breaking", Database::VAR_INTEGER, 0, true)); } // Default assertion for other adapters @@ -5136,7 +5378,7 @@ public function testExceptionAttributeLimit(): void public function testCheckAttributeCountLimit(): void { if ($this->getDatabase()->getLimitForAttributes() > 0) { - $collection = $this->getDatabase()->getCollection('attributeLimit'); + $collection = static::getDatabase()->getCollection('attributeLimit'); // create same attribute in testExceptionAttributeLimit $attribute = new Document([ @@ -5151,7 +5393,7 @@ public function testCheckAttributeCountLimit(): void ]); $this->expectException(LimitException::class); - $this->assertEquals(false, $this->getDatabase()->checkAttribute($collection, $attribute)); + $this->assertEquals(false, static::getDatabase()->checkAttribute($collection, $attribute)); } // Default assertion for other adapters @@ -5187,7 +5429,7 @@ public function rowWidthExceedsMaximum(): array */ public function testExceptionWidthLimit(int $key, int $stringSize, int $stringCount, int $intCount, int $floatCount, int $boolCount): void { - if ($this->getDatabase()->getAdapter()::getDocumentSizeLimit() > 0) { + if (static::getDatabase()->getAdapter()::getDocumentSizeLimit() > 0) { $attributes = []; // Load the collection up to the limit @@ -5247,10 +5489,10 @@ public function testExceptionWidthLimit(int $key, int $stringSize, int $stringCo ]); } - $collection = $this->getDatabase()->createCollection("widthLimit{$key}", $attributes); + $collection = static::getDatabase()->createCollection("widthLimit{$key}", $attributes); $this->expectException(LimitException::class); - $this->assertEquals(false, $this->getDatabase()->createAttribute("widthLimit{$key}", "breaking", Database::VAR_STRING, 100, true)); + $this->assertEquals(false, static::getDatabase()->createAttribute("widthLimit{$key}", "breaking", Database::VAR_STRING, 100, true)); } // Default assertion for other adapters @@ -5263,8 +5505,8 @@ public function testExceptionWidthLimit(int $key, int $stringSize, int $stringCo */ public function testCheckAttributeWidthLimit(int $key, int $stringSize, int $stringCount, int $intCount, int $floatCount, int $boolCount): void { - if ($this->getDatabase()->getAdapter()::getDocumentSizeLimit() > 0) { - $collection = $this->getDatabase()->getCollection("widthLimit{$key}"); + if (static::getDatabase()->getAdapter()::getDocumentSizeLimit() > 0) { + $collection = static::getDatabase()->getCollection("widthLimit{$key}"); // create same attribute in testExceptionWidthLimit $attribute = new Document([ @@ -5279,7 +5521,7 @@ public function testCheckAttributeWidthLimit(int $key, int $stringSize, int $str ]); $this->expectException(LimitException::class); - $this->assertEquals(false, $this->getDatabase()->checkAttribute($collection, $attribute)); + $this->assertEquals(false, static::getDatabase()->checkAttribute($collection, $attribute)); } // Default assertion for other adapters @@ -5288,22 +5530,22 @@ public function testCheckAttributeWidthLimit(int $key, int $stringSize, int $str public function testExceptionIndexLimit(): void { - $this->getDatabase()->createCollection('indexLimit'); + static::getDatabase()->createCollection('indexLimit'); // add unique attributes for indexing for ($i = 0; $i < 64; $i++) { - $this->assertEquals(true, $this->getDatabase()->createAttribute('indexLimit', "test{$i}", Database::VAR_STRING, 16, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('indexLimit', "test{$i}", Database::VAR_STRING, 16, true)); } // Testing for indexLimit // Add up to the limit, then check if the next index throws IndexLimitException for ($i = 0; $i < ($this->getDatabase()->getLimitForIndexes()); $i++) { - $this->assertEquals(true, $this->getDatabase()->createIndex('indexLimit', "index{$i}", Database::INDEX_KEY, ["test{$i}"], [16])); + $this->assertEquals(true, static::getDatabase()->createIndex('indexLimit', "index{$i}", Database::INDEX_KEY, ["test{$i}"], [16])); } $this->expectException(LimitException::class); - $this->assertEquals(false, $this->getDatabase()->createIndex('indexLimit', "index64", Database::INDEX_KEY, ["test64"], [16])); + $this->assertEquals(false, static::getDatabase()->createIndex('indexLimit', "index64", Database::INDEX_KEY, ["test64"], [16])); - $this->getDatabase()->deleteCollection('indexLimit'); + static::getDatabase()->deleteCollection('indexLimit'); } /** @@ -5312,10 +5554,9 @@ public function testExceptionIndexLimit(): void public function testExceptionDuplicate(Document $document): void { $document->setAttribute('$id', 'duplicated'); - $this->getDatabase()->createDocument($document->getCollection(), $document); - + static::getDatabase()->createDocument($document->getCollection(), $document); $this->expectException(DuplicateException::class); - $this->getDatabase()->createDocument($document->getCollection(), $document); + static::getDatabase()->createDocument($document->getCollection(), $document); } /** @@ -5325,12 +5566,12 @@ public function testExceptionCaseInsensitiveDuplicate(Document $document): Docum { $document->setAttribute('$id', 'caseSensitive'); $document->setAttribute('$internalId', '200'); - $this->getDatabase()->createDocument($document->getCollection(), $document); + static::getDatabase()->createDocument($document->getCollection(), $document); $document->setAttribute('$id', 'CaseSensitive'); $this->expectException(DuplicateException::class); - $this->getDatabase()->createDocument($document->getCollection(), $document); + static::getDatabase()->createDocument($document->getCollection(), $document); return $document; } @@ -5342,9 +5583,9 @@ public function testUniqueIndexDuplicate(): void { $this->expectException(DuplicateException::class); - $this->assertEquals(true, $this->getDatabase()->createIndex('movies', 'uniqueIndex', Database::INDEX_UNIQUE, ['name'], [128], [Database::ORDER_ASC])); + $this->assertEquals(true, static::getDatabase()->createIndex('movies', 'uniqueIndex', Database::INDEX_UNIQUE, ['name'], [128], [Database::ORDER_ASC])); - $this->getDatabase()->createDocument('movies', new Document([ + static::getDatabase()->createDocument('movies', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::read(Role::user('1')), @@ -5374,9 +5615,9 @@ public function testUniqueIndexDuplicate(): void */ public function testUniqueIndexDuplicateUpdate(): void { - self::$authorization->addRole(Role::users()->toString()); + Authorization::setRole(Role::users()->toString()); // create document then update to conflict with index - $document = $this->getDatabase()->createDocument('movies', new Document([ + $document = static::getDatabase()->createDocument('movies', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::read(Role::user('1')), @@ -5402,7 +5643,7 @@ public function testUniqueIndexDuplicateUpdate(): void $this->expectException(DuplicateException::class); - $this->getDatabase()->updateDocument('movies', $document->getId(), $document->setAttribute('name', 'Frozen')); + static::getDatabase()->updateDocument('movies', $document->getId(), $document->setAttribute('name', 'Frozen')); } public function testGetAttributeLimit(): void @@ -5428,7 +5669,7 @@ public function testGetId(): void public function testRenameIndex(): void { - $database = $this->getDatabase(); + $database = static::getDatabase(); $numbers = $database->createCollection('numbers'); $database->createAttribute('numbers', 'verbose', Database::VAR_STRING, 128, true); @@ -5454,7 +5695,7 @@ public function testRenameIndex(): void */ public function testRenameIndexMissing(): void { - $database = $this->getDatabase(); + $database = static::getDatabase(); $this->expectExceptionMessage('Index not found'); $index = $database->renameIndex('numbers', 'index1', 'index4'); } @@ -5465,14 +5706,14 @@ public function testRenameIndexMissing(): void */ public function testRenameIndexExisting(): void { - $database = $this->getDatabase(); + $database = static::getDatabase(); $this->expectExceptionMessage('Index name already used'); $index = $database->renameIndex('numbers', 'index3', 'index2'); } public function testRenameAttribute(): void { - $database = $this->getDatabase(); + $database = static::getDatabase(); $colors = $database->createCollection('colors'); $database->createAttribute('colors', 'name', Database::VAR_STRING, 128, true); @@ -5518,7 +5759,7 @@ public function testRenameAttribute(): void */ public function textRenameAttributeMissing(): void { - $database = $this->getDatabase(); + $database = static::getDatabase(); $this->expectExceptionMessage('Attribute not found'); $database->renameAttribute('colors', 'name2', 'name3'); } @@ -5529,14 +5770,14 @@ public function textRenameAttributeMissing(): void */ public function testRenameAttributeExisting(): void { - $database = $this->getDatabase(); + $database = static::getDatabase(); $this->expectExceptionMessage('Attribute name already used'); $database->renameAttribute('colors', 'verbose', 'hex'); } public function testUpdateAttributeDefault(): void { - $database = $this->getDatabase(); + $database = static::getDatabase(); $flowers = $database->createCollection('flowers'); $database->createAttribute('flowers', 'name', Database::VAR_STRING, 128, true); @@ -5591,7 +5832,7 @@ public function testUpdateAttributeDefault(): void */ public function testUpdateAttributeRequired(): void { - $database = $this->getDatabase(); + $database = static::getDatabase(); $database->updateAttributeRequired('flowers', 'inStock', true); @@ -5613,7 +5854,7 @@ public function testUpdateAttributeRequired(): void */ public function testUpdateAttributeFilter(): void { - $database = $this->getDatabase(); + $database = static::getDatabase(); $database->createAttribute('flowers', 'cartModel', Database::VAR_STRING, 2000, false); @@ -5646,7 +5887,7 @@ public function testUpdateAttributeFilter(): void */ public function testUpdateAttributeFormat(): void { - $database = $this->getDatabase(); + $database = static::getDatabase(); $database->createAttribute('flowers', 'price', Database::VAR_INTEGER, 0, false); @@ -5707,7 +5948,7 @@ public function testUpdateAttributeStructure(): void return new Range($min, $max); }, Database::VAR_INTEGER); - $database = $this->getDatabase(); + $database = static::getDatabase(); // price attribute $collection = $database->getCollection('flowers'); @@ -5886,14 +6127,21 @@ public function testUpdateAttributeRename(): void $collection = static::getDatabase()->getCollection('rename_test'); $this->assertEquals('renamed', $collection->getAttribute('attributes')[0]['key']); $this->assertEquals('renamed', $collection->getAttribute('attributes')[0]['$id']); + $this->assertEquals('renamed', $collection->getAttribute('indexes')[0]['attributes'][0]); - // Check empty key doesn't cause issues + // Check empty newKey doesn't cause issues static::getDatabase()->updateAttribute( collection: 'rename_test', id: 'renamed', type: Database::VAR_STRING, ); + $collection = static::getDatabase()->getCollection('rename_test'); + + $this->assertEquals('renamed', $collection->getAttribute('attributes')[0]['key']); + $this->assertEquals('renamed', $collection->getAttribute('attributes')[0]['$id']); + $this->assertEquals('renamed', $collection->getAttribute('indexes')[0]['attributes'][0]); + $doc = static::getDatabase()->getDocument('rename_test', $doc->getId()); $this->assertEquals('string2', $doc->getAttribute('renamed')); @@ -5938,17 +6186,73 @@ public function testUpdateAttributeRename(): void $this->assertInstanceOf(StructureException::class, $e); } - // Check new key filtering - static::getDatabase()->updateAttribute( - collection: 'rename_test', - id: 'renamed', - newKey: 'renamed-test', + // Check new key filtering + static::getDatabase()->updateAttribute( + collection: 'rename_test', + id: 'renamed', + newKey: 'renamed-test', + ); + + $doc = static::getDatabase()->getDocument('rename_test', $doc->getId()); + + $this->assertEquals('string', $doc->getAttribute('renamed-test')); + $this->assertArrayNotHasKey('renamed', $doc->getAttributes()); + } + + public function testUpdateAttributeRenameRelationshipTwoWay(): void + { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + $this->expectNotToPerformAssertions(); + return; + } + + static::getDatabase()->createCollection('rn_rs_test_a'); + static::getDatabase()->createCollection('rn_rs_test_b'); + + static::getDatabase()->createAttribute('rn_rs_test_b', 'name', Database::VAR_STRING, 255, true); + + static::getDatabase()->createRelationship( + 'rn_rs_test_a', + 'rn_rs_test_b', + Database::RELATION_ONE_TO_ONE, + true + ); + + $docA = static::getDatabase()->createDocument('rn_rs_test_a', new Document([ + '$permissions' => [ + Permission::read(Role::any()), + Permission::create(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'rn_rs_test_b' => [ + '$id' => 'b1', + 'name' => 'B1' + ] + ])); + + $docB = static::getDatabase()->getDocument('rn_rs_test_b', 'b1'); + $this->assertArrayHasKey('rn_rs_test_a', $docB->getAttributes()); + $this->assertEquals('B1', $docB->getAttribute('name')); + + // Rename attribute + static::getDatabase()->updateRelationship( + collection: 'rn_rs_test_a', + id: 'rn_rs_test_b', + newKey: 'rn_rs_test_b_renamed' ); - $doc = static::getDatabase()->getDocument('rename_test', $doc->getId()); + // Rename again + static::getDatabase()->updateRelationship( + collection: 'rn_rs_test_a', + id: 'rn_rs_test_b_renamed', + newKey: 'rn_rs_test_b_renamed_2' + ); - $this->assertEquals('string', $doc->getAttribute('renamed-test')); - $this->assertArrayNotHasKey('renamed', $doc->getAttributes()); + // Check our data is OK + $docA = static::getDatabase()->getDocument('rn_rs_test_a', $docA->getId()); + $this->assertArrayHasKey('rn_rs_test_b_renamed_2', $docA->getAttributes()); + $this->assertEquals($docB->getId(), $docA->getAttribute('rn_rs_test_b_renamed_2')['$id']); } public function createRandomString(int $length = 10): string @@ -6001,8 +6305,7 @@ public function testUpdateAttributeSize(): void $document = $this->updateStringAttributeSize(65536, $document); // 65536-16777216 to PHP_INT_MAX or adapter limit - $maxStringSize = 16777217; - $document = $this->updateStringAttributeSize($maxStringSize, $document); + $document = $this->updateStringAttributeSize(16777217, $document); // Test going down in size with data that is too big (Expect Failure) try { @@ -6024,6 +6327,60 @@ public function testUpdateAttributeSize(): void $this->fail('Succeeded updating attribute size to smaller size with data that is too big'); } catch (TruncateException $e) { } + + if (static::getDatabase()->getAdapter()->getMaxIndexLength() > 0) { + $length = intval(static::getDatabase()->getAdapter()->getMaxIndexLength() / 2); + + $this->assertEquals(true, static::getDatabase()->createAttribute('resize_test', 'attr1', Database::VAR_STRING, $length, true)); + $this->assertEquals(true, static::getDatabase()->createAttribute('resize_test', 'attr2', Database::VAR_STRING, $length, true)); + + /** + * No index length provided, we are able to validate + */ + static::getDatabase()->createIndex('resize_test', 'index1', Database::INDEX_KEY, ['attr1', 'attr2']); + + try { + static::getDatabase()->updateAttribute('resize_test', 'attr1', Database::VAR_STRING, 5000); + $this->fail('Failed to throw exception'); + } catch (Throwable $e) { + $this->assertEquals('Index length is longer than the maximum: '.static::getDatabase()->getAdapter()->getMaxIndexLength(), $e->getMessage()); + } + + static::getDatabase()->deleteIndex('resize_test', 'index1'); + + /** + * Index lengths are provided, We are able to validate + * Index $length === attr1, $length === attr2, so $length is removed, so we are able to validate + */ + static::getDatabase()->createIndex('resize_test', 'index1', Database::INDEX_KEY, ['attr1', 'attr2'], [$length, $length]); + + $collection = static::getDatabase()->getCollection('resize_test'); + $indexes = $collection->getAttribute('indexes', []); + $this->assertEquals(null, $indexes[0]['lengths'][0]); + $this->assertEquals(null, $indexes[0]['lengths'][1]); + + try { + static::getDatabase()->updateAttribute('resize_test', 'attr1', Database::VAR_STRING, 5000); + $this->fail('Failed to throw exception'); + } catch (Throwable $e) { + $this->assertEquals('Index length is longer than the maximum: '.static::getDatabase()->getAdapter()->getMaxIndexLength(), $e->getMessage()); + } + + static::getDatabase()->deleteIndex('resize_test', 'index1'); + + /** + * Index lengths are provided + * We are able to increase size because index length remains 50 + */ + static::getDatabase()->createIndex('resize_test', 'index1', Database::INDEX_KEY, ['attr1', 'attr2'], [50, 50]); + + $collection = static::getDatabase()->getCollection('resize_test'); + $indexes = $collection->getAttribute('indexes', []); + $this->assertEquals(50, $indexes[0]['lengths'][0]); + $this->assertEquals(50, $indexes[0]['lengths'][1]); + + static::getDatabase()->updateAttribute('resize_test', 'attr1', Database::VAR_STRING, 5000); + } } /** @@ -6031,27 +6388,36 @@ public function testUpdateAttributeSize(): void */ public function testCreatedAtUpdatedAtAssert(): void { - $document = $this->getDatabase()->getDocument('created_at', 'uid123'); + $document = static::getDatabase()->getDocument('created_at', 'uid123'); $this->assertEquals(true, !$document->isEmpty()); sleep(1); $document->setAttribute('title', 'new title'); - $this->getDatabase()->updateDocument('created_at', 'uid123', $document); - $document = $this->getDatabase()->getDocument('created_at', 'uid123'); + static::getDatabase()->updateDocument('created_at', 'uid123', $document); + $document = static::getDatabase()->getDocument('created_at', 'uid123'); $this->assertGreaterThan($document->getCreatedAt(), $document->getUpdatedAt()); $this->expectException(DuplicateException::class); - $this->getDatabase()->createCollection('created_at'); + static::getDatabase()->createCollection('created_at'); } public function testCreateDatetime(): void { - $this->getDatabase()->createCollection('datetime'); + static::getDatabase()->createCollection('datetime'); - $this->assertEquals(true, $this->getDatabase()->createAttribute('datetime', 'date', Database::VAR_DATETIME, 0, true, null, true, false, null, [], ['datetime'])); - $this->assertEquals(true, $this->getDatabase()->createAttribute('datetime', 'date2', Database::VAR_DATETIME, 0, false, null, true, false, null, [], ['datetime'])); + $this->assertEquals(true, static::getDatabase()->createAttribute('datetime', 'date', Database::VAR_DATETIME, 0, true, null, true, false, null, [], ['datetime'])); + $this->assertEquals(true, static::getDatabase()->createAttribute('datetime', 'date2', Database::VAR_DATETIME, 0, false, null, true, false, null, [], ['datetime'])); + + try { + static::getDatabase()->createDocument('datetime', new Document([ + 'date' => ['2020-01-01'], // array + ])); + $this->fail('Failed to throw exception'); + } catch (Exception $e) { + $this->assertInstanceOf(StructureException::class, $e); + } - $doc = $this->getDatabase()->createDocument('datetime', new Document([ + $doc = static::getDatabase()->createDocument('datetime', new Document([ '$id' => ID::custom('id1234'), '$permissions' => [ Permission::read(Role::any()), @@ -6069,25 +6435,28 @@ public function testCreateDatetime(): void $this->assertGreaterThan('2020-08-16T19:30:08.363+00:00', $doc->getCreatedAt()); $this->assertGreaterThan('2020-08-16T19:30:08.363+00:00', $doc->getUpdatedAt()); - $document = $this->getDatabase()->getDocument('datetime', 'id1234'); - $dateValidator = new DatetimeValidator(); + $document = static::getDatabase()->getDocument('datetime', 'id1234'); + + $min = static::getDatabase()->getAdapter()->getMinDateTime(); + $max = static::getDatabase()->getAdapter()->getMaxDateTime(); + $dateValidator = new DatetimeValidator($min, $max); $this->assertEquals(null, $document->getAttribute('date2')); $this->assertEquals(true, $dateValidator->isValid($document->getAttribute('date'))); $this->assertEquals(false, $dateValidator->isValid($document->getAttribute('date2'))); - $documents = $this->getDatabase()->find('datetime', [ + $documents = static::getDatabase()->find('datetime', [ Query::greaterThan('date', '1975-12-06 10:00:00+01:00'), Query::lessThan('date', '2030-12-06 10:00:00-01:00'), ]); $this->assertEquals(1, count($documents)); - $documents = $this->getDatabase()->find('datetime', [ + $documents = static::getDatabase()->find('datetime', [ Query::greaterThan('$createdAt', '1975-12-06 11:00:00.000'), ]); $this->assertCount(1, $documents); try { - $this->getDatabase()->createDocument('datetime', new Document([ + static::getDatabase()->createDocument('datetime', new Document([ 'date' => "1975-12-06 00:00:61" // 61 seconds is invalid ])); $this->fail('Failed to throw exception'); @@ -6112,7 +6481,17 @@ public function testCreateDatetime(): void foreach ($invalidDates as $date) { try { - $this->getDatabase()->find('datetime', [ + static::getDatabase()->find('datetime', [ + Query::equal('$createdAt', [$date]) + ]); + $this->fail('Failed to throw exception'); + } catch (Throwable $e) { + $this->assertTrue($e instanceof QueryException); + $this->assertEquals('Invalid query: Query value is invalid for attribute "$createdAt"', $e->getMessage()); + } + + try { + static::getDatabase()->find('datetime', [ Query::equal('date', [$date]) ]); $this->fail('Failed to throw exception'); @@ -6121,20 +6500,37 @@ public function testCreateDatetime(): void $this->assertEquals('Invalid query: Query value is invalid for attribute "date"', $e->getMessage()); } } + + $validDates = [ + '2024-12-2509:00:21.891119', + 'Tue Dec 31 2024', + ]; + + foreach ($validDates as $date) { + $docs = static::getDatabase()->find('datetime', [ + Query::equal('$createdAt', [$date]) + ]); + $this->assertCount(0, $docs); + + $docs = static::getDatabase()->find('datetime', [ + Query::equal('date', [$date]) + ]); + $this->assertCount(0, $docs); + } } public function testCreateDateTimeAttributeFailure(): void { - $this->getDatabase()->createCollection('datetime_fail'); + static::getDatabase()->createCollection('datetime_fail'); /** Test for FAILURE */ $this->expectException(Exception::class); - $this->getDatabase()->createAttribute('datetime_fail', 'date_fail', Database::VAR_DATETIME, 0, false); + static::getDatabase()->createAttribute('datetime_fail', 'date_fail', Database::VAR_DATETIME, 0, false); } public function testKeywords(): void { - $database = $this->getDatabase(); + $database = static::getDatabase(); $keywords = $database->getKeywords(); // Collection name tests @@ -6196,7 +6592,7 @@ public function testKeywords(): void $collection = $database->createCollection($collectionName); $this->assertEquals($collectionName, $collection->getId()); - $attribute = $this->getDatabase()->createAttribute($collectionName, $keyword, Database::VAR_STRING, 128, true); + $attribute = static::getDatabase()->createAttribute($collectionName, $keyword, Database::VAR_STRING, 128, true); $this->assertEquals(true, $attribute); $document = new Document([ @@ -6233,20 +6629,15 @@ public function testKeywords(): void $this->assertCount(1, $documents); $this->assertEquals('reservedKeyDocument', $documents[0]->getId()); - $collection = $database->deleteCollection($collectionName); $this->assertTrue($collection); - - // TODO: updateAttribute name tests } - - // TODO: Index name tests } public function testWritePermissions(): void { - self::$authorization->addRole(Role::any()->toString()); - $database = $this->getDatabase(); + Authorization::setRole(Role::any()->toString()); + $database = static::getDatabase(); $database->createCollection('animals', permissions: [ Permission::create(Role::any()), @@ -6311,7 +6702,7 @@ public function testWritePermissions(): void $newCat = $cat->setAttribute('type', 'newCat'); $database->updateDocument('animals', 'cat', $newCat); - $docs = self::$authorization->skip(fn () => $database->find('animals')); + $docs = Authorization::skip(fn () => $database->find('animals')); $this->assertCount(1, $docs); $this->assertEquals('cat', $docs[0]['$id']); $this->assertEquals('newCat', $docs[0]['type']); @@ -6319,19 +6710,19 @@ public function testWritePermissions(): void public function testNoInvalidKeysWithRelationships(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('species'); - $this->getDatabase()->createCollection('creatures'); - $this->getDatabase()->createCollection('characterstics'); + static::getDatabase()->createCollection('species'); + static::getDatabase()->createCollection('creatures'); + static::getDatabase()->createCollection('characteristics'); - $this->getDatabase()->createAttribute('species', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('creatures', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('characterstics', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('species', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('creatures', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('characteristics', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'species', relatedCollection: 'creatures', type: Database::RELATION_ONE_TO_ONE, @@ -6339,16 +6730,16 @@ public function testNoInvalidKeysWithRelationships(): void id: 'creature', twoWayKey:'species' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'creatures', - relatedCollection: 'characterstics', + relatedCollection: 'characteristics', type: Database::RELATION_ONE_TO_ONE, twoWay: true, - id: 'characterstic', + id: 'characteristic', twoWayKey:'creature' ); - $species = $this->getDatabase()->createDocument('species', new Document([ + $species = static::getDatabase()->createDocument('species', new Document([ '$id' => ID::custom('1'), '$permissions' => [ Permission::read(Role::any()), @@ -6360,7 +6751,7 @@ public function testNoInvalidKeysWithRelationships(): void Permission::read(Role::any()), ], 'name' => 'Dog', - 'characterstic' => [ + 'characteristic' => [ '$id' => ID::custom('1'), '$permissions' => [ Permission::read(Role::any()), @@ -6370,46 +6761,48 @@ public function testNoInvalidKeysWithRelationships(): void ] ] ])); - $this->getDatabase()->updateDocument('species', $species->getId(), new Document([ + static::getDatabase()->updateDocument('species', $species->getId(), new Document([ '$id' => ID::custom('1'), '$collection' => 'species', 'creature' => [ '$id' => ID::custom('1'), '$collection' => 'creatures', - 'characterstic' => [ + 'characteristic' => [ '$id' => ID::custom('1'), 'name' => 'active', - '$collection' => 'characterstics', + '$collection' => 'characteristics', ] ] ])); - $updatedSpecies = $this->getDatabase()->getDocument('species', $species->getId()); + + $updatedSpecies = static::getDatabase()->getDocument('species', $species->getId()); + $this->assertEquals($species, $updatedSpecies); } // Relationships public function testOneToOneOneWayRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('person'); - $this->getDatabase()->createCollection('library'); + static::getDatabase()->createCollection('person'); + static::getDatabase()->createCollection('library'); - $this->getDatabase()->createAttribute('person', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('library', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('library', 'area', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('person', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('library', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('library', 'area', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'person', relatedCollection: 'library', type: Database::RELATION_ONE_TO_ONE ); // Check metadata for collection - $collection = $this->getDatabase()->getCollection('person'); + $collection = static::getDatabase()->getCollection('person'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { @@ -6425,14 +6818,14 @@ public function testOneToOneOneWayRelationship(): void } try { - $this->getDatabase()->deleteAttribute('person', 'library'); + static::getDatabase()->deleteAttribute('person', 'library'); $this->fail('Failed to throw Exception'); } catch (Exception $e) { $this->assertEquals('Cannot delete relationship as an attribute', $e->getMessage()); } // Create document with relationship with nested data - $person1 = $this->getDatabase()->createDocument('person', new Document([ + $person1 = static::getDatabase()->createDocument('person', new Document([ '$id' => 'person1', '$permissions' => [ Permission::read(Role::any()), @@ -6453,24 +6846,24 @@ public function testOneToOneOneWayRelationship(): void ])); // Update a document with non existing related document. It should not get added to the list. - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'person', 'person1', $person1->setAttribute('library', 'no-library') ); - $person1Document = $this->getDatabase()->getDocument('person', 'person1'); + $person1Document = static::getDatabase()->getDocument('person', 'person1'); // Assert document does not contain non existing relation document. $this->assertEquals(null, $person1Document->getAttribute('library')); - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'person', 'person1', $person1->setAttribute('library', 'library1') ); // Update through create - $library10 = $this->getDatabase()->createDocument('library', new Document([ + $library10 = static::getDatabase()->createDocument('library', new Document([ '$id' => 'library10', '$permissions' => [ Permission::read(Role::any()), @@ -6479,7 +6872,7 @@ public function testOneToOneOneWayRelationship(): void 'name' => 'Library 10', 'area' => 'Area 10', ])); - $person10 = $this->getDatabase()->createDocument('person', new Document([ + $person10 = static::getDatabase()->createDocument('person', new Document([ '$id' => 'person10', '$permissions' => [ Permission::read(Role::any()), @@ -6494,11 +6887,11 @@ public function testOneToOneOneWayRelationship(): void ], ])); $this->assertEquals('Library 10 Updated', $person10->getAttribute('library')->getAttribute('name')); - $library10 = $this->getDatabase()->getDocument('library', $library10->getId()); + $library10 = static::getDatabase()->getDocument('library', $library10->getId()); $this->assertEquals('Library 10 Updated', $library10->getAttribute('name')); // Create document with relationship with related ID - $this->getDatabase()->createDocument('library', new Document([ + static::getDatabase()->createDocument('library', new Document([ '$id' => 'library2', '$permissions' => [ Permission::read(Role::any()), @@ -6507,7 +6900,7 @@ public function testOneToOneOneWayRelationship(): void 'name' => 'Library 2', 'area' => 'Area 2', ])); - $this->getDatabase()->createDocument('person', new Document([ + static::getDatabase()->createDocument('person', new Document([ '$id' => 'person2', '$permissions' => [ Permission::read(Role::any()), @@ -6519,34 +6912,34 @@ public function testOneToOneOneWayRelationship(): void ])); // Get documents with relationship - $person1 = $this->getDatabase()->getDocument('person', 'person1'); + $person1 = static::getDatabase()->getDocument('person', 'person1'); $library = $person1->getAttribute('library'); $this->assertEquals('library1', $library['$id']); $this->assertArrayNotHasKey('person', $library); - $person = $this->getDatabase()->getDocument('person', 'person2'); + $person = static::getDatabase()->getDocument('person', 'person2'); $library = $person->getAttribute('library'); $this->assertEquals('library2', $library['$id']); $this->assertArrayNotHasKey('person', $library); // Get related documents - $library = $this->getDatabase()->getDocument('library', 'library1'); + $library = static::getDatabase()->getDocument('library', 'library1'); $this->assertArrayNotHasKey('person', $library); - $library = $this->getDatabase()->getDocument('library', 'library2'); + $library = static::getDatabase()->getDocument('library', 'library2'); $this->assertArrayNotHasKey('person', $library); - $people = $this->getDatabase()->find('person', [ + $people = static::getDatabase()->find('person', [ Query::select(['name']) ]); $this->assertArrayNotHasKey('library', $people[0]); - $people = $this->getDatabase()->find('person'); + $people = static::getDatabase()->find('person'); $this->assertEquals(3, \count($people)); // Select related document attributes - $person = $this->getDatabase()->findOne('person', [ + $person = static::getDatabase()->findOne('person', [ Query::select(['*', 'library.name']) ]); @@ -6557,7 +6950,7 @@ public function testOneToOneOneWayRelationship(): void $this->assertEquals('Library 1', $person->getAttribute('library')->getAttribute('name')); $this->assertArrayNotHasKey('area', $person->getAttribute('library')); - $person = $this->getDatabase()->getDocument('person', 'person1', [ + $person = static::getDatabase()->getDocument('person', 'person1', [ Query::select(['*', 'library.name', '$id']) ]); @@ -6566,52 +6959,52 @@ public function testOneToOneOneWayRelationship(): void - $document = $this->getDatabase()->getDocument('person', $person->getId(), [ + $document = static::getDatabase()->getDocument('person', $person->getId(), [ Query::select(['name']), ]); $this->assertArrayNotHasKey('library', $document); $this->assertEquals('Person 1', $document['name']); - $document = $this->getDatabase()->getDocument('person', $person->getId(), [ + $document = static::getDatabase()->getDocument('person', $person->getId(), [ Query::select(['*']), ]); $this->assertEquals('library1', $document['library']); - $document = $this->getDatabase()->getDocument('person', $person->getId(), [ + $document = static::getDatabase()->getDocument('person', $person->getId(), [ Query::select(['library.*']), ]); $this->assertEquals('Library 1', $document['library']['name']); $this->assertArrayNotHasKey('name', $document); // Update root document attribute without altering relationship - $person1 = $this->getDatabase()->updateDocument( + $person1 = static::getDatabase()->updateDocument( 'person', $person1->getId(), $person1->setAttribute('name', 'Person 1 Updated') ); $this->assertEquals('Person 1 Updated', $person1->getAttribute('name')); - $person1 = $this->getDatabase()->getDocument('person', 'person1'); + $person1 = static::getDatabase()->getDocument('person', 'person1'); $this->assertEquals('Person 1 Updated', $person1->getAttribute('name')); // Update nested document attribute - $person1 = $this->getDatabase()->updateDocument( + $person1 = static::getDatabase()->updateDocument( 'person', $person1->getId(), $person1->setAttribute( 'library', $person1 - ->getAttribute('library') - ->setAttribute('name', 'Library 1 Updated') + ->getAttribute('library') + ->setAttribute('name', 'Library 1 Updated') ) ); $this->assertEquals('Library 1 Updated', $person1->getAttribute('library')->getAttribute('name')); - $person1 = $this->getDatabase()->getDocument('person', 'person1'); + $person1 = static::getDatabase()->getDocument('person', 'person1'); $this->assertEquals('Library 1 Updated', $person1->getAttribute('library')->getAttribute('name')); // Create new document with no relationship - $person3 = $this->getDatabase()->createDocument('person', new Document([ + $person3 = static::getDatabase()->createDocument('person', new Document([ '$id' => 'person3', '$permissions' => [ Permission::read(Role::any()), @@ -6622,7 +7015,7 @@ public function testOneToOneOneWayRelationship(): void ])); // Update to relate to created document - $person3 = $this->getDatabase()->updateDocument( + $person3 = static::getDatabase()->updateDocument( 'person', $person3->getId(), $person3->setAttribute('library', new Document([ @@ -6637,23 +7030,23 @@ public function testOneToOneOneWayRelationship(): void ); $this->assertEquals('library3', $person3->getAttribute('library')['$id']); - $person3 = $this->getDatabase()->getDocument('person', 'person3'); + $person3 = static::getDatabase()->getDocument('person', 'person3'); $this->assertEquals('Library 3', $person3['library']['name']); - $libraryDocument = $this->getDatabase()->getDocument('library', 'library3'); + $libraryDocument = static::getDatabase()->getDocument('library', 'library3'); $libraryDocument->setAttribute('name', 'Library 3 updated'); - $this->getDatabase()->updateDocument('library', 'library3', $libraryDocument); - $libraryDocument = $this->getDatabase()->getDocument('library', 'library3'); + static::getDatabase()->updateDocument('library', 'library3', $libraryDocument); + $libraryDocument = static::getDatabase()->getDocument('library', 'library3'); $this->assertEquals('Library 3 updated', $libraryDocument['name']); - $person3 = $this->getDatabase()->getDocument('person', 'person3'); + $person3 = static::getDatabase()->getDocument('person', 'person3'); // Todo: This is failing $this->assertEquals($libraryDocument['name'], $person3['library']['name']); $this->assertEquals('library3', $person3->getAttribute('library')['$id']); // One to one can't relate to multiple documents, unique index throws duplicate try { - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'person', $person1->getId(), $person1->setAttribute('library', 'library2') @@ -6664,7 +7057,7 @@ public function testOneToOneOneWayRelationship(): void } // Create new document - $library4 = $this->getDatabase()->createDocument('library', new Document([ + $library4 = static::getDatabase()->createDocument('library', new Document([ '$id' => 'library4', '$permissions' => [ Permission::read(Role::any()), @@ -6675,33 +7068,33 @@ public function testOneToOneOneWayRelationship(): void ])); // Relate existing document to new document - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'person', $person1->getId(), $person1->setAttribute('library', 'library4') ); // Relate existing document to new document as nested data - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'person', $person1->getId(), $person1->setAttribute('library', $library4) ); // Rename relationship key - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'person', id: 'library', newKey: 'newLibrary' ); // Get document with again - $person = $this->getDatabase()->getDocument('person', 'person1'); + $person = static::getDatabase()->getDocument('person', 'person1'); $library = $person->getAttribute('newLibrary'); $this->assertEquals('library4', $library['$id']); // Create person with no relationship - $this->getDatabase()->createDocument('person', new Document([ + static::getDatabase()->createDocument('person', new Document([ '$id' => 'person4', '$permissions' => [ Permission::read(Role::any()), @@ -6712,22 +7105,22 @@ public function testOneToOneOneWayRelationship(): void ])); // Can delete parent document with no relation with on delete set to restrict - $deleted = $this->getDatabase()->deleteDocument('person', 'person4'); + $deleted = static::getDatabase()->deleteDocument('person', 'person4'); $this->assertEquals(true, $deleted); - $person4 = $this->getDatabase()->getDocument('person', 'person4'); + $person4 = static::getDatabase()->getDocument('person', 'person4'); $this->assertEquals(true, $person4->isEmpty()); // Cannot delete document while still related to another with on delete set to restrict try { - $this->getDatabase()->deleteDocument('person', 'person1'); + static::getDatabase()->deleteDocument('person', 'person1'); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } // Can delete child document while still related to another with on delete set to restrict - $person5 = $this->getDatabase()->createDocument('person', new Document([ + $person5 = static::getDatabase()->createDocument('person', new Document([ '$id' => 'person5', '$permissions' => [ Permission::read(Role::any()), @@ -6745,60 +7138,60 @@ public function testOneToOneOneWayRelationship(): void 'area' => 'Area 5', ], ])); - $deleted = $this->getDatabase()->deleteDocument('library', 'library5'); + $deleted = static::getDatabase()->deleteDocument('library', 'library5'); $this->assertEquals(true, $deleted); - $person5 = $this->getDatabase()->getDocument('person', 'person5'); + $person5 = static::getDatabase()->getDocument('person', 'person5'); $this->assertEquals(null, $person5->getAttribute('newLibrary')); // Change on delete to set null - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'person', id: 'newLibrary', onDelete: Database::RELATION_MUTATE_SET_NULL ); // Delete parent, no effect on children for one-way - $this->getDatabase()->deleteDocument('person', 'person1'); + static::getDatabase()->deleteDocument('person', 'person1'); // Delete child, set parent relating attribute to null for one-way - $this->getDatabase()->deleteDocument('library', 'library2'); + static::getDatabase()->deleteDocument('library', 'library2'); // Check relation was set to null - $person2 = $this->getDatabase()->getDocument('person', 'person2'); + $person2 = static::getDatabase()->getDocument('person', 'person2'); $this->assertEquals(null, $person2->getAttribute('newLibrary', '')); // Relate to another document - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'person', $person2->getId(), $person2->setAttribute('newLibrary', 'library4') ); // Change on delete to cascade - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'person', id: 'newLibrary', onDelete: Database::RELATION_MUTATE_CASCADE ); // Delete parent, will delete child - $this->getDatabase()->deleteDocument('person', 'person2'); + static::getDatabase()->deleteDocument('person', 'person2'); // Check parent and child were deleted - $person = $this->getDatabase()->getDocument('person', 'person2'); + $person = static::getDatabase()->getDocument('person', 'person2'); $this->assertEquals(true, $person->isEmpty()); - $library = $this->getDatabase()->getDocument('library', 'library4'); + $library = static::getDatabase()->getDocument('library', 'library4'); $this->assertEquals(true, $library->isEmpty()); // Delete relationship - $this->getDatabase()->deleteRelationship( + static::getDatabase()->deleteRelationship( 'person', 'newLibrary' ); // Check parent doesn't have relationship anymore - $person = $this->getDatabase()->getDocument('person', 'person1'); + $person = static::getDatabase()->getDocument('person', 'person1'); $library = $person->getAttribute('newLibrary', ''); $this->assertEquals(null, $library); } @@ -6812,26 +7205,26 @@ public function testOneToOneOneWayRelationship(): void */ public function testOneToOneTwoWayRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('country'); - $this->getDatabase()->createCollection('city'); + static::getDatabase()->createCollection('country'); + static::getDatabase()->createCollection('city'); - $this->getDatabase()->createAttribute('country', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('city', 'code', Database::VAR_STRING, 3, true); - $this->getDatabase()->createAttribute('city', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('country', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('city', 'code', Database::VAR_STRING, 3, true); + static::getDatabase()->createAttribute('city', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'country', relatedCollection: 'city', type: Database::RELATION_ONE_TO_ONE, twoWay: true ); - $collection = $this->getDatabase()->getCollection('country'); + $collection = static::getDatabase()->getCollection('country'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'city') { @@ -6845,7 +7238,7 @@ public function testOneToOneTwoWayRelationship(): void } } - $collection = $this->getDatabase()->getCollection('city'); + $collection = static::getDatabase()->getCollection('city'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'country') { @@ -6880,40 +7273,40 @@ public function testOneToOneTwoWayRelationship(): void ], ]); - $this->getDatabase()->createDocument('country', new Document($doc->getArrayCopy())); - $country1 = $this->getDatabase()->getDocument('country', 'country1'); + static::getDatabase()->createDocument('country', new Document($doc->getArrayCopy())); + $country1 = static::getDatabase()->getDocument('country', 'country1'); $this->assertEquals('London', $country1->getAttribute('city')->getAttribute('name')); // Update a document with non existing related document. It should not get added to the list. - $this->getDatabase()->updateDocument('country', 'country1', (new Document($doc->getArrayCopy()))->setAttribute('city', 'no-city')); + static::getDatabase()->updateDocument('country', 'country1', (new Document($doc->getArrayCopy()))->setAttribute('city', 'no-city')); - $country1Document = $this->getDatabase()->getDocument('country', 'country1'); + $country1Document = static::getDatabase()->getDocument('country', 'country1'); // Assert document does not contain non existing relation document. $this->assertEquals(null, $country1Document->getAttribute('city')); - $this->getDatabase()->updateDocument('country', 'country1', (new Document($doc->getArrayCopy()))->setAttribute('city', 'city1')); + static::getDatabase()->updateDocument('country', 'country1', (new Document($doc->getArrayCopy()))->setAttribute('city', 'city1')); try { - $this->getDatabase()->deleteDocument('country', 'country1'); + static::getDatabase()->deleteDocument('country', 'country1'); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertInstanceOf(RestrictedException::class, $e); } - $this->assertTrue($this->getDatabase()->deleteDocument('city', 'city1')); + $this->assertTrue(static::getDatabase()->deleteDocument('city', 'city1')); - $city1 = $this->getDatabase()->getDocument('city', 'city1'); + $city1 = static::getDatabase()->getDocument('city', 'city1'); $this->assertTrue($city1->isEmpty()); - $country1 = $this->getDatabase()->getDocument('country', 'country1'); + $country1 = static::getDatabase()->getDocument('country', 'country1'); $this->assertTrue($country1->getAttribute('city')->isEmpty()); - $this->assertTrue($this->getDatabase()->deleteDocument('country', 'country1')); + $this->assertTrue(static::getDatabase()->deleteDocument('country', 'country1')); - $this->getDatabase()->createDocument('country', new Document($doc->getArrayCopy())); - $country1 = $this->getDatabase()->getDocument('country', 'country1'); + static::getDatabase()->createDocument('country', new Document($doc->getArrayCopy())); + $country1 = static::getDatabase()->getDocument('country', 'country1'); $this->assertEquals('London', $country1->getAttribute('city')->getAttribute('name')); // Create document with relationship with related ID - $this->getDatabase()->createDocument('city', new Document([ + static::getDatabase()->createDocument('city', new Document([ '$id' => 'city2', '$permissions' => [ Permission::read(Role::any()), @@ -6923,7 +7316,7 @@ public function testOneToOneTwoWayRelationship(): void 'name' => 'Paris', 'code' => 'PAR', ])); - $this->getDatabase()->createDocument('country', new Document([ + static::getDatabase()->createDocument('country', new Document([ '$id' => 'country2', '$permissions' => [ Permission::read(Role::any()), @@ -6935,7 +7328,7 @@ public function testOneToOneTwoWayRelationship(): void ])); // Create from child side - $this->getDatabase()->createDocument('city', new Document([ + static::getDatabase()->createDocument('city', new Document([ '$id' => 'city3', '$permissions' => [ Permission::read(Role::any()), @@ -6954,7 +7347,7 @@ public function testOneToOneTwoWayRelationship(): void 'name' => 'New Zealand', ], ])); - $this->getDatabase()->createDocument('country', new Document([ + static::getDatabase()->createDocument('country', new Document([ '$id' => 'country4', '$permissions' => [ Permission::read(Role::any()), @@ -6963,7 +7356,7 @@ public function testOneToOneTwoWayRelationship(): void ], 'name' => 'Australia', ])); - $this->getDatabase()->createDocument('city', new Document([ + static::getDatabase()->createDocument('city', new Document([ '$id' => 'city4', '$permissions' => [ Permission::read(Role::any()), @@ -6976,53 +7369,53 @@ public function testOneToOneTwoWayRelationship(): void ])); // Get document with relationship - $city = $this->getDatabase()->getDocument('city', 'city1'); + $city = static::getDatabase()->getDocument('city', 'city1'); $country = $city->getAttribute('country'); $this->assertEquals('country1', $country['$id']); $this->assertArrayNotHasKey('city', $country); - $city = $this->getDatabase()->getDocument('city', 'city2'); + $city = static::getDatabase()->getDocument('city', 'city2'); $country = $city->getAttribute('country'); $this->assertEquals('country2', $country['$id']); $this->assertArrayNotHasKey('city', $country); - $city = $this->getDatabase()->getDocument('city', 'city3'); + $city = static::getDatabase()->getDocument('city', 'city3'); $country = $city->getAttribute('country'); $this->assertEquals('country3', $country['$id']); $this->assertArrayNotHasKey('city', $country); - $city = $this->getDatabase()->getDocument('city', 'city4'); + $city = static::getDatabase()->getDocument('city', 'city4'); $country = $city->getAttribute('country'); $this->assertEquals('country4', $country['$id']); $this->assertArrayNotHasKey('city', $country); // Get inverse document with relationship - $country = $this->getDatabase()->getDocument('country', 'country1'); + $country = static::getDatabase()->getDocument('country', 'country1'); $city = $country->getAttribute('city'); $this->assertEquals('city1', $city['$id']); $this->assertArrayNotHasKey('country', $city); - $country = $this->getDatabase()->getDocument('country', 'country2'); + $country = static::getDatabase()->getDocument('country', 'country2'); $city = $country->getAttribute('city'); $this->assertEquals('city2', $city['$id']); $this->assertArrayNotHasKey('country', $city); - $country = $this->getDatabase()->getDocument('country', 'country3'); + $country = static::getDatabase()->getDocument('country', 'country3'); $city = $country->getAttribute('city'); $this->assertEquals('city3', $city['$id']); $this->assertArrayNotHasKey('country', $city); - $country = $this->getDatabase()->getDocument('country', 'country4'); + $country = static::getDatabase()->getDocument('country', 'country4'); $city = $country->getAttribute('city'); $this->assertEquals('city4', $city['$id']); $this->assertArrayNotHasKey('country', $city); - $countries = $this->getDatabase()->find('country'); + $countries = static::getDatabase()->find('country'); $this->assertEquals(4, \count($countries)); // Select related document attributes - $country = $this->getDatabase()->findOne('country', [ + $country = static::getDatabase()->findOne('country', [ Query::select(['*', 'city.name']) ]); @@ -7033,73 +7426,73 @@ public function testOneToOneTwoWayRelationship(): void $this->assertEquals('London', $country->getAttribute('city')->getAttribute('name')); $this->assertArrayNotHasKey('code', $country->getAttribute('city')); - $country = $this->getDatabase()->getDocument('country', 'country1', [ + $country = static::getDatabase()->getDocument('country', 'country1', [ Query::select(['*', 'city.name']) ]); $this->assertEquals('London', $country->getAttribute('city')->getAttribute('name')); $this->assertArrayNotHasKey('code', $country->getAttribute('city')); - $country1 = $this->getDatabase()->getDocument('country', 'country1'); + $country1 = static::getDatabase()->getDocument('country', 'country1'); // Update root document attribute without altering relationship - $country1 = $this->getDatabase()->updateDocument( + $country1 = static::getDatabase()->updateDocument( 'country', $country1->getId(), $country1->setAttribute('name', 'Country 1 Updated') ); $this->assertEquals('Country 1 Updated', $country1->getAttribute('name')); - $country1 = $this->getDatabase()->getDocument('country', 'country1'); + $country1 = static::getDatabase()->getDocument('country', 'country1'); $this->assertEquals('Country 1 Updated', $country1->getAttribute('name')); - $city2 = $this->getDatabase()->getDocument('city', 'city2'); + $city2 = static::getDatabase()->getDocument('city', 'city2'); // Update inverse root document attribute without altering relationship - $city2 = $this->getDatabase()->updateDocument( + $city2 = static::getDatabase()->updateDocument( 'city', $city2->getId(), $city2->setAttribute('name', 'City 2 Updated') ); $this->assertEquals('City 2 Updated', $city2->getAttribute('name')); - $city2 = $this->getDatabase()->getDocument('city', 'city2'); + $city2 = static::getDatabase()->getDocument('city', 'city2'); $this->assertEquals('City 2 Updated', $city2->getAttribute('name')); // Update nested document attribute - $country1 = $this->getDatabase()->updateDocument( + $country1 = static::getDatabase()->updateDocument( 'country', $country1->getId(), $country1->setAttribute( 'city', $country1 - ->getAttribute('city') - ->setAttribute('name', 'City 1 Updated') + ->getAttribute('city') + ->setAttribute('name', 'City 1 Updated') ) ); $this->assertEquals('City 1 Updated', $country1->getAttribute('city')->getAttribute('name')); - $country1 = $this->getDatabase()->getDocument('country', 'country1'); + $country1 = static::getDatabase()->getDocument('country', 'country1'); $this->assertEquals('City 1 Updated', $country1->getAttribute('city')->getAttribute('name')); // Update inverse nested document attribute - $city2 = $this->getDatabase()->updateDocument( + $city2 = static::getDatabase()->updateDocument( 'city', $city2->getId(), $city2->setAttribute( 'country', $city2 - ->getAttribute('country') - ->setAttribute('name', 'Country 2 Updated') + ->getAttribute('country') + ->setAttribute('name', 'Country 2 Updated') ) ); $this->assertEquals('Country 2 Updated', $city2->getAttribute('country')->getAttribute('name')); - $city2 = $this->getDatabase()->getDocument('city', 'city2'); + $city2 = static::getDatabase()->getDocument('city', 'city2'); $this->assertEquals('Country 2 Updated', $city2->getAttribute('country')->getAttribute('name')); // Create new document with no relationship - $country5 = $this->getDatabase()->createDocument('country', new Document([ + $country5 = static::getDatabase()->createDocument('country', new Document([ '$id' => 'country5', '$permissions' => [ Permission::read(Role::any()), @@ -7110,7 +7503,7 @@ public function testOneToOneTwoWayRelationship(): void ])); // Update to relate to created document - $country5 = $this->getDatabase()->updateDocument( + $country5 = static::getDatabase()->updateDocument( 'country', $country5->getId(), $country5->setAttribute('city', new Document([ @@ -7125,11 +7518,11 @@ public function testOneToOneTwoWayRelationship(): void ); $this->assertEquals('city5', $country5->getAttribute('city')['$id']); - $country5 = $this->getDatabase()->getDocument('country', 'country5'); + $country5 = static::getDatabase()->getDocument('country', 'country5'); $this->assertEquals('city5', $country5->getAttribute('city')['$id']); // Create new document with no relationship - $city6 = $this->getDatabase()->createDocument('city', new Document([ + $city6 = static::getDatabase()->createDocument('city', new Document([ '$id' => 'city6', '$permissions' => [ Permission::read(Role::any()), @@ -7141,7 +7534,7 @@ public function testOneToOneTwoWayRelationship(): void ])); // Update to relate to created document - $city6 = $this->getDatabase()->updateDocument( + $city6 = static::getDatabase()->updateDocument( 'city', $city6->getId(), $city6->setAttribute('country', new Document([ @@ -7155,12 +7548,12 @@ public function testOneToOneTwoWayRelationship(): void ); $this->assertEquals('country6', $city6->getAttribute('country')['$id']); - $city6 = $this->getDatabase()->getDocument('city', 'city6'); + $city6 = static::getDatabase()->getDocument('city', 'city6'); $this->assertEquals('country6', $city6->getAttribute('country')['$id']); // One to one can't relate to multiple documents, unique index throws duplicate try { - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'country', $country1->getId(), $country1->setAttribute('city', 'city2') @@ -7170,21 +7563,21 @@ public function testOneToOneTwoWayRelationship(): void $this->assertInstanceOf(DuplicateException::class, $e); } - $city1 = $this->getDatabase()->getDocument('city', 'city1'); + $city1 = static::getDatabase()->getDocument('city', 'city1'); // Set relationship to null - $city1 = $this->getDatabase()->updateDocument( + $city1 = static::getDatabase()->updateDocument( 'city', $city1->getId(), $city1->setAttribute('country', null) ); $this->assertEquals(null, $city1->getAttribute('country')); - $city1 = $this->getDatabase()->getDocument('city', 'city1'); + $city1 = static::getDatabase()->getDocument('city', 'city1'); $this->assertEquals(null, $city1->getAttribute('country')); // Create a new city with no relation - $city7 = $this->getDatabase()->createDocument('city', new Document([ + $city7 = static::getDatabase()->createDocument('city', new Document([ '$id' => 'city7', '$permissions' => [ Permission::read(Role::any()), @@ -7196,21 +7589,21 @@ public function testOneToOneTwoWayRelationship(): void ])); // Update document with relation to new document - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'country', $country1->getId(), $country1->setAttribute('city', 'city7') ); // Relate existing document to new document as nested data - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'country', $country1->getId(), $country1->setAttribute('city', $city7) ); // Create a new country with no relation - $this->getDatabase()->createDocument('country', new Document([ + static::getDatabase()->createDocument('country', new Document([ '$id' => 'country7', '$permissions' => [ Permission::read(Role::any()), @@ -7221,14 +7614,14 @@ public function testOneToOneTwoWayRelationship(): void ])); // Update inverse document with new related document - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'city', $city1->getId(), $city1->setAttribute('country', 'country7') ); // Rename relationship keys on both sides - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( 'country', 'city', 'newCity', @@ -7236,17 +7629,17 @@ public function testOneToOneTwoWayRelationship(): void ); // Get document with new relationship key - $city = $this->getDatabase()->getDocument('city', 'city1'); + $city = static::getDatabase()->getDocument('city', 'city1'); $country = $city->getAttribute('newCountry'); $this->assertEquals('country7', $country['$id']); // Get inverse document with new relationship key - $country = $this->getDatabase()->getDocument('country', 'country7'); + $country = static::getDatabase()->getDocument('country', 'country7'); $city = $country->getAttribute('newCity'); $this->assertEquals('city1', $city['$id']); // Create a new country with no relation - $this->getDatabase()->createDocument('country', new Document([ + static::getDatabase()->createDocument('country', new Document([ '$id' => 'country8', '$permissions' => [ Permission::read(Role::any()), @@ -7257,87 +7650,87 @@ public function testOneToOneTwoWayRelationship(): void ])); // Can delete parent document with no relation with on delete set to restrict - $deleted = $this->getDatabase()->deleteDocument('country', 'country8'); + $deleted = static::getDatabase()->deleteDocument('country', 'country8'); $this->assertEquals(1, $deleted); - $country8 = $this->getDatabase()->getDocument('country', 'country8'); + $country8 = static::getDatabase()->getDocument('country', 'country8'); $this->assertEquals(true, $country8->isEmpty()); // Cannot delete document while still related to another with on delete set to restrict try { - $this->getDatabase()->deleteDocument('country', 'country1'); + static::getDatabase()->deleteDocument('country', 'country1'); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } // Change on delete to set null - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'country', id: 'newCity', onDelete: Database::RELATION_MUTATE_SET_NULL ); - $this->getDatabase()->updateDocument('city', 'city1', new Document(['newCountry' => null, '$id' => 'city1'])); - $city1 = $this->getDatabase()->getDocument('city', 'city1'); + static::getDatabase()->updateDocument('city', 'city1', new Document(['newCountry' => null, '$id' => 'city1'])); + $city1 = static::getDatabase()->getDocument('city', 'city1'); $this->assertNull($city1->getAttribute('newCountry')); // Check Delete TwoWay TRUE && RELATION_MUTATE_SET_NULL && related value NULL - $this->assertTrue($this->getDatabase()->deleteDocument('city', 'city1')); - $city1 = $this->getDatabase()->getDocument('city', 'city1'); + $this->assertTrue(static::getDatabase()->deleteDocument('city', 'city1')); + $city1 = static::getDatabase()->getDocument('city', 'city1'); $this->assertTrue($city1->isEmpty()); // Delete parent, will set child relationship to null for two-way - $this->getDatabase()->deleteDocument('country', 'country1'); + static::getDatabase()->deleteDocument('country', 'country1'); // Check relation was set to null - $city7 = $this->getDatabase()->getDocument('city', 'city7'); + $city7 = static::getDatabase()->getDocument('city', 'city7'); $this->assertEquals(null, $city7->getAttribute('country', '')); // Delete child, set parent relationship to null for two-way - $this->getDatabase()->deleteDocument('city', 'city2'); + static::getDatabase()->deleteDocument('city', 'city2'); // Check relation was set to null - $country2 = $this->getDatabase()->getDocument('country', 'country2'); + $country2 = static::getDatabase()->getDocument('country', 'country2'); $this->assertEquals(null, $country2->getAttribute('city', '')); // Relate again - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'city', $city7->getId(), $city7->setAttribute('newCountry', 'country2') ); // Change on delete to cascade - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'country', id: 'newCity', onDelete: Database::RELATION_MUTATE_CASCADE ); // Delete parent, will delete child - $this->getDatabase()->deleteDocument('country', 'country7'); + static::getDatabase()->deleteDocument('country', 'country7'); // Check parent and child were deleted - $library = $this->getDatabase()->getDocument('country', 'country7'); + $library = static::getDatabase()->getDocument('country', 'country7'); $this->assertEquals(true, $library->isEmpty()); - $library = $this->getDatabase()->getDocument('city', 'city1'); + $library = static::getDatabase()->getDocument('city', 'city1'); $this->assertEquals(true, $library->isEmpty()); // Delete child, will delete parent for two-way - $this->getDatabase()->deleteDocument('city', 'city7'); + static::getDatabase()->deleteDocument('city', 'city7'); // Check parent and child were deleted - $library = $this->getDatabase()->getDocument('city', 'city7'); + $library = static::getDatabase()->getDocument('city', 'city7'); $this->assertEquals(true, $library->isEmpty()); - $library = $this->getDatabase()->getDocument('country', 'country2'); + $library = static::getDatabase()->getDocument('country', 'country2'); $this->assertEquals(true, $library->isEmpty()); // Create new document to check after deleting relationship - $this->getDatabase()->createDocument('city', new Document([ + static::getDatabase()->createDocument('city', new Document([ '$id' => 'city7', '$permissions' => [ Permission::read(Role::any()), @@ -7353,33 +7746,33 @@ public function testOneToOneTwoWayRelationship(): void ])); // Delete relationship - $this->getDatabase()->deleteRelationship( + static::getDatabase()->deleteRelationship( 'country', 'newCity' ); // Try to get document again - $country = $this->getDatabase()->getDocument('country', 'country4'); + $country = static::getDatabase()->getDocument('country', 'country4'); $city = $country->getAttribute('newCity'); $this->assertEquals(null, $city); // Try to get inverse document again - $city = $this->getDatabase()->getDocument('city', 'city7'); + $city = static::getDatabase()->getDocument('city', 'city7'); $country = $city->getAttribute('newCountry'); $this->assertEquals(null, $country); } public function testIdenticalTwoWayKeyRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('parent'); - $this->getDatabase()->createCollection('child'); + static::getDatabase()->createCollection('parent'); + static::getDatabase()->createCollection('child'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'parent', relatedCollection: 'child', type: Database::RELATION_ONE_TO_ONE, @@ -7387,7 +7780,7 @@ public function testIdenticalTwoWayKeyRelationship(): void ); try { - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'parent', relatedCollection: 'child', type: Database::RELATION_ONE_TO_MANY, @@ -7398,7 +7791,7 @@ public function testIdenticalTwoWayKeyRelationship(): void $this->assertEquals('Related attribute already exists', $e->getMessage()); } - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'parent', relatedCollection: 'child', type: Database::RELATION_ONE_TO_MANY, @@ -7406,7 +7799,7 @@ public function testIdenticalTwoWayKeyRelationship(): void twoWayKey: 'parent_id' ); - $collection = $this->getDatabase()->getCollection('parent'); + $collection = static::getDatabase()->getCollection('parent'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'child1') { @@ -7418,7 +7811,7 @@ public function testIdenticalTwoWayKeyRelationship(): void } } - $this->getDatabase()->createDocument('parent', new Document([ + static::getDatabase()->createDocument('parent', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::update(Role::any()), @@ -7436,7 +7829,7 @@ public function testIdenticalTwoWayKeyRelationship(): void ], ])); - $documents = $this->getDatabase()->find('parent', []); + $documents = static::getDatabase()->find('parent', []); $document = array_pop($documents); $this->assertArrayHasKey('child1', $document); $this->assertEquals('foo', $document->getAttribute('child1')->getId()); @@ -7444,7 +7837,7 @@ public function testIdenticalTwoWayKeyRelationship(): void $this->assertEquals('bar', $document->getAttribute('children')[0]->getId()); try { - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'parent', id: 'children', newKey: 'child1' @@ -7455,7 +7848,7 @@ public function testIdenticalTwoWayKeyRelationship(): void } try { - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'parent', id: 'children', newTwoWayKey: 'parent' @@ -7468,19 +7861,19 @@ public function testIdenticalTwoWayKeyRelationship(): void public function testOneToManyOneWayRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('artist'); - $this->getDatabase()->createCollection('album'); + static::getDatabase()->createCollection('artist'); + static::getDatabase()->createCollection('album'); - $this->getDatabase()->createAttribute('artist', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('album', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('album', 'price', Database::VAR_FLOAT, 0, true); + static::getDatabase()->createAttribute('artist', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('album', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('album', 'price', Database::VAR_FLOAT, 0, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'artist', relatedCollection: 'album', type: Database::RELATION_ONE_TO_MANY, @@ -7488,7 +7881,7 @@ public function testOneToManyOneWayRelationship(): void ); // Check metadata for collection - $collection = $this->getDatabase()->getCollection('artist'); + $collection = static::getDatabase()->getCollection('artist'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { @@ -7504,7 +7897,7 @@ public function testOneToManyOneWayRelationship(): void } // Create document with relationship with nested data - $artist1 = $this->getDatabase()->createDocument('artist', new Document([ + $artist1 = static::getDatabase()->createDocument('artist', new Document([ '$id' => 'artist1', '$permissions' => [ Permission::read(Role::any()), @@ -7526,14 +7919,14 @@ public function testOneToManyOneWayRelationship(): void ])); // Update a document with non existing related document. It should not get added to the list. - $this->getDatabase()->updateDocument('artist', 'artist1', $artist1->setAttribute('albums', ['album1', 'no-album'])); + static::getDatabase()->updateDocument('artist', 'artist1', $artist1->setAttribute('albums', ['album1', 'no-album'])); - $artist1Document = $this->getDatabase()->getDocument('artist', 'artist1'); + $artist1Document = static::getDatabase()->getDocument('artist', 'artist1'); // Assert document does not contain non existing relation document. $this->assertEquals(1, \count($artist1Document->getAttribute('albums'))); // Create document with relationship with related ID - $this->getDatabase()->createDocument('album', new Document([ + static::getDatabase()->createDocument('album', new Document([ '$id' => 'album2', '$permissions' => [ Permission::read(Role::any()), @@ -7543,7 +7936,7 @@ public function testOneToManyOneWayRelationship(): void 'name' => 'Album 2', 'price' => 19.99, ])); - $this->getDatabase()->createDocument('artist', new Document([ + static::getDatabase()->createDocument('artist', new Document([ '$id' => 'artist2', '$permissions' => [ Permission::read(Role::any()), @@ -7565,19 +7958,19 @@ public function testOneToManyOneWayRelationship(): void ] ])); - $documents = $this->getDatabase()->find('artist', [ + $documents = static::getDatabase()->find('artist', [ Query::select(['name']), Query::limit(1) ]); $this->assertArrayNotHasKey('albums', $documents[0]); // Get document with relationship - $artist = $this->getDatabase()->getDocument('artist', 'artist1'); + $artist = static::getDatabase()->getDocument('artist', 'artist1'); $albums = $artist->getAttribute('albums', []); $this->assertEquals('album1', $albums[0]['$id']); $this->assertArrayNotHasKey('artist', $albums[0]); - $artist = $this->getDatabase()->getDocument('artist', 'artist2'); + $artist = static::getDatabase()->getDocument('artist', 'artist2'); $albums = $artist->getAttribute('albums', []); $this->assertEquals('album2', $albums[0]['$id']); $this->assertArrayNotHasKey('artist', $albums[0]); @@ -7585,18 +7978,18 @@ public function testOneToManyOneWayRelationship(): void $this->assertCount(2, $albums); // Get related document - $album = $this->getDatabase()->getDocument('album', 'album1'); + $album = static::getDatabase()->getDocument('album', 'album1'); $this->assertArrayNotHasKey('artist', $album); - $album = $this->getDatabase()->getDocument('album', 'album2'); + $album = static::getDatabase()->getDocument('album', 'album2'); $this->assertArrayNotHasKey('artist', $album); - $artists = $this->getDatabase()->find('artist'); + $artists = static::getDatabase()->find('artist'); $this->assertEquals(2, \count($artists)); // Select related document attributes - $artist = $this->getDatabase()->findOne('artist', [ + $artist = static::getDatabase()->findOne('artist', [ Query::select(['*', 'albums.name']) ]); @@ -7607,7 +8000,7 @@ public function testOneToManyOneWayRelationship(): void $this->assertEquals('Album 1', $artist->getAttribute('albums')[0]->getAttribute('name')); $this->assertArrayNotHasKey('price', $artist->getAttribute('albums')[0]); - $artist = $this->getDatabase()->getDocument('artist', 'artist1', [ + $artist = static::getDatabase()->getDocument('artist', 'artist1', [ Query::select(['*', 'albums.name']) ]); @@ -7615,43 +8008,43 @@ public function testOneToManyOneWayRelationship(): void $this->assertArrayNotHasKey('price', $artist->getAttribute('albums')[0]); // Update root document attribute without altering relationship - $artist1 = $this->getDatabase()->updateDocument( + $artist1 = static::getDatabase()->updateDocument( 'artist', $artist1->getId(), $artist1->setAttribute('name', 'Artist 1 Updated') ); $this->assertEquals('Artist 1 Updated', $artist1->getAttribute('name')); - $artist1 = $this->getDatabase()->getDocument('artist', 'artist1'); + $artist1 = static::getDatabase()->getDocument('artist', 'artist1'); $this->assertEquals('Artist 1 Updated', $artist1->getAttribute('name')); // Update nested document attribute $albums = $artist1->getAttribute('albums', []); $albums[0]->setAttribute('name', 'Album 1 Updated'); - $artist1 = $this->getDatabase()->updateDocument( + $artist1 = static::getDatabase()->updateDocument( 'artist', $artist1->getId(), $artist1->setAttribute('albums', $albums) ); $this->assertEquals('Album 1 Updated', $artist1->getAttribute('albums')[0]->getAttribute('name')); - $artist1 = $this->getDatabase()->getDocument('artist', 'artist1'); + $artist1 = static::getDatabase()->getDocument('artist', 'artist1'); $this->assertEquals('Album 1 Updated', $artist1->getAttribute('albums')[0]->getAttribute('name')); $albumId = $artist1->getAttribute('albums')[0]->getAttribute('$id'); - $albumDocument = $this->getDatabase()->getDocument('album', $albumId); + $albumDocument = static::getDatabase()->getDocument('album', $albumId); $albumDocument->setAttribute('name', 'Album 1 Updated!!!'); - $this->getDatabase()->updateDocument('album', $albumDocument->getId(), $albumDocument); - $albumDocument = $this->getDatabase()->getDocument('album', $albumDocument->getId()); - $artist1 = $this->getDatabase()->getDocument('artist', $artist1->getId()); + static::getDatabase()->updateDocument('album', $albumDocument->getId(), $albumDocument); + $albumDocument = static::getDatabase()->getDocument('album', $albumDocument->getId()); + $artist1 = static::getDatabase()->getDocument('artist', $artist1->getId()); $this->assertEquals('Album 1 Updated!!!', $albumDocument['name']); $this->assertEquals($albumDocument->getId(), $artist1->getAttribute('albums')[0]->getId()); $this->assertEquals($albumDocument->getAttribute('name'), $artist1->getAttribute('albums')[0]->getAttribute('name')); // Create new document with no relationship - $artist3 = $this->getDatabase()->createDocument('artist', new Document([ + $artist3 = static::getDatabase()->createDocument('artist', new Document([ '$id' => 'artist3', '$permissions' => [ Permission::read(Role::any()), @@ -7662,7 +8055,7 @@ public function testOneToManyOneWayRelationship(): void ])); // Update to relate to created document - $artist3 = $this->getDatabase()->updateDocument( + $artist3 = static::getDatabase()->updateDocument( 'artist', $artist3->getId(), $artist3->setAttribute('albums', [new Document([ @@ -7678,37 +8071,37 @@ public function testOneToManyOneWayRelationship(): void ); $this->assertEquals('Album 3', $artist3->getAttribute('albums')[0]->getAttribute('name')); - $artist3 = $this->getDatabase()->getDocument('artist', 'artist3'); + $artist3 = static::getDatabase()->getDocument('artist', 'artist3'); $this->assertEquals('Album 3', $artist3->getAttribute('albums')[0]->getAttribute('name')); // Update document with new related documents, will remove existing relations - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'artist', $artist1->getId(), $artist1->setAttribute('albums', ['album2']) ); // Update document with new related documents, will remove existing relations - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'artist', $artist1->getId(), $artist1->setAttribute('albums', ['album1', 'album2']) ); // Rename relationship key - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( 'artist', 'albums', 'newAlbums' ); // Get document with new relationship key - $artist = $this->getDatabase()->getDocument('artist', 'artist1'); + $artist = static::getDatabase()->getDocument('artist', 'artist1'); $albums = $artist->getAttribute('newAlbums'); $this->assertEquals('album1', $albums[0]['$id']); // Create new document with no relationship - $this->getDatabase()->createDocument('artist', new Document([ + static::getDatabase()->createDocument('artist', new Document([ '$id' => 'artist4', '$permissions' => [ Permission::read(Role::any()), @@ -7719,56 +8112,56 @@ public function testOneToManyOneWayRelationship(): void ])); // Can delete document with no relationship when on delete is set to restrict - $deleted = $this->getDatabase()->deleteDocument('artist', 'artist4'); + $deleted = static::getDatabase()->deleteDocument('artist', 'artist4'); $this->assertEquals(true, $deleted); - $artist4 = $this->getDatabase()->getDocument('artist', 'artist4'); + $artist4 = static::getDatabase()->getDocument('artist', 'artist4'); $this->assertEquals(true, $artist4->isEmpty()); // Try to delete document while still related to another with on delete: restrict try { - $this->getDatabase()->deleteDocument('artist', 'artist1'); + static::getDatabase()->deleteDocument('artist', 'artist1'); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } // Change on delete to set null - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'artist', id: 'newAlbums', onDelete: Database::RELATION_MUTATE_SET_NULL ); // Delete parent, set child relationship to null - $this->getDatabase()->deleteDocument('artist', 'artist1'); + static::getDatabase()->deleteDocument('artist', 'artist1'); // Check relation was set to null - $album2 = $this->getDatabase()->getDocument('album', 'album2'); + $album2 = static::getDatabase()->getDocument('album', 'album2'); $this->assertEquals(null, $album2->getAttribute('artist', '')); // Relate again - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'album', $album2->getId(), $album2->setAttribute('artist', 'artist2') ); // Change on delete to cascade - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'artist', id: 'newAlbums', onDelete: Database::RELATION_MUTATE_CASCADE ); // Delete parent, will delete child - $this->getDatabase()->deleteDocument('artist', 'artist2'); + static::getDatabase()->deleteDocument('artist', 'artist2'); // Check parent and child were deleted - $library = $this->getDatabase()->getDocument('artist', 'artist2'); + $library = static::getDatabase()->getDocument('artist', 'artist2'); $this->assertEquals(true, $library->isEmpty()); - $library = $this->getDatabase()->getDocument('album', 'album2'); + $library = static::getDatabase()->getDocument('album', 'album2'); $this->assertEquals(true, $library->isEmpty()); $albums = []; @@ -7785,7 +8178,7 @@ public function testOneToManyOneWayRelationship(): void ]; } - $artist = $this->getDatabase()->createDocument('artist', new Document([ + $artist = static::getDatabase()->createDocument('artist', new Document([ '$permissions' => [ Permission::read(Role::any()), Permission::delete(Role::any()), @@ -7794,29 +8187,29 @@ public function testOneToManyOneWayRelationship(): void 'newAlbums' => $albums ])); - $artist = $this->getDatabase()->getDocument('artist', $artist->getId()); + $artist = static::getDatabase()->getDocument('artist', $artist->getId()); $this->assertCount(50, $artist->getAttribute('newAlbums')); - $albums = $this->getDatabase()->find('album', [ + $albums = static::getDatabase()->find('album', [ Query::equal('artist', [$artist->getId()]), Query::limit(999) ]); $this->assertCount(50, $albums); - $count = $this->getDatabase()->count('album', [ + $count = static::getDatabase()->count('album', [ Query::equal('artist', [$artist->getId()]), ]); $this->assertEquals(50, $count); - $this->getDatabase()->deleteDocument('album', 'album_1'); - $artist = $this->getDatabase()->getDocument('artist', $artist->getId()); + static::getDatabase()->deleteDocument('album', 'album_1'); + $artist = static::getDatabase()->getDocument('artist', $artist->getId()); $this->assertCount(49, $artist->getAttribute('newAlbums')); - $this->getDatabase()->deleteDocument('artist', $artist->getId()); + static::getDatabase()->deleteDocument('artist', $artist->getId()); - $albums = $this->getDatabase()->find('album', [ + $albums = static::getDatabase()->find('album', [ Query::equal('artist', [$artist->getId()]), Query::limit(999) ]); @@ -7824,32 +8217,32 @@ public function testOneToManyOneWayRelationship(): void $this->assertCount(0, $albums); // Delete relationship - $this->getDatabase()->deleteRelationship( + static::getDatabase()->deleteRelationship( 'artist', 'newAlbums' ); // Try to get document again - $artist = $this->getDatabase()->getDocument('artist', 'artist1'); + $artist = static::getDatabase()->getDocument('artist', 'artist1'); $albums = $artist->getAttribute('newAlbums', ''); $this->assertEquals(null, $albums); } public function testOneToManyTwoWayRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('customer'); - $this->getDatabase()->createCollection('account'); + static::getDatabase()->createCollection('customer'); + static::getDatabase()->createCollection('account'); - $this->getDatabase()->createAttribute('customer', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('account', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('account', 'number', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('customer', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('account', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('account', 'number', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'customer', relatedCollection: 'account', type: Database::RELATION_ONE_TO_MANY, @@ -7858,7 +8251,7 @@ public function testOneToManyTwoWayRelationship(): void ); // Check metadata for collection - $collection = $this->getDatabase()->getCollection('customer'); + $collection = static::getDatabase()->getCollection('customer'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'accounts') { @@ -7873,7 +8266,7 @@ public function testOneToManyTwoWayRelationship(): void } // Check metadata for related collection - $collection = $this->getDatabase()->getCollection('account'); + $collection = static::getDatabase()->getCollection('account'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'customer') { @@ -7888,7 +8281,7 @@ public function testOneToManyTwoWayRelationship(): void } // Create document with relationship with nested data - $customer1 = $this->getDatabase()->createDocument('customer', new Document([ + $customer1 = static::getDatabase()->createDocument('customer', new Document([ '$id' => 'customer1', '$permissions' => [ Permission::read(Role::any()), @@ -7911,14 +8304,14 @@ public function testOneToManyTwoWayRelationship(): void ])); // Update a document with non existing related document. It should not get added to the list. - $this->getDatabase()->updateDocument('customer', 'customer1', $customer1->setAttribute('accounts', ['account1','no-account'])); + static::getDatabase()->updateDocument('customer', 'customer1', $customer1->setAttribute('accounts', ['account1','no-account'])); - $customer1Document = $this->getDatabase()->getDocument('customer', 'customer1'); + $customer1Document = static::getDatabase()->getDocument('customer', 'customer1'); // Assert document does not contain non existing relation document. $this->assertEquals(1, \count($customer1Document->getAttribute('accounts'))); // Create document with relationship with related ID - $account2 = $this->getDatabase()->createDocument('account', new Document([ + $account2 = static::getDatabase()->createDocument('account', new Document([ '$id' => 'account2', '$permissions' => [ Permission::read(Role::any()), @@ -7928,7 +8321,7 @@ public function testOneToManyTwoWayRelationship(): void 'name' => 'Account 2', 'number' => '987654321', ])); - $this->getDatabase()->createDocument('customer', new Document([ + static::getDatabase()->createDocument('customer', new Document([ '$id' => 'customer2', '$permissions' => [ Permission::read(Role::any()), @@ -7942,7 +8335,7 @@ public function testOneToManyTwoWayRelationship(): void ])); // Create from child side - $this->getDatabase()->createDocument('account', new Document([ + static::getDatabase()->createDocument('account', new Document([ '$id' => 'account3', '$permissions' => [ Permission::read(Role::any()), @@ -7961,7 +8354,7 @@ public function testOneToManyTwoWayRelationship(): void 'name' => 'Customer 3' ] ])); - $this->getDatabase()->createDocument('customer', new Document([ + static::getDatabase()->createDocument('customer', new Document([ '$id' => 'customer4', '$permissions' => [ Permission::read(Role::any()), @@ -7970,7 +8363,7 @@ public function testOneToManyTwoWayRelationship(): void ], 'name' => 'Customer 4', ])); - $this->getDatabase()->createDocument('account', new Document([ + static::getDatabase()->createDocument('account', new Document([ '$id' => 'account4', '$permissions' => [ Permission::read(Role::any()), @@ -7983,53 +8376,53 @@ public function testOneToManyTwoWayRelationship(): void ])); // Get documents with relationship - $customer = $this->getDatabase()->getDocument('customer', 'customer1'); + $customer = static::getDatabase()->getDocument('customer', 'customer1'); $accounts = $customer->getAttribute('accounts', []); $this->assertEquals('account1', $accounts[0]['$id']); $this->assertArrayNotHasKey('customer', $accounts[0]); - $customer = $this->getDatabase()->getDocument('customer', 'customer2'); + $customer = static::getDatabase()->getDocument('customer', 'customer2'); $accounts = $customer->getAttribute('accounts', []); $this->assertEquals('account2', $accounts[0]['$id']); $this->assertArrayNotHasKey('customer', $accounts[0]); - $customer = $this->getDatabase()->getDocument('customer', 'customer3'); + $customer = static::getDatabase()->getDocument('customer', 'customer3'); $accounts = $customer->getAttribute('accounts', []); $this->assertEquals('account3', $accounts[0]['$id']); $this->assertArrayNotHasKey('customer', $accounts[0]); - $customer = $this->getDatabase()->getDocument('customer', 'customer4'); + $customer = static::getDatabase()->getDocument('customer', 'customer4'); $accounts = $customer->getAttribute('accounts', []); $this->assertEquals('account4', $accounts[0]['$id']); $this->assertArrayNotHasKey('customer', $accounts[0]); // Get related documents - $account = $this->getDatabase()->getDocument('account', 'account1'); + $account = static::getDatabase()->getDocument('account', 'account1'); $customer = $account->getAttribute('customer'); $this->assertEquals('customer1', $customer['$id']); $this->assertArrayNotHasKey('accounts', $customer); - $account = $this->getDatabase()->getDocument('account', 'account2'); + $account = static::getDatabase()->getDocument('account', 'account2'); $customer = $account->getAttribute('customer'); $this->assertEquals('customer2', $customer['$id']); $this->assertArrayNotHasKey('accounts', $customer); - $account = $this->getDatabase()->getDocument('account', 'account3'); + $account = static::getDatabase()->getDocument('account', 'account3'); $customer = $account->getAttribute('customer'); $this->assertEquals('customer3', $customer['$id']); $this->assertArrayNotHasKey('accounts', $customer); - $account = $this->getDatabase()->getDocument('account', 'account4'); + $account = static::getDatabase()->getDocument('account', 'account4'); $customer = $account->getAttribute('customer'); $this->assertEquals('customer4', $customer['$id']); $this->assertArrayNotHasKey('accounts', $customer); - $customers = $this->getDatabase()->find('customer'); + $customers = static::getDatabase()->find('customer'); $this->assertEquals(4, \count($customers)); // Select related document attributes - $customer = $this->getDatabase()->findOne('customer', [ + $customer = static::getDatabase()->findOne('customer', [ Query::select(['*', 'accounts.name']) ]); @@ -8040,7 +8433,7 @@ public function testOneToManyTwoWayRelationship(): void $this->assertEquals('Account 1', $customer->getAttribute('accounts')[0]->getAttribute('name')); $this->assertArrayNotHasKey('number', $customer->getAttribute('accounts')[0]); - $customer = $this->getDatabase()->getDocument('customer', 'customer1', [ + $customer = static::getDatabase()->getDocument('customer', 'customer1', [ Query::select(['*', 'accounts.name']) ]); @@ -8048,61 +8441,61 @@ public function testOneToManyTwoWayRelationship(): void $this->assertArrayNotHasKey('number', $customer->getAttribute('accounts')[0]); // Update root document attribute without altering relationship - $customer1 = $this->getDatabase()->updateDocument( + $customer1 = static::getDatabase()->updateDocument( 'customer', $customer1->getId(), $customer1->setAttribute('name', 'Customer 1 Updated') ); $this->assertEquals('Customer 1 Updated', $customer1->getAttribute('name')); - $customer1 = $this->getDatabase()->getDocument('customer', 'customer1'); + $customer1 = static::getDatabase()->getDocument('customer', 'customer1'); $this->assertEquals('Customer 1 Updated', $customer1->getAttribute('name')); - $account2 = $this->getDatabase()->getDocument('account', 'account2'); + $account2 = static::getDatabase()->getDocument('account', 'account2'); // Update inverse root document attribute without altering relationship - $account2 = $this->getDatabase()->updateDocument( + $account2 = static::getDatabase()->updateDocument( 'account', $account2->getId(), $account2->setAttribute('name', 'Account 2 Updated') ); $this->assertEquals('Account 2 Updated', $account2->getAttribute('name')); - $account2 = $this->getDatabase()->getDocument('account', 'account2'); + $account2 = static::getDatabase()->getDocument('account', 'account2'); $this->assertEquals('Account 2 Updated', $account2->getAttribute('name')); // Update nested document attribute $accounts = $customer1->getAttribute('accounts', []); $accounts[0]->setAttribute('name', 'Account 1 Updated'); - $customer1 = $this->getDatabase()->updateDocument( + $customer1 = static::getDatabase()->updateDocument( 'customer', $customer1->getId(), $customer1->setAttribute('accounts', $accounts) ); $this->assertEquals('Account 1 Updated', $customer1->getAttribute('accounts')[0]->getAttribute('name')); - $customer1 = $this->getDatabase()->getDocument('customer', 'customer1'); + $customer1 = static::getDatabase()->getDocument('customer', 'customer1'); $this->assertEquals('Account 1 Updated', $customer1->getAttribute('accounts')[0]->getAttribute('name')); // Update inverse nested document attribute - $account2 = $this->getDatabase()->updateDocument( + $account2 = static::getDatabase()->updateDocument( 'account', $account2->getId(), $account2->setAttribute( 'customer', $account2 - ->getAttribute('customer') - ->setAttribute('name', 'Customer 2 Updated') + ->getAttribute('customer') + ->setAttribute('name', 'Customer 2 Updated') ) ); $this->assertEquals('Customer 2 Updated', $account2->getAttribute('customer')->getAttribute('name')); - $account2 = $this->getDatabase()->getDocument('account', 'account2'); + $account2 = static::getDatabase()->getDocument('account', 'account2'); $this->assertEquals('Customer 2 Updated', $account2->getAttribute('customer')->getAttribute('name')); // Create new document with no relationship - $customer5 = $this->getDatabase()->createDocument('customer', new Document([ + $customer5 = static::getDatabase()->createDocument('customer', new Document([ '$id' => 'customer5', '$permissions' => [ Permission::read(Role::any()), @@ -8113,7 +8506,7 @@ public function testOneToManyTwoWayRelationship(): void ])); // Update to relate to created document - $customer5 = $this->getDatabase()->updateDocument( + $customer5 = static::getDatabase()->updateDocument( 'customer', $customer5->getId(), $customer5->setAttribute('accounts', [new Document([ @@ -8129,11 +8522,11 @@ public function testOneToManyTwoWayRelationship(): void ); $this->assertEquals('Account 5', $customer5->getAttribute('accounts')[0]->getAttribute('name')); - $customer5 = $this->getDatabase()->getDocument('customer', 'customer5'); + $customer5 = static::getDatabase()->getDocument('customer', 'customer5'); $this->assertEquals('Account 5', $customer5->getAttribute('accounts')[0]->getAttribute('name')); // Create new child document with no relationship - $account6 = $this->getDatabase()->createDocument('account', new Document([ + $account6 = static::getDatabase()->createDocument('account', new Document([ '$id' => 'account6', '$permissions' => [ Permission::read(Role::any()), @@ -8145,7 +8538,7 @@ public function testOneToManyTwoWayRelationship(): void ])); // Update inverse to relate to created document - $account6 = $this->getDatabase()->updateDocument( + $account6 = static::getDatabase()->updateDocument( 'account', $account6->getId(), $account6->setAttribute('customer', new Document([ @@ -8160,32 +8553,32 @@ public function testOneToManyTwoWayRelationship(): void ); $this->assertEquals('Customer 6', $account6->getAttribute('customer')->getAttribute('name')); - $account6 = $this->getDatabase()->getDocument('account', 'account6'); + $account6 = static::getDatabase()->getDocument('account', 'account6'); $this->assertEquals('Customer 6', $account6->getAttribute('customer')->getAttribute('name')); // Update document with new related document, will remove existing relations - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'customer', $customer1->getId(), $customer1->setAttribute('accounts', ['account2']) ); // Update document with new related document - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'customer', $customer1->getId(), $customer1->setAttribute('accounts', ['account1', 'account2']) ); // Update inverse document - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'account', $account2->getId(), $account2->setAttribute('customer', 'customer2') ); // Rename relationship keys on both sides - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( 'customer', 'accounts', 'newAccounts', @@ -8193,17 +8586,17 @@ public function testOneToManyTwoWayRelationship(): void ); // Get document with new relationship key - $customer = $this->getDatabase()->getDocument('customer', 'customer1'); + $customer = static::getDatabase()->getDocument('customer', 'customer1'); $accounts = $customer->getAttribute('newAccounts'); $this->assertEquals('account1', $accounts[0]['$id']); // Get inverse document with new relationship key - $account = $this->getDatabase()->getDocument('account', 'account1'); + $account = static::getDatabase()->getDocument('account', 'account1'); $customer = $account->getAttribute('newCustomer'); $this->assertEquals('customer1', $customer['$id']); // Create new document with no relationship - $this->getDatabase()->createDocument('customer', new Document([ + static::getDatabase()->createDocument('customer', new Document([ '$id' => 'customer7', '$permissions' => [ Permission::read(Role::any()), @@ -8214,91 +8607,91 @@ public function testOneToManyTwoWayRelationship(): void ])); // Can delete document with no relationship when on delete is set to restrict - $deleted = $this->getDatabase()->deleteDocument('customer', 'customer7'); + $deleted = static::getDatabase()->deleteDocument('customer', 'customer7'); $this->assertEquals(true, $deleted); - $customer7 = $this->getDatabase()->getDocument('customer', 'customer7'); + $customer7 = static::getDatabase()->getDocument('customer', 'customer7'); $this->assertEquals(true, $customer7->isEmpty()); // Try to delete document while still related to another with on delete: restrict try { - $this->getDatabase()->deleteDocument('customer', 'customer1'); + static::getDatabase()->deleteDocument('customer', 'customer1'); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } // Change on delete to set null - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'customer', id: 'newAccounts', onDelete: Database::RELATION_MUTATE_SET_NULL ); // Delete parent, set child relationship to null - $this->getDatabase()->deleteDocument('customer', 'customer1'); + static::getDatabase()->deleteDocument('customer', 'customer1'); // Check relation was set to null - $account1 = $this->getDatabase()->getDocument('account', 'account1'); + $account1 = static::getDatabase()->getDocument('account', 'account1'); $this->assertEquals(null, $account2->getAttribute('newCustomer', '')); // Relate again - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'account', $account1->getId(), $account1->setAttribute('newCustomer', 'customer2') ); // Change on delete to cascade - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'customer', id: 'newAccounts', onDelete: Database::RELATION_MUTATE_CASCADE ); // Delete parent, will delete child - $this->getDatabase()->deleteDocument('customer', 'customer2'); + static::getDatabase()->deleteDocument('customer', 'customer2'); // Check parent and child were deleted - $library = $this->getDatabase()->getDocument('customer', 'customer2'); + $library = static::getDatabase()->getDocument('customer', 'customer2'); $this->assertEquals(true, $library->isEmpty()); - $library = $this->getDatabase()->getDocument('account', 'account2'); + $library = static::getDatabase()->getDocument('account', 'account2'); $this->assertEquals(true, $library->isEmpty()); // Delete relationship - $this->getDatabase()->deleteRelationship( + static::getDatabase()->deleteRelationship( 'customer', 'newAccounts' ); // Try to get document again - $customer = $this->getDatabase()->getDocument('customer', 'customer1'); + $customer = static::getDatabase()->getDocument('customer', 'customer1'); $accounts = $customer->getAttribute('newAccounts'); $this->assertEquals(null, $accounts); // Try to get inverse document again - $accounts = $this->getDatabase()->getDocument('account', 'account1'); + $accounts = static::getDatabase()->getDocument('account', 'account1'); $customer = $accounts->getAttribute('newCustomer'); $this->assertEquals(null, $customer); } public function testManyToOneOneWayRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('review'); - $this->getDatabase()->createCollection('movie'); + static::getDatabase()->createCollection('review'); + static::getDatabase()->createCollection('movie'); - $this->getDatabase()->createAttribute('review', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('movie', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('movie', 'length', Database::VAR_INTEGER, 0, true, formatOptions: ['min' => 0, 'max' => 999]); - $this->getDatabase()->createAttribute('movie', 'date', Database::VAR_DATETIME, 0, false, filters: ['datetime']); - $this->getDatabase()->createAttribute('review', 'date', Database::VAR_DATETIME, 0, false, filters: ['datetime']); - $this->getDatabase()->createRelationship( + static::getDatabase()->createAttribute('review', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('movie', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('movie', 'length', Database::VAR_INTEGER, 0, true, formatOptions: ['min' => 0, 'max' => 999]); + static::getDatabase()->createAttribute('movie', 'date', Database::VAR_DATETIME, 0, false, filters: ['datetime']); + static::getDatabase()->createAttribute('review', 'date', Database::VAR_DATETIME, 0, false, filters: ['datetime']); + static::getDatabase()->createRelationship( collection: 'review', relatedCollection: 'movie', type: Database::RELATION_MANY_TO_ONE, @@ -8306,7 +8699,7 @@ public function testManyToOneOneWayRelationship(): void ); // Check metadata for collection - $collection = $this->getDatabase()->getCollection('review'); + $collection = static::getDatabase()->getCollection('review'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'movie') { @@ -8321,7 +8714,7 @@ public function testManyToOneOneWayRelationship(): void } // Check metadata for related collection - $collection = $this->getDatabase()->getCollection('movie'); + $collection = static::getDatabase()->getCollection('movie'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'reviews') { @@ -8336,7 +8729,7 @@ public function testManyToOneOneWayRelationship(): void } // Create document with relationship with nested data - $review1 = $this->getDatabase()->createDocument('review', new Document([ + $review1 = static::getDatabase()->createDocument('review', new Document([ '$id' => 'review1', '$permissions' => [ Permission::read(Role::any()), @@ -8359,16 +8752,16 @@ public function testManyToOneOneWayRelationship(): void ])); // Update a document with non existing related document. It should not get added to the list. - $this->getDatabase()->updateDocument('review', 'review1', $review1->setAttribute('movie', 'no-movie')); + static::getDatabase()->updateDocument('review', 'review1', $review1->setAttribute('movie', 'no-movie')); - $review1Document = $this->getDatabase()->getDocument('review', 'review1'); + $review1Document = static::getDatabase()->getDocument('review', 'review1'); // Assert document does not contain non existing relation document. $this->assertEquals(null, $review1Document->getAttribute('movie')); - $this->getDatabase()->updateDocument('review', 'review1', $review1->setAttribute('movie', 'movie1')); + static::getDatabase()->updateDocument('review', 'review1', $review1->setAttribute('movie', 'movie1')); // Create document with relationship to existing document by ID - $review10 = $this->getDatabase()->createDocument('review', new Document([ + $review10 = static::getDatabase()->createDocument('review', new Document([ '$id' => 'review10', '$permissions' => [ Permission::read(Role::any()), @@ -8381,7 +8774,7 @@ public function testManyToOneOneWayRelationship(): void ])); // Create document with relationship with related ID - $this->getDatabase()->createDocument('movie', new Document([ + static::getDatabase()->createDocument('movie', new Document([ '$id' => 'movie2', '$permissions' => [ Permission::read(Role::any()), @@ -8392,7 +8785,7 @@ public function testManyToOneOneWayRelationship(): void 'length' => 90, 'date' => '2023-04-03 10:35:27.390', ])); - $this->getDatabase()->createDocument('review', new Document([ + static::getDatabase()->createDocument('review', new Document([ '$id' => 'review2', '$permissions' => [ Permission::read(Role::any()), @@ -8405,12 +8798,12 @@ public function testManyToOneOneWayRelationship(): void ])); // Get document with relationship - $review = $this->getDatabase()->getDocument('review', 'review1'); + $review = static::getDatabase()->getDocument('review', 'review1'); $movie = $review->getAttribute('movie', []); $this->assertEquals('movie1', $movie['$id']); $this->assertArrayNotHasKey('reviews', $movie); - $documents = $this->getDatabase()->find('review', [ + $documents = static::getDatabase()->find('review', [ Query::select(['date', 'movie.date']) ]); @@ -8424,24 +8817,24 @@ public function testManyToOneOneWayRelationship(): void $this->assertEquals(29, strlen($document['date'])); // checks filter $this->assertEquals(29, strlen($document['movie']['date'])); - $review = $this->getDatabase()->getDocument('review', 'review2'); + $review = static::getDatabase()->getDocument('review', 'review2'); $movie = $review->getAttribute('movie', []); $this->assertEquals('movie2', $movie['$id']); $this->assertArrayNotHasKey('reviews', $movie); // Get related document - $movie = $this->getDatabase()->getDocument('movie', 'movie1'); + $movie = static::getDatabase()->getDocument('movie', 'movie1'); $this->assertArrayNotHasKey('reviews', $movie); - $movie = $this->getDatabase()->getDocument('movie', 'movie2'); + $movie = static::getDatabase()->getDocument('movie', 'movie2'); $this->assertArrayNotHasKey('reviews', $movie); - $reviews = $this->getDatabase()->find('review'); + $reviews = static::getDatabase()->find('review'); $this->assertEquals(3, \count($reviews)); // Select related document attributes - $review = $this->getDatabase()->findOne('review', [ + $review = static::getDatabase()->findOne('review', [ Query::select(['*', 'movie.name']) ]); @@ -8452,7 +8845,7 @@ public function testManyToOneOneWayRelationship(): void $this->assertEquals('Movie 1', $review->getAttribute('movie')->getAttribute('name')); $this->assertArrayNotHasKey('length', $review->getAttribute('movie')); - $review = $this->getDatabase()->getDocument('review', 'review1', [ + $review = static::getDatabase()->getDocument('review', 'review1', [ Query::select(['*', 'movie.name']) ]); @@ -8460,32 +8853,32 @@ public function testManyToOneOneWayRelationship(): void $this->assertArrayNotHasKey('length', $review->getAttribute('movie')); // Update root document attribute without altering relationship - $review1 = $this->getDatabase()->updateDocument( + $review1 = static::getDatabase()->updateDocument( 'review', $review1->getId(), $review1->setAttribute('name', 'Review 1 Updated') ); $this->assertEquals('Review 1 Updated', $review1->getAttribute('name')); - $review1 = $this->getDatabase()->getDocument('review', 'review1'); + $review1 = static::getDatabase()->getDocument('review', 'review1'); $this->assertEquals('Review 1 Updated', $review1->getAttribute('name')); // Update nested document attribute $movie = $review1->getAttribute('movie'); $movie->setAttribute('name', 'Movie 1 Updated'); - $review1 = $this->getDatabase()->updateDocument( + $review1 = static::getDatabase()->updateDocument( 'review', $review1->getId(), $review1->setAttribute('movie', $movie) ); $this->assertEquals('Movie 1 Updated', $review1->getAttribute('movie')->getAttribute('name')); - $review1 = $this->getDatabase()->getDocument('review', 'review1'); + $review1 = static::getDatabase()->getDocument('review', 'review1'); $this->assertEquals('Movie 1 Updated', $review1->getAttribute('movie')->getAttribute('name')); // Create new document with no relationship - $review5 = $this->getDatabase()->createDocument('review', new Document([ + $review5 = static::getDatabase()->createDocument('review', new Document([ '$id' => 'review5', '$permissions' => [ Permission::read(Role::any()), @@ -8496,7 +8889,7 @@ public function testManyToOneOneWayRelationship(): void ])); // Update to relate to created document - $review5 = $this->getDatabase()->updateDocument( + $review5 = static::getDatabase()->updateDocument( 'review', $review5->getId(), $review5->setAttribute('movie', new Document([ @@ -8512,39 +8905,39 @@ public function testManyToOneOneWayRelationship(): void ); $this->assertEquals('Movie 5', $review5->getAttribute('movie')->getAttribute('name')); - $review5 = $this->getDatabase()->getDocument('review', 'review5'); + $review5 = static::getDatabase()->getDocument('review', 'review5'); $this->assertEquals('Movie 5', $review5->getAttribute('movie')->getAttribute('name')); // Update document with new related document - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'review', $review1->getId(), $review1->setAttribute('movie', 'movie2') ); // Rename relationship keys on both sides - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( 'review', 'movie', 'newMovie', ); // Get document with new relationship key - $review = $this->getDatabase()->getDocument('review', 'review1'); + $review = static::getDatabase()->getDocument('review', 'review1'); $movie = $review->getAttribute('newMovie'); $this->assertEquals('movie2', $movie['$id']); // Reset values - $review1 = $this->getDatabase()->getDocument('review', 'review1'); + $review1 = static::getDatabase()->getDocument('review', 'review1'); - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'review', $review1->getId(), $review1->setAttribute('newMovie', 'movie1') ); // Create new document with no relationship - $this->getDatabase()->createDocument('movie', new Document([ + static::getDatabase()->createDocument('movie', new Document([ '$id' => 'movie3', '$permissions' => [ Permission::read(Role::any()), @@ -8556,78 +8949,78 @@ public function testManyToOneOneWayRelationship(): void ])); // Can delete document with no relationship when on delete is set to restrict - $deleted = $this->getDatabase()->deleteDocument('movie', 'movie3'); + $deleted = static::getDatabase()->deleteDocument('movie', 'movie3'); $this->assertEquals(true, $deleted); - $movie3 = $this->getDatabase()->getDocument('movie', 'movie3'); + $movie3 = static::getDatabase()->getDocument('movie', 'movie3'); $this->assertEquals(true, $movie3->isEmpty()); // Try to delete document while still related to another with on delete: restrict try { - $this->getDatabase()->deleteDocument('movie', 'movie1'); + static::getDatabase()->deleteDocument('movie', 'movie1'); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } // Change on delete to set null - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'review', id: 'newMovie', onDelete: Database::RELATION_MUTATE_SET_NULL ); // Delete child, set parent relationship to null - $this->getDatabase()->deleteDocument('movie', 'movie1'); + static::getDatabase()->deleteDocument('movie', 'movie1'); // Check relation was set to null - $review1 = $this->getDatabase()->getDocument('review', 'review1'); + $review1 = static::getDatabase()->getDocument('review', 'review1'); $this->assertEquals(null, $review1->getAttribute('newMovie')); // Change on delete to cascade - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'review', id: 'newMovie', onDelete: Database::RELATION_MUTATE_CASCADE ); // Delete child, will delete parent - $this->getDatabase()->deleteDocument('movie', 'movie2'); + static::getDatabase()->deleteDocument('movie', 'movie2'); // Check parent and child were deleted - $library = $this->getDatabase()->getDocument('movie', 'movie2'); + $library = static::getDatabase()->getDocument('movie', 'movie2'); $this->assertEquals(true, $library->isEmpty()); - $library = $this->getDatabase()->getDocument('review', 'review2'); + $library = static::getDatabase()->getDocument('review', 'review2'); $this->assertEquals(true, $library->isEmpty()); // Delete relationship - $this->getDatabase()->deleteRelationship( + static::getDatabase()->deleteRelationship( 'review', 'newMovie' ); // Try to get document again - $review = $this->getDatabase()->getDocument('review', 'review1'); + $review = static::getDatabase()->getDocument('review', 'review1'); $movie = $review->getAttribute('newMovie'); $this->assertEquals(null, $movie); } public function testManyToOneTwoWayRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('product'); - $this->getDatabase()->createCollection('store'); + static::getDatabase()->createCollection('product'); + static::getDatabase()->createCollection('store'); - $this->getDatabase()->createAttribute('store', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('store', 'opensAt', Database::VAR_STRING, 5, true); + static::getDatabase()->createAttribute('store', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('store', 'opensAt', Database::VAR_STRING, 5, true); - $this->getDatabase()->createAttribute( + static::getDatabase()->createAttribute( collection: 'product', id: 'name', type: Database::VAR_STRING, @@ -8635,7 +9028,7 @@ public function testManyToOneTwoWayRelationship(): void required: true ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'product', relatedCollection: 'store', type: Database::RELATION_MANY_TO_ONE, @@ -8644,7 +9037,7 @@ public function testManyToOneTwoWayRelationship(): void ); // Check metadata for collection - $collection = $this->getDatabase()->getCollection('product'); + $collection = static::getDatabase()->getCollection('product'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'store') { @@ -8659,7 +9052,7 @@ public function testManyToOneTwoWayRelationship(): void } // Check metadata for related collection - $collection = $this->getDatabase()->getCollection('store'); + $collection = static::getDatabase()->getCollection('store'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'products') { @@ -8674,7 +9067,7 @@ public function testManyToOneTwoWayRelationship(): void } // Create document with relationship with nested data - $product1 = $this->getDatabase()->createDocument('product', new Document([ + $product1 = static::getDatabase()->createDocument('product', new Document([ '$id' => 'product1', '$permissions' => [ Permission::read(Role::any()), @@ -8695,16 +9088,16 @@ public function testManyToOneTwoWayRelationship(): void ])); // Update a document with non existing related document. It should not get added to the list. - $this->getDatabase()->updateDocument('product', 'product1', $product1->setAttribute('store', 'no-store')); + static::getDatabase()->updateDocument('product', 'product1', $product1->setAttribute('store', 'no-store')); - $product1Document = $this->getDatabase()->getDocument('product', 'product1'); + $product1Document = static::getDatabase()->getDocument('product', 'product1'); // Assert document does not contain non existing relation document. $this->assertEquals(null, $product1Document->getAttribute('store')); - $this->getDatabase()->updateDocument('product', 'product1', $product1->setAttribute('store', 'store1')); + static::getDatabase()->updateDocument('product', 'product1', $product1->setAttribute('store', 'store1')); // Create document with relationship with related ID - $this->getDatabase()->createDocument('store', new Document([ + static::getDatabase()->createDocument('store', new Document([ '$id' => 'store2', '$permissions' => [ Permission::read(Role::any()), @@ -8714,7 +9107,7 @@ public function testManyToOneTwoWayRelationship(): void 'name' => 'Store 2', 'opensAt' => '09:30', ])); - $this->getDatabase()->createDocument('product', new Document([ + static::getDatabase()->createDocument('product', new Document([ '$id' => 'product2', '$permissions' => [ Permission::read(Role::any()), @@ -8726,7 +9119,7 @@ public function testManyToOneTwoWayRelationship(): void ])); // Create from child side - $this->getDatabase()->createDocument('store', new Document([ + static::getDatabase()->createDocument('store', new Document([ '$id' => 'store3', '$permissions' => [ Permission::read(Role::any()), @@ -8748,7 +9141,7 @@ public function testManyToOneTwoWayRelationship(): void ], ])); - $this->getDatabase()->createDocument('product', new Document([ + static::getDatabase()->createDocument('product', new Document([ '$id' => 'product4', '$permissions' => [ Permission::read(Role::any()), @@ -8757,7 +9150,7 @@ public function testManyToOneTwoWayRelationship(): void ], 'name' => 'Product 4', ])); - $this->getDatabase()->createDocument('store', new Document([ + static::getDatabase()->createDocument('store', new Document([ '$id' => 'store4', '$permissions' => [ Permission::read(Role::any()), @@ -8772,53 +9165,53 @@ public function testManyToOneTwoWayRelationship(): void ])); // Get document with relationship - $product = $this->getDatabase()->getDocument('product', 'product1'); + $product = static::getDatabase()->getDocument('product', 'product1'); $store = $product->getAttribute('store', []); $this->assertEquals('store1', $store['$id']); $this->assertArrayNotHasKey('products', $store); - $product = $this->getDatabase()->getDocument('product', 'product2'); + $product = static::getDatabase()->getDocument('product', 'product2'); $store = $product->getAttribute('store', []); $this->assertEquals('store2', $store['$id']); $this->assertArrayNotHasKey('products', $store); - $product = $this->getDatabase()->getDocument('product', 'product3'); + $product = static::getDatabase()->getDocument('product', 'product3'); $store = $product->getAttribute('store', []); $this->assertEquals('store3', $store['$id']); $this->assertArrayNotHasKey('products', $store); - $product = $this->getDatabase()->getDocument('product', 'product4'); + $product = static::getDatabase()->getDocument('product', 'product4'); $store = $product->getAttribute('store', []); $this->assertEquals('store4', $store['$id']); $this->assertArrayNotHasKey('products', $store); // Get related document - $store = $this->getDatabase()->getDocument('store', 'store1'); + $store = static::getDatabase()->getDocument('store', 'store1'); $products = $store->getAttribute('products'); $this->assertEquals('product1', $products[0]['$id']); $this->assertArrayNotHasKey('store', $products[0]); - $store = $this->getDatabase()->getDocument('store', 'store2'); + $store = static::getDatabase()->getDocument('store', 'store2'); $products = $store->getAttribute('products'); $this->assertEquals('product2', $products[0]['$id']); $this->assertArrayNotHasKey('store', $products[0]); - $store = $this->getDatabase()->getDocument('store', 'store3'); + $store = static::getDatabase()->getDocument('store', 'store3'); $products = $store->getAttribute('products'); $this->assertEquals('product3', $products[0]['$id']); $this->assertArrayNotHasKey('store', $products[0]); - $store = $this->getDatabase()->getDocument('store', 'store4'); + $store = static::getDatabase()->getDocument('store', 'store4'); $products = $store->getAttribute('products'); $this->assertEquals('product4', $products[0]['$id']); $this->assertArrayNotHasKey('store', $products[0]); - $products = $this->getDatabase()->find('product'); + $products = static::getDatabase()->find('product'); $this->assertEquals(4, \count($products)); // Select related document attributes - $product = $this->getDatabase()->findOne('product', [ + $product = static::getDatabase()->findOne('product', [ Query::select(['*', 'store.name']) ]); @@ -8829,7 +9222,7 @@ public function testManyToOneTwoWayRelationship(): void $this->assertEquals('Store 1', $product->getAttribute('store')->getAttribute('name')); $this->assertArrayNotHasKey('opensAt', $product->getAttribute('store')); - $product = $this->getDatabase()->getDocument('product', 'product1', [ + $product = static::getDatabase()->getDocument('product', 'product1', [ Query::select(['*', 'store.name']) ]); @@ -8837,58 +9230,58 @@ public function testManyToOneTwoWayRelationship(): void $this->assertArrayNotHasKey('opensAt', $product->getAttribute('store')); // Update root document attribute without altering relationship - $product1 = $this->getDatabase()->updateDocument( + $product1 = static::getDatabase()->updateDocument( 'product', $product1->getId(), $product1->setAttribute('name', 'Product 1 Updated') ); $this->assertEquals('Product 1 Updated', $product1->getAttribute('name')); - $product1 = $this->getDatabase()->getDocument('product', 'product1'); + $product1 = static::getDatabase()->getDocument('product', 'product1'); $this->assertEquals('Product 1 Updated', $product1->getAttribute('name')); // Update inverse document attribute without altering relationship - $store1 = $this->getDatabase()->getDocument('store', 'store1'); - $store1 = $this->getDatabase()->updateDocument( + $store1 = static::getDatabase()->getDocument('store', 'store1'); + $store1 = static::getDatabase()->updateDocument( 'store', $store1->getId(), $store1->setAttribute('name', 'Store 1 Updated') ); $this->assertEquals('Store 1 Updated', $store1->getAttribute('name')); - $store1 = $this->getDatabase()->getDocument('store', 'store1'); + $store1 = static::getDatabase()->getDocument('store', 'store1'); $this->assertEquals('Store 1 Updated', $store1->getAttribute('name')); // Update nested document attribute $store = $product1->getAttribute('store'); $store->setAttribute('name', 'Store 1 Updated'); - $product1 = $this->getDatabase()->updateDocument( + $product1 = static::getDatabase()->updateDocument( 'product', $product1->getId(), $product1->setAttribute('store', $store) ); $this->assertEquals('Store 1 Updated', $product1->getAttribute('store')->getAttribute('name')); - $product1 = $this->getDatabase()->getDocument('product', 'product1'); + $product1 = static::getDatabase()->getDocument('product', 'product1'); $this->assertEquals('Store 1 Updated', $product1->getAttribute('store')->getAttribute('name')); // Update inverse nested document attribute $product = $store1->getAttribute('products')[0]; $product->setAttribute('name', 'Product 1 Updated'); - $store1 = $this->getDatabase()->updateDocument( + $store1 = static::getDatabase()->updateDocument( 'store', $store1->getId(), $store1->setAttribute('products', [$product]) ); $this->assertEquals('Product 1 Updated', $store1->getAttribute('products')[0]->getAttribute('name')); - $store1 = $this->getDatabase()->getDocument('store', 'store1'); + $store1 = static::getDatabase()->getDocument('store', 'store1'); $this->assertEquals('Product 1 Updated', $store1->getAttribute('products')[0]->getAttribute('name')); // Create new document with no relationship - $product5 = $this->getDatabase()->createDocument('product', new Document([ + $product5 = static::getDatabase()->createDocument('product', new Document([ '$id' => 'product5', '$permissions' => [ Permission::read(Role::any()), @@ -8899,7 +9292,7 @@ public function testManyToOneTwoWayRelationship(): void ])); // Update to relate to created document - $product5 = $this->getDatabase()->updateDocument( + $product5 = static::getDatabase()->updateDocument( 'product', $product5->getId(), $product5->setAttribute('store', new Document([ @@ -8915,11 +9308,11 @@ public function testManyToOneTwoWayRelationship(): void ); $this->assertEquals('Store 5', $product5->getAttribute('store')->getAttribute('name')); - $product5 = $this->getDatabase()->getDocument('product', 'product5'); + $product5 = static::getDatabase()->getDocument('product', 'product5'); $this->assertEquals('Store 5', $product5->getAttribute('store')->getAttribute('name')); // Create new child document with no relationship - $store6 = $this->getDatabase()->createDocument('store', new Document([ + $store6 = static::getDatabase()->createDocument('store', new Document([ '$id' => 'store6', '$permissions' => [ Permission::read(Role::any()), @@ -8931,7 +9324,7 @@ public function testManyToOneTwoWayRelationship(): void ])); // Update inverse to related to newly created document - $store6 = $this->getDatabase()->updateDocument( + $store6 = static::getDatabase()->updateDocument( 'store', $store6->getId(), $store6->setAttribute('products', [new Document([ @@ -8946,36 +9339,36 @@ public function testManyToOneTwoWayRelationship(): void ); $this->assertEquals('Product 6', $store6->getAttribute('products')[0]->getAttribute('name')); - $store6 = $this->getDatabase()->getDocument('store', 'store6'); + $store6 = static::getDatabase()->getDocument('store', 'store6'); $this->assertEquals('Product 6', $store6->getAttribute('products')[0]->getAttribute('name')); // Update document with new related document - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'product', $product1->getId(), $product1->setAttribute('store', 'store2') ); - $store1 = $this->getDatabase()->getDocument('store', 'store1'); + $store1 = static::getDatabase()->getDocument('store', 'store1'); // Update inverse document - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'store', $store1->getId(), $store1->setAttribute('products', ['product1']) ); - $store2 = $this->getDatabase()->getDocument('store', 'store2'); + $store2 = static::getDatabase()->getDocument('store', 'store2'); // Update inverse document - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'store', $store2->getId(), $store2->setAttribute('products', ['product1', 'product2']) ); // Rename relationship keys on both sides - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( 'product', 'store', 'newStore', @@ -8983,25 +9376,25 @@ public function testManyToOneTwoWayRelationship(): void ); // Get document with new relationship key - $store = $this->getDatabase()->getDocument('store', 'store2'); + $store = static::getDatabase()->getDocument('store', 'store2'); $products = $store->getAttribute('newProducts'); $this->assertEquals('product1', $products[0]['$id']); // Get inverse document with new relationship key - $product = $this->getDatabase()->getDocument('product', 'product1'); + $product = static::getDatabase()->getDocument('product', 'product1'); $store = $product->getAttribute('newStore'); $this->assertEquals('store2', $store['$id']); // Reset relationships - $store1 = $this->getDatabase()->getDocument('store', 'store1'); - $this->getDatabase()->updateDocument( + $store1 = static::getDatabase()->getDocument('store', 'store1'); + static::getDatabase()->updateDocument( 'store', $store1->getId(), $store1->setAttribute('newProducts', ['product1']) ); // Create new document with no relationship - $this->getDatabase()->createDocument('store', new Document([ + static::getDatabase()->createDocument('store', new Document([ '$id' => 'store7', '$permissions' => [ Permission::read(Role::any()), @@ -9013,87 +9406,87 @@ public function testManyToOneTwoWayRelationship(): void ])); // Can delete document with no relationship when on delete is set to restrict - $deleted = $this->getDatabase()->deleteDocument('store', 'store7'); + $deleted = static::getDatabase()->deleteDocument('store', 'store7'); $this->assertEquals(true, $deleted); - $store7 = $this->getDatabase()->getDocument('store', 'store7'); + $store7 = static::getDatabase()->getDocument('store', 'store7'); $this->assertEquals(true, $store7->isEmpty()); // Try to delete child while still related to another with on delete: restrict try { - $this->getDatabase()->deleteDocument('store', 'store1'); + static::getDatabase()->deleteDocument('store', 'store1'); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } // Delete parent while still related to another with on delete: restrict - $result = $this->getDatabase()->deleteDocument('product', 'product5'); + $result = static::getDatabase()->deleteDocument('product', 'product5'); $this->assertEquals(true, $result); // Change on delete to set null - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'product', id: 'newStore', onDelete: Database::RELATION_MUTATE_SET_NULL ); // Delete child, set parent relationship to null - $this->getDatabase()->deleteDocument('store', 'store1'); + static::getDatabase()->deleteDocument('store', 'store1'); // Check relation was set to null - $this->getDatabase()->getDocument('product', 'product1'); + static::getDatabase()->getDocument('product', 'product1'); $this->assertEquals(null, $product1->getAttribute('newStore')); // Change on delete to cascade - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'product', id: 'newStore', onDelete: Database::RELATION_MUTATE_CASCADE ); // Delete child, will delete parent - $this->getDatabase()->deleteDocument('store', 'store2'); + static::getDatabase()->deleteDocument('store', 'store2'); // Check parent and child were deleted - $library = $this->getDatabase()->getDocument('store', 'store2'); + $library = static::getDatabase()->getDocument('store', 'store2'); $this->assertEquals(true, $library->isEmpty()); - $library = $this->getDatabase()->getDocument('product', 'product2'); + $library = static::getDatabase()->getDocument('product', 'product2'); $this->assertEquals(true, $library->isEmpty()); // Delete relationship - $this->getDatabase()->deleteRelationship( + static::getDatabase()->deleteRelationship( 'product', 'newStore' ); // Try to get document again - $products = $this->getDatabase()->getDocument('product', 'product1'); + $products = static::getDatabase()->getDocument('product', 'product1'); $store = $products->getAttribute('newStore'); $this->assertEquals(null, $store); // Try to get inverse document again - $store = $this->getDatabase()->getDocument('store', 'store1'); + $store = static::getDatabase()->getDocument('store', 'store1'); $products = $store->getAttribute('newProducts'); $this->assertEquals(null, $products); } public function testManyToManyOneWayRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('playlist'); - $this->getDatabase()->createCollection('song'); + static::getDatabase()->createCollection('playlist'); + static::getDatabase()->createCollection('song'); - $this->getDatabase()->createAttribute('playlist', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('song', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('song', 'length', Database::VAR_INTEGER, 0, true); + static::getDatabase()->createAttribute('playlist', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('song', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('song', 'length', Database::VAR_INTEGER, 0, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'playlist', relatedCollection: 'song', type: Database::RELATION_MANY_TO_MANY, @@ -9101,7 +9494,7 @@ public function testManyToManyOneWayRelationship(): void ); // Check metadata for collection - $collection = $this->getDatabase()->getCollection('playlist'); + $collection = static::getDatabase()->getCollection('playlist'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { @@ -9117,7 +9510,7 @@ public function testManyToManyOneWayRelationship(): void } // Create document with relationship with nested data - $playlist1 = $this->getDatabase()->createDocument('playlist', new Document([ + $playlist1 = static::getDatabase()->createDocument('playlist', new Document([ '$id' => 'playlist1', '$permissions' => [ Permission::read(Role::any()), @@ -9140,7 +9533,7 @@ public function testManyToManyOneWayRelationship(): void ])); // Create document with relationship with related ID - $this->getDatabase()->createDocument('song', new Document([ + static::getDatabase()->createDocument('song', new Document([ '$id' => 'song2', '$permissions' => [ Permission::read(Role::any()), @@ -9150,7 +9543,7 @@ public function testManyToManyOneWayRelationship(): void 'name' => 'Song 2', 'length' => 140, ])); - $this->getDatabase()->createDocument('playlist', new Document([ + static::getDatabase()->createDocument('playlist', new Document([ '$id' => 'playlist2', '$permissions' => [ Permission::read(Role::any()), @@ -9164,13 +9557,13 @@ public function testManyToManyOneWayRelationship(): void ])); // Update a document with non existing related document. It should not get added to the list. - $this->getDatabase()->updateDocument('playlist', 'playlist1', $playlist1->setAttribute('songs', ['song1','no-song'])); + static::getDatabase()->updateDocument('playlist', 'playlist1', $playlist1->setAttribute('songs', ['song1','no-song'])); - $playlist1Document = $this->getDatabase()->getDocument('playlist', 'playlist1'); + $playlist1Document = static::getDatabase()->getDocument('playlist', 'playlist1'); // Assert document does not contain non existing relation document. $this->assertEquals(1, \count($playlist1Document->getAttribute('songs'))); - $documents = $this->getDatabase()->find('playlist', [ + $documents = static::getDatabase()->find('playlist', [ Query::select(['name']), Query::limit(1) ]); @@ -9178,29 +9571,29 @@ public function testManyToManyOneWayRelationship(): void $this->assertArrayNotHasKey('songs', $documents[0]); // Get document with relationship - $playlist = $this->getDatabase()->getDocument('playlist', 'playlist1'); + $playlist = static::getDatabase()->getDocument('playlist', 'playlist1'); $songs = $playlist->getAttribute('songs', []); $this->assertEquals('song1', $songs[0]['$id']); $this->assertArrayNotHasKey('playlist', $songs[0]); - $playlist = $this->getDatabase()->getDocument('playlist', 'playlist2'); + $playlist = static::getDatabase()->getDocument('playlist', 'playlist2'); $songs = $playlist->getAttribute('songs', []); $this->assertEquals('song2', $songs[0]['$id']); $this->assertArrayNotHasKey('playlist', $songs[0]); // Get related document - $library = $this->getDatabase()->getDocument('song', 'song1'); + $library = static::getDatabase()->getDocument('song', 'song1'); $this->assertArrayNotHasKey('songs', $library); - $library = $this->getDatabase()->getDocument('song', 'song2'); + $library = static::getDatabase()->getDocument('song', 'song2'); $this->assertArrayNotHasKey('songs', $library); - $playlists = $this->getDatabase()->find('playlist'); + $playlists = static::getDatabase()->find('playlist'); $this->assertEquals(2, \count($playlists)); // Select related document attributes - $playlist = $this->getDatabase()->findOne('playlist', [ + $playlist = static::getDatabase()->findOne('playlist', [ Query::select(['*', 'songs.name']) ]); @@ -9211,7 +9604,7 @@ public function testManyToManyOneWayRelationship(): void $this->assertEquals('Song 1', $playlist->getAttribute('songs')[0]->getAttribute('name')); $this->assertArrayNotHasKey('length', $playlist->getAttribute('songs')[0]); - $playlist = $this->getDatabase()->getDocument('playlist', 'playlist1', [ + $playlist = static::getDatabase()->getDocument('playlist', 'playlist1', [ Query::select(['*', 'songs.name']) ]); @@ -9219,32 +9612,32 @@ public function testManyToManyOneWayRelationship(): void $this->assertArrayNotHasKey('length', $playlist->getAttribute('songs')[0]); // Update root document attribute without altering relationship - $playlist1 = $this->getDatabase()->updateDocument( + $playlist1 = static::getDatabase()->updateDocument( 'playlist', $playlist1->getId(), $playlist1->setAttribute('name', 'Playlist 1 Updated') ); $this->assertEquals('Playlist 1 Updated', $playlist1->getAttribute('name')); - $playlist1 = $this->getDatabase()->getDocument('playlist', 'playlist1'); + $playlist1 = static::getDatabase()->getDocument('playlist', 'playlist1'); $this->assertEquals('Playlist 1 Updated', $playlist1->getAttribute('name')); // Update nested document attribute $songs = $playlist1->getAttribute('songs', []); $songs[0]->setAttribute('name', 'Song 1 Updated'); - $playlist1 = $this->getDatabase()->updateDocument( + $playlist1 = static::getDatabase()->updateDocument( 'playlist', $playlist1->getId(), $playlist1->setAttribute('songs', $songs) ); $this->assertEquals('Song 1 Updated', $playlist1->getAttribute('songs')[0]->getAttribute('name')); - $playlist1 = $this->getDatabase()->getDocument('playlist', 'playlist1'); + $playlist1 = static::getDatabase()->getDocument('playlist', 'playlist1'); $this->assertEquals('Song 1 Updated', $playlist1->getAttribute('songs')[0]->getAttribute('name')); // Create new document with no relationship - $playlist5 = $this->getDatabase()->createDocument('playlist', new Document([ + $playlist5 = static::getDatabase()->createDocument('playlist', new Document([ '$id' => 'playlist5', '$permissions' => [ Permission::read(Role::any()), @@ -9255,7 +9648,7 @@ public function testManyToManyOneWayRelationship(): void ])); // Update to relate to created document - $playlist5 = $this->getDatabase()->updateDocument( + $playlist5 = static::getDatabase()->updateDocument( 'playlist', $playlist5->getId(), $playlist5->setAttribute('songs', [new Document([ @@ -9271,7 +9664,7 @@ public function testManyToManyOneWayRelationship(): void ); // Playlist relating to existing songs that belong to other playlists - $this->getDatabase()->createDocument('playlist', new Document([ + static::getDatabase()->createDocument('playlist', new Document([ '$id' => 'playlist6', '$permissions' => [ Permission::read(Role::any()), @@ -9287,30 +9680,30 @@ public function testManyToManyOneWayRelationship(): void ])); $this->assertEquals('Song 5', $playlist5->getAttribute('songs')[0]->getAttribute('name')); - $playlist5 = $this->getDatabase()->getDocument('playlist', 'playlist5'); + $playlist5 = static::getDatabase()->getDocument('playlist', 'playlist5'); $this->assertEquals('Song 5', $playlist5->getAttribute('songs')[0]->getAttribute('name')); // Update document with new related document - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'playlist', $playlist1->getId(), $playlist1->setAttribute('songs', ['song2']) ); // Rename relationship key - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( 'playlist', 'songs', 'newSongs' ); // Get document with new relationship key - $playlist = $this->getDatabase()->getDocument('playlist', 'playlist1'); + $playlist = static::getDatabase()->getDocument('playlist', 'playlist1'); $songs = $playlist->getAttribute('newSongs'); $this->assertEquals('song2', $songs[0]['$id']); // Create new document with no relationship - $this->getDatabase()->createDocument('playlist', new Document([ + static::getDatabase()->createDocument('playlist', new Document([ '$id' => 'playlist3', '$permissions' => [ Permission::read(Role::any()), @@ -9321,87 +9714,87 @@ public function testManyToManyOneWayRelationship(): void ])); // Can delete document with no relationship when on delete is set to restrict - $deleted = $this->getDatabase()->deleteDocument('playlist', 'playlist3'); + $deleted = static::getDatabase()->deleteDocument('playlist', 'playlist3'); $this->assertEquals(true, $deleted); - $playlist3 = $this->getDatabase()->getDocument('playlist', 'playlist3'); + $playlist3 = static::getDatabase()->getDocument('playlist', 'playlist3'); $this->assertEquals(true, $playlist3->isEmpty()); // Try to delete document while still related to another with on delete: restrict try { - $this->getDatabase()->deleteDocument('playlist', 'playlist1'); + static::getDatabase()->deleteDocument('playlist', 'playlist1'); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } // Change on delete to set null - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'playlist', id: 'newSongs', onDelete: Database::RELATION_MUTATE_SET_NULL ); - $playlist1 = $this->getDatabase()->getDocument('playlist', 'playlist1'); + $playlist1 = static::getDatabase()->getDocument('playlist', 'playlist1'); // Reset relationships - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'playlist', $playlist1->getId(), $playlist1->setAttribute('newSongs', ['song1']) ); // Delete child, will delete junction - $this->getDatabase()->deleteDocument('song', 'song1'); + static::getDatabase()->deleteDocument('song', 'song1'); // Check relation was set to null - $playlist1 = $this->getDatabase()->getDocument('playlist', 'playlist1'); + $playlist1 = static::getDatabase()->getDocument('playlist', 'playlist1'); $this->assertEquals(0, \count($playlist1->getAttribute('newSongs'))); // Change on delete to cascade - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'playlist', id: 'newSongs', onDelete: Database::RELATION_MUTATE_CASCADE ); // Delete parent, will delete child - $this->getDatabase()->deleteDocument('playlist', 'playlist2'); + static::getDatabase()->deleteDocument('playlist', 'playlist2'); // Check parent and child were deleted - $library = $this->getDatabase()->getDocument('playlist', 'playlist2'); + $library = static::getDatabase()->getDocument('playlist', 'playlist2'); $this->assertEquals(true, $library->isEmpty()); - $library = $this->getDatabase()->getDocument('song', 'song2'); + $library = static::getDatabase()->getDocument('song', 'song2'); $this->assertEquals(true, $library->isEmpty()); // Delete relationship - $this->getDatabase()->deleteRelationship( + static::getDatabase()->deleteRelationship( 'playlist', 'newSongs' ); // Try to get document again - $playlist = $this->getDatabase()->getDocument('playlist', 'playlist1'); + $playlist = static::getDatabase()->getDocument('playlist', 'playlist1'); $songs = $playlist->getAttribute('newSongs'); $this->assertEquals(null, $songs); } public function testManyToManyTwoWayRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('students'); - $this->getDatabase()->createCollection('classes'); + static::getDatabase()->createCollection('students'); + static::getDatabase()->createCollection('classes'); - $this->getDatabase()->createAttribute('students', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('classes', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('classes', 'number', Database::VAR_INTEGER, 0, true); + static::getDatabase()->createAttribute('students', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('classes', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('classes', 'number', Database::VAR_INTEGER, 0, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'students', relatedCollection: 'classes', type: Database::RELATION_MANY_TO_MANY, @@ -9409,7 +9802,7 @@ public function testManyToManyTwoWayRelationship(): void ); // Check metadata for collection - $collection = $this->getDatabase()->getCollection('students'); + $collection = static::getDatabase()->getCollection('students'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'students') { @@ -9424,7 +9817,7 @@ public function testManyToManyTwoWayRelationship(): void } // Check metadata for related collection - $collection = $this->getDatabase()->getCollection('classes'); + $collection = static::getDatabase()->getCollection('classes'); $attributes = $collection->getAttribute('attributes', []); foreach ($attributes as $attribute) { if ($attribute['key'] === 'classes') { @@ -9439,7 +9832,7 @@ public function testManyToManyTwoWayRelationship(): void } // Create document with relationship with nested data - $student1 = $this->getDatabase()->createDocument('students', new Document([ + $student1 = static::getDatabase()->createDocument('students', new Document([ '$id' => 'student1', '$permissions' => [ Permission::read(Role::any()), @@ -9462,14 +9855,14 @@ public function testManyToManyTwoWayRelationship(): void ])); // Update a document with non existing related document. It should not get added to the list. - $this->getDatabase()->updateDocument('students', 'student1', $student1->setAttribute('classes', ['class1', 'no-class'])); + static::getDatabase()->updateDocument('students', 'student1', $student1->setAttribute('classes', ['class1', 'no-class'])); - $student1Document = $this->getDatabase()->getDocument('students', 'student1'); + $student1Document = static::getDatabase()->getDocument('students', 'student1'); // Assert document does not contain non existing relation document. $this->assertEquals(1, \count($student1Document->getAttribute('classes'))); // Create document with relationship with related ID - $this->getDatabase()->createDocument('classes', new Document([ + static::getDatabase()->createDocument('classes', new Document([ '$id' => 'class2', '$permissions' => [ Permission::read(Role::any()), @@ -9480,7 +9873,7 @@ public function testManyToManyTwoWayRelationship(): void 'name' => 'Class 2', 'number' => 2, ])); - $this->getDatabase()->createDocument('students', new Document([ + static::getDatabase()->createDocument('students', new Document([ '$id' => 'student2', '$permissions' => [ Permission::read(Role::any()), @@ -9494,7 +9887,7 @@ public function testManyToManyTwoWayRelationship(): void ])); // Create from child side - $this->getDatabase()->createDocument('classes', new Document([ + static::getDatabase()->createDocument('classes', new Document([ '$id' => 'class3', '$permissions' => [ Permission::read(Role::any()), @@ -9515,7 +9908,7 @@ public function testManyToManyTwoWayRelationship(): void ] ], ])); - $this->getDatabase()->createDocument('students', new Document([ + static::getDatabase()->createDocument('students', new Document([ '$id' => 'student4', '$permissions' => [ Permission::read(Role::any()), @@ -9524,7 +9917,7 @@ public function testManyToManyTwoWayRelationship(): void ], 'name' => 'Student 4' ])); - $this->getDatabase()->createDocument('classes', new Document([ + static::getDatabase()->createDocument('classes', new Document([ '$id' => 'class4', '$permissions' => [ Permission::read(Role::any()), @@ -9540,49 +9933,49 @@ public function testManyToManyTwoWayRelationship(): void ])); // Get document with relationship - $student = $this->getDatabase()->getDocument('students', 'student1'); + $student = static::getDatabase()->getDocument('students', 'student1'); $classes = $student->getAttribute('classes', []); $this->assertEquals('class1', $classes[0]['$id']); $this->assertArrayNotHasKey('students', $classes[0]); - $student = $this->getDatabase()->getDocument('students', 'student2'); + $student = static::getDatabase()->getDocument('students', 'student2'); $classes = $student->getAttribute('classes', []); $this->assertEquals('class2', $classes[0]['$id']); $this->assertArrayNotHasKey('students', $classes[0]); - $student = $this->getDatabase()->getDocument('students', 'student3'); + $student = static::getDatabase()->getDocument('students', 'student3'); $classes = $student->getAttribute('classes', []); $this->assertEquals('class3', $classes[0]['$id']); $this->assertArrayNotHasKey('students', $classes[0]); - $student = $this->getDatabase()->getDocument('students', 'student4'); + $student = static::getDatabase()->getDocument('students', 'student4'); $classes = $student->getAttribute('classes', []); $this->assertEquals('class4', $classes[0]['$id']); $this->assertArrayNotHasKey('students', $classes[0]); // Get related document - $class = $this->getDatabase()->getDocument('classes', 'class1'); + $class = static::getDatabase()->getDocument('classes', 'class1'); $student = $class->getAttribute('students'); $this->assertEquals('student1', $student[0]['$id']); $this->assertArrayNotHasKey('classes', $student[0]); - $class = $this->getDatabase()->getDocument('classes', 'class2'); + $class = static::getDatabase()->getDocument('classes', 'class2'); $student = $class->getAttribute('students'); $this->assertEquals('student2', $student[0]['$id']); $this->assertArrayNotHasKey('classes', $student[0]); - $class = $this->getDatabase()->getDocument('classes', 'class3'); + $class = static::getDatabase()->getDocument('classes', 'class3'); $student = $class->getAttribute('students'); $this->assertEquals('student3', $student[0]['$id']); $this->assertArrayNotHasKey('classes', $student[0]); - $class = $this->getDatabase()->getDocument('classes', 'class4'); + $class = static::getDatabase()->getDocument('classes', 'class4'); $student = $class->getAttribute('students'); $this->assertEquals('student4', $student[0]['$id']); $this->assertArrayNotHasKey('classes', $student[0]); // Select related document attributes - $student = $this->getDatabase()->findOne('students', [ + $student = static::getDatabase()->findOne('students', [ Query::select(['*', 'classes.name']) ]); @@ -9593,7 +9986,7 @@ public function testManyToManyTwoWayRelationship(): void $this->assertEquals('Class 1', $student->getAttribute('classes')[0]->getAttribute('name')); $this->assertArrayNotHasKey('number', $student->getAttribute('classes')[0]); - $student = $this->getDatabase()->getDocument('students', 'student1', [ + $student = static::getDatabase()->getDocument('students', 'student1', [ Query::select(['*', 'classes.name']) ]); @@ -9601,58 +9994,58 @@ public function testManyToManyTwoWayRelationship(): void $this->assertArrayNotHasKey('number', $student->getAttribute('classes')[0]); // Update root document attribute without altering relationship - $student1 = $this->getDatabase()->updateDocument( + $student1 = static::getDatabase()->updateDocument( 'students', $student1->getId(), $student1->setAttribute('name', 'Student 1 Updated') ); $this->assertEquals('Student 1 Updated', $student1->getAttribute('name')); - $student1 = $this->getDatabase()->getDocument('students', 'student1'); + $student1 = static::getDatabase()->getDocument('students', 'student1'); $this->assertEquals('Student 1 Updated', $student1->getAttribute('name')); // Update inverse root document attribute without altering relationship - $class2 = $this->getDatabase()->getDocument('classes', 'class2'); - $class2 = $this->getDatabase()->updateDocument( + $class2 = static::getDatabase()->getDocument('classes', 'class2'); + $class2 = static::getDatabase()->updateDocument( 'classes', $class2->getId(), $class2->setAttribute('name', 'Class 2 Updated') ); $this->assertEquals('Class 2 Updated', $class2->getAttribute('name')); - $class2 = $this->getDatabase()->getDocument('classes', 'class2'); + $class2 = static::getDatabase()->getDocument('classes', 'class2'); $this->assertEquals('Class 2 Updated', $class2->getAttribute('name')); // Update nested document attribute $classes = $student1->getAttribute('classes', []); $classes[0]->setAttribute('name', 'Class 1 Updated'); - $student1 = $this->getDatabase()->updateDocument( + $student1 = static::getDatabase()->updateDocument( 'students', $student1->getId(), $student1->setAttribute('classes', $classes) ); $this->assertEquals('Class 1 Updated', $student1->getAttribute('classes')[0]->getAttribute('name')); - $student1 = $this->getDatabase()->getDocument('students', 'student1'); + $student1 = static::getDatabase()->getDocument('students', 'student1'); $this->assertEquals('Class 1 Updated', $student1->getAttribute('classes')[0]->getAttribute('name')); // Update inverse nested document attribute $students = $class2->getAttribute('students', []); $students[0]->setAttribute('name', 'Student 2 Updated'); - $class2 = $this->getDatabase()->updateDocument( + $class2 = static::getDatabase()->updateDocument( 'classes', $class2->getId(), $class2->setAttribute('students', $students) ); $this->assertEquals('Student 2 Updated', $class2->getAttribute('students')[0]->getAttribute('name')); - $class2 = $this->getDatabase()->getDocument('classes', 'class2'); + $class2 = static::getDatabase()->getDocument('classes', 'class2'); $this->assertEquals('Student 2 Updated', $class2->getAttribute('students')[0]->getAttribute('name')); // Create new document with no relationship - $student5 = $this->getDatabase()->createDocument('students', new Document([ + $student5 = static::getDatabase()->createDocument('students', new Document([ '$id' => 'student5', '$permissions' => [ Permission::read(Role::any()), @@ -9663,7 +10056,7 @@ public function testManyToManyTwoWayRelationship(): void ])); // Update to relate to created document - $student5 = $this->getDatabase()->updateDocument( + $student5 = static::getDatabase()->updateDocument( 'students', $student5->getId(), $student5->setAttribute('classes', [new Document([ @@ -9679,11 +10072,11 @@ public function testManyToManyTwoWayRelationship(): void ); $this->assertEquals('Class 5', $student5->getAttribute('classes')[0]->getAttribute('name')); - $student5 = $this->getDatabase()->getDocument('students', 'student5'); + $student5 = static::getDatabase()->getDocument('students', 'student5'); $this->assertEquals('Class 5', $student5->getAttribute('classes')[0]->getAttribute('name')); // Create child document with no relationship - $class6 = $this->getDatabase()->createDocument('classes', new Document([ + $class6 = static::getDatabase()->createDocument('classes', new Document([ '$id' => 'class6', '$permissions' => [ Permission::read(Role::any()), @@ -9695,7 +10088,7 @@ public function testManyToManyTwoWayRelationship(): void ])); // Update to relate to created document - $class6 = $this->getDatabase()->updateDocument( + $class6 = static::getDatabase()->updateDocument( 'classes', $class6->getId(), $class6->setAttribute('students', [new Document([ @@ -9710,27 +10103,27 @@ public function testManyToManyTwoWayRelationship(): void ); $this->assertEquals('Student 6', $class6->getAttribute('students')[0]->getAttribute('name')); - $class6 = $this->getDatabase()->getDocument('classes', 'class6'); + $class6 = static::getDatabase()->getDocument('classes', 'class6'); $this->assertEquals('Student 6', $class6->getAttribute('students')[0]->getAttribute('name')); // Update document with new related document - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'students', $student1->getId(), $student1->setAttribute('classes', ['class2']) ); - $class1 = $this->getDatabase()->getDocument('classes', 'class1'); + $class1 = static::getDatabase()->getDocument('classes', 'class1'); // Update inverse document - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'classes', $class1->getId(), $class1->setAttribute('students', ['student1']) ); // Rename relationship keys on both sides - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( 'students', 'classes', 'newClasses', @@ -9738,17 +10131,17 @@ public function testManyToManyTwoWayRelationship(): void ); // Get document with new relationship key - $students = $this->getDatabase()->getDocument('students', 'student1'); + $students = static::getDatabase()->getDocument('students', 'student1'); $classes = $students->getAttribute('newClasses'); $this->assertEquals('class2', $classes[0]['$id']); // Get inverse document with new relationship key - $class = $this->getDatabase()->getDocument('classes', 'class1'); + $class = static::getDatabase()->getDocument('classes', 'class1'); $students = $class->getAttribute('newStudents'); $this->assertEquals('student1', $students[0]['$id']); // Create new document with no relationship - $this->getDatabase()->createDocument('students', new Document([ + static::getDatabase()->createDocument('students', new Document([ '$id' => 'student7', '$permissions' => [ Permission::read(Role::any()), @@ -9759,107 +10152,107 @@ public function testManyToManyTwoWayRelationship(): void ])); // Can delete document with no relationship when on delete is set to restrict - $deleted = $this->getDatabase()->deleteDocument('students', 'student7'); + $deleted = static::getDatabase()->deleteDocument('students', 'student7'); $this->assertEquals(true, $deleted); - $student6 = $this->getDatabase()->getDocument('students', 'student7'); + $student6 = static::getDatabase()->getDocument('students', 'student7'); $this->assertEquals(true, $student6->isEmpty()); // Try to delete document while still related to another with on delete: restrict try { - $this->getDatabase()->deleteDocument('students', 'student1'); + static::getDatabase()->deleteDocument('students', 'student1'); $this->fail('Failed to throw exception'); } catch (Exception $e) { $this->assertEquals('Cannot delete document because it has at least one related document.', $e->getMessage()); } // Change on delete to set null - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'students', id: 'newClasses', onDelete: Database::RELATION_MUTATE_SET_NULL ); - $student1 = $this->getDatabase()->getDocument('students', 'student1'); + $student1 = static::getDatabase()->getDocument('students', 'student1'); // Reset relationships - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'students', $student1->getId(), $student1->setAttribute('newClasses', ['class1']) ); // Delete child, will delete junction - $this->getDatabase()->deleteDocument('classes', 'class1'); + static::getDatabase()->deleteDocument('classes', 'class1'); // Check relation was set to null - $student1 = $this->getDatabase()->getDocument('students', 'student1'); + $student1 = static::getDatabase()->getDocument('students', 'student1'); $this->assertEquals(0, \count($student1->getAttribute('newClasses'))); // Change on delete to cascade - $this->getDatabase()->updateRelationship( + static::getDatabase()->updateRelationship( collection: 'students', id: 'newClasses', onDelete: Database::RELATION_MUTATE_CASCADE ); // Delete parent, will delete child - $this->getDatabase()->deleteDocument('students', 'student2'); + static::getDatabase()->deleteDocument('students', 'student2'); // Check parent and child were deleted - $library = $this->getDatabase()->getDocument('students', 'student2'); + $library = static::getDatabase()->getDocument('students', 'student2'); $this->assertEquals(true, $library->isEmpty()); // Delete child, should not delete parent - $this->getDatabase()->deleteDocument('classes', 'class6'); + static::getDatabase()->deleteDocument('classes', 'class6'); // Check only child was deleted - $student6 = $this->getDatabase()->getDocument('students', 'student6'); + $student6 = static::getDatabase()->getDocument('students', 'student6'); $this->assertEquals(false, $student6->isEmpty()); $this->assertEmpty($student6->getAttribute('newClasses')); - $library = $this->getDatabase()->getDocument('classes', 'class2'); + $library = static::getDatabase()->getDocument('classes', 'class2'); $this->assertEquals(true, $library->isEmpty()); // Delete relationship - $this->getDatabase()->deleteRelationship( + static::getDatabase()->deleteRelationship( 'students', 'newClasses' ); // Try to get documents again - $student = $this->getDatabase()->getDocument('students', 'student1'); + $student = static::getDatabase()->getDocument('students', 'student1'); $classes = $student->getAttribute('newClasses'); $this->assertEquals(null, $classes); // Try to get inverse documents again - $classes = $this->getDatabase()->getDocument('classes', 'class1'); + $classes = static::getDatabase()->getDocument('classes', 'class1'); $students = $classes->getAttribute('newStudents'); $this->assertEquals(null, $students); } public function testSelectRelationshipAttributes(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('make'); - $this->getDatabase()->createCollection('model'); + static::getDatabase()->createCollection('make'); + static::getDatabase()->createCollection('model'); - $this->getDatabase()->createAttribute('make', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('model', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('model', 'year', Database::VAR_INTEGER, 0, true); + static::getDatabase()->createAttribute('make', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('model', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('model', 'year', Database::VAR_INTEGER, 0, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'make', relatedCollection: 'model', type: Database::RELATION_ONE_TO_MANY, id: 'models' ); - $this->getDatabase()->createDocument('make', new Document([ + static::getDatabase()->createDocument('make', new Document([ '$id' => 'ford', '$permissions' => [ Permission::read(Role::any()), @@ -9886,7 +10279,7 @@ public function testSelectRelationshipAttributes(): void ])); // Select some parent attributes, some child attributes - $make = $this->getDatabase()->findOne('make', [ + $make = static::getDatabase()->findOne('make', [ Query::select(['name', 'models.name']), ]); @@ -9908,7 +10301,7 @@ public function testSelectRelationshipAttributes(): void $this->assertArrayNotHasKey('$updatedAt', $make); // Select internal attributes - $make = $this->getDatabase()->findOne('make', [ + $make = static::getDatabase()->findOne('make', [ Query::select(['name', '$id']), ]); @@ -9923,7 +10316,7 @@ public function testSelectRelationshipAttributes(): void $this->assertArrayNotHasKey('$updatedAt', $make); $this->assertArrayNotHasKey('$permissions', $make); - $make = $this->getDatabase()->findOne('make', [ + $make = static::getDatabase()->findOne('make', [ Query::select(['name', '$internalId']), ]); @@ -9938,7 +10331,7 @@ public function testSelectRelationshipAttributes(): void $this->assertArrayNotHasKey('$updatedAt', $make); $this->assertArrayNotHasKey('$permissions', $make); - $make = $this->getDatabase()->findOne('make', [ + $make = static::getDatabase()->findOne('make', [ Query::select(['name', '$collection']), ]); @@ -9953,7 +10346,7 @@ public function testSelectRelationshipAttributes(): void $this->assertArrayNotHasKey('$updatedAt', $make); $this->assertArrayNotHasKey('$permissions', $make); - $make = $this->getDatabase()->findOne('make', [ + $make = static::getDatabase()->findOne('make', [ Query::select(['name', '$createdAt']), ]); @@ -9968,7 +10361,7 @@ public function testSelectRelationshipAttributes(): void $this->assertArrayNotHasKey('$updatedAt', $make); $this->assertArrayNotHasKey('$permissions', $make); - $make = $this->getDatabase()->findOne('make', [ + $make = static::getDatabase()->findOne('make', [ Query::select(['name', '$updatedAt']), ]); @@ -9983,7 +10376,7 @@ public function testSelectRelationshipAttributes(): void $this->assertArrayHasKey('$updatedAt', $make); $this->assertArrayNotHasKey('$permissions', $make); - $make = $this->getDatabase()->findOne('make', [ + $make = static::getDatabase()->findOne('make', [ Query::select(['name', '$permissions']), ]); @@ -9999,7 +10392,7 @@ public function testSelectRelationshipAttributes(): void $this->assertArrayHasKey('$permissions', $make); // Select all parent attributes, some child attributes - $make = $this->getDatabase()->findOne('make', [ + $make = static::getDatabase()->findOne('make', [ Query::select(['*', 'models.year']), ]); @@ -10015,7 +10408,7 @@ public function testSelectRelationshipAttributes(): void $this->assertEquals(2011, $make['models'][1]['year']); // Select all parent attributes, all child attributes - $make = $this->getDatabase()->findOne('make', [ + $make = static::getDatabase()->findOne('make', [ Query::select(['*', 'models.*']), ]); @@ -10032,7 +10425,7 @@ public function testSelectRelationshipAttributes(): void // Select all parent attributes, all child attributes // Must select parent if selecting children - $make = $this->getDatabase()->findOne('make', [ + $make = static::getDatabase()->findOne('make', [ Query::select(['models.*']), ]); @@ -10048,7 +10441,7 @@ public function testSelectRelationshipAttributes(): void $this->assertEquals(2011, $make['models'][1]['year']); // Select all parent attributes, no child attributes - $make = $this->getDatabase()->findOne('make', [ + $make = static::getDatabase()->findOne('make', [ Query::select(['name']), ]); @@ -10062,20 +10455,20 @@ public function testSelectRelationshipAttributes(): void public function testNestedOneToOne_OneToOneRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('pattern'); - $this->getDatabase()->createCollection('shirt'); - $this->getDatabase()->createCollection('team'); + static::getDatabase()->createCollection('pattern'); + static::getDatabase()->createCollection('shirt'); + static::getDatabase()->createCollection('team'); - $this->getDatabase()->createAttribute('pattern', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('shirt', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('team', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('pattern', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('shirt', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('team', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'pattern', relatedCollection: 'shirt', type: Database::RELATION_ONE_TO_ONE, @@ -10083,7 +10476,7 @@ public function testNestedOneToOne_OneToOneRelationship(): void id: 'shirt', twoWayKey: 'pattern' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'shirt', relatedCollection: 'team', type: Database::RELATION_ONE_TO_ONE, @@ -10092,7 +10485,7 @@ public function testNestedOneToOne_OneToOneRelationship(): void twoWayKey: 'shirt' ); - $this->getDatabase()->createDocument('pattern', new Document([ + static::getDatabase()->createDocument('pattern', new Document([ '$id' => 'stripes', '$permissions' => [ Permission::read(Role::any()), @@ -10114,13 +10507,13 @@ public function testNestedOneToOne_OneToOneRelationship(): void ], ])); - $pattern = $this->getDatabase()->getDocument('pattern', 'stripes'); + $pattern = static::getDatabase()->getDocument('pattern', 'stripes'); $this->assertEquals('red', $pattern['shirt']['$id']); $this->assertArrayNotHasKey('pattern', $pattern['shirt']); $this->assertEquals('reds', $pattern['shirt']['team']['$id']); $this->assertArrayNotHasKey('shirt', $pattern['shirt']['team']); - $this->getDatabase()->createDocument('team', new Document([ + static::getDatabase()->createDocument('team', new Document([ '$id' => 'blues', '$permissions' => [ Permission::read(Role::any()), @@ -10142,7 +10535,7 @@ public function testNestedOneToOne_OneToOneRelationship(): void ], ])); - $team = $this->getDatabase()->getDocument('team', 'blues'); + $team = static::getDatabase()->getDocument('team', 'blues'); $this->assertEquals('blue', $team['shirt']['$id']); $this->assertArrayNotHasKey('team', $team['shirt']); $this->assertEquals('plain', $team['shirt']['pattern']['$id']); @@ -10151,20 +10544,20 @@ public function testNestedOneToOne_OneToOneRelationship(): void public function testNestedOneToOne_OneToManyRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('teachers'); - $this->getDatabase()->createCollection('classrooms'); - $this->getDatabase()->createCollection('children'); + static::getDatabase()->createCollection('teachers'); + static::getDatabase()->createCollection('classrooms'); + static::getDatabase()->createCollection('children'); - $this->getDatabase()->createAttribute('children', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('teachers', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('classrooms', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('children', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('teachers', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('classrooms', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'teachers', relatedCollection: 'classrooms', type: Database::RELATION_ONE_TO_ONE, @@ -10172,7 +10565,7 @@ public function testNestedOneToOne_OneToManyRelationship(): void id: 'classroom', twoWayKey: 'teacher' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'classrooms', relatedCollection: 'children', type: Database::RELATION_ONE_TO_MANY, @@ -10180,7 +10573,7 @@ public function testNestedOneToOne_OneToManyRelationship(): void twoWayKey: 'classroom' ); - $this->getDatabase()->createDocument('teachers', new Document([ + static::getDatabase()->createDocument('teachers', new Document([ '$id' => 'teacher1', '$permissions' => [ Permission::read(Role::any()), @@ -10211,14 +10604,14 @@ public function testNestedOneToOne_OneToManyRelationship(): void ], ])); - $teacher1 = $this->getDatabase()->getDocument('teachers', 'teacher1'); + $teacher1 = static::getDatabase()->getDocument('teachers', 'teacher1'); $this->assertEquals('classroom1', $teacher1['classroom']['$id']); $this->assertArrayNotHasKey('teacher', $teacher1['classroom']); $this->assertEquals(2, \count($teacher1['classroom']['children'])); $this->assertEquals('Child 1', $teacher1['classroom']['children'][0]['name']); $this->assertEquals('Child 2', $teacher1['classroom']['children'][1]['name']); - $this->getDatabase()->createDocument('children', new Document([ + static::getDatabase()->createDocument('children', new Document([ '$id' => 'child3', '$permissions' => [ Permission::read(Role::any()), @@ -10240,7 +10633,7 @@ public function testNestedOneToOne_OneToManyRelationship(): void ], ])); - $child3 = $this->getDatabase()->getDocument('children', 'child3'); + $child3 = static::getDatabase()->getDocument('children', 'child3'); $this->assertEquals('classroom2', $child3['classroom']['$id']); $this->assertArrayNotHasKey('children', $child3['classroom']); $this->assertEquals('teacher2', $child3['classroom']['teacher']['$id']); @@ -10249,20 +10642,20 @@ public function testNestedOneToOne_OneToManyRelationship(): void public function testNestedOneToOne_ManyToOneRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('users'); - $this->getDatabase()->createCollection('profiles'); - $this->getDatabase()->createCollection('avatars'); + static::getDatabase()->createCollection('users'); + static::getDatabase()->createCollection('profiles'); + static::getDatabase()->createCollection('avatars'); - $this->getDatabase()->createAttribute('users', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('profiles', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('avatars', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('users', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('profiles', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('avatars', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'users', relatedCollection: 'profiles', type: Database::RELATION_ONE_TO_ONE, @@ -10270,7 +10663,7 @@ public function testNestedOneToOne_ManyToOneRelationship(): void id: 'profile', twoWayKey: 'user' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'profiles', relatedCollection: 'avatars', type: Database::RELATION_MANY_TO_ONE, @@ -10278,7 +10671,7 @@ public function testNestedOneToOne_ManyToOneRelationship(): void id: 'avatar', ); - $this->getDatabase()->createDocument('users', new Document([ + static::getDatabase()->createDocument('users', new Document([ '$id' => 'user1', '$permissions' => [ Permission::read(Role::any()), @@ -10300,13 +10693,13 @@ public function testNestedOneToOne_ManyToOneRelationship(): void ], ])); - $user1 = $this->getDatabase()->getDocument('users', 'user1'); + $user1 = static::getDatabase()->getDocument('users', 'user1'); $this->assertEquals('profile1', $user1['profile']['$id']); $this->assertArrayNotHasKey('user', $user1['profile']); $this->assertEquals('avatar1', $user1['profile']['avatar']['$id']); $this->assertArrayNotHasKey('profile', $user1['profile']['avatar']); - $this->getDatabase()->createDocument('avatars', new Document([ + static::getDatabase()->createDocument('avatars', new Document([ '$id' => 'avatar2', '$permissions' => [ Permission::read(Role::any()), @@ -10330,7 +10723,7 @@ public function testNestedOneToOne_ManyToOneRelationship(): void ], ])); - $avatar2 = $this->getDatabase()->getDocument('avatars', 'avatar2'); + $avatar2 = static::getDatabase()->getDocument('avatars', 'avatar2'); $this->assertEquals('profile2', $avatar2['profiles'][0]['$id']); $this->assertArrayNotHasKey('avatars', $avatar2['profiles'][0]); $this->assertEquals('user2', $avatar2['profiles'][0]['user']['$id']); @@ -10339,20 +10732,20 @@ public function testNestedOneToOne_ManyToOneRelationship(): void public function testNestedOneToOne_ManyToManyRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('addresses'); - $this->getDatabase()->createCollection('houses'); - $this->getDatabase()->createCollection('buildings'); + static::getDatabase()->createCollection('addresses'); + static::getDatabase()->createCollection('houses'); + static::getDatabase()->createCollection('buildings'); - $this->getDatabase()->createAttribute('addresses', 'street', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('houses', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('buildings', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('addresses', 'street', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('houses', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('buildings', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'addresses', relatedCollection: 'houses', type: Database::RELATION_ONE_TO_ONE, @@ -10360,14 +10753,14 @@ public function testNestedOneToOne_ManyToManyRelationship(): void id: 'house', twoWayKey: 'address' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'houses', relatedCollection: 'buildings', type: Database::RELATION_MANY_TO_MANY, twoWay: true, ); - $this->getDatabase()->createDocument('addresses', new Document([ + static::getDatabase()->createDocument('addresses', new Document([ '$id' => 'address1', '$permissions' => [ Permission::read(Role::any()), @@ -10398,7 +10791,7 @@ public function testNestedOneToOne_ManyToManyRelationship(): void ], ])); - $address1 = $this->getDatabase()->getDocument('addresses', 'address1'); + $address1 = static::getDatabase()->getDocument('addresses', 'address1'); $this->assertEquals('house1', $address1['house']['$id']); $this->assertArrayNotHasKey('address', $address1['house']); $this->assertEquals('building1', $address1['house']['buildings'][0]['$id']); @@ -10406,7 +10799,7 @@ public function testNestedOneToOne_ManyToManyRelationship(): void $this->assertArrayNotHasKey('houses', $address1['house']['buildings'][0]); $this->assertArrayNotHasKey('houses', $address1['house']['buildings'][1]); - $this->getDatabase()->createDocument('buildings', new Document([ + static::getDatabase()->createDocument('buildings', new Document([ '$id' => 'building3', '$permissions' => [ Permission::read(Role::any()), @@ -10433,27 +10826,27 @@ public function testNestedOneToOne_ManyToManyRelationship(): void public function testNestedOneToMany_OneToOneRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('countries'); - $this->getDatabase()->createCollection('cities'); - $this->getDatabase()->createCollection('mayors'); + static::getDatabase()->createCollection('countries'); + static::getDatabase()->createCollection('cities'); + static::getDatabase()->createCollection('mayors'); - $this->getDatabase()->createAttribute('cities', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('countries', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('mayors', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('cities', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('countries', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('mayors', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'countries', relatedCollection: 'cities', type: Database::RELATION_ONE_TO_MANY, twoWay: true, twoWayKey: 'country' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'cities', relatedCollection: 'mayors', type: Database::RELATION_ONE_TO_ONE, @@ -10462,7 +10855,7 @@ public function testNestedOneToMany_OneToOneRelationship(): void twoWayKey: 'city' ); - $this->getDatabase()->createDocument('countries', new Document([ + static::getDatabase()->createDocument('countries', new Document([ '$id' => 'country1', '$permissions' => [ Permission::read(Role::any()), @@ -10503,26 +10896,26 @@ public function testNestedOneToMany_OneToOneRelationship(): void ], ])); - $documents = $this->getDatabase()->find('countries', [ + $documents = static::getDatabase()->find('countries', [ Query::limit(1) ]); $this->assertEquals('Mayor 1', $documents[0]['cities'][0]['mayor']['name']); - $documents = $this->getDatabase()->find('countries', [ + $documents = static::getDatabase()->find('countries', [ Query::select(['name']), Query::limit(1) ]); $this->assertArrayHasKey('name', $documents[0]); $this->assertArrayNotHasKey('cities', $documents[0]); - $documents = $this->getDatabase()->find('countries', [ + $documents = static::getDatabase()->find('countries', [ Query::select(['*']), Query::limit(1) ]); $this->assertArrayHasKey('name', $documents[0]); $this->assertArrayNotHasKey('cities', $documents[0]); - $documents = $this->getDatabase()->find('countries', [ + $documents = static::getDatabase()->find('countries', [ Query::select(['*', 'cities.*', 'cities.mayor.*']), Query::limit(1) ]); @@ -10530,12 +10923,12 @@ public function testNestedOneToMany_OneToOneRelationship(): void $this->assertEquals('Mayor 1', $documents[0]['cities'][0]['mayor']['name']); // Insert docs to cache: - $country1 = $this->getDatabase()->getDocument('countries', 'country1'); - $mayor1 = $this->getDatabase()->getDocument('mayors', 'mayor1'); + $country1 = static::getDatabase()->getDocument('countries', 'country1'); + $mayor1 = static::getDatabase()->getDocument('mayors', 'mayor1'); $this->assertEquals('City 1', $mayor1['city']['name']); $this->assertEquals('City 1', $country1['cities'][0]['name']); - $this->getDatabase()->updateDocument('cities', 'city1', new Document([ + static::getDatabase()->updateDocument('cities', 'city1', new Document([ '$id' => 'city1', '$collection' => 'cities', 'name' => 'City 1 updated', @@ -10546,8 +10939,8 @@ public function testNestedOneToMany_OneToOneRelationship(): void ], ])); - $mayor1 = $this->getDatabase()->getDocument('mayors', 'mayor1'); - $country1 = $this->getDatabase()->getDocument('countries', 'country1'); + $mayor1 = static::getDatabase()->getDocument('mayors', 'mayor1'); + $country1 = static::getDatabase()->getDocument('countries', 'country1'); $this->assertEquals('City 1 updated', $mayor1['city']['name']); $this->assertEquals('City 1 updated', $country1['cities'][0]['name']); @@ -10558,7 +10951,7 @@ public function testNestedOneToMany_OneToOneRelationship(): void $this->assertArrayNotHasKey('city', $country1['cities'][0]['mayor']); $this->assertArrayNotHasKey('city', $country1['cities'][1]['mayor']); - $this->getDatabase()->createDocument('mayors', new Document([ + static::getDatabase()->createDocument('mayors', new Document([ '$id' => 'mayor3', '$permissions' => [ Permission::read(Role::any()), @@ -10580,7 +10973,7 @@ public function testNestedOneToMany_OneToOneRelationship(): void ], ])); - $country2 = $this->getDatabase()->getDocument('countries', 'country2'); + $country2 = static::getDatabase()->getDocument('countries', 'country2'); $this->assertEquals('city3', $country2['cities'][0]['$id']); $this->assertEquals('mayor3', $country2['cities'][0]['mayor']['$id']); $this->assertArrayNotHasKey('country', $country2['cities'][0]); @@ -10589,27 +10982,27 @@ public function testNestedOneToMany_OneToOneRelationship(): void public function testNestedOneToMany_OneToManyRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('dormitories'); - $this->getDatabase()->createCollection('occupants'); - $this->getDatabase()->createCollection('pets'); + static::getDatabase()->createCollection('dormitories'); + static::getDatabase()->createCollection('occupants'); + static::getDatabase()->createCollection('pets'); - $this->getDatabase()->createAttribute('dormitories', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('occupants', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('pets', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('dormitories', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('occupants', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('pets', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'dormitories', relatedCollection: 'occupants', type: Database::RELATION_ONE_TO_MANY, twoWay: true, twoWayKey: 'dormitory' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'occupants', relatedCollection: 'pets', type: Database::RELATION_ONE_TO_MANY, @@ -10617,7 +11010,7 @@ public function testNestedOneToMany_OneToManyRelationship(): void twoWayKey: 'occupant' ); - $this->getDatabase()->createDocument('dormitories', new Document([ + static::getDatabase()->createDocument('dormitories', new Document([ '$id' => 'dormitory1', '$permissions' => [ Permission::read(Role::any()), @@ -10673,7 +11066,7 @@ public function testNestedOneToMany_OneToManyRelationship(): void ], ])); - $dormitory1 = $this->getDatabase()->getDocument('dormitories', 'dormitory1'); + $dormitory1 = static::getDatabase()->getDocument('dormitories', 'dormitory1'); $this->assertEquals('occupant1', $dormitory1['occupants'][0]['$id']); $this->assertEquals('occupant2', $dormitory1['occupants'][1]['$id']); $this->assertEquals('pet1', $dormitory1['occupants'][0]['pets'][0]['$id']); @@ -10687,7 +11080,7 @@ public function testNestedOneToMany_OneToManyRelationship(): void $this->assertArrayNotHasKey('occupant', $dormitory1['occupants'][1]['pets'][0]); $this->assertArrayNotHasKey('occupant', $dormitory1['occupants'][1]['pets'][1]); - $this->getDatabase()->createDocument('pets', new Document([ + static::getDatabase()->createDocument('pets', new Document([ '$id' => 'pet5', '$permissions' => [ Permission::read(Role::any()), @@ -10709,7 +11102,7 @@ public function testNestedOneToMany_OneToManyRelationship(): void ], ])); - $pet5 = $this->getDatabase()->getDocument('pets', 'pet5'); + $pet5 = static::getDatabase()->getDocument('pets', 'pet5'); $this->assertEquals('occupant3', $pet5['occupant']['$id']); $this->assertEquals('dormitory2', $pet5['occupant']['dormitory']['$id']); $this->assertArrayNotHasKey('pets', $pet5['occupant']); @@ -10718,26 +11111,26 @@ public function testNestedOneToMany_OneToManyRelationship(): void public function testNestedOneToMany_ManyToOneRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('home'); - $this->getDatabase()->createCollection('renters'); - $this->getDatabase()->createCollection('floors'); + static::getDatabase()->createCollection('home'); + static::getDatabase()->createCollection('renters'); + static::getDatabase()->createCollection('floors'); - $this->getDatabase()->createAttribute('home', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('renters', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('floors', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('home', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('renters', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('floors', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'home', relatedCollection: 'renters', type: Database::RELATION_ONE_TO_MANY, twoWay: true ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'renters', relatedCollection: 'floors', type: Database::RELATION_MANY_TO_ONE, @@ -10745,7 +11138,7 @@ public function testNestedOneToMany_ManyToOneRelationship(): void id: 'floor' ); - $this->getDatabase()->createDocument('home', new Document([ + static::getDatabase()->createDocument('home', new Document([ '$id' => 'home1', '$permissions' => [ Permission::read(Role::any()), @@ -10769,13 +11162,13 @@ public function testNestedOneToMany_ManyToOneRelationship(): void ], ])); - $home1 = $this->getDatabase()->getDocument('home', 'home1'); + $home1 = static::getDatabase()->getDocument('home', 'home1'); $this->assertEquals('renter1', $home1['renters'][0]['$id']); $this->assertEquals('floor1', $home1['renters'][0]['floor']['$id']); $this->assertArrayNotHasKey('home', $home1['renters'][0]); $this->assertArrayNotHasKey('renters', $home1['renters'][0]['floor']); - $this->getDatabase()->createDocument('floors', new Document([ + static::getDatabase()->createDocument('floors', new Document([ '$id' => 'floor2', '$permissions' => [ Permission::read(Role::any()), @@ -10799,7 +11192,7 @@ public function testNestedOneToMany_ManyToOneRelationship(): void ], ])); - $floor2 = $this->getDatabase()->getDocument('floors', 'floor2'); + $floor2 = static::getDatabase()->getDocument('floors', 'floor2'); $this->assertEquals('renter2', $floor2['renters'][0]['$id']); $this->assertArrayNotHasKey('floor', $floor2['renters'][0]); $this->assertEquals('home2', $floor2['renters'][0]['home']['$id']); @@ -10808,34 +11201,34 @@ public function testNestedOneToMany_ManyToOneRelationship(): void public function testNestedOneToMany_ManyToManyRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('owners'); - $this->getDatabase()->createCollection('cats'); - $this->getDatabase()->createCollection('toys'); + static::getDatabase()->createCollection('owners'); + static::getDatabase()->createCollection('cats'); + static::getDatabase()->createCollection('toys'); - $this->getDatabase()->createAttribute('owners', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('cats', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('toys', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('owners', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('cats', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('toys', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'owners', relatedCollection: 'cats', type: Database::RELATION_ONE_TO_MANY, twoWay: true, twoWayKey: 'owner' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'cats', relatedCollection: 'toys', type: Database::RELATION_MANY_TO_MANY, twoWay: true ); - $this->getDatabase()->createDocument('owners', new Document([ + static::getDatabase()->createDocument('owners', new Document([ '$id' => 'owner1', '$permissions' => [ Permission::read(Role::any()), @@ -10861,13 +11254,13 @@ public function testNestedOneToMany_ManyToManyRelationship(): void ], ])); - $owner1 = $this->getDatabase()->getDocument('owners', 'owner1'); + $owner1 = static::getDatabase()->getDocument('owners', 'owner1'); $this->assertEquals('cat1', $owner1['cats'][0]['$id']); $this->assertArrayNotHasKey('owner', $owner1['cats'][0]); $this->assertEquals('toy1', $owner1['cats'][0]['toys'][0]['$id']); $this->assertArrayNotHasKey('cats', $owner1['cats'][0]['toys'][0]); - $this->getDatabase()->createDocument('toys', new Document([ + static::getDatabase()->createDocument('toys', new Document([ '$id' => 'toy2', '$permissions' => [ Permission::read(Role::any()), @@ -10891,7 +11284,7 @@ public function testNestedOneToMany_ManyToManyRelationship(): void ], ])); - $toy2 = $this->getDatabase()->getDocument('toys', 'toy2'); + $toy2 = static::getDatabase()->getDocument('toys', 'toy2'); $this->assertEquals('cat2', $toy2['cats'][0]['$id']); $this->assertArrayNotHasKey('toys', $toy2['cats'][0]); $this->assertEquals('owner2', $toy2['cats'][0]['owner']['$id']); @@ -10900,27 +11293,27 @@ public function testNestedOneToMany_ManyToManyRelationship(): void public function testNestedManyToOne_OneToOneRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('towns'); - $this->getDatabase()->createCollection('homelands'); - $this->getDatabase()->createCollection('capitals'); + static::getDatabase()->createCollection('towns'); + static::getDatabase()->createCollection('homelands'); + static::getDatabase()->createCollection('capitals'); - $this->getDatabase()->createAttribute('towns', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('homelands', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('capitals', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('towns', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('homelands', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('capitals', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'towns', relatedCollection: 'homelands', type: Database::RELATION_MANY_TO_ONE, twoWay: true, id: 'homeland' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'homelands', relatedCollection: 'capitals', type: Database::RELATION_ONE_TO_ONE, @@ -10929,7 +11322,7 @@ public function testNestedManyToOne_OneToOneRelationship(): void twoWayKey: 'homeland' ); - $this->getDatabase()->createDocument('towns', new Document([ + static::getDatabase()->createDocument('towns', new Document([ '$id' => 'town1', '$permissions' => [ Permission::read(Role::any()), @@ -10951,13 +11344,13 @@ public function testNestedManyToOne_OneToOneRelationship(): void ], ])); - $town1 = $this->getDatabase()->getDocument('towns', 'town1'); + $town1 = static::getDatabase()->getDocument('towns', 'town1'); $this->assertEquals('homeland1', $town1['homeland']['$id']); $this->assertArrayNotHasKey('towns', $town1['homeland']); $this->assertEquals('capital1', $town1['homeland']['capital']['$id']); $this->assertArrayNotHasKey('homeland', $town1['homeland']['capital']); - $this->getDatabase()->createDocument('capitals', new Document([ + static::getDatabase()->createDocument('capitals', new Document([ '$id' => 'capital2', '$permissions' => [ Permission::read(Role::any()), @@ -10988,7 +11381,7 @@ public function testNestedManyToOne_OneToOneRelationship(): void ], ])); - $capital2 = $this->getDatabase()->getDocument('capitals', 'capital2'); + $capital2 = static::getDatabase()->getDocument('capitals', 'capital2'); $this->assertEquals('homeland2', $capital2['homeland']['$id']); $this->assertArrayNotHasKey('capital', $capital2['homeland']); $this->assertEquals(2, \count($capital2['homeland']['towns'])); @@ -10998,27 +11391,27 @@ public function testNestedManyToOne_OneToOneRelationship(): void public function testNestedManyToOne_OneToManyRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('players'); - $this->getDatabase()->createCollection('teams'); - $this->getDatabase()->createCollection('supporters'); + static::getDatabase()->createCollection('players'); + static::getDatabase()->createCollection('teams'); + static::getDatabase()->createCollection('supporters'); - $this->getDatabase()->createAttribute('players', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('teams', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('supporters', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('players', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('teams', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('supporters', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'players', relatedCollection: 'teams', type: Database::RELATION_MANY_TO_ONE, twoWay: true, id: 'team' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'teams', relatedCollection: 'supporters', type: Database::RELATION_ONE_TO_MANY, @@ -11027,7 +11420,7 @@ public function testNestedManyToOne_OneToManyRelationship(): void twoWayKey: 'team' ); - $this->getDatabase()->createDocument('players', new Document([ + static::getDatabase()->createDocument('players', new Document([ '$id' => 'player1', '$permissions' => [ Permission::read(Role::any()), @@ -11058,14 +11451,14 @@ public function testNestedManyToOne_OneToManyRelationship(): void ], ])); - $player1 = $this->getDatabase()->getDocument('players', 'player1'); + $player1 = static::getDatabase()->getDocument('players', 'player1'); $this->assertEquals('team1', $player1['team']['$id']); $this->assertArrayNotHasKey('players', $player1['team']); $this->assertEquals(2, \count($player1['team']['supporters'])); $this->assertEquals('supporter1', $player1['team']['supporters'][0]['$id']); $this->assertEquals('supporter2', $player1['team']['supporters'][1]['$id']); - $this->getDatabase()->createDocument('supporters', new Document([ + static::getDatabase()->createDocument('supporters', new Document([ '$id' => 'supporter3', '$permissions' => [ Permission::read(Role::any()), @@ -11096,7 +11489,7 @@ public function testNestedManyToOne_OneToManyRelationship(): void ], ])); - $supporter3 = $this->getDatabase()->getDocument('supporters', 'supporter3'); + $supporter3 = static::getDatabase()->getDocument('supporters', 'supporter3'); $this->assertEquals('team2', $supporter3['team']['$id']); $this->assertArrayNotHasKey('supporters', $supporter3['team']); $this->assertEquals(2, \count($supporter3['team']['players'])); @@ -11106,27 +11499,27 @@ public function testNestedManyToOne_OneToManyRelationship(): void public function testNestedManyToOne_ManyToOne(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('cows'); - $this->getDatabase()->createCollection('farms'); - $this->getDatabase()->createCollection('farmer'); + static::getDatabase()->createCollection('cows'); + static::getDatabase()->createCollection('farms'); + static::getDatabase()->createCollection('farmer'); - $this->getDatabase()->createAttribute('cows', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('farms', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('farmer', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('cows', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('farms', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('farmer', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'cows', relatedCollection: 'farms', type: Database::RELATION_MANY_TO_ONE, twoWay: true, id: 'farm' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'farms', relatedCollection: 'farmer', type: Database::RELATION_MANY_TO_ONE, @@ -11134,7 +11527,7 @@ public function testNestedManyToOne_ManyToOne(): void id: 'farmer' ); - $this->getDatabase()->createDocument('cows', new Document([ + static::getDatabase()->createDocument('cows', new Document([ '$id' => 'cow1', '$permissions' => [ Permission::read(Role::any()), @@ -11156,13 +11549,13 @@ public function testNestedManyToOne_ManyToOne(): void ], ])); - $cow1 = $this->getDatabase()->getDocument('cows', 'cow1'); + $cow1 = static::getDatabase()->getDocument('cows', 'cow1'); $this->assertEquals('farm1', $cow1['farm']['$id']); $this->assertArrayNotHasKey('cows', $cow1['farm']); $this->assertEquals('farmer1', $cow1['farm']['farmer']['$id']); $this->assertArrayNotHasKey('farms', $cow1['farm']['farmer']); - $this->getDatabase()->createDocument('farmer', new Document([ + static::getDatabase()->createDocument('farmer', new Document([ '$id' => 'farmer2', '$permissions' => [ Permission::read(Role::any()), @@ -11195,7 +11588,7 @@ public function testNestedManyToOne_ManyToOne(): void ], ])); - $farmer2 = $this->getDatabase()->getDocument('farmer', 'farmer2'); + $farmer2 = static::getDatabase()->getDocument('farmer', 'farmer2'); $this->assertEquals('farm2', $farmer2['farms'][0]['$id']); $this->assertArrayNotHasKey('farmer', $farmer2['farms'][0]); $this->assertEquals(2, \count($farmer2['farms'][0]['cows'])); @@ -11205,34 +11598,34 @@ public function testNestedManyToOne_ManyToOne(): void public function testNestedManyToOne_ManyToManyRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('books'); - $this->getDatabase()->createCollection('entrants'); - $this->getDatabase()->createCollection('rooms'); + static::getDatabase()->createCollection('books'); + static::getDatabase()->createCollection('entrants'); + static::getDatabase()->createCollection('rooms'); - $this->getDatabase()->createAttribute('books', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('entrants', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('rooms', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('books', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('entrants', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('rooms', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'books', relatedCollection: 'entrants', type: Database::RELATION_MANY_TO_ONE, twoWay: true, id: 'entrant' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'entrants', relatedCollection: 'rooms', type: Database::RELATION_MANY_TO_MANY, twoWay: true, ); - $this->getDatabase()->createDocument('books', new Document([ + static::getDatabase()->createDocument('books', new Document([ '$id' => 'book1', '$permissions' => [ Permission::read(Role::any()), @@ -11263,7 +11656,7 @@ public function testNestedManyToOne_ManyToManyRelationship(): void ], ])); - $book1 = $this->getDatabase()->getDocument('books', 'book1'); + $book1 = static::getDatabase()->getDocument('books', 'book1'); $this->assertEquals('entrant1', $book1['entrant']['$id']); $this->assertArrayNotHasKey('books', $book1['entrant']); $this->assertEquals(2, \count($book1['entrant']['rooms'])); @@ -11273,26 +11666,26 @@ public function testNestedManyToOne_ManyToManyRelationship(): void public function testNestedManyToMany_OneToOneRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('stones'); - $this->getDatabase()->createCollection('hearths'); - $this->getDatabase()->createCollection('plots'); + static::getDatabase()->createCollection('stones'); + static::getDatabase()->createCollection('hearths'); + static::getDatabase()->createCollection('plots'); - $this->getDatabase()->createAttribute('stones', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('hearths', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('plots', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('stones', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('hearths', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('plots', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'stones', relatedCollection: 'hearths', type: Database::RELATION_MANY_TO_MANY, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'hearths', relatedCollection: 'plots', type: Database::RELATION_ONE_TO_ONE, @@ -11301,7 +11694,7 @@ public function testNestedManyToMany_OneToOneRelationship(): void twoWayKey: 'hearth' ); - $this->getDatabase()->createDocument('stones', new Document([ + static::getDatabase()->createDocument('stones', new Document([ '$id' => 'stone1', '$permissions' => [ Permission::read(Role::any()), @@ -11339,7 +11732,7 @@ public function testNestedManyToMany_OneToOneRelationship(): void ], ])); - $stone1 = $this->getDatabase()->getDocument('stones', 'stone1'); + $stone1 = static::getDatabase()->getDocument('stones', 'stone1'); $this->assertEquals(2, \count($stone1['hearths'])); $this->assertEquals('hearth1', $stone1['hearths'][0]['$id']); $this->assertEquals('hearth2', $stone1['hearths'][1]['$id']); @@ -11348,7 +11741,7 @@ public function testNestedManyToMany_OneToOneRelationship(): void $this->assertEquals('plot2', $stone1['hearths'][1]['plot']['$id']); $this->assertArrayNotHasKey('hearth', $stone1['hearths'][0]['plot']); - $this->getDatabase()->createDocument('plots', new Document([ + static::getDatabase()->createDocument('plots', new Document([ '$id' => 'plot3', '$permissions' => [ Permission::read(Role::any()), @@ -11372,7 +11765,7 @@ public function testNestedManyToMany_OneToOneRelationship(): void ], ])); - $plot3 = $this->getDatabase()->getDocument('plots', 'plot3'); + $plot3 = static::getDatabase()->getDocument('plots', 'plot3'); $this->assertEquals('hearth3', $plot3['hearth']['$id']); $this->assertArrayNotHasKey('plot', $plot3['hearth']); $this->assertEquals('stone2', $plot3['hearth']['stones'][0]['$id']); @@ -11381,26 +11774,26 @@ public function testNestedManyToMany_OneToOneRelationship(): void public function testNestedManyToMany_OneToManyRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('groups'); - $this->getDatabase()->createCollection('tounaments'); - $this->getDatabase()->createCollection('prizes'); + static::getDatabase()->createCollection('groups'); + static::getDatabase()->createCollection('tounaments'); + static::getDatabase()->createCollection('prizes'); - $this->getDatabase()->createAttribute('groups', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('tounaments', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('prizes', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('groups', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('tounaments', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('prizes', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'groups', relatedCollection: 'tounaments', type: Database::RELATION_MANY_TO_MANY, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'tounaments', relatedCollection: 'prizes', type: Database::RELATION_ONE_TO_MANY, @@ -11465,7 +11858,7 @@ public function testNestedManyToMany_OneToManyRelationship(): void ], ])); - $group1 = $this->getDatabase()->getDocument('groups', 'group1'); + $group1 = static::getDatabase()->getDocument('groups', 'group1'); $this->assertEquals(2, \count($group1['tounaments'])); $this->assertEquals('tounament1', $group1['tounaments'][0]['$id']); $this->assertEquals('tounament2', $group1['tounaments'][1]['$id']); @@ -11478,26 +11871,26 @@ public function testNestedManyToMany_OneToManyRelationship(): void public function testNestedManyToMany_ManyToOneRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('platforms'); - $this->getDatabase()->createCollection('games'); - $this->getDatabase()->createCollection('publishers'); + static::getDatabase()->createCollection('platforms'); + static::getDatabase()->createCollection('games'); + static::getDatabase()->createCollection('publishers'); - $this->getDatabase()->createAttribute('platforms', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('games', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('publishers', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('platforms', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('games', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('publishers', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'platforms', relatedCollection: 'games', type: Database::RELATION_MANY_TO_MANY, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'games', relatedCollection: 'publishers', type: Database::RELATION_MANY_TO_ONE, @@ -11506,7 +11899,7 @@ public function testNestedManyToMany_ManyToOneRelationship(): void twoWayKey: 'games' ); - $this->getDatabase()->createDocument('platforms', new Document([ + static::getDatabase()->createDocument('platforms', new Document([ '$id' => 'platform1', '$permissions' => [ Permission::read(Role::any()), @@ -11544,7 +11937,7 @@ public function testNestedManyToMany_ManyToOneRelationship(): void ] ])); - $platform1 = $this->getDatabase()->getDocument('platforms', 'platform1'); + $platform1 = static::getDatabase()->getDocument('platforms', 'platform1'); $this->assertEquals(2, \count($platform1['games'])); $this->assertEquals('game1', $platform1['games'][0]['$id']); $this->assertEquals('game2', $platform1['games'][1]['$id']); @@ -11553,7 +11946,7 @@ public function testNestedManyToMany_ManyToOneRelationship(): void $this->assertEquals('publisher2', $platform1['games'][1]['publisher']['$id']); $this->assertArrayNotHasKey('games', $platform1['games'][0]['publisher']); - $this->getDatabase()->createDocument('publishers', new Document([ + static::getDatabase()->createDocument('publishers', new Document([ '$id' => 'publisher3', '$permissions' => [ Permission::read(Role::any()), @@ -11579,7 +11972,7 @@ public function testNestedManyToMany_ManyToOneRelationship(): void ], ])); - $publisher3 = $this->getDatabase()->getDocument('publishers', 'publisher3'); + $publisher3 = static::getDatabase()->getDocument('publishers', 'publisher3'); $this->assertEquals(1, \count($publisher3['games'])); $this->assertEquals('game3', $publisher3['games'][0]['$id']); $this->assertArrayNotHasKey('publisher', $publisher3['games'][0]); @@ -11589,26 +11982,26 @@ public function testNestedManyToMany_ManyToOneRelationship(): void public function testNestedManyToMany_ManyToManyRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('sauces'); - $this->getDatabase()->createCollection('pizzas'); - $this->getDatabase()->createCollection('toppings'); + static::getDatabase()->createCollection('sauces'); + static::getDatabase()->createCollection('pizzas'); + static::getDatabase()->createCollection('toppings'); - $this->getDatabase()->createAttribute('sauces', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('pizzas', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('toppings', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('sauces', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('pizzas', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('toppings', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'sauces', relatedCollection: 'pizzas', type: Database::RELATION_MANY_TO_MANY, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'pizzas', relatedCollection: 'toppings', type: Database::RELATION_MANY_TO_MANY, @@ -11617,7 +12010,7 @@ public function testNestedManyToMany_ManyToManyRelationship(): void twoWayKey: 'pizzas' ); - $this->getDatabase()->createDocument('sauces', new Document([ + static::getDatabase()->createDocument('sauces', new Document([ '$id' => 'sauce1', '$permissions' => [ Permission::read(Role::any()), @@ -11673,7 +12066,7 @@ public function testNestedManyToMany_ManyToManyRelationship(): void ] ])); - $sauce1 = $this->getDatabase()->getDocument('sauces', 'sauce1'); + $sauce1 = static::getDatabase()->getDocument('sauces', 'sauce1'); $this->assertEquals(2, \count($sauce1['pizzas'])); $this->assertEquals('pizza1', $sauce1['pizzas'][0]['$id']); $this->assertEquals('pizza2', $sauce1['pizzas'][1]['$id']); @@ -11690,20 +12083,20 @@ public function testNestedManyToMany_ManyToManyRelationship(): void public function testInheritRelationshipPermissions(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('lawns', permissions: [Permission::create(Role::any())], documentSecurity: true); - $this->getDatabase()->createCollection('trees', permissions: [Permission::create(Role::any())], documentSecurity: true); - $this->getDatabase()->createCollection('birds', permissions: [Permission::create(Role::any())], documentSecurity: true); + static::getDatabase()->createCollection('lawns', permissions: [Permission::create(Role::any())], documentSecurity: true); + static::getDatabase()->createCollection('trees', permissions: [Permission::create(Role::any())], documentSecurity: true); + static::getDatabase()->createCollection('birds', permissions: [Permission::create(Role::any())], documentSecurity: true); - $this->getDatabase()->createAttribute('lawns', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('trees', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('birds', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('lawns', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('trees', 'name', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('birds', 'name', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'lawns', relatedCollection: 'trees', type: Database::RELATION_ONE_TO_MANY, @@ -11711,7 +12104,7 @@ public function testInheritRelationshipPermissions(): void twoWayKey: 'lawn', onDelete: Database::RELATION_MUTATE_CASCADE, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'trees', relatedCollection: 'birds', type: Database::RELATION_MANY_TO_MANY, @@ -11726,7 +12119,7 @@ public function testInheritRelationshipPermissions(): void Permission::delete(Role::user('user2')), ]; - $this->getDatabase()->createDocument('lawns', new Document([ + static::getDatabase()->createDocument('lawns', new Document([ '$id' => 'lawn1', '$permissions' => $permissions, 'name' => 'Lawn 1', @@ -11748,13 +12141,13 @@ public function testInheritRelationshipPermissions(): void ], ])); - $lawn1 = $this->getDatabase()->getDocument('lawns', 'lawn1'); + $lawn1 = static::getDatabase()->getDocument('lawns', 'lawn1'); $this->assertEquals($permissions, $lawn1->getPermissions()); $this->assertEquals($permissions, $lawn1['trees'][0]->getPermissions()); $this->assertEquals($permissions, $lawn1['trees'][0]['birds'][0]->getPermissions()); $this->assertEquals($permissions, $lawn1['trees'][0]['birds'][1]->getPermissions()); - $tree1 = $this->getDatabase()->getDocument('trees', 'tree1'); + $tree1 = static::getDatabase()->getDocument('trees', 'tree1'); $this->assertEquals($permissions, $tree1->getPermissions()); $this->assertEquals($permissions, $tree1['lawn']->getPermissions()); $this->assertEquals($permissions, $tree1['birds'][0]->getPermissions()); @@ -11766,18 +12159,18 @@ public function testInheritRelationshipPermissions(): void */ public function testEnforceRelationshipPermissions(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); - $lawn1 = $this->getDatabase()->getDocument('lawns', 'lawn1'); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); + $lawn1 = static::getDatabase()->getDocument('lawns', 'lawn1'); $this->assertEquals('Lawn 1', $lawn1['name']); // Try update root document try { - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'lawns', $lawn1->getId(), $lawn1->setAttribute('name', 'Lawn 1 Updated') @@ -11789,7 +12182,7 @@ public function testEnforceRelationshipPermissions(): void // Try delete root document try { - $this->getDatabase()->deleteDocument( + static::getDatabase()->deleteDocument( 'lawns', $lawn1->getId(), ); @@ -11798,11 +12191,11 @@ public function testEnforceRelationshipPermissions(): void $this->assertEquals('Missing "delete" permission for role "user:user2". Only "["any"]" scopes are allowed and "["user:user2"]" was given.', $e->getMessage()); } - $tree1 = $this->getDatabase()->getDocument('trees', 'tree1'); + $tree1 = static::getDatabase()->getDocument('trees', 'tree1'); // Try update nested document try { - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'trees', $tree1->getId(), $tree1->setAttribute('name', 'Tree 1 Updated') @@ -11814,7 +12207,7 @@ public function testEnforceRelationshipPermissions(): void // Try delete nested document try { - $this->getDatabase()->deleteDocument( + static::getDatabase()->deleteDocument( 'trees', $tree1->getId(), ); @@ -11823,11 +12216,11 @@ public function testEnforceRelationshipPermissions(): void $this->assertEquals('Missing "delete" permission for role "user:user2". Only "["any"]" scopes are allowed and "["user:user2"]" was given.', $e->getMessage()); } - $bird1 = $this->getDatabase()->getDocument('birds', 'bird1'); + $bird1 = static::getDatabase()->getDocument('birds', 'bird1'); // Try update multi-level nested document try { - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( 'birds', $bird1->getId(), $bird1->setAttribute('name', 'Bird 1 Updated') @@ -11839,7 +12232,7 @@ public function testEnforceRelationshipPermissions(): void // Try delete multi-level nested document try { - $this->getDatabase()->deleteDocument( + static::getDatabase()->deleteDocument( 'birds', $bird1->getId(), ); @@ -11848,12 +12241,12 @@ public function testEnforceRelationshipPermissions(): void $this->assertEquals('Missing "delete" permission for role "user:user2". Only "["any"]" scopes are allowed and "["user:user2"]" was given.', $e->getMessage()); } - self::$authorization->addRole(Role::user('user1')->toString()); + Authorization::setRole(Role::user('user1')->toString()); - $bird1 = $this->getDatabase()->getDocument('birds', 'bird1'); + $bird1 = static::getDatabase()->getDocument('birds', 'bird1'); // Try update multi-level nested document - $bird1 = $this->getDatabase()->updateDocument( + $bird1 = static::getDatabase()->updateDocument( 'birds', $bird1->getId(), $bird1->setAttribute('name', 'Bird 1 Updated') @@ -11861,20 +12254,20 @@ public function testEnforceRelationshipPermissions(): void $this->assertEquals('Bird 1 Updated', $bird1['name']); - self::$authorization->addRole(Role::user('user2')->toString()); + Authorization::setRole(Role::user('user2')->toString()); // Try delete multi-level nested document - $deleted = $this->getDatabase()->deleteDocument( + $deleted = static::getDatabase()->deleteDocument( 'birds', $bird1->getId(), ); $this->assertEquals(true, $deleted); - $tree1 = $this->getDatabase()->getDocument('trees', 'tree1'); + $tree1 = static::getDatabase()->getDocument('trees', 'tree1'); $this->assertEquals(1, count($tree1['birds'])); // Try update nested document - $tree1 = $this->getDatabase()->updateDocument( + $tree1 = static::getDatabase()->updateDocument( 'trees', $tree1->getId(), $tree1->setAttribute('name', 'Tree 1 Updated') @@ -11883,17 +12276,17 @@ public function testEnforceRelationshipPermissions(): void $this->assertEquals('Tree 1 Updated', $tree1['name']); // Try delete nested document - $deleted = $this->getDatabase()->deleteDocument( + $deleted = static::getDatabase()->deleteDocument( 'trees', $tree1->getId(), ); $this->assertEquals(true, $deleted); - $lawn1 = $this->getDatabase()->getDocument('lawns', 'lawn1'); + $lawn1 = static::getDatabase()->getDocument('lawns', 'lawn1'); $this->assertEquals(0, count($lawn1['trees'])); // Create document with no permissions - $this->getDatabase()->createDocument('lawns', new Document([ + static::getDatabase()->createDocument('lawns', new Document([ '$id' => 'lawn2', 'name' => 'Lawn 2', 'trees' => [ @@ -11910,19 +12303,19 @@ public function testEnforceRelationshipPermissions(): void ], ])); - $lawn2 = $this->getDatabase()->getDocument('lawns', 'lawn2'); + $lawn2 = static::getDatabase()->getDocument('lawns', 'lawn2'); $this->assertEquals(true, $lawn2->isEmpty()); - $tree2 = $this->getDatabase()->getDocument('trees', 'tree2'); + $tree2 = static::getDatabase()->getDocument('trees', 'tree2'); $this->assertEquals(true, $tree2->isEmpty()); - $bird3 = $this->getDatabase()->getDocument('birds', 'bird3'); + $bird3 = static::getDatabase()->getDocument('birds', 'bird3'); $this->assertEquals(true, $bird3->isEmpty()); } public function testExceedMaxDepthOneToMany(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -11932,24 +12325,24 @@ public function testExceedMaxDepthOneToMany(): void $level3Collection = 'level3OneToMany'; $level4Collection = 'level4OneToMany'; - $this->getDatabase()->createCollection($level1Collection); - $this->getDatabase()->createCollection($level2Collection); - $this->getDatabase()->createCollection($level3Collection); - $this->getDatabase()->createCollection($level4Collection); + static::getDatabase()->createCollection($level1Collection); + static::getDatabase()->createCollection($level2Collection); + static::getDatabase()->createCollection($level3Collection); + static::getDatabase()->createCollection($level4Collection); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level1Collection, relatedCollection: $level2Collection, type: Database::RELATION_ONE_TO_MANY, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level2Collection, relatedCollection: $level3Collection, type: Database::RELATION_ONE_TO_MANY, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level3Collection, relatedCollection: $level4Collection, type: Database::RELATION_ONE_TO_MANY, @@ -11957,7 +12350,7 @@ public function testExceedMaxDepthOneToMany(): void ); // Exceed create depth - $level1 = $this->getDatabase()->createDocument($level1Collection, new Document([ + $level1 = static::getDatabase()->createDocument($level1Collection, new Document([ '$id' => 'level1', '$permissions' => [ Permission::read(Role::any()), @@ -11986,13 +12379,13 @@ public function testExceedMaxDepthOneToMany(): void $this->assertArrayNotHasKey('level4', $level1[$level2Collection][0][$level3Collection][0]); // Make sure level 4 document was not created - $level3 = $this->getDatabase()->getDocument($level3Collection, 'level3'); + $level3 = static::getDatabase()->getDocument($level3Collection, 'level3'); $this->assertEquals(0, count($level3[$level4Collection])); - $level4 = $this->getDatabase()->getDocument($level4Collection, 'level4'); + $level4 = static::getDatabase()->getDocument($level4Collection, 'level4'); $this->assertTrue($level4->isEmpty()); // Exceed fetch depth - $level1 = $this->getDatabase()->getDocument($level1Collection, 'level1'); + $level1 = static::getDatabase()->getDocument($level1Collection, 'level1'); $this->assertEquals(1, count($level1[$level2Collection])); $this->assertEquals('level2', $level1[$level2Collection][0]->getId()); $this->assertEquals(1, count($level1[$level2Collection][0][$level3Collection])); @@ -12001,23 +12394,23 @@ public function testExceedMaxDepthOneToMany(): void // Exceed update depth - $level1 = $this->getDatabase()->updateDocument( + $level1 = static::getDatabase()->updateDocument( $level1Collection, 'level1', $level1 - ->setAttribute($level2Collection, [new Document([ - '$id' => 'level2new', - $level3Collection => [ - [ - '$id' => 'level3new', - $level4Collection => [ - [ - '$id' => 'level4new', + ->setAttribute($level2Collection, [new Document([ + '$id' => 'level2new', + $level3Collection => [ + [ + '$id' => 'level3new', + $level4Collection => [ + [ + '$id' => 'level4new', + ], ], ], ], - ], - ])]) + ])]) ); $this->assertEquals(1, count($level1[$level2Collection])); $this->assertEquals('level2new', $level1[$level2Collection][0]->getId()); @@ -12026,15 +12419,15 @@ public function testExceedMaxDepthOneToMany(): void $this->assertArrayNotHasKey($level4Collection, $level1[$level2Collection][0][$level3Collection][0]); // Make sure level 4 document was not created - $level3 = $this->getDatabase()->getDocument($level3Collection, 'level3new'); + $level3 = static::getDatabase()->getDocument($level3Collection, 'level3new'); $this->assertEquals(0, count($level3[$level4Collection])); - $level4 = $this->getDatabase()->getDocument($level4Collection, 'level4new'); + $level4 = static::getDatabase()->getDocument($level4Collection, 'level4new'); $this->assertTrue($level4->isEmpty()); } public function testExceedMaxDepthOneToOne(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -12044,24 +12437,24 @@ public function testExceedMaxDepthOneToOne(): void $level3Collection = 'level3OneToOne'; $level4Collection = 'level4OneToOne'; - $this->getDatabase()->createCollection($level1Collection); - $this->getDatabase()->createCollection($level2Collection); - $this->getDatabase()->createCollection($level3Collection); - $this->getDatabase()->createCollection($level4Collection); + static::getDatabase()->createCollection($level1Collection); + static::getDatabase()->createCollection($level2Collection); + static::getDatabase()->createCollection($level3Collection); + static::getDatabase()->createCollection($level4Collection); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level1Collection, relatedCollection: $level2Collection, type: Database::RELATION_ONE_TO_ONE, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level2Collection, relatedCollection: $level3Collection, type: Database::RELATION_ONE_TO_ONE, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level3Collection, relatedCollection: $level4Collection, type: Database::RELATION_ONE_TO_ONE, @@ -12069,7 +12462,7 @@ public function testExceedMaxDepthOneToOne(): void ); // Exceed create depth - $level1 = $this->getDatabase()->createDocument($level1Collection, new Document([ + $level1 = static::getDatabase()->createDocument($level1Collection, new Document([ '$id' => 'level1', '$permissions' => [ Permission::read(Role::any()), @@ -12092,18 +12485,18 @@ public function testExceedMaxDepthOneToOne(): void $this->assertArrayNotHasKey($level4Collection, $level1[$level2Collection][$level3Collection]); // Confirm the 4th level document does not exist - $level3 = $this->getDatabase()->getDocument($level3Collection, 'level3'); + $level3 = static::getDatabase()->getDocument($level3Collection, 'level3'); $this->assertNull($level3[$level4Collection]); // Create level 4 document $level3->setAttribute($level4Collection, new Document([ '$id' => 'level4', ])); - $level3 = $this->getDatabase()->updateDocument($level3Collection, $level3->getId(), $level3); + $level3 = static::getDatabase()->updateDocument($level3Collection, $level3->getId(), $level3); $this->assertEquals('level4', $level3[$level4Collection]->getId()); // Exceed fetch depth - $level1 = $this->getDatabase()->getDocument($level1Collection, 'level1'); + $level1 = static::getDatabase()->getDocument($level1Collection, 'level1'); $this->assertArrayHasKey($level2Collection, $level1); $this->assertEquals('level2', $level1[$level2Collection]->getId()); $this->assertArrayHasKey($level3Collection, $level1[$level2Collection]); @@ -12113,7 +12506,7 @@ public function testExceedMaxDepthOneToOne(): void public function testExceedMaxDepthOneToOneNull(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -12123,31 +12516,31 @@ public function testExceedMaxDepthOneToOneNull(): void $level3Collection = 'level3OneToOneNull'; $level4Collection = 'level4OneToOneNull'; - $this->getDatabase()->createCollection($level1Collection); - $this->getDatabase()->createCollection($level2Collection); - $this->getDatabase()->createCollection($level3Collection); - $this->getDatabase()->createCollection($level4Collection); + static::getDatabase()->createCollection($level1Collection); + static::getDatabase()->createCollection($level2Collection); + static::getDatabase()->createCollection($level3Collection); + static::getDatabase()->createCollection($level4Collection); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level1Collection, relatedCollection: $level2Collection, type: Database::RELATION_ONE_TO_ONE, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level2Collection, relatedCollection: $level3Collection, type: Database::RELATION_ONE_TO_ONE, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level3Collection, relatedCollection: $level4Collection, type: Database::RELATION_ONE_TO_ONE, twoWay: true, ); - $level1 = $this->getDatabase()->createDocument($level1Collection, new Document([ + $level1 = static::getDatabase()->createDocument($level1Collection, new Document([ '$id' => 'level1', '$permissions' => [ Permission::read(Role::any()), @@ -12170,20 +12563,20 @@ public function testExceedMaxDepthOneToOneNull(): void $this->assertArrayNotHasKey($level4Collection, $level1[$level2Collection][$level3Collection]); // Confirm the 4th level document does not exist - $level3 = $this->getDatabase()->getDocument($level3Collection, 'level3'); + $level3 = static::getDatabase()->getDocument($level3Collection, 'level3'); $this->assertNull($level3[$level4Collection]); // Create level 4 document $level3->setAttribute($level4Collection, new Document([ '$id' => 'level4', ])); - $level3 = $this->getDatabase()->updateDocument($level3Collection, $level3->getId(), $level3); + $level3 = static::getDatabase()->updateDocument($level3Collection, $level3->getId(), $level3); $this->assertEquals('level4', $level3[$level4Collection]->getId()); - $level3 = $this->getDatabase()->getDocument($level3Collection, 'level3'); + $level3 = static::getDatabase()->getDocument($level3Collection, 'level3'); $this->assertEquals('level4', $level3[$level4Collection]->getId()); // Exceed fetch depth - $level1 = $this->getDatabase()->getDocument($level1Collection, 'level1'); + $level1 = static::getDatabase()->getDocument($level1Collection, 'level1'); $this->assertArrayHasKey($level2Collection, $level1); $this->assertEquals('level2', $level1[$level2Collection]->getId()); $this->assertArrayHasKey($level3Collection, $level1[$level2Collection]); @@ -12193,7 +12586,7 @@ public function testExceedMaxDepthOneToOneNull(): void public function testExceedMaxDepthManyToOneParent(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -12203,31 +12596,31 @@ public function testExceedMaxDepthManyToOneParent(): void $level3Collection = 'level3ManyToOneParent'; $level4Collection = 'level4ManyToOneParent'; - $this->getDatabase()->createCollection($level1Collection); - $this->getDatabase()->createCollection($level2Collection); - $this->getDatabase()->createCollection($level3Collection); - $this->getDatabase()->createCollection($level4Collection); + static::getDatabase()->createCollection($level1Collection); + static::getDatabase()->createCollection($level2Collection); + static::getDatabase()->createCollection($level3Collection); + static::getDatabase()->createCollection($level4Collection); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level1Collection, relatedCollection: $level2Collection, type: Database::RELATION_MANY_TO_ONE, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level2Collection, relatedCollection: $level3Collection, type: Database::RELATION_MANY_TO_ONE, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level3Collection, relatedCollection: $level4Collection, type: Database::RELATION_MANY_TO_ONE, twoWay: true, ); - $level1 = $this->getDatabase()->createDocument($level1Collection, new Document([ + $level1 = static::getDatabase()->createDocument($level1Collection, new Document([ '$id' => 'level1', '$permissions' => [ Permission::read(Role::any()), @@ -12250,20 +12643,20 @@ public function testExceedMaxDepthManyToOneParent(): void $this->assertArrayNotHasKey($level4Collection, $level1[$level2Collection][$level3Collection]); // Confirm the 4th level document does not exist - $level3 = $this->getDatabase()->getDocument($level3Collection, 'level3'); + $level3 = static::getDatabase()->getDocument($level3Collection, 'level3'); $this->assertNull($level3[$level4Collection]); // Create level 4 document $level3->setAttribute($level4Collection, new Document([ '$id' => 'level4', ])); - $level3 = $this->getDatabase()->updateDocument($level3Collection, $level3->getId(), $level3); + $level3 = static::getDatabase()->updateDocument($level3Collection, $level3->getId(), $level3); $this->assertEquals('level4', $level3[$level4Collection]->getId()); - $level3 = $this->getDatabase()->getDocument($level3Collection, 'level3'); + $level3 = static::getDatabase()->getDocument($level3Collection, 'level3'); $this->assertEquals('level4', $level3[$level4Collection]->getId()); // Exceed fetch depth - $level1 = $this->getDatabase()->getDocument($level1Collection, 'level1'); + $level1 = static::getDatabase()->getDocument($level1Collection, 'level1'); $this->assertArrayHasKey($level2Collection, $level1); $this->assertEquals('level2', $level1[$level2Collection]->getId()); $this->assertArrayHasKey($level3Collection, $level1[$level2Collection]); @@ -12273,7 +12666,7 @@ public function testExceedMaxDepthManyToOneParent(): void public function testExceedMaxDepthOneToManyChild(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -12283,31 +12676,31 @@ public function testExceedMaxDepthOneToManyChild(): void $level3Collection = 'level3OneToManyChild'; $level4Collection = 'level4OneToManyChild'; - $this->getDatabase()->createCollection($level1Collection); - $this->getDatabase()->createCollection($level2Collection); - $this->getDatabase()->createCollection($level3Collection); - $this->getDatabase()->createCollection($level4Collection); + static::getDatabase()->createCollection($level1Collection); + static::getDatabase()->createCollection($level2Collection); + static::getDatabase()->createCollection($level3Collection); + static::getDatabase()->createCollection($level4Collection); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level1Collection, relatedCollection: $level2Collection, type: Database::RELATION_ONE_TO_MANY, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level2Collection, relatedCollection: $level3Collection, type: Database::RELATION_ONE_TO_MANY, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: $level3Collection, relatedCollection: $level4Collection, type: Database::RELATION_ONE_TO_MANY, twoWay: true, ); - $level1 = $this->getDatabase()->createDocument($level1Collection, new Document([ + $level1 = static::getDatabase()->createDocument($level1Collection, new Document([ '$id' => 'level1', '$permissions' => [ Permission::read(Role::any()), @@ -12336,23 +12729,23 @@ public function testExceedMaxDepthOneToManyChild(): void $this->assertArrayNotHasKey($level4Collection, $level1[$level2Collection][0][$level3Collection][0]); // Confirm the 4th level document does not exist - $level3 = $this->getDatabase()->getDocument($level3Collection, 'level3'); + $level3 = static::getDatabase()->getDocument($level3Collection, 'level3'); $this->assertEquals(0, count($level3[$level4Collection])); // Create level 4 document $level3->setAttribute($level4Collection, [new Document([ '$id' => 'level4', ])]); - $level3 = $this->getDatabase()->updateDocument($level3Collection, $level3->getId(), $level3); + $level3 = static::getDatabase()->updateDocument($level3Collection, $level3->getId(), $level3); $this->assertEquals('level4', $level3[$level4Collection][0]->getId()); // Verify level 4 document is set - $level3 = $this->getDatabase()->getDocument($level3Collection, 'level3'); + $level3 = static::getDatabase()->getDocument($level3Collection, 'level3'); $this->assertArrayHasKey($level4Collection, $level3); $this->assertEquals('level4', $level3[$level4Collection][0]->getId()); // Exceed fetch depth - $level4 = $this->getDatabase()->getDocument($level4Collection, 'level4'); + $level4 = static::getDatabase()->getDocument($level4Collection, 'level4'); $this->assertArrayHasKey($level3Collection, $level4); $this->assertEquals('level3', $level4[$level3Collection]->getId()); $this->assertArrayHasKey($level2Collection, $level4[$level3Collection]); @@ -12362,7 +12755,7 @@ public function testExceedMaxDepthOneToManyChild(): void public function testCreateRelationshipMissingCollection(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -12370,7 +12763,7 @@ public function testCreateRelationshipMissingCollection(): void $this->expectException(Exception::class); $this->expectExceptionMessage('Collection not found'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'missing', relatedCollection: 'missing', type: Database::RELATION_ONE_TO_MANY, @@ -12380,17 +12773,17 @@ public function testCreateRelationshipMissingCollection(): void public function testCreateRelationshipMissingRelatedCollection(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('test'); + static::getDatabase()->createCollection('test'); $this->expectException(Exception::class); $this->expectExceptionMessage('Related collection not found'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'test', relatedCollection: 'missing', type: Database::RELATION_ONE_TO_MANY, @@ -12400,15 +12793,15 @@ public function testCreateRelationshipMissingRelatedCollection(): void public function testCreateDuplicateRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('test1'); - $this->getDatabase()->createCollection('test2'); + static::getDatabase()->createCollection('test1'); + static::getDatabase()->createCollection('test2'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'test1', relatedCollection: 'test2', type: Database::RELATION_ONE_TO_MANY, @@ -12418,7 +12811,7 @@ public function testCreateDuplicateRelationship(): void $this->expectException(Exception::class); $this->expectExceptionMessage('Attribute already exists'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'test1', relatedCollection: 'test2', type: Database::RELATION_ONE_TO_MANY, @@ -12428,18 +12821,18 @@ public function testCreateDuplicateRelationship(): void public function testCreateInvalidRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('test3'); - $this->getDatabase()->createCollection('test4'); + static::getDatabase()->createCollection('test3'); + static::getDatabase()->createCollection('test4'); $this->expectException(Exception::class); $this->expectExceptionMessage('Invalid relationship type'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'test3', relatedCollection: 'test4', type: 'invalid', @@ -12504,7 +12897,7 @@ public function testOneToManyAndManyToOneDeleteRelationship(): void public function testDeleteMissingRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -12512,20 +12905,20 @@ public function testDeleteMissingRelationship(): void $this->expectException(Exception::class); $this->expectExceptionMessage('Attribute not found'); - $this->getDatabase()->deleteRelationship('test', 'test2'); + static::getDatabase()->deleteRelationship('test', 'test2'); } public function testCreateInvalidIntValueRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('invalid1'); - $this->getDatabase()->createCollection('invalid2'); + static::getDatabase()->createCollection('invalid1'); + static::getDatabase()->createCollection('invalid2'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'invalid1', relatedCollection: 'invalid2', type: Database::RELATION_ONE_TO_ONE, @@ -12535,7 +12928,7 @@ public function testCreateInvalidIntValueRelationship(): void $this->expectException(RelationshipException::class); $this->expectExceptionMessage('Invalid relationship value. Must be either a document, document ID, or an array of documents or document IDs.'); - $this->getDatabase()->createDocument('invalid1', new Document([ + static::getDatabase()->createDocument('invalid1', new Document([ '$id' => ID::unique(), 'invalid2' => 10, ])); @@ -12546,7 +12939,7 @@ public function testCreateInvalidIntValueRelationship(): void */ public function testCreateInvalidObjectValueRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } @@ -12554,7 +12947,7 @@ public function testCreateInvalidObjectValueRelationship(): void $this->expectException(RelationshipException::class); $this->expectExceptionMessage('Invalid relationship value. Must be either a document, document ID, or an array of documents or document IDs.'); - $this->getDatabase()->createDocument('invalid1', new Document([ + static::getDatabase()->createDocument('invalid1', new Document([ '$id' => ID::unique(), 'invalid2' => new \stdClass(), ])); @@ -12565,12 +12958,12 @@ public function testCreateInvalidObjectValueRelationship(): void */ public function testCreateInvalidArrayIntValueRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'invalid1', relatedCollection: 'invalid2', type: Database::RELATION_ONE_TO_MANY, @@ -12582,7 +12975,7 @@ public function testCreateInvalidArrayIntValueRelationship(): void $this->expectException(RelationshipException::class); $this->expectExceptionMessage('Invalid relationship value. Must be either a document, document ID, or an array of documents or document IDs.'); - $this->getDatabase()->createDocument('invalid1', new Document([ + static::getDatabase()->createDocument('invalid1', new Document([ '$id' => ID::unique(), 'invalid3' => [10], ])); @@ -12590,21 +12983,21 @@ public function testCreateInvalidArrayIntValueRelationship(): void public function testCreateEmptyValueRelationship(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('null1'); - $this->getDatabase()->createCollection('null2'); + static::getDatabase()->createCollection('null1'); + static::getDatabase()->createCollection('null2'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'null1', relatedCollection: 'null2', type: Database::RELATION_ONE_TO_ONE, twoWay: true, ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'null1', relatedCollection: 'null2', type: Database::RELATION_ONE_TO_MANY, @@ -12612,7 +13005,7 @@ public function testCreateEmptyValueRelationship(): void id: 'null3', twoWayKey: 'null4', ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'null1', relatedCollection: 'null2', type: Database::RELATION_MANY_TO_ONE, @@ -12620,7 +13013,7 @@ public function testCreateEmptyValueRelationship(): void id: 'null4', twoWayKey: 'null5', ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'null1', relatedCollection: 'null2', type: Database::RELATION_MANY_TO_MANY, @@ -12629,21 +13022,21 @@ public function testCreateEmptyValueRelationship(): void twoWayKey: 'null7', ); - $document = $this->getDatabase()->createDocument('null1', new Document([ + $document = static::getDatabase()->createDocument('null1', new Document([ '$id' => ID::unique(), 'null2' => null, ])); $this->assertEquals(null, $document->getAttribute('null2')); - $document = $this->getDatabase()->createDocument('null2', new Document([ + $document = static::getDatabase()->createDocument('null2', new Document([ '$id' => ID::unique(), 'null1' => null, ])); $this->assertEquals(null, $document->getAttribute('null1')); - $document = $this->getDatabase()->createDocument('null1', new Document([ + $document = static::getDatabase()->createDocument('null1', new Document([ '$id' => ID::unique(), 'null3' => null, ])); @@ -12651,35 +13044,35 @@ public function testCreateEmptyValueRelationship(): void // One to many will be empty array instead of null $this->assertEquals([], $document->getAttribute('null3')); - $document = $this->getDatabase()->createDocument('null2', new Document([ + $document = static::getDatabase()->createDocument('null2', new Document([ '$id' => ID::unique(), 'null4' => null, ])); $this->assertEquals(null, $document->getAttribute('null4')); - $document = $this->getDatabase()->createDocument('null1', new Document([ + $document = static::getDatabase()->createDocument('null1', new Document([ '$id' => ID::unique(), 'null4' => null, ])); $this->assertEquals(null, $document->getAttribute('null4')); - $document = $this->getDatabase()->createDocument('null2', new Document([ + $document = static::getDatabase()->createDocument('null2', new Document([ '$id' => ID::unique(), 'null5' => null, ])); $this->assertEquals([], $document->getAttribute('null5')); - $document = $this->getDatabase()->createDocument('null1', new Document([ + $document = static::getDatabase()->createDocument('null1', new Document([ '$id' => ID::unique(), 'null6' => null, ])); $this->assertEquals([], $document->getAttribute('null6')); - $document = $this->getDatabase()->createDocument('null2', new Document([ + $document = static::getDatabase()->createDocument('null2', new Document([ '$id' => ID::unique(), 'null7' => null, ])); @@ -12689,15 +13082,15 @@ public function testCreateEmptyValueRelationship(): void public function testDeleteCollectionDeletesRelationships(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('testers'); - $this->getDatabase()->createCollection('devices'); + static::getDatabase()->createCollection('testers'); + static::getDatabase()->createCollection('devices'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'testers', relatedCollection: 'devices', type: Database::RELATION_ONE_TO_MANY, @@ -12705,17 +13098,17 @@ public function testDeleteCollectionDeletesRelationships(): void twoWayKey: 'tester' ); - $testers = $this->getDatabase()->getCollection('testers'); - $devices = $this->getDatabase()->getCollection('devices'); + $testers = static::getDatabase()->getCollection('testers'); + $devices = static::getDatabase()->getCollection('devices'); $this->assertEquals(1, \count($testers->getAttribute('attributes'))); $this->assertEquals(1, \count($devices->getAttribute('attributes'))); $this->assertEquals(1, \count($devices->getAttribute('indexes'))); - $this->getDatabase()->deleteCollection('testers'); + static::getDatabase()->deleteCollection('testers'); - $testers = $this->getDatabase()->getCollection('testers'); - $devices = $this->getDatabase()->getCollection('devices'); + $testers = static::getDatabase()->getCollection('testers'); + $devices = static::getDatabase()->getCollection('devices'); $this->assertEquals(true, $testers->isEmpty()); $this->assertEquals(0, \count($devices->getAttribute('attributes'))); @@ -12724,15 +13117,15 @@ public function testDeleteCollectionDeletesRelationships(): void public function testDeleteTwoWayRelationshipFromChild(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('drivers'); - $this->getDatabase()->createCollection('licenses'); + static::getDatabase()->createCollection('drivers'); + static::getDatabase()->createCollection('licenses'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'drivers', relatedCollection: 'licenses', type: Database::RELATION_ONE_TO_ONE, @@ -12741,25 +13134,25 @@ public function testDeleteTwoWayRelationshipFromChild(): void twoWayKey: 'driver' ); - $drivers = $this->getDatabase()->getCollection('drivers'); - $licenses = $this->getDatabase()->getCollection('licenses'); + $drivers = static::getDatabase()->getCollection('drivers'); + $licenses = static::getDatabase()->getCollection('licenses'); $this->assertEquals(1, \count($drivers->getAttribute('attributes'))); $this->assertEquals(1, \count($drivers->getAttribute('indexes'))); $this->assertEquals(1, \count($licenses->getAttribute('attributes'))); $this->assertEquals(1, \count($licenses->getAttribute('indexes'))); - $this->getDatabase()->deleteRelationship('licenses', 'driver'); + static::getDatabase()->deleteRelationship('licenses', 'driver'); - $drivers = $this->getDatabase()->getCollection('drivers'); - $licenses = $this->getDatabase()->getCollection('licenses'); + $drivers = static::getDatabase()->getCollection('drivers'); + $licenses = static::getDatabase()->getCollection('licenses'); $this->assertEquals(0, \count($drivers->getAttribute('attributes'))); $this->assertEquals(0, \count($drivers->getAttribute('indexes'))); $this->assertEquals(0, \count($licenses->getAttribute('attributes'))); $this->assertEquals(0, \count($licenses->getAttribute('indexes'))); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'drivers', relatedCollection: 'licenses', type: Database::RELATION_ONE_TO_MANY, @@ -12768,25 +13161,25 @@ public function testDeleteTwoWayRelationshipFromChild(): void twoWayKey: 'driver' ); - $drivers = $this->getDatabase()->getCollection('drivers'); - $licenses = $this->getDatabase()->getCollection('licenses'); + $drivers = static::getDatabase()->getCollection('drivers'); + $licenses = static::getDatabase()->getCollection('licenses'); $this->assertEquals(1, \count($drivers->getAttribute('attributes'))); $this->assertEquals(0, \count($drivers->getAttribute('indexes'))); $this->assertEquals(1, \count($licenses->getAttribute('attributes'))); $this->assertEquals(1, \count($licenses->getAttribute('indexes'))); - $this->getDatabase()->deleteRelationship('licenses', 'driver'); + static::getDatabase()->deleteRelationship('licenses', 'driver'); - $drivers = $this->getDatabase()->getCollection('drivers'); - $licenses = $this->getDatabase()->getCollection('licenses'); + $drivers = static::getDatabase()->getCollection('drivers'); + $licenses = static::getDatabase()->getCollection('licenses'); $this->assertEquals(0, \count($drivers->getAttribute('attributes'))); $this->assertEquals(0, \count($drivers->getAttribute('indexes'))); $this->assertEquals(0, \count($licenses->getAttribute('attributes'))); $this->assertEquals(0, \count($licenses->getAttribute('indexes'))); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'licenses', relatedCollection: 'drivers', type: Database::RELATION_MANY_TO_ONE, @@ -12795,25 +13188,25 @@ public function testDeleteTwoWayRelationshipFromChild(): void twoWayKey: 'licenses' ); - $drivers = $this->getDatabase()->getCollection('drivers'); - $licenses = $this->getDatabase()->getCollection('licenses'); + $drivers = static::getDatabase()->getCollection('drivers'); + $licenses = static::getDatabase()->getCollection('licenses'); $this->assertEquals(1, \count($drivers->getAttribute('attributes'))); $this->assertEquals(0, \count($drivers->getAttribute('indexes'))); $this->assertEquals(1, \count($licenses->getAttribute('attributes'))); $this->assertEquals(1, \count($licenses->getAttribute('indexes'))); - $this->getDatabase()->deleteRelationship('drivers', 'licenses'); + static::getDatabase()->deleteRelationship('drivers', 'licenses'); - $drivers = $this->getDatabase()->getCollection('drivers'); - $licenses = $this->getDatabase()->getCollection('licenses'); + $drivers = static::getDatabase()->getCollection('drivers'); + $licenses = static::getDatabase()->getCollection('licenses'); $this->assertEquals(0, \count($drivers->getAttribute('attributes'))); $this->assertEquals(0, \count($drivers->getAttribute('indexes'))); $this->assertEquals(0, \count($licenses->getAttribute('attributes'))); $this->assertEquals(0, \count($licenses->getAttribute('indexes'))); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'licenses', relatedCollection: 'drivers', type: Database::RELATION_MANY_TO_MANY, @@ -12822,9 +13215,9 @@ public function testDeleteTwoWayRelationshipFromChild(): void twoWayKey: 'licenses' ); - $drivers = $this->getDatabase()->getCollection('drivers'); - $licenses = $this->getDatabase()->getCollection('licenses'); - $junction = $this->getDatabase()->getCollection('_' . $licenses->getInternalId() . '_' . $drivers->getInternalId()); + $drivers = static::getDatabase()->getCollection('drivers'); + $licenses = static::getDatabase()->getCollection('licenses'); + $junction = static::getDatabase()->getCollection('_' . $licenses->getInternalId() . '_' . $drivers->getInternalId()); $this->assertEquals(1, \count($drivers->getAttribute('attributes'))); $this->assertEquals(0, \count($drivers->getAttribute('indexes'))); @@ -12833,11 +13226,11 @@ public function testDeleteTwoWayRelationshipFromChild(): void $this->assertEquals(2, \count($junction->getAttribute('attributes'))); $this->assertEquals(2, \count($junction->getAttribute('indexes'))); - $this->getDatabase()->deleteRelationship('drivers', 'licenses'); + static::getDatabase()->deleteRelationship('drivers', 'licenses'); - $drivers = $this->getDatabase()->getCollection('drivers'); - $licenses = $this->getDatabase()->getCollection('licenses'); - $junction = $this->getDatabase()->getCollection('_licenses_drivers'); + $drivers = static::getDatabase()->getCollection('drivers'); + $licenses = static::getDatabase()->getCollection('licenses'); + $junction = static::getDatabase()->getCollection('_licenses_drivers'); $this->assertEquals(0, \count($drivers->getAttribute('attributes'))); $this->assertEquals(0, \count($drivers->getAttribute('indexes'))); @@ -12849,20 +13242,20 @@ public function testDeleteTwoWayRelationshipFromChild(): void public function testUpdateRelationshipToExistingKey(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('ovens'); - $this->getDatabase()->createCollection('cakes'); + static::getDatabase()->createCollection('ovens'); + static::getDatabase()->createCollection('cakes'); - $this->getDatabase()->createAttribute('ovens', 'maxTemp', Database::VAR_INTEGER, 0, true); - $this->getDatabase()->createAttribute('ovens', 'owner', Database::VAR_STRING, 255, true); - $this->getDatabase()->createAttribute('cakes', 'height', Database::VAR_INTEGER, 0, true); - $this->getDatabase()->createAttribute('cakes', 'colour', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('ovens', 'maxTemp', Database::VAR_INTEGER, 0, true); + static::getDatabase()->createAttribute('ovens', 'owner', Database::VAR_STRING, 255, true); + static::getDatabase()->createAttribute('cakes', 'height', Database::VAR_INTEGER, 0, true); + static::getDatabase()->createAttribute('cakes', 'colour', Database::VAR_STRING, 255, true); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'ovens', relatedCollection: 'cakes', type: Database::RELATION_ONE_TO_MANY, @@ -12872,14 +13265,14 @@ public function testUpdateRelationshipToExistingKey(): void ); try { - $this->getDatabase()->updateRelationship('ovens', 'cakes', newKey: 'owner'); + static::getDatabase()->updateRelationship('ovens', 'cakes', newKey: 'owner'); $this->fail('Failed to throw exception'); } catch (DuplicateException $e) { $this->assertEquals('Attribute already exists', $e->getMessage()); } try { - $this->getDatabase()->updateRelationship('ovens', 'cakes', newTwoWayKey: 'height'); + static::getDatabase()->updateRelationship('ovens', 'cakes', newTwoWayKey: 'height'); $this->fail('Failed to throw exception'); } catch (DuplicateException $e) { $this->assertEquals('Related attribute already exists', $e->getMessage()); @@ -12888,29 +13281,29 @@ public function testUpdateRelationshipToExistingKey(): void public function testOneToOneRelationshipKeyWithSymbols(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('$symbols_coll.ection1'); - $this->getDatabase()->createCollection('$symbols_coll.ection2'); + static::getDatabase()->createCollection('$symbols_coll.ection1'); + static::getDatabase()->createCollection('$symbols_coll.ection2'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: '$symbols_coll.ection1', relatedCollection: '$symbols_coll.ection2', type: Database::RELATION_ONE_TO_ONE, twoWay: true, ); - $doc1 = $this->getDatabase()->createDocument('$symbols_coll.ection2', new Document([ + $doc1 = static::getDatabase()->createDocument('$symbols_coll.ection2', new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::any()), Permission::update(Role::any()) ] ])); - $doc2 = $this->getDatabase()->createDocument('$symbols_coll.ection1', new Document([ + $doc2 = static::getDatabase()->createDocument('$symbols_coll.ection1', new Document([ '$id' => ID::unique(), '$symbols_coll.ection2' => $doc1->getId(), '$permissions' => [ @@ -12919,8 +13312,8 @@ public function testOneToOneRelationshipKeyWithSymbols(): void ] ])); - $doc1 = $this->getDatabase()->getDocument('$symbols_coll.ection2', $doc1->getId()); - $doc2 = $this->getDatabase()->getDocument('$symbols_coll.ection1', $doc2->getId()); + $doc1 = static::getDatabase()->getDocument('$symbols_coll.ection2', $doc1->getId()); + $doc2 = static::getDatabase()->getDocument('$symbols_coll.ection1', $doc2->getId()); $this->assertEquals($doc2->getId(), $doc1->getAttribute('$symbols_coll.ection1')->getId()); $this->assertEquals($doc1->getId(), $doc2->getAttribute('$symbols_coll.ection2')->getId()); @@ -12928,29 +13321,29 @@ public function testOneToOneRelationshipKeyWithSymbols(): void public function testOneToManyRelationshipKeyWithSymbols(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('$symbols_coll.ection3'); - $this->getDatabase()->createCollection('$symbols_coll.ection4'); + static::getDatabase()->createCollection('$symbols_coll.ection3'); + static::getDatabase()->createCollection('$symbols_coll.ection4'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: '$symbols_coll.ection3', relatedCollection: '$symbols_coll.ection4', type: Database::RELATION_ONE_TO_MANY, twoWay: true, ); - $doc1 = $this->getDatabase()->createDocument('$symbols_coll.ection4', new Document([ + $doc1 = static::getDatabase()->createDocument('$symbols_coll.ection4', new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::any()), Permission::update(Role::any()) ] ])); - $doc2 = $this->getDatabase()->createDocument('$symbols_coll.ection3', new Document([ + $doc2 = static::getDatabase()->createDocument('$symbols_coll.ection3', new Document([ '$id' => ID::unique(), '$symbols_coll.ection4' => [$doc1->getId()], '$permissions' => [ @@ -12959,8 +13352,8 @@ public function testOneToManyRelationshipKeyWithSymbols(): void ] ])); - $doc1 = $this->getDatabase()->getDocument('$symbols_coll.ection4', $doc1->getId()); - $doc2 = $this->getDatabase()->getDocument('$symbols_coll.ection3', $doc2->getId()); + $doc1 = static::getDatabase()->getDocument('$symbols_coll.ection4', $doc1->getId()); + $doc2 = static::getDatabase()->getDocument('$symbols_coll.ection3', $doc2->getId()); $this->assertEquals($doc2->getId(), $doc1->getAttribute('$symbols_coll.ection3')->getId()); $this->assertEquals($doc1->getId(), $doc2->getAttribute('$symbols_coll.ection4')[0]->getId()); @@ -12968,29 +13361,29 @@ public function testOneToManyRelationshipKeyWithSymbols(): void public function testManyToOneRelationshipKeyWithSymbols(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('$symbols_coll.ection5'); - $this->getDatabase()->createCollection('$symbols_coll.ection6'); + static::getDatabase()->createCollection('$symbols_coll.ection5'); + static::getDatabase()->createCollection('$symbols_coll.ection6'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: '$symbols_coll.ection5', relatedCollection: '$symbols_coll.ection6', type: Database::RELATION_MANY_TO_ONE, twoWay: true, ); - $doc1 = $this->getDatabase()->createDocument('$symbols_coll.ection6', new Document([ + $doc1 = static::getDatabase()->createDocument('$symbols_coll.ection6', new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::any()), Permission::update(Role::any()) ] ])); - $doc2 = $this->getDatabase()->createDocument('$symbols_coll.ection5', new Document([ + $doc2 = static::getDatabase()->createDocument('$symbols_coll.ection5', new Document([ '$id' => ID::unique(), '$symbols_coll.ection6' => $doc1->getId(), '$permissions' => [ @@ -12999,8 +13392,8 @@ public function testManyToOneRelationshipKeyWithSymbols(): void ] ])); - $doc1 = $this->getDatabase()->getDocument('$symbols_coll.ection6', $doc1->getId()); - $doc2 = $this->getDatabase()->getDocument('$symbols_coll.ection5', $doc2->getId()); + $doc1 = static::getDatabase()->getDocument('$symbols_coll.ection6', $doc1->getId()); + $doc2 = static::getDatabase()->getDocument('$symbols_coll.ection5', $doc2->getId()); $this->assertEquals($doc2->getId(), $doc1->getAttribute('$symbols_coll.ection5')[0]->getId()); $this->assertEquals($doc1->getId(), $doc2->getAttribute('$symbols_coll.ection6')->getId()); @@ -13008,29 +13401,29 @@ public function testManyToOneRelationshipKeyWithSymbols(): void public function testManyToManyRelationshipKeyWithSymbols(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('$symbols_coll.ection7'); - $this->getDatabase()->createCollection('$symbols_coll.ection8'); + static::getDatabase()->createCollection('$symbols_coll.ection7'); + static::getDatabase()->createCollection('$symbols_coll.ection8'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: '$symbols_coll.ection7', relatedCollection: '$symbols_coll.ection8', type: Database::RELATION_MANY_TO_MANY, twoWay: true, ); - $doc1 = $this->getDatabase()->createDocument('$symbols_coll.ection8', new Document([ + $doc1 = static::getDatabase()->createDocument('$symbols_coll.ection8', new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::any()), Permission::update(Role::any()) ] ])); - $doc2 = $this->getDatabase()->createDocument('$symbols_coll.ection7', new Document([ + $doc2 = static::getDatabase()->createDocument('$symbols_coll.ection7', new Document([ '$id' => ID::unique(), '$symbols_coll.ection8' => [$doc1->getId()], '$permissions' => [ @@ -13039,8 +13432,8 @@ public function testManyToManyRelationshipKeyWithSymbols(): void ] ])); - $doc1 = $this->getDatabase()->getDocument('$symbols_coll.ection8', $doc1->getId()); - $doc2 = $this->getDatabase()->getDocument('$symbols_coll.ection7', $doc2->getId()); + $doc1 = static::getDatabase()->getDocument('$symbols_coll.ection8', $doc1->getId()); + $doc2 = static::getDatabase()->getDocument('$symbols_coll.ection7', $doc2->getId()); $this->assertEquals($doc2->getId(), $doc1->getAttribute('$symbols_coll.ection7')[0]->getId()); $this->assertEquals($doc1->getId(), $doc2->getAttribute('$symbols_coll.ection8')[0]->getId()); @@ -13048,16 +13441,16 @@ public function testManyToManyRelationshipKeyWithSymbols(): void public function testCascadeMultiDelete(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('cascadeMultiDelete1'); - $this->getDatabase()->createCollection('cascadeMultiDelete2'); - $this->getDatabase()->createCollection('cascadeMultiDelete3'); + static::getDatabase()->createCollection('cascadeMultiDelete1'); + static::getDatabase()->createCollection('cascadeMultiDelete2'); + static::getDatabase()->createCollection('cascadeMultiDelete3'); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'cascadeMultiDelete1', relatedCollection: 'cascadeMultiDelete2', type: Database::RELATION_ONE_TO_MANY, @@ -13065,7 +13458,7 @@ public function testCascadeMultiDelete(): void onDelete: Database::RELATION_MUTATE_CASCADE ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'cascadeMultiDelete2', relatedCollection: 'cascadeMultiDelete3', type: Database::RELATION_ONE_TO_MANY, @@ -13073,7 +13466,7 @@ public function testCascadeMultiDelete(): void onDelete: Database::RELATION_MUTATE_CASCADE ); - $root = $this->getDatabase()->createDocument('cascadeMultiDelete1', new Document([ + $root = static::getDatabase()->createDocument('cascadeMultiDelete1', new Document([ '$id' => 'cascadeMultiDelete1', '$permissions' => [ Permission::read(Role::any()), @@ -13102,18 +13495,18 @@ public function testCascadeMultiDelete(): void $this->assertCount(1, $root->getAttribute('cascadeMultiDelete2')); $this->assertCount(1, $root->getAttribute('cascadeMultiDelete2')[0]->getAttribute('cascadeMultiDelete3')); - $this->assertEquals(true, $this->getDatabase()->deleteDocument('cascadeMultiDelete1', $root->getId())); + $this->assertEquals(true, static::getDatabase()->deleteDocument('cascadeMultiDelete1', $root->getId())); - $multi2 = $this->getDatabase()->getDocument('cascadeMultiDelete2', 'cascadeMultiDelete2'); + $multi2 = static::getDatabase()->getDocument('cascadeMultiDelete2', 'cascadeMultiDelete2'); $this->assertEquals(true, $multi2->isEmpty()); - $multi3 = $this->getDatabase()->getDocument('cascadeMultiDelete3', 'cascadeMultiDelete3'); + $multi3 = static::getDatabase()->getDocument('cascadeMultiDelete3', 'cascadeMultiDelete3'); $this->assertEquals(true, $multi3->isEmpty()); } public function testCollectionUpdate(): Document { - $collection = $this->getDatabase()->createCollection('collectionUpdate', permissions: [ + $collection = static::getDatabase()->createCollection('collectionUpdate', permissions: [ Permission::create(Role::users()), Permission::read(Role::users()), Permission::update(Role::users()), @@ -13122,19 +13515,19 @@ public function testCollectionUpdate(): Document $this->assertInstanceOf(Document::class, $collection); - $collection = $this->getDatabase()->getCollection('collectionUpdate'); + $collection = static::getDatabase()->getCollection('collectionUpdate'); $this->assertFalse($collection->getAttribute('documentSecurity')); $this->assertIsArray($collection->getPermissions()); $this->assertCount(4, $collection->getPermissions()); - $collection = $this->getDatabase()->updateCollection('collectionUpdate', [], true); + $collection = static::getDatabase()->updateCollection('collectionUpdate', [], true); $this->assertTrue($collection->getAttribute('documentSecurity')); $this->assertIsArray($collection->getPermissions()); $this->assertEmpty($collection->getPermissions()); - $collection = $this->getDatabase()->getCollection('collectionUpdate'); + $collection = static::getDatabase()->getCollection('collectionUpdate'); $this->assertTrue($collection->getAttribute('documentSecurity')); $this->assertIsArray($collection->getPermissions()); @@ -13149,14 +13542,14 @@ public function testCollectionUpdate(): Document public function testCollectionUpdatePermissionsThrowException(Document $collection): void { $this->expectException(DatabaseException::class); - $this->getDatabase()->updateCollection($collection->getId(), permissions: [ + static::getDatabase()->updateCollection($collection->getId(), permissions: [ 'i dont work' ], documentSecurity: false); } public function testCollectionPermissions(): Document { - $collection = $this->getDatabase()->createCollection('collectionSecurity', permissions: [ + $collection = static::getDatabase()->createCollection('collectionSecurity', permissions: [ Permission::create(Role::users()), Permission::read(Role::users()), Permission::update(Role::users()), @@ -13165,7 +13558,7 @@ public function testCollectionPermissions(): Document $this->assertInstanceOf(Document::class, $collection); - $this->assertTrue($this->getDatabase()->createAttribute( + $this->assertTrue(static::getDatabase()->createAttribute( collection: $collection->getId(), id: 'test', type: Database::VAR_STRING, @@ -13179,7 +13572,7 @@ public function testCollectionPermissions(): Document public function testCollectionPermissionsExceptions(): void { $this->expectException(DatabaseException::class); - $this->getDatabase()->createCollection('collectionSecurity', permissions: [ + static::getDatabase()->createCollection('collectionSecurity', permissions: [ 'i dont work' ]); } @@ -13190,10 +13583,10 @@ public function testCollectionPermissionsExceptions(): void */ public function testCollectionPermissionsCreateWorks(Document $collection): array { - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::users()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::users()->toString()); - $document = $this->getDatabase()->createDocument($collection->getId(), new Document([ + $document = static::getDatabase()->createDocument($collection->getId(), new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::user('random')), @@ -13213,11 +13606,11 @@ public function testCollectionPermissionsCreateWorks(Document $collection): arra */ public function testCollectionPermissionsCreateThrowsException(Document $collection): void { - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); - $this->getDatabase()->createDocument($collection->getId(), new Document([ + static::getDatabase()->createDocument($collection->getId(), new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::any()), @@ -13237,10 +13630,10 @@ public function testCollectionPermissionsGetWorks(array $data): array { [$collection, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::users()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::users()->toString()); - $document = $this->getDatabase()->getDocument( + $document = static::getDatabase()->getDocument( $collection->getId(), $document->getId() ); @@ -13258,10 +13651,10 @@ public function testCollectionPermissionsGetThrowsException(array $data): void { [$collection, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); - $document = $this->getDatabase()->getDocument( + $document = static::getDatabase()->getDocument( $collection->getId(), $document->getId(), ); @@ -13278,17 +13671,17 @@ public function testCollectionPermissionsFindWorks(array $data): array { [$collection, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::users()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::users()->toString()); - $documents = $this->getDatabase()->find($collection->getId()); + $documents = static::getDatabase()->find($collection->getId()); $this->assertNotEmpty($documents); - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::user('random')->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::user('random')->toString()); try { - $this->getDatabase()->find($collection->getId()); + static::getDatabase()->find($collection->getId()); $this->fail('Failed to throw exception'); } catch (AuthorizationException) { } @@ -13304,11 +13697,11 @@ public function testCollectionPermissionsFindThrowsException(array $data): void { [$collection, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); - $this->getDatabase()->find($collection->getId()); + static::getDatabase()->find($collection->getId()); } /** @@ -13320,10 +13713,10 @@ public function testCollectionPermissionsCountWorks(array $data): array { [$collection, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::users()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::users()->toString()); - $count = $this->getDatabase()->count( + $count = static::getDatabase()->count( $collection->getId() ); @@ -13340,10 +13733,10 @@ public function testCollectionPermissionsCountThrowsException(array $data): void { [$collection, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); - $count = $this->getDatabase()->count( + $count = static::getDatabase()->count( $collection->getId() ); $this->assertEmpty($count); @@ -13358,10 +13751,10 @@ public function testCollectionPermissionsUpdateWorks(array $data): array { [$collection, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::users()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::users()->toString()); - $this->assertInstanceOf(Document::class, $this->getDatabase()->updateDocument( + $this->assertInstanceOf(Document::class, static::getDatabase()->updateDocument( $collection->getId(), $document->getId(), $document->setAttribute('test', 'ipsum') @@ -13377,11 +13770,11 @@ public function testCollectionPermissionsUpdateWorks(array $data): array public function testCollectionPermissionsUpdateThrowsException(array $data): void { [$collection, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); - $document = $this->getDatabase()->updateDocument( + $document = static::getDatabase()->updateDocument( $collection->getId(), $document->getId(), $document->setAttribute('test', 'lorem') @@ -13396,11 +13789,11 @@ public function testCollectionPermissionsDeleteThrowsException(array $data): voi { [$collection, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); - $this->getDatabase()->deleteDocument( + static::getDatabase()->deleteDocument( $collection->getId(), $document->getId() ); @@ -13414,10 +13807,10 @@ public function testCollectionPermissionsDeleteWorks(array $data): void { [$collection, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::users()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::users()->toString()); - $this->assertTrue($this->getDatabase()->deleteDocument( + $this->assertTrue(static::getDatabase()->deleteDocument( $collection->getId(), $document->getId() )); @@ -13428,7 +13821,7 @@ public function testCollectionPermissionsDeleteWorks(array $data): void */ public function testCollectionPermissionsRelationships(): array { - $collection = $this->getDatabase()->createCollection('collectionSecurity.Parent', permissions: [ + $collection = static::getDatabase()->createCollection('collectionSecurity.Parent', permissions: [ Permission::create(Role::users()), Permission::read(Role::users()), Permission::update(Role::users()), @@ -13437,7 +13830,7 @@ public function testCollectionPermissionsRelationships(): array $this->assertInstanceOf(Document::class, $collection); - $this->assertTrue($this->getDatabase()->createAttribute( + $this->assertTrue(static::getDatabase()->createAttribute( collection: $collection->getId(), id: 'test', type: Database::VAR_STRING, @@ -13445,7 +13838,7 @@ public function testCollectionPermissionsRelationships(): array required: false )); - $collectionOneToOne = $this->getDatabase()->createCollection('collectionSecurity.OneToOne', permissions: [ + $collectionOneToOne = static::getDatabase()->createCollection('collectionSecurity.OneToOne', permissions: [ Permission::create(Role::users()), Permission::read(Role::users()), Permission::update(Role::users()), @@ -13454,7 +13847,7 @@ public function testCollectionPermissionsRelationships(): array $this->assertInstanceOf(Document::class, $collectionOneToOne); - $this->assertTrue($this->getDatabase()->createAttribute( + $this->assertTrue(static::getDatabase()->createAttribute( collection: $collectionOneToOne->getId(), id: 'test', type: Database::VAR_STRING, @@ -13462,7 +13855,7 @@ public function testCollectionPermissionsRelationships(): array required: false )); - $this->assertTrue($this->getDatabase()->createRelationship( + $this->assertTrue(static::getDatabase()->createRelationship( collection: $collection->getId(), relatedCollection: $collectionOneToOne->getId(), type: Database::RELATION_ONE_TO_ONE, @@ -13470,7 +13863,7 @@ public function testCollectionPermissionsRelationships(): array onDelete: Database::RELATION_MUTATE_CASCADE )); - $collectionOneToMany = $this->getDatabase()->createCollection('collectionSecurity.OneToMany', permissions: [ + $collectionOneToMany = static::getDatabase()->createCollection('collectionSecurity.OneToMany', permissions: [ Permission::create(Role::users()), Permission::read(Role::users()), Permission::update(Role::users()), @@ -13479,7 +13872,7 @@ public function testCollectionPermissionsRelationships(): array $this->assertInstanceOf(Document::class, $collectionOneToMany); - $this->assertTrue($this->getDatabase()->createAttribute( + $this->assertTrue(static::getDatabase()->createAttribute( collection: $collectionOneToMany->getId(), id: 'test', type: Database::VAR_STRING, @@ -13487,7 +13880,7 @@ public function testCollectionPermissionsRelationships(): array required: false )); - $this->assertTrue($this->getDatabase()->createRelationship( + $this->assertTrue(static::getDatabase()->createRelationship( collection: $collection->getId(), relatedCollection: $collectionOneToMany->getId(), type: Database::RELATION_ONE_TO_MANY, @@ -13506,10 +13899,10 @@ public function testCollectionPermissionsRelationships(): array public function testCollectionPermissionsRelationshipsCreateWorks(array $data): array { [$collection, $collectionOneToOne, $collectionOneToMany] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::users()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::users()->toString()); - $document = $this->getDatabase()->createDocument($collection->getId(), new Document([ + $document = static::getDatabase()->createDocument($collection->getId(), new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::user('random')), @@ -13559,11 +13952,11 @@ public function testCollectionPermissionsRelationshipsCreateThrowsException(arra { [$collection, $collectionOneToOne, $collectionOneToMany] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); - $this->getDatabase()->createDocument($collection->getId(), new Document([ + static::getDatabase()->createDocument($collection->getId(), new Document([ '$id' => ID::unique(), '$permissions' => [ Permission::read(Role::any()), @@ -13582,10 +13975,10 @@ public function testCollectionPermissionsRelationshipsGetWorks(array $data): arr { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::users()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::users()->toString()); - $document = $this->getDatabase()->getDocument( + $document = static::getDatabase()->getDocument( $collection->getId(), $document->getId() ); @@ -13596,10 +13989,10 @@ public function testCollectionPermissionsRelationshipsGetWorks(array $data): arr $this->assertCount(2, $document->getAttribute(Database::RELATION_ONE_TO_MANY)); $this->assertFalse($document->isEmpty()); - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::user('random')->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::user('random')->toString()); - $document = $this->getDatabase()->getDocument( + $document = static::getDatabase()->getDocument( $collection->getId(), $document->getId() ); @@ -13621,10 +14014,10 @@ public function testCollectionPermissionsRelationshipsGetThrowsException(array $ { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); - $document = $this->getDatabase()->getDocument( + $document = static::getDatabase()->getDocument( $collection->getId(), $document->getId(), ); @@ -13640,10 +14033,10 @@ public function testCollectionPermissionsRelationshipsFindWorks(array $data): vo { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::users()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::users()->toString()); - $documents = $this->getDatabase()->find( + $documents = static::getDatabase()->find( $collection->getId() ); @@ -13656,10 +14049,10 @@ public function testCollectionPermissionsRelationshipsFindWorks(array $data): vo $this->assertCount(2, $document->getAttribute(Database::RELATION_ONE_TO_MANY)); $this->assertFalse($document->isEmpty()); - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::user('random')->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::user('random')->toString()); - $documents = $this->getDatabase()->find( + $documents = static::getDatabase()->find( $collection->getId() ); @@ -13672,10 +14065,10 @@ public function testCollectionPermissionsRelationshipsFindWorks(array $data): vo $this->assertCount(1, $document->getAttribute(Database::RELATION_ONE_TO_MANY)); $this->assertFalse($document->isEmpty()); - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::user('unknown')->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::user('unknown')->toString()); - $documents = $this->getDatabase()->find( + $documents = static::getDatabase()->find( $collection->getId() ); @@ -13691,28 +14084,28 @@ public function testCollectionPermissionsRelationshipsCountWorks(array $data): v { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::users()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::users()->toString()); - $documents = $this->getDatabase()->count( + $documents = static::getDatabase()->count( $collection->getId() ); $this->assertEquals(1, $documents); - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::user('random')->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::user('random')->toString()); - $documents = $this->getDatabase()->count( + $documents = static::getDatabase()->count( $collection->getId() ); $this->assertEquals(1, $documents); - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::user('unknown')->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::user('unknown')->toString()); - $documents = $this->getDatabase()->count( + $documents = static::getDatabase()->count( $collection->getId() ); @@ -13728,9 +14121,9 @@ public function testCollectionPermissionsRelationshipsUpdateWorks(array $data): { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::users()->toString()); - $this->getDatabase()->updateDocument( + Authorization::cleanRoles(); + Authorization::setRole(Role::users()->toString()); + static::getDatabase()->updateDocument( $collection->getId(), $document->getId(), $document @@ -13738,10 +14131,10 @@ public function testCollectionPermissionsRelationshipsUpdateWorks(array $data): $this->assertTrue(true); - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::user('random')->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::user('random')->toString()); - $this->getDatabase()->updateDocument( + static::getDatabase()->updateDocument( $collection->getId(), $document->getId(), $document->setAttribute('test', 'ipsum') @@ -13760,11 +14153,11 @@ public function testCollectionPermissionsRelationshipsUpdateThrowsException(arra { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); - $document = $this->getDatabase()->updateDocument( + $document = static::getDatabase()->updateDocument( $collection->getId(), $document->getId(), $document->setAttribute('test', $document->getAttribute('test').'new_value') @@ -13779,11 +14172,11 @@ public function testCollectionPermissionsRelationshipsDeleteThrowsException(arra { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); $this->expectException(AuthorizationException::class); - $document = $this->getDatabase()->deleteDocument( + $document = static::getDatabase()->deleteDocument( $collection->getId(), $document->getId() ); @@ -13797,10 +14190,10 @@ public function testCollectionPermissionsRelationshipsDeleteWorks(array $data): { [$collection, $collectionOneToOne, $collectionOneToMany, $document] = $data; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::users()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::users()->toString()); - $this->assertTrue($this->getDatabase()->deleteDocument( + $this->assertTrue(static::getDatabase()->deleteDocument( $collection->getId(), $document->getId() )); @@ -13808,28 +14201,28 @@ public function testCollectionPermissionsRelationshipsDeleteWorks(array $data): public function testCreateRelationDocumentWithoutUpdatePermission(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::user('a')->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::user('a')->toString()); - $this->getDatabase()->createCollection('parentRelationTest', [], [], [ + static::getDatabase()->createCollection('parentRelationTest', [], [], [ Permission::read(Role::user('a')), Permission::create(Role::user('a')), Permission::update(Role::user('a')), Permission::delete(Role::user('a')) ]); - $this->getDatabase()->createCollection('childRelationTest', [], [], [ + static::getDatabase()->createCollection('childRelationTest', [], [], [ Permission::create(Role::user('a')), Permission::read(Role::user('a')), ]); - $this->getDatabase()->createAttribute('parentRelationTest', 'name', Database::VAR_STRING, 255, false); - $this->getDatabase()->createAttribute('childRelationTest', 'name', Database::VAR_STRING, 255, false); + static::getDatabase()->createAttribute('parentRelationTest', 'name', Database::VAR_STRING, 255, false); + static::getDatabase()->createAttribute('childRelationTest', 'name', Database::VAR_STRING, 255, false); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'parentRelationTest', relatedCollection: 'childRelationTest', type: Database::RELATION_ONE_TO_MANY, @@ -13837,7 +14230,7 @@ public function testCreateRelationDocumentWithoutUpdatePermission(): void ); // Create document with relationship with nested data - $parent = $this->getDatabase()->createDocument('parentRelationTest', new Document([ + $parent = static::getDatabase()->createDocument('parentRelationTest', new Document([ '$id' => 'parent1', 'name' => 'Parent 1', 'children' => [ @@ -13853,21 +14246,21 @@ public function testCreateRelationDocumentWithoutUpdatePermission(): void '$id' => 'child2', ], ]); - $updatedParent = $this->getDatabase()->updateDocument('parentRelationTest', 'parent1', $parent); + $updatedParent = static::getDatabase()->updateDocument('parentRelationTest', 'parent1', $parent); $this->assertEquals('child2', $updatedParent->getAttribute('children')[0]->getId()); - $this->getDatabase()->deleteCollection('parentRelationTest'); - $this->getDatabase()->deleteCollection('childRelationTest'); + static::getDatabase()->deleteCollection('parentRelationTest'); + static::getDatabase()->deleteCollection('childRelationTest'); } public function testUpdateDocumentWithRelationships(): void { - if (!$this->getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { $this->expectNotToPerformAssertions(); return; } - $this->getDatabase()->createCollection('userProfiles', [ + static::getDatabase()->createCollection('userProfiles', [ new Document([ '$id' => ID::custom('username'), 'type' => Database::VAR_STRING, @@ -13885,7 +14278,7 @@ public function testUpdateDocumentWithRelationships(): void Permission::update(Role::any()), Permission::delete(Role::any()) ]); - $this->getDatabase()->createCollection('links', [ + static::getDatabase()->createCollection('links', [ new Document([ '$id' => ID::custom('title'), 'type' => Database::VAR_STRING, @@ -13903,7 +14296,7 @@ public function testUpdateDocumentWithRelationships(): void Permission::update(Role::any()), Permission::delete(Role::any()) ]); - $this->getDatabase()->createCollection('videos', [ + static::getDatabase()->createCollection('videos', [ new Document([ '$id' => ID::custom('title'), 'type' => Database::VAR_STRING, @@ -13921,7 +14314,7 @@ public function testUpdateDocumentWithRelationships(): void Permission::update(Role::any()), Permission::delete(Role::any()) ]); - $this->getDatabase()->createCollection('products', [ + static::getDatabase()->createCollection('products', [ new Document([ '$id' => ID::custom('title'), 'type' => Database::VAR_STRING, @@ -13939,7 +14332,7 @@ public function testUpdateDocumentWithRelationships(): void Permission::update(Role::any()), Permission::delete(Role::any()) ]); - $this->getDatabase()->createCollection('settings', [ + static::getDatabase()->createCollection('settings', [ new Document([ '$id' => ID::custom('metaTitle'), 'type' => Database::VAR_STRING, @@ -13957,7 +14350,7 @@ public function testUpdateDocumentWithRelationships(): void Permission::update(Role::any()), Permission::delete(Role::any()) ]); - $this->getDatabase()->createCollection('appearance', [ + static::getDatabase()->createCollection('appearance', [ new Document([ '$id' => ID::custom('metaTitle'), 'type' => Database::VAR_STRING, @@ -13975,7 +14368,7 @@ public function testUpdateDocumentWithRelationships(): void Permission::update(Role::any()), Permission::delete(Role::any()) ]); - $this->getDatabase()->createCollection('group', [ + static::getDatabase()->createCollection('group', [ new Document([ '$id' => ID::custom('name'), 'type' => Database::VAR_STRING, @@ -13993,7 +14386,7 @@ public function testUpdateDocumentWithRelationships(): void Permission::update(Role::any()), Permission::delete(Role::any()) ]); - $this->getDatabase()->createCollection('community', [ + static::getDatabase()->createCollection('community', [ new Document([ '$id' => ID::custom('name'), 'type' => Database::VAR_STRING, @@ -14012,21 +14405,21 @@ public function testUpdateDocumentWithRelationships(): void Permission::delete(Role::any()) ]); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'userProfiles', relatedCollection: 'links', type: Database::RELATION_ONE_TO_MANY, id: 'links' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'userProfiles', relatedCollection: 'videos', type: Database::RELATION_ONE_TO_MANY, id: 'videos' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'userProfiles', relatedCollection: 'products', type: Database::RELATION_ONE_TO_MANY, @@ -14035,35 +14428,35 @@ public function testUpdateDocumentWithRelationships(): void twoWayKey: 'userProfile', ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'userProfiles', relatedCollection: 'settings', type: Database::RELATION_ONE_TO_ONE, id: 'settings' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'userProfiles', relatedCollection: 'appearance', type: Database::RELATION_ONE_TO_ONE, id: 'appearance' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'userProfiles', relatedCollection: 'group', type: Database::RELATION_MANY_TO_ONE, id: 'group' ); - $this->getDatabase()->createRelationship( + static::getDatabase()->createRelationship( collection: 'userProfiles', relatedCollection: 'community', type: Database::RELATION_MANY_TO_ONE, id: 'community' ); - $profile = $this->getDatabase()->createDocument('userProfiles', new Document([ + $profile = static::getDatabase()->createDocument('userProfiles', new Document([ '$id' => '1', 'username' => 'user1', 'links' => [ @@ -14126,7 +14519,7 @@ public function testUpdateDocumentWithRelationships(): void 'name' => 'New Group Name', ]); - $updatedProfile = $this->getDatabase()->updateDocument('userProfiles', '1', $profile); + $updatedProfile = static::getDatabase()->updateDocument('userProfiles', '1', $profile); $this->assertEquals('New Link Value', $updatedProfile->getAttribute('links')[0]->getAttribute('title')); $this->assertEquals('New Meta Title', $updatedProfile->getAttribute('settings')->getAttribute('metaTitle')); @@ -14139,25 +14532,25 @@ public function testUpdateDocumentWithRelationships(): void $this->assertEquals('Community 1', $updatedProfile->getAttribute('community')->getAttribute('name')); // updating document using two way key in one to many relationship - $product = $this->getDatabase()->getDocument('products', 'product1'); + $product = static::getDatabase()->getDocument('products', 'product1'); $product->setAttribute('userProfile', [ '$id' => '1', 'username' => 'updated user value', ]); - $updatedProduct = $this->getDatabase()->updateDocument('products', 'product1', $product); + $updatedProduct = static::getDatabase()->updateDocument('products', 'product1', $product); $this->assertEquals('updated user value', $updatedProduct->getAttribute('userProfile')->getAttribute('username')); $this->assertEquals('Product 1', $updatedProduct->getAttribute('title')); $this->assertEquals('product1', $updatedProduct->getId()); $this->assertEquals('1', $updatedProduct->getAttribute('userProfile')->getId()); - $this->getDatabase()->deleteCollection('userProfiles'); - $this->getDatabase()->deleteCollection('links'); - $this->getDatabase()->deleteCollection('settings'); - $this->getDatabase()->deleteCollection('group'); - $this->getDatabase()->deleteCollection('community'); - $this->getDatabase()->deleteCollection('videos'); - $this->getDatabase()->deleteCollection('products'); - $this->getDatabase()->deleteCollection('appearance'); + static::getDatabase()->deleteCollection('userProfiles'); + static::getDatabase()->deleteCollection('links'); + static::getDatabase()->deleteCollection('settings'); + static::getDatabase()->deleteCollection('group'); + static::getDatabase()->deleteCollection('community'); + static::getDatabase()->deleteCollection('videos'); + static::getDatabase()->deleteCollection('products'); + static::getDatabase()->deleteCollection('appearance'); } public function testRecreateOneToOneOneWayRelationshipFromParent(): void @@ -15186,12 +15579,12 @@ public function testRecreateManyToManyTwoWayRelationshipFromChild(): void public function testLabels(): void { - $this->assertInstanceOf('Utopia\Database\Document', $this->getDatabase()->createCollection( + $this->assertInstanceOf('Utopia\Database\Document', static::getDatabase()->createCollection( 'labels_test', )); - $this->getDatabase()->createAttribute('labels_test', 'attr1', Database::VAR_STRING, 10, false); + static::getDatabase()->createAttribute('labels_test', 'attr1', Database::VAR_STRING, 10, false); - $this->getDatabase()->createDocument('labels_test', new Document([ + static::getDatabase()->createDocument('labels_test', new Document([ '$id' => 'doc1', 'attr1' => 'value1', '$permissions' => [ @@ -15199,20 +15592,20 @@ public function testLabels(): void ], ])); - $documents = $this->getDatabase()->find('labels_test'); + $documents = static::getDatabase()->find('labels_test'); $this->assertEmpty($documents); - self::$authorization->addRole(Role::label('reader')->toString()); + Authorization::setRole(Role::label('reader')->toString()); - $documents = $this->getDatabase()->find('labels_test'); + $documents = static::getDatabase()->find('labels_test'); $this->assertCount(1, $documents); } public function testEnableDisableValidation(): void { - $database = $this->getDatabase(); + $database = static::getDatabase(); $database->createCollection('validation', permissions: [ Permission::create(Role::any()), @@ -15269,21 +15662,21 @@ public function testEnableDisableValidation(): void public function testMetadata(): void { - $this->getDatabase()->setMetadata('key', 'value'); + static::getDatabase()->setMetadata('key', 'value'); - $this->getDatabase()->createCollection('testers'); + static::getDatabase()->createCollection('testers'); - $this->assertEquals(['key' => 'value'], $this->getDatabase()->getMetadata()); + $this->assertEquals(['key' => 'value'], static::getDatabase()->getMetadata()); - $this->getDatabase()->resetMetadata(); + static::getDatabase()->resetMetadata(); - $this->assertEquals([], $this->getDatabase()->getMetadata()); + $this->assertEquals([], static::getDatabase()->getMetadata()); } public function testEmptyOperatorValues(): void { try { - $this->getDatabase()->findOne('documents', [ + static::getDatabase()->findOne('documents', [ Query::equal('string', []), ]); $this->fail('Failed to throw exception'); @@ -15293,7 +15686,7 @@ public function testEmptyOperatorValues(): void } try { - $this->getDatabase()->findOne('documents', [ + static::getDatabase()->findOne('documents', [ Query::contains('string', []), ]); $this->fail('Failed to throw exception'); @@ -15317,7 +15710,7 @@ public function testSharedTables(): void /** * Default mode already tested, we'll test 'schema' and 'table' isolation here */ - $database = $this->getDatabase(); + $database = static::getDatabase(); if (!$database->getAdapter()->getSupportForSchemas()) { $this->expectNotToPerformAssertions(); @@ -15354,7 +15747,6 @@ public function testSharedTables(): void /** * Table */ - $tenant1 = 1; $tenant2 = 2; @@ -15482,7 +15874,7 @@ public function testSharedTables(): void $database->getDocument('people', $docId); $this->fail('Failed to throw exception'); } catch (Exception $e) { - $this->assertEquals('Missing tenant. Tenant must be set when table sharing is enabled.', $e->getMessage()); + $this->assertEquals('Collection not found', $e->getMessage()); } // Reset state @@ -15491,11 +15883,11 @@ public function testSharedTables(): void $database->setDatabase($this->testDatabase); } - public function testSharedTablesDuplicatesDontThrow(): void + public function testSharedTablesDuplicates(): void { $database = static::getDatabase(); - if (!$database->getAdapter()->getSupportForAttributes()) { + if (!$database->getAdapter()->getSupportForSchemas()) { $this->expectNotToPerformAssertions(); return; } @@ -15508,7 +15900,7 @@ public function testSharedTablesDuplicatesDontThrow(): void ->setDatabase('sharedTables') ->setNamespace('') ->setSharedTables(true) - ->setTenant(1) + ->setTenant(null) ->create(); // Create collection @@ -15524,8 +15916,17 @@ public function testSharedTablesDuplicatesDontThrow(): void // Ignore } - $database->createAttribute('duplicates', 'name', Database::VAR_STRING, 10, false); - $database->createIndex('duplicates', 'nameIndex', Database::INDEX_KEY, ['name']); + try { + $database->createAttribute('duplicates', 'name', Database::VAR_STRING, 10, false); + } catch (DuplicateException) { + // Ignore + } + + try { + $database->createIndex('duplicates', 'nameIndex', Database::INDEX_KEY, ['name']); + } catch (DuplicateException) { + // Ignore + } $collection = $database->getCollection('duplicates'); $this->assertEquals(1, \count($collection->getAttribute('attributes'))); @@ -15544,7 +15945,7 @@ public function testSharedTablesDuplicatesDontThrow(): void public function testTransformations(): void { - $this->getDatabase()->createCollection('docs', attributes: [ + static::getDatabase()->createCollection('docs', attributes: [ new Document([ '$id' => 'name', 'type' => Database::VAR_STRING, @@ -15553,24 +15954,24 @@ public function testTransformations(): void ]) ]); - $this->getDatabase()->createDocument('docs', new Document([ + static::getDatabase()->createDocument('docs', new Document([ '$id' => 'doc1', 'name' => 'value1', ])); - $this->getDatabase()->before(Database::EVENT_DOCUMENT_READ, 'test', function (string $query) { + static::getDatabase()->before(Database::EVENT_DOCUMENT_READ, 'test', function (string $query) { return "SELECT 1"; }); - $result = $this->getDatabase()->getDocument('docs', 'doc1'); + $result = static::getDatabase()->getDocument('docs', 'doc1'); $this->assertTrue($result->isEmpty()); } - public function propegateBulkDocuments(bool $documentSecurity = false): void + public function propegateBulkDocuments(string $collection, int $amount = 10, bool $documentSecurity = false): void { - for ($i = 0; $i < 10; $i++) { - static::getDatabase()->createDocument('bulk_delete', new Document( + for ($i = 0; $i < $amount; $i++) { + static::getDatabase()->createDocument($collection, new Document( array_merge([ '$id' => 'doc' . $i, 'text' => 'value' . $i, @@ -15587,6 +15988,11 @@ public function propegateBulkDocuments(bool $documentSecurity = false): void public function testDeleteBulkDocuments(): void { + if (!static::getDatabase()->getAdapter()->getSupportForBatchOperations()) { + $this->expectNotToPerformAssertions(); + return; + } + static::getDatabase()->createCollection( 'bulk_delete', attributes: [ @@ -15611,29 +16017,44 @@ public function testDeleteBulkDocuments(): void ] ); - $this->propegateBulkDocuments(); + $this->propegateBulkDocuments('bulk_delete'); $docs = static::getDatabase()->find('bulk_delete'); $this->assertCount(10, $docs); // TEST: Bulk Delete All Documents - $deleted = static::getDatabase()->deleteDocuments('bulk_delete'); - $this->assertEquals(10, $deleted); + $this->assertCount(10, static::getDatabase()->deleteDocuments('bulk_delete')); $docs = static::getDatabase()->find('bulk_delete'); $this->assertCount(0, $docs); // TEST: Bulk delete documents with queries. - $this->propegateBulkDocuments(); + $this->propegateBulkDocuments('bulk_delete'); - $deleted = static::getDatabase()->deleteDocuments('bulk_delete', [ + $modified = static::getDatabase()->deleteDocuments('bulk_delete', [ Query::greaterThanEqual('integer', 5) ]); - $this->assertEquals(5, $deleted); + $this->assertCount(5, $modified); + + foreach ($modified as $document) { + $this->assertGreaterThanOrEqual(5, $document->getAttribute('integer')); + } $docs = static::getDatabase()->find('bulk_delete'); $this->assertCount(5, $docs); + // TEST (FAIL): Can't delete documents in the past + $oneHourAgo = (new \DateTime())->sub(new \DateInterval('PT1H')); + + try { + $this->getDatabase()->withRequestTimestamp($oneHourAgo, function () { + return $this->getDatabase()->deleteDocuments('bulk_delete'); + }); + $this->fail('Failed to throw exception'); + } catch (ConflictException $e) { + $this->assertEquals('Document was updated after the request timestamp', $e->getMessage()); + } + // TEST (FAIL): Bulk delete all documents with invalid collection permission static::getDatabase()->updateCollection('bulk_delete', [], false); try { @@ -15647,21 +16068,19 @@ public function testDeleteBulkDocuments(): void Permission::read(Role::any()), Permission::delete(Role::any()) ], false); - $deleted = static::getDatabase()->deleteDocuments('bulk_delete'); - $this->assertEquals(5, $deleted); + $this->assertCount(5, static::getDatabase()->deleteDocuments('bulk_delete')); $this->assertEquals(0, count($this->getDatabase()->find('bulk_delete'))); // TEST: Make sure we can't delete documents we don't have permissions for static::getDatabase()->updateCollection('bulk_delete', [ Permission::create(Role::any()), ], true); - $this->propegateBulkDocuments(true); + $this->propegateBulkDocuments('bulk_delete', documentSecurity: true); - $deleted = static::getDatabase()->deleteDocuments('bulk_delete'); - $this->assertEquals(0, $deleted); + $this->assertCount(0, static::getDatabase()->deleteDocuments('bulk_delete')); - $documents = static::$authorization->skip(function () { + $documents = Authorization::skip(function () { return static::getDatabase()->find('bulk_delete'); }); @@ -15679,9 +16098,73 @@ public function testDeleteBulkDocuments(): void static::getDatabase()->deleteCollection('bulk_delete'); } + public function testDeleteBulkDocumentsQueries(): void + { + if (!static::getDatabase()->getAdapter()->getSupportForBatchOperations()) { + $this->expectNotToPerformAssertions(); + return; + } + + static::getDatabase()->createCollection( + 'bulk_delete_queries', + attributes: [ + new Document([ + '$id' => 'text', + 'type' => Database::VAR_STRING, + 'size' => 100, + 'required' => true, + ]), + new Document([ + '$id' => 'integer', + 'type' => Database::VAR_INTEGER, + 'size' => 10, + 'required' => true, + ]) + ], + documentSecurity: false, + permissions: [ + Permission::create(Role::any()), + Permission::read(Role::any()), + Permission::delete(Role::any()) + ] + ); + + // Test limit + $this->propegateBulkDocuments('bulk_delete_queries'); + + $this->assertCount(5, static::getDatabase()->deleteDocuments('bulk_delete_queries', [Query::limit(5)])); + $this->assertCount(5, static::getDatabase()->find('bulk_delete_queries')); + + $this->assertCount(5, static::getDatabase()->deleteDocuments('bulk_delete_queries', [Query::limit(5)])); + $this->assertCount(0, static::getDatabase()->find('bulk_delete_queries')); + + // Test Limit more than batchSize + $this->propegateBulkDocuments('bulk_delete_queries', Database::DELETE_BATCH_SIZE * 2); + $this->assertCount(Database::DELETE_BATCH_SIZE * 2, static::getDatabase()->find('bulk_delete_queries', [Query::limit(200)])); + + $this->assertCount(Database::DELETE_BATCH_SIZE + 2, static::getDatabase()->deleteDocuments('bulk_delete_queries', [Query::limit(Database::DELETE_BATCH_SIZE + 2)])); + + $this->assertCount(Database::DELETE_BATCH_SIZE - 2, static::getDatabase()->find('bulk_delete_queries', [Query::limit(200)])); + $this->assertCount(Database::DELETE_BATCH_SIZE - 2, $this->getDatabase()->deleteDocuments('bulk_delete_queries')); + + // Test Offset + $this->propegateBulkDocuments('bulk_delete_queries', 100); + $this->assertCount(50, static::getDatabase()->deleteDocuments('bulk_delete_queries', [Query::offset(50)])); + + $docs = static::getDatabase()->find('bulk_delete_queries', [Query::limit(100)]); + $this->assertCount(50, $docs); + + $lastDoc = end($docs); + $this->assertNotEmpty($lastDoc); + $this->assertEquals('doc49', $lastDoc->getId()); + $this->assertCount(50, static::getDatabase()->deleteDocuments('bulk_delete_queries')); + + static::getDatabase()->deleteCollection('bulk_delete_queries'); + } + public function testDeleteBulkDocumentsOneToOneRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships() || !static::getDatabase()->getAdapter()->getSupportForBatchOperations()) { $this->expectNotToPerformAssertions(); return; } @@ -15877,7 +16360,7 @@ public function testDeleteBulkDocumentsOneToOneRelationship(): void public function testDeleteBulkDocumentsOneToManyRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships() || !static::getDatabase()->getAdapter()->getSupportForBatchOperations()) { $this->expectNotToPerformAssertions(); return; } @@ -16056,7 +16539,7 @@ public function testDeleteBulkDocumentsOneToManyRelationship(): void public function testDeleteBulkDocumentsManyToManyRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships() || !static::getDatabase()->getAdapter()->getSupportForBatchOperations()) { $this->expectNotToPerformAssertions(); return; } @@ -16131,7 +16614,7 @@ public function testDeleteBulkDocumentsManyToManyRelationship(): void public function testDeleteBulkDocumentsManyToOneRelationship(): void { - if (!static::getDatabase()->getAdapter()->getSupportForRelationships()) { + if (!static::getDatabase()->getAdapter()->getSupportForRelationships() || !static::getDatabase()->getAdapter()->getSupportForBatchOperations()) { $this->expectNotToPerformAssertions(); return; } @@ -16218,8 +16701,8 @@ public function testUpdateDocuments(): void } $collection = 'testUpdateDocuments'; - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); static::getDatabase()->createCollection($collection, attributes: [ new Document([ @@ -16260,22 +16743,26 @@ public function testUpdateDocuments(): void } // Test Update half of the documents - $affected = static::getDatabase()->updateDocuments($collection, new Document([ + $modified = static::getDatabase()->updateDocuments($collection, new Document([ 'string' => 'text📝 updated', ]), [ Query::greaterThanEqual('integer', 5), ]); + $this->assertCount(5, $modified); - $this->assertEquals($affected, 5); + foreach ($modified as $document) { + $this->assertEquals('text📝 updated', $document->getAttribute('string')); + } $updatedDocuments = static::getDatabase()->find($collection, [ Query::greaterThanEqual('integer', 5), ]); - $this->assertEquals(count($updatedDocuments), 5); + $this->assertCount(5, $updatedDocuments); foreach ($updatedDocuments as $document) { $this->assertEquals('text📝 updated', $document->getAttribute('string')); + $this->assertGreaterThanOrEqual(5, $document->getAttribute('integer')); } $controlDocuments = static::getDatabase()->find($collection, [ @@ -16289,11 +16776,9 @@ public function testUpdateDocuments(): void } // Test Update all documents - $affected = static::getDatabase()->updateDocuments($collection, new Document([ + $this->assertCount(10, static::getDatabase()->updateDocuments($collection, new Document([ 'string' => 'text📝 updated all', - ])); - - $this->assertEquals(10, $affected); + ]))); $updatedDocuments = static::getDatabase()->find($collection); @@ -16303,6 +16788,20 @@ public function testUpdateDocuments(): void $this->assertEquals('text📝 updated all', $document->getAttribute('string')); } + // TEST: Can't delete documents in the past + $oneHourAgo = (new \DateTime())->sub(new \DateInterval('PT1H')); + + try { + $this->getDatabase()->withRequestTimestamp($oneHourAgo, function () use ($collection) { + return static::getDatabase()->updateDocuments($collection, new Document([ + 'string' => 'text📝 updated all', + ])); + }); + $this->fail('Failed to throw exception'); + } catch (ConflictException $e) { + $this->assertEquals('Document was updated after the request timestamp', $e->getMessage()); + } + // Check collection level permissions static::getDatabase()->updateCollection($collection, permissions: [ Permission::read(Role::user('asd')), @@ -16323,7 +16822,7 @@ public function testUpdateDocuments(): void // Check document level permissions static::getDatabase()->updateCollection($collection, permissions: [], documentSecurity: true); - static::$authorization->skip(function () use ($collection) { + Authorization::skip(function () use ($collection) { static::getDatabase()->updateDocument($collection, 'doc0', new Document([ 'string' => 'text📝 updated all', '$permissions' => [ @@ -16335,7 +16834,7 @@ public function testUpdateDocuments(): void ])); }); - static::$authorization->addRole(Role::user('asd')->toString()); + Authorization::setRole(Role::user('asd')->toString()); static::getDatabase()->updateDocuments($collection, new Document([ 'string' => 'permission text', @@ -16347,7 +16846,7 @@ public function testUpdateDocuments(): void $this->assertCount(1, $documents); - self::$authorization->skip(function () use ($collection) { + Authorization::skip(function () use ($collection) { $unmodifiedDocuments = static::getDatabase()->find($collection, [ Query::equal('string', ['text📝 updated all']), ]); @@ -16355,7 +16854,7 @@ public function testUpdateDocuments(): void $this->assertCount(9, $unmodifiedDocuments); }); - static::$authorization->skip(function () use ($collection) { + Authorization::skip(function () use ($collection) { static::getDatabase()->updateDocuments($collection, new Document([ '$permissions' => [ Permission::read(Role::any()), @@ -16367,20 +16866,73 @@ public function testUpdateDocuments(): void }); // Test we can update more documents than batchSize - $affected = static::getDatabase()->updateDocuments($collection, new Document([ + $this->assertCount(10, static::getDatabase()->updateDocuments($collection, new Document([ 'string' => 'batchSize Test' - ]), batchSize: 2); + ]), batchSize: 2)); $documents = static::getDatabase()->find($collection); - $this->assertEquals(10, $affected); - foreach ($documents as $document) { $this->assertEquals('batchSize Test', $document->getAttribute('string')); } - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); + } + + public function testUpdateDocumentsQueries(): void + { + if (!static::getDatabase()->getAdapter()->getSupportForBatchOperations()) { + $this->expectNotToPerformAssertions(); + return; + } + + $collection = 'testUpdateDocumentsQueries'; + + static::getDatabase()->createCollection($collection, attributes: [ + new Document([ + '$id' => ID::custom('text'), + 'type' => Database::VAR_STRING, + 'size' => 64, + 'required' => true, + ]), + new Document([ + '$id' => ID::custom('integer'), + 'type' => Database::VAR_INTEGER, + 'size' => 64, + 'required' => true, + ]), + ], permissions: [ + Permission::read(Role::any()), + Permission::create(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()) + ], documentSecurity: true); + + // Test limit + $this->propegateBulkDocuments($collection, 100); + + $this->assertCount(10, static::getDatabase()->updateDocuments($collection, new Document([ + 'text' => 'text📝 updated', + ]), [Query::limit(10)])); + $this->assertCount(10, static::getDatabase()->find($collection, [Query::equal('text', ['text📝 updated'])])); + $this->assertCount(100, static::getDatabase()->deleteDocuments($collection)); + $this->assertCount(0, static::getDatabase()->find($collection)); + + // Test Offset + $this->propegateBulkDocuments($collection, 100); + $this->assertCount(50, static::getDatabase()->updateDocuments($collection, new Document([ + 'text' => 'text📝 updated', + ]), [Query::offset(50)])); + + $docs = static::getDatabase()->find($collection, [Query::equal('text', ['text📝 updated']), Query::limit(100)]); + $this->assertCount(50, $docs); + + $lastDoc = end($docs); + $this->assertNotEmpty($lastDoc); + $this->assertEquals('doc99', $lastDoc->getId()); + + $this->assertCount(100, static::getDatabase()->deleteDocuments($collection)); } public function testUpdateDocumentsPermissions(): void @@ -16402,7 +16954,7 @@ public function testUpdateDocumentsPermissions(): void ], permissions: [], documentSecurity: true); // Test we can bulk update permissions we have access to - static::$authorization->skip(function () use ($collection) { + Authorization::skip(function () use ($collection) { for ($i = 0; $i < 10; $i++) { static::getDatabase()->createDocument($collection, new Document([ '$id' => 'doc' . $i, @@ -16437,11 +16989,11 @@ public function testUpdateDocumentsPermissions(): void ], ])); - $documents = static::$authorization->skip(function () use ($collection) { + $documents = Authorization::skip(function () use ($collection) { return static::getDatabase()->find($collection); }); - $this->assertEquals(10, $affected); + $this->assertCount(10, $affected); $this->assertCount(11, $documents); $modifiedDocuments = array_filter($documents, function (Document $document) { @@ -16466,7 +17018,7 @@ public function testUpdateDocumentsPermissions(): void $this->assertCount(1, $unmodifiedDocuments); - static::$authorization->addRole(Role::user('user2')->toString()); + Authorization::setRole(Role::user('user2')->toString()); // Test Bulk permission update with data $affected = static::getDatabase()->updateDocuments($collection, new Document([ @@ -16479,12 +17031,11 @@ public function testUpdateDocumentsPermissions(): void 'string' => 'text📝 updated', ])); - $this->assertEquals(10, $affected); + $this->assertCount(10, $affected); - $documents = static::$authorization - ->skip(function () use ($collection) { - return $this->getDatabase()->find($collection); - }); + $documents = Authorization::skip(function () use ($collection) { + return $this->getDatabase()->find($collection); + }); $this->assertCount(11, $documents); @@ -16509,8 +17060,8 @@ public function testUpdateDocumentsRelationships(): void return; } - self::$authorization->cleanRoles(); - self::$authorization->addRole(Role::any()->toString()); + Authorization::cleanRoles(); + Authorization::setRole(Role::any()->toString()); $this->getDatabase()->createCollection('testUpdateDocumentsRelationships1', attributes: [ new Document([ @@ -16614,10 +17165,51 @@ public function testUpdateDocumentsRelationships(): void } } + public function testNestedQueryValidation(): void + { + $this->getDatabase()->createCollection(__FUNCTION__, [ + new Document([ + '$id' => ID::custom('name'), + 'type' => Database::VAR_STRING, + 'size' => 255, + 'required' => true, + ]) + ], permissions: [ + Permission::read(Role::any()), + Permission::create(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()) + ]); + + $this->getDatabase()->createDocuments(__FUNCTION__, [ + new Document([ + '$id' => ID::unique(), + 'name' => 'test1', + ]), + new Document([ + '$id' => ID::unique(), + 'name' => 'doc2', + ]), + ]); + + try { + $this->getDatabase()->find(__FUNCTION__, [ + Query::or([ + Query::equal('name', ['test1']), + Query::search('name', 'doc'), + ]) + ]); + $this->fail('Failed to throw exception'); + } catch (Throwable $e) { + $this->assertInstanceOf(QueryException::class, $e); + $this->assertEquals('Searching by attribute "name" requires a fulltext index.', $e->getMessage()); + } + } + public function testEvents(): void { - self::$authorization->skip(function () { - $database = $this->getDatabase(); + Authorization::skip(function () { + $database = static::getDatabase(); $events = [ Database::EVENT_DATABASE_CREATE, @@ -16637,16 +17229,18 @@ public function testEvents(): void Database::EVENT_DOCUMENT_SUM, Database::EVENT_DOCUMENT_INCREASE, Database::EVENT_DOCUMENT_DECREASE, + Database::EVENT_DOCUMENTS_CREATE, + Database::EVENT_DOCUMENTS_UPDATE, Database::EVENT_INDEX_DELETE, Database::EVENT_DOCUMENT_DELETE, + Database::EVENT_DOCUMENTS_DELETE, Database::EVENT_ATTRIBUTE_DELETE, Database::EVENT_COLLECTION_DELETE, - Database::EVENT_DATABASE_DELETE, + Database::EVENT_DATABASE_DELETE ]; $database->on(Database::EVENT_ALL, 'test', function ($event, $data) use (&$events) { $shifted = array_shift($events); - $this->assertEquals($shifted, $event); }); @@ -16654,7 +17248,7 @@ public function testEvents(): void $database->setDatabase('hellodb'); $database->create(); } else { - array_shift($events); + \array_shift($events); } $database->list(); @@ -16698,8 +17292,23 @@ public function testEvents(): void $this->assertFalse($executed); + $database->createDocuments($collectionId, [ + new Document([ + 'attr1' => 10, + ]), + new Document([ + 'attr1' => 20, + ]), + ]); + + $database->updateDocuments($collectionId, new Document([ + 'attr1' => 15, + ])); + $database->deleteIndex($collectionId, $indexId1); $database->deleteDocument($collectionId, 'doc1'); + + $database->deleteDocuments($collectionId); $database->deleteAttribute($collectionId, 'attr1'); $database->deleteCollection($collectionId); $database->delete('hellodb'); diff --git a/tests/e2e/Adapter/MariaDBTest.php b/tests/e2e/Adapter/MariaDBTest.php index c60dfbed9..32d8c0c0c 100644 --- a/tests/e2e/Adapter/MariaDBTest.php +++ b/tests/e2e/Adapter/MariaDBTest.php @@ -12,6 +12,7 @@ class MariaDBTest extends Base { protected static ?Database $database = null; + protected static ?PDO $pdo = null; protected static string $namespace; // Remove once all methods are implemented @@ -28,7 +29,7 @@ public static function getAdapterName(): string /** * @return Database */ - public function getDatabase(bool $fresh = false): Database + public static function getDatabase(bool $fresh = false): Database { if (!is_null(self::$database) && !$fresh) { return self::$database; @@ -46,9 +47,9 @@ public function getDatabase(bool $fresh = false): Database $cache = new Cache(new RedisAdapter($redis)); $database = new Database(new MariaDB($pdo), $cache); - $database->setAuthorization(self::$authorization); - $database->setDatabase('utopiaTests'); - $database->setNamespace(static::$namespace = 'myapp_' . uniqid()); + $database + ->setDatabase('utopiaTests') + ->setNamespace(static::$namespace = 'myapp_' . uniqid()); if ($database->exists()) { $database->delete(); @@ -56,6 +57,27 @@ public function getDatabase(bool $fresh = false): Database $database->create(); + self::$pdo = $pdo; return self::$database = $database; } + + protected static function deleteColumn(string $collection, string $column): bool + { + $sqlTable = "`" . self::getDatabase()->getDatabase() . "`.`" . self::getDatabase()->getNamespace() . "_" . $collection . "`"; + $sql = "ALTER TABLE {$sqlTable} DROP COLUMN `{$column}`"; + + self::$pdo->exec($sql); + + return true; + } + + protected static function deleteIndex(string $collection, string $index): bool + { + $sqlTable = "`" . self::getDatabase()->getDatabase() . "`.`" . self::getDatabase()->getNamespace() . "_" . $collection . "`"; + $sql = "DROP INDEX `{$index}` ON {$sqlTable}"; + + self::$pdo->exec($sql); + + return true; + } } diff --git a/tests/e2e/Adapter/MirrorTest.php b/tests/e2e/Adapter/MirrorTest.php new file mode 100644 index 000000000..a3d457624 --- /dev/null +++ b/tests/e2e/Adapter/MirrorTest.php @@ -0,0 +1,349 @@ +connect('redis'); + $redis->flushAll(); + $cache = new Cache(new RedisAdapter($redis)); + + self::$sourcePdo = $pdo; + self::$source = new Database(new MariaDB($pdo), $cache); + + $mirrorHost = 'mariadb-mirror'; + $mirrorPort = '3306'; + $mirrorUser = 'root'; + $mirrorPass = 'password'; + + $mirrorPdo = new PDO("mysql:host={$mirrorHost};port={$mirrorPort};charset=utf8mb4", $mirrorUser, $mirrorPass, MariaDB::getPDOAttributes()); + $mirrorRedis = new Redis(); + $mirrorRedis->connect('redis-mirror'); + $mirrorRedis->flushAll(); + $mirrorCache = new Cache(new RedisAdapter($mirrorRedis)); + + self::$destinationPdo = $mirrorPdo; + self::$destination = new Database(new MariaDB($mirrorPdo), $mirrorCache); + + $database = new Mirror(self::$source, self::$destination); + + // Handle cases where the source and destination databases are not in sync because of previous tests + if ($database->getSource()->exists('schema1')) { + $database->getSource()->setDatabase('schema1')->delete(); + } + if ($database->getDestination()->exists('schema1')) { + $database->getDestination()->setDatabase('schema1')->delete(); + } + if ($database->getSource()->exists('schema2')) { + $database->getSource()->setDatabase('schema2')->delete(); + } + if ($database->getDestination()->exists('schema2')) { + $database->getDestination()->setDatabase('schema2')->delete(); + } + if ($database->getSource()->exists('sharedTables')) { + $database->getSource()->setDatabase('sharedTables')->delete(); + } + if ($database->getDestination()->exists('sharedTables')) { + $database->getDestination()->setDatabase('sharedTables')->delete(); + } + + $database + ->setDatabase('utopiaTests') + ->setNamespace(static::$namespace = 'myapp_' . uniqid()); + + if ($database->exists()) { + $database->delete(); + } + + $database->create(); + + return self::$database = $database; + } + + protected static function getAdapterName(): string + { + return "Mirror"; + } + + /** + * @throws Exception + * @throws \RedisException + */ + public function testGetMirrorSource(): void + { + $database = self::getDatabase(); + $source = $database->getSource(); + $this->assertInstanceOf(Database::class, $source); + $this->assertEquals(self::$source, $source); + } + + /** + * @throws Exception + * @throws \RedisException + */ + public function testGetMirrorDestination(): void + { + $database = self::getDatabase(); + $destination = $database->getDestination(); + $this->assertInstanceOf(Database::class, $destination); + $this->assertEquals(self::$destination, $destination); + } + + /** + * @throws Limit + * @throws Duplicate + * @throws Exception + * @throws \RedisException + */ + public function testCreateMirroredCollection(): void + { + $database = self::getDatabase(); + + $database->createCollection('testCreateMirroredCollection'); + + // Assert collection exists in both databases + $this->assertFalse($database->getSource()->getCollection('testCreateMirroredCollection')->isEmpty()); + $this->assertFalse($database->getDestination()->getCollection('testCreateMirroredCollection')->isEmpty()); + } + + /** + * @throws Limit + * @throws Duplicate + * @throws \RedisException + * @throws Conflict + * @throws Exception + */ + public function testUpdateMirroredCollection(): void + { + $database = self::getDatabase(); + + $database->createCollection('testUpdateMirroredCollection', permissions: [ + Permission::read(Role::any()), + ]); + + $collection = $database->getCollection('testUpdateMirroredCollection'); + + $database->updateCollection( + 'testUpdateMirroredCollection', + [ + Permission::read(Role::users()), + ], + $collection->getAttribute('documentSecurity') + ); + + // Asset both databases have updated the collection + $this->assertEquals( + [Permission::read(Role::users())], + $database->getSource()->getCollection('testUpdateMirroredCollection')->getPermissions() + ); + + $this->assertEquals( + [Permission::read(Role::users())], + $database->getDestination()->getCollection('testUpdateMirroredCollection')->getPermissions() + ); + } + + public function testDeleteMirroredCollection(): void + { + $database = self::getDatabase(); + + $database->createCollection('testDeleteMirroredCollection'); + + $database->deleteCollection('testDeleteMirroredCollection'); + + // Assert collection is deleted in both databases + $this->assertTrue($database->getSource()->getCollection('testDeleteMirroredCollection')->isEmpty()); + $this->assertTrue($database->getDestination()->getCollection('testDeleteMirroredCollection')->isEmpty()); + } + + /** + * @throws Authorization + * @throws Duplicate + * @throws \RedisException + * @throws Limit + * @throws Structure + * @throws Exception + */ + public function testCreateMirroredDocument(): void + { + $database = self::getDatabase(); + + $database->createCollection('testCreateMirroredDocument', attributes: [ + new Document([ + '$id' => 'name', + 'type' => Database::VAR_STRING, + 'required' => true, + 'size' => Database::LENGTH_KEY, + ]), + ], permissions: [ + Permission::create(Role::any()), + Permission::read(Role::any()), + ], documentSecurity: false); + + $document = $database->createDocument('testCreateMirroredDocument', new Document([ + 'name' => 'Jake', + '$permissions' => [] + ])); + + // Assert document is created in both databases + $this->assertEquals( + $document, + $database->getSource()->getDocument('testCreateMirroredDocument', $document->getId()) + ); + + $this->assertEquals( + $document, + $database->getDestination()->getDocument('testCreateMirroredDocument', $document->getId()) + ); + } + + /** + * @throws Authorization + * @throws Duplicate + * @throws \RedisException + * @throws Conflict + * @throws Limit + * @throws Structure + * @throws Exception + */ + public function testUpdateMirroredDocument(): void + { + $database = self::getDatabase(); + + $database->createCollection('testUpdateMirroredDocument', attributes: [ + new Document([ + '$id' => 'name', + 'type' => Database::VAR_STRING, + 'required' => true, + 'size' => Database::LENGTH_KEY, + ]), + ], permissions: [ + Permission::create(Role::any()), + Permission::read(Role::any()), + Permission::update(Role::any()), + ], documentSecurity: false); + + $document = $database->createDocument('testUpdateMirroredDocument', new Document([ + 'name' => 'Jake', + '$permissions' => [] + ])); + + $document = $database->updateDocument( + 'testUpdateMirroredDocument', + $document->getId(), + $document->setAttribute('name', 'John') + ); + + // Assert document is updated in both databases + $this->assertEquals( + $document, + $database->getSource()->getDocument('testUpdateMirroredDocument', $document->getId()) + ); + + $this->assertEquals( + $document, + $database->getDestination()->getDocument('testUpdateMirroredDocument', $document->getId()) + ); + } + + public function testDeleteMirroredDocument(): void + { + $database = self::getDatabase(); + + $database->createCollection('testDeleteMirroredDocument', attributes: [ + new Document([ + '$id' => 'name', + 'type' => Database::VAR_STRING, + 'required' => true, + 'size' => Database::LENGTH_KEY, + ]), + ], permissions: [ + Permission::create(Role::any()), + Permission::read(Role::any()), + Permission::delete(Role::any()), + ], documentSecurity: false); + + $document = $database->createDocument('testDeleteMirroredDocument', new Document([ + 'name' => 'Jake', + '$permissions' => [] + ])); + + $database->deleteDocument('testDeleteMirroredDocument', $document->getId()); + + // Assert document is deleted in both databases + $this->assertTrue($database->getSource()->getDocument('testDeleteMirroredDocument', $document->getId())->isEmpty()); + $this->assertTrue($database->getDestination()->getDocument('testDeleteMirroredDocument', $document->getId())->isEmpty()); + } + + protected static function deleteColumn(string $collection, string $column): bool + { + $sqlTable = "`" . self::$source->getDatabase() . "`.`" . self::$source->getNamespace() . "_" . $collection . "`"; + $sql = "ALTER TABLE {$sqlTable} DROP COLUMN `{$column}`"; + + self::$sourcePdo->exec($sql); + + $sqlTable = "`" . self::$destination->getDatabase() . "`.`" . self::$destination->getNamespace() . "_" . $collection . "`"; + $sql = "ALTER TABLE {$sqlTable} DROP COLUMN `{$column}`"; + + self::$destinationPdo->exec($sql); + + return true; + } + + protected static function deleteIndex(string $collection, string $index): bool + { + $sqlTable = "`" . self::$source->getDatabase() . "`.`" . self::$source->getNamespace() . "_" . $collection . "`"; + $sql = "DROP INDEX `{$index}` ON {$sqlTable}"; + + self::$sourcePdo->exec($sql); + + $sqlTable = "`" . self::$destination->getDatabase() . "`.`" . self::$destination->getNamespace() . "_" . $collection . "`"; + $sql = "DROP INDEX `{$index}` ON {$sqlTable}"; + + self::$destinationPdo->exec($sql); + + return true; + } +} diff --git a/tests/e2e/Adapter/MongoDBTest.php b/tests/e2e/Adapter/MongoDBTest.php index a17e595bd..e582aef59 100644 --- a/tests/e2e/Adapter/MongoDBTest.php +++ b/tests/e2e/Adapter/MongoDBTest.php @@ -29,7 +29,7 @@ public static function getAdapterName(): string * @return Database * @throws Exception */ - public function getDatabase(): Database + public static function getDatabase(): Database { if (!is_null(self::$database)) { return self::$database; @@ -51,9 +51,9 @@ public function getDatabase(): Database ); $database = new Database(new Mongo($client), $cache); - $database->setAuthorization(self::$authorization); - $database->setDatabase($schema); - $database->setNamespace(static::$namespace = 'myapp_' . uniqid()); + $database + ->setDatabase($schema) + ->setNamespace(static::$namespace = 'myapp_' . uniqid()); if ($database->exists()) { $database->delete(); @@ -70,10 +70,10 @@ public function getDatabase(): Database public function testCreateExistsDelete(): void { // Mongo creates databases on the fly, so exists would always pass. So we override this test to remove the exists check. - $this->assertNotNull($this->getDatabase()->create()); - $this->assertEquals(true, $this->getDatabase()->delete($this->testDatabase)); - $this->assertEquals(true, $this->getDatabase()->create()); - $this->assertEquals($this->getDatabase(), $this->getDatabase()->setDatabase($this->testDatabase)); + $this->assertNotNull(static::getDatabase()->create()); + $this->assertEquals(true, static::getDatabase()->delete($this->testDatabase)); + $this->assertEquals(true, static::getDatabase()->create()); + $this->assertEquals(static::getDatabase(), static::getDatabase()->setDatabase($this->testDatabase)); } public function testRenameAttribute(): void @@ -95,4 +95,14 @@ public function testKeywords(): void { $this->assertTrue(true); } + + protected static function deleteColumn(string $collection, string $column): bool + { + return true; + } + + protected static function deleteIndex(string $collection, string $index): bool + { + return true; + } } diff --git a/tests/e2e/Adapter/MySQLTest.php b/tests/e2e/Adapter/MySQLTest.php index bae839a10..369958f07 100644 --- a/tests/e2e/Adapter/MySQLTest.php +++ b/tests/e2e/Adapter/MySQLTest.php @@ -12,6 +12,7 @@ class MySQLTest extends Base { public static ?Database $database = null; + protected static ?PDO $pdo = null; protected static string $namespace; // Remove once all methods are implemented @@ -28,7 +29,7 @@ public static function getAdapterName(): string /** * @return Database */ - public function getDatabase(): Database + public static function getDatabase(): Database { if (!is_null(self::$database)) { return self::$database; @@ -48,9 +49,9 @@ public function getDatabase(): Database $cache = new Cache(new RedisAdapter($redis)); $database = new Database(new MySQL($pdo), $cache); - $database->setAuthorization(self::$authorization); - $database->setDatabase('utopiaTests'); - $database->setNamespace(static::$namespace = 'myapp_' . uniqid()); + $database + ->setDatabase('utopiaTests') + ->setNamespace(static::$namespace = 'myapp_' . uniqid()); if ($database->exists()) { $database->delete(); @@ -58,6 +59,27 @@ public function getDatabase(): Database $database->create(); + self::$pdo = $pdo; return self::$database = $database; } + + protected static function deleteColumn(string $collection, string $column): bool + { + $sqlTable = "`" . self::getDatabase()->getDatabase() . "`.`" . self::getDatabase()->getNamespace() . "_" . $collection . "`"; + $sql = "ALTER TABLE {$sqlTable} DROP COLUMN `{$column}`"; + + self::$pdo->exec($sql); + + return true; + } + + protected static function deleteIndex(string $collection, string $index): bool + { + $sqlTable = "`" . self::getDatabase()->getDatabase() . "`.`" . self::getDatabase()->getNamespace() . "_" . $collection . "`"; + $sql = "DROP INDEX `{$index}` ON {$sqlTable}"; + + self::$pdo->exec($sql); + + return true; + } } diff --git a/tests/e2e/Adapter/PostgresTest.php b/tests/e2e/Adapter/PostgresTest.php index 19b972115..62977c913 100644 --- a/tests/e2e/Adapter/PostgresTest.php +++ b/tests/e2e/Adapter/PostgresTest.php @@ -12,6 +12,7 @@ class PostgresTest extends Base { public static ?Database $database = null; + protected static ?PDO $pdo = null; protected static string $namespace; /** @@ -27,7 +28,7 @@ public static function getAdapterName(): string /** * @reture Adapter */ - public function getDatabase(): Database + public static function getDatabase(): Database { if (!is_null(self::$database)) { return self::$database; @@ -45,9 +46,9 @@ public function getDatabase(): Database $cache = new Cache(new RedisAdapter($redis)); $database = new Database(new Postgres($pdo), $cache); - $database->setAuthorization(self::$authorization); - $database->setDatabase('utopiaTests'); - $database->setNamespace(static::$namespace = 'myapp_' . uniqid()); + $database + ->setDatabase('utopiaTests') + ->setNamespace(static::$namespace = 'myapp_' . uniqid()); if ($database->exists()) { $database->delete(); @@ -55,6 +56,28 @@ public function getDatabase(): Database $database->create(); + self::$pdo = $pdo; return self::$database = $database; } + + protected static function deleteColumn(string $collection, string $column): bool + { + $sqlTable = '"' . self::getDatabase()->getDatabase() . '"."' . self::getDatabase()->getNamespace() . '_' . $collection . '"'; + $sql = "ALTER TABLE {$sqlTable} DROP COLUMN \"{$column}\""; + + self::$pdo->exec($sql); + + return true; + } + + protected static function deleteIndex(string $collection, string $index): bool + { + $key = "\"".self::getDatabase()->getNamespace()."_".self::getDatabase()->getTenant()."_{$collection}_{$index}\""; + + $sql = "DROP INDEX \"".self::getDatabase()->getDatabase()."\".{$key}"; + + self::$pdo->exec($sql); + + return true; + } } diff --git a/tests/e2e/Adapter/SQLiteTest.php b/tests/e2e/Adapter/SQLiteTest.php index bc903fd7d..87676b7f5 100644 --- a/tests/e2e/Adapter/SQLiteTest.php +++ b/tests/e2e/Adapter/SQLiteTest.php @@ -12,6 +12,7 @@ class SQLiteTest extends Base { public static ?Database $database = null; + protected static ?PDO $pdo = null; protected static string $namespace; // Remove once all methods are implemented @@ -28,7 +29,7 @@ public static function getAdapterName(): string /** * @return Database */ - public function getDatabase(): Database + public static function getDatabase(): Database { if (!is_null(self::$database)) { return self::$database; @@ -51,9 +52,9 @@ public function getDatabase(): Database $cache = new Cache(new RedisAdapter($redis)); $database = new Database(new SQLite($pdo), $cache); - $database->setAuthorization(self::$authorization); - $database->setDatabase('utopiaTests'); - $database->setNamespace(static::$namespace = 'myapp_' . uniqid()); + $database + ->setDatabase('utopiaTests') + ->setNamespace(static::$namespace = 'myapp_' . uniqid()); if ($database->exists()) { $database->delete(); @@ -61,6 +62,27 @@ public function getDatabase(): Database $database->create(); + self::$pdo = $pdo; return self::$database = $database; } + + protected static function deleteColumn(string $collection, string $column): bool + { + $sqlTable = "`" . self::getDatabase()->getNamespace() . "_" . $collection . "`"; + $sql = "ALTER TABLE {$sqlTable} DROP COLUMN `{$column}`"; + + self::$pdo->exec($sql); + + return true; + } + + protected static function deleteIndex(string $collection, string $index): bool + { + $index = "`".self::getDatabase()->getNamespace()."_".self::getDatabase()->getTenant()."_{$collection}_{$index}`"; + $sql = "DROP INDEX {$index}"; + + self::$pdo->exec($sql); + + return true; + } } diff --git a/tests/e2e/Adapter/SharedTables/MariaDBTest.php b/tests/e2e/Adapter/SharedTables/MariaDBTest.php index 7ee04ac5b..b747c3244 100644 --- a/tests/e2e/Adapter/SharedTables/MariaDBTest.php +++ b/tests/e2e/Adapter/SharedTables/MariaDBTest.php @@ -13,6 +13,7 @@ class MariaDBTest extends Base { protected static ?Database $database = null; + protected static ?PDO $pdo = null; protected static string $namespace; // Remove once all methods are implemented @@ -29,7 +30,7 @@ public static function getAdapterName(): string /** * @return Database */ - public function getDatabase(bool $fresh = false): Database + public static function getDatabase(bool $fresh = false): Database { if (!is_null(self::$database) && !$fresh) { return self::$database; @@ -48,7 +49,6 @@ public function getDatabase(bool $fresh = false): Database $database = new Database(new MariaDB($pdo), $cache); $database - ->setAuthorization(self::$authorization) ->setDatabase('utopiaTests') ->setSharedTables(true) ->setTenant(999) @@ -60,6 +60,27 @@ public function getDatabase(bool $fresh = false): Database $database->create(); + self::$pdo = $pdo; return self::$database = $database; } + + protected static function deleteColumn(string $collection, string $column): bool + { + $sqlTable = "`" . self::getDatabase()->getDatabase() . "`.`" . self::getDatabase()->getNamespace() . "_" . $collection . "`"; + $sql = "ALTER TABLE {$sqlTable} DROP COLUMN `{$column}`"; + + self::$pdo->exec($sql); + + return true; + } + + protected static function deleteIndex(string $collection, string $index): bool + { + $sqlTable = "`" . self::getDatabase()->getDatabase() . "`.`" . self::getDatabase()->getNamespace() . "_" . $collection . "`"; + $sql = "DROP INDEX `{$index}` ON {$sqlTable}"; + + self::$pdo->exec($sql); + + return true; + } } diff --git a/tests/e2e/Adapter/SharedTables/MongoDBTest.php b/tests/e2e/Adapter/SharedTables/MongoDBTest.php index c5968727c..7d41bb711 100644 --- a/tests/e2e/Adapter/SharedTables/MongoDBTest.php +++ b/tests/e2e/Adapter/SharedTables/MongoDBTest.php @@ -30,7 +30,7 @@ public static function getAdapterName(): string * @return Database * @throws Exception */ - public function getDatabase(): Database + public static function getDatabase(): Database { if (!is_null(self::$database)) { return self::$database; @@ -53,7 +53,6 @@ public function getDatabase(): Database $database = new Database(new Mongo($client), $cache); $database - ->setAuthorization(self::$authorization) ->setDatabase($schema) ->setSharedTables(true) ->setTenant(999) @@ -99,4 +98,14 @@ public function testKeywords(): void { $this->assertTrue(true); } + + protected static function deleteColumn(string $collection, string $column): bool + { + return true; + } + + protected static function deleteIndex(string $collection, string $index): bool + { + return true; + } } diff --git a/tests/e2e/Adapter/SharedTables/MySQLTest.php b/tests/e2e/Adapter/SharedTables/MySQLTest.php index af244d985..e56a2ba51 100644 --- a/tests/e2e/Adapter/SharedTables/MySQLTest.php +++ b/tests/e2e/Adapter/SharedTables/MySQLTest.php @@ -13,6 +13,7 @@ class MySQLTest extends Base { public static ?Database $database = null; + protected static ?PDO $pdo = null; protected static string $namespace; // Remove once all methods are implemented @@ -29,7 +30,7 @@ public static function getAdapterName(): string /** * @return Database */ - public function getDatabase(): Database + public static function getDatabase(): Database { if (!is_null(self::$database)) { return self::$database; @@ -50,7 +51,6 @@ public function getDatabase(): Database $database = new Database(new MySQL($pdo), $cache); $database - ->setAuthorization(self::$authorization) ->setDatabase('utopiaTests') ->setSharedTables(true) ->setTenant(999) @@ -62,6 +62,27 @@ public function getDatabase(): Database $database->create(); + self::$pdo = $pdo; return self::$database = $database; } + + protected static function deleteColumn(string $collection, string $column): bool + { + $sqlTable = "`" . self::getDatabase()->getDatabase() . "`.`" . self::getDatabase()->getNamespace() . "_" . $collection . "`"; + $sql = "ALTER TABLE {$sqlTable} DROP COLUMN `{$column}`"; + + self::$pdo->exec($sql); + + return true; + } + + protected static function deleteIndex(string $collection, string $index): bool + { + $sqlTable = "`" . self::getDatabase()->getDatabase() . "`.`" . self::getDatabase()->getNamespace() . "_" . $collection . "`"; + $sql = "DROP INDEX `{$index}` ON {$sqlTable}"; + + self::$pdo->exec($sql); + + return true; + } } diff --git a/tests/e2e/Adapter/SharedTables/PostgresTest.php b/tests/e2e/Adapter/SharedTables/PostgresTest.php index 4de48ee1d..8319311d5 100644 --- a/tests/e2e/Adapter/SharedTables/PostgresTest.php +++ b/tests/e2e/Adapter/SharedTables/PostgresTest.php @@ -13,6 +13,7 @@ class PostgresTest extends Base { public static ?Database $database = null; + public static ?PDO $pdo = null; protected static string $namespace; /** @@ -28,7 +29,7 @@ public static function getAdapterName(): string /** * @reture Adapter */ - public function getDatabase(): Database + public static function getDatabase(): Database { if (!is_null(self::$database)) { return self::$database; @@ -47,7 +48,6 @@ public function getDatabase(): Database $database = new Database(new Postgres($pdo), $cache); $database - ->setAuthorization(self::$authorization) ->setDatabase('utopiaTests') ->setSharedTables(true) ->setTenant(999) @@ -59,6 +59,28 @@ public function getDatabase(): Database $database->create(); + self::$pdo = $pdo; return self::$database = $database; } + + protected static function deleteColumn(string $collection, string $column): bool + { + $sqlTable = '"' . self::getDatabase()->getDatabase() . '"."' . self::getDatabase()->getNamespace() . '_' . $collection . '"'; + $sql = "ALTER TABLE {$sqlTable} DROP COLUMN \"{$column}\""; + + self::$pdo->exec($sql); + + return true; + } + + protected static function deleteIndex(string $collection, string $index): bool + { + $key = "\"".self::getDatabase()->getNamespace()."_".self::getDatabase()->getTenant()."_{$collection}_{$index}\""; + + $sql = "DROP INDEX \"".self::getDatabase()->getDatabase()."\".{$key}"; + + self::$pdo->exec($sql); + + return true; + } } diff --git a/tests/e2e/Adapter/SharedTables/SQLiteTest.php b/tests/e2e/Adapter/SharedTables/SQLiteTest.php index a1254505d..daa39d6be 100644 --- a/tests/e2e/Adapter/SharedTables/SQLiteTest.php +++ b/tests/e2e/Adapter/SharedTables/SQLiteTest.php @@ -13,6 +13,7 @@ class SQLiteTest extends Base { public static ?Database $database = null; + public static ?PDO $pdo = null; protected static string $namespace; // Remove once all methods are implemented @@ -29,7 +30,7 @@ public static function getAdapterName(): string /** * @return Database */ - public function getDatabase(): Database + public static function getDatabase(): Database { if (!is_null(self::$database)) { return self::$database; @@ -53,7 +54,6 @@ public function getDatabase(): Database $database = new Database(new SQLite($pdo), $cache); $database - ->setAuthorization(self::$authorization) ->setDatabase('utopiaTests') ->setSharedTables(true) ->setTenant(999) @@ -65,6 +65,27 @@ public function getDatabase(): Database $database->create(); + self::$pdo = $pdo; return self::$database = $database; } + + protected static function deleteColumn(string $collection, string $column): bool + { + $sqlTable = "`" . self::getDatabase()->getNamespace() . "_" . $collection . "`"; + $sql = "ALTER TABLE {$sqlTable} DROP COLUMN `{$column}`"; + + self::$pdo->exec($sql); + + return true; + } + + protected static function deleteIndex(string $collection, string $index): bool + { + $index = "`".self::getDatabase()->getNamespace()."_".self::getDatabase()->getTenant()."_{$collection}_{$index}`"; + $sql = "DROP INDEX {$index}"; + + self::$pdo->exec($sql); + + return true; + } } diff --git a/tests/unit/Format.php b/tests/unit/Format.php index 92cf10f28..f4f4a4a0f 100644 --- a/tests/unit/Format.php +++ b/tests/unit/Format.php @@ -2,15 +2,14 @@ namespace Tests\Unit; -use Utopia\Http\Validator; -use Utopia\Http\Validator\Text; +use Utopia\Validator\Text; /** * Format Test for Email * * Validate that an variable is a valid email address * - * @package Utopia\Http\Validator + * @package Utopia\Validator */ class Format extends Text { diff --git a/tests/unit/QueryTest.php b/tests/unit/QueryTest.php index 9666ebf3a..d9ad6cd93 100644 --- a/tests/unit/QueryTest.php +++ b/tests/unit/QueryTest.php @@ -213,6 +213,13 @@ public function testParse(): void $this->assertEquals('actors', $queries[0]->getAttribute()); $this->assertEquals($json, '{"method":"or","values":[{"method":"equal","attribute":"actors","values":["Brad Pitt"]},{"method":"equal","attribute":"actors","values":["Johnny Depp"]}]}'); + try { + Query::parse('{"method":["equal"],"attribute":["title"],"values":["test"]}'); + $this->fail('Failed to throw exception'); + } catch (QueryException $e) { + $this->assertEquals('Invalid query method. Must be a string, got array', $e->getMessage()); + } + try { Query::parse('{"method":"equal","attribute":["title"],"values":["test"]}'); $this->fail('Failed to throw exception'); @@ -220,6 +227,13 @@ public function testParse(): void $this->assertEquals('Invalid query attribute. Must be a string, got array', $e->getMessage()); } + try { + Query::parse('{"method":"equal","attribute":"title","values":"test"}'); + $this->fail('Failed to throw exception'); + } catch (QueryException $e) { + $this->assertEquals('Invalid query values. Must be an array, got string', $e->getMessage()); + } + try { Query::parse('false'); $this->fail('Failed to throw exception'); diff --git a/tests/unit/Validator/AuthorizationTest.php b/tests/unit/Validator/AuthorizationTest.php index 37e5a6e22..08c1e46f2 100644 --- a/tests/unit/Validator/AuthorizationTest.php +++ b/tests/unit/Validator/AuthorizationTest.php @@ -9,15 +9,11 @@ use Utopia\Database\Helpers\Permission; use Utopia\Database\Helpers\Role; use Utopia\Database\Validator\Authorization; -use Utopia\Database\Validator\Authorization\Input; class AuthorizationTest extends TestCase { - protected Authorization $authorization; - public function setUp(): void { - $this->authorization = new Authorization(); } public function tearDown(): void @@ -26,7 +22,7 @@ public function tearDown(): void public function testValues(): void { - $this->authorization->addRole(Role::any()->toString()); + Authorization::setRole(Role::any()->toString()); $document = new Document([ '$id' => ID::unique(), @@ -39,88 +35,88 @@ public function testValues(): void Permission::delete(Role::any()), ], ]); + $object = new Authorization(Database::PERMISSION_READ); - $object = $this->authorization; - - $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), false); - $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, [])), false); + $this->assertEquals($object->isValid($document->getRead()), false); + $this->assertEquals($object->isValid(''), false); + $this->assertEquals($object->isValid([]), false); $this->assertEquals($object->getDescription(), 'No permissions provided for action \'read\''); - $this->authorization->addRole(Role::user('456')->toString()); - $this->authorization->addRole(Role::user('123')->toString()); + Authorization::setRole(Role::user('456')->toString()); + Authorization::setRole(Role::user('123')->toString()); - $this->assertEquals($this->authorization->isRole(Role::user('456')->toString()), true); - $this->assertEquals($this->authorization->isRole(Role::user('457')->toString()), false); - $this->assertEquals($this->authorization->isRole(''), false); - $this->assertEquals($this->authorization->isRole(Role::any()->toString()), true); + $this->assertEquals(Authorization::isRole(Role::user('456')->toString()), true); + $this->assertEquals(Authorization::isRole(Role::user('457')->toString()), false); + $this->assertEquals(Authorization::isRole(''), false); + $this->assertEquals(Authorization::isRole(Role::any()->toString()), true); - $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), true); + $this->assertEquals($object->isValid($document->getRead()), true); - $this->authorization->cleanRoles(); + Authorization::cleanRoles(); - $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), false); + $this->assertEquals($object->isValid($document->getRead()), false); - $this->authorization->addRole(Role::team('123')->toString()); + Authorization::setRole(Role::team('123')->toString()); - $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), true); + $this->assertEquals($object->isValid($document->getRead()), true); - $this->authorization->cleanRoles(); - $this->authorization->disable(); + Authorization::cleanRoles(); + Authorization::disable(); - $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), true); + $this->assertEquals($object->isValid($document->getRead()), true); - $this->authorization->reset(); + Authorization::reset(); - $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), false); + $this->assertEquals($object->isValid($document->getRead()), false); - $this->authorization->setDefaultStatus(false); - $this->authorization->disable(); + Authorization::setDefaultStatus(false); + Authorization::disable(); - $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), true); + $this->assertEquals($object->isValid($document->getRead()), true); - $this->authorization->reset(); + Authorization::reset(); - $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), true); + $this->assertEquals($object->isValid($document->getRead()), true); - $this->authorization->enable(); + Authorization::enable(); - $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), false); + $this->assertEquals($object->isValid($document->getRead()), false); - $this->authorization->addRole('textX'); + Authorization::setRole('textX'); - $this->assertContains('textX', $this->authorization->getRoles()); + $this->assertContains('textX', Authorization::getRoles()); - $this->authorization->removeRole('textX'); + Authorization::unsetRole('textX'); - $this->assertNotContains('textX', $this->authorization->getRoles()); + $this->assertNotContains('textX', Authorization::getRoles()); // Test skip method - $this->assertEquals($object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())), false); - $this->assertEquals($this->authorization->skip(function () use ($object, $document) { - return $object->isValid(new Input(Database::PERMISSION_READ, $document->getRead())); + $this->assertEquals($object->isValid($document->getRead()), false); + $this->assertEquals(Authorization::skip(function () use ($object, $document) { + return $object->isValid($document->getRead()); }), true); } public function testNestedSkips(): void { - $this->assertEquals(true, $this->authorization->getStatus()); + $this->assertEquals(true, Authorization::$status); - $this->authorization->skip(function () { - $this->assertEquals(false, $this->authorization->getStatus()); + Authorization::skip(function () { + $this->assertEquals(false, Authorization::$status); - $this->authorization->skip(function () { - $this->assertEquals(false, $this->authorization->getStatus()); + Authorization::skip(function () { + $this->assertEquals(false, Authorization::$status); - $this->authorization->skip(function () { - $this->assertEquals(false, $this->authorization->getStatus()); + Authorization::skip(function () { + $this->assertEquals(false, Authorization::$status); }); - $this->assertEquals(false, $this->authorization->getStatus()); + $this->assertEquals(false, Authorization::$status); }); - $this->assertEquals(false, $this->authorization->getStatus()); + $this->assertEquals(false, Authorization::$status); }); - $this->assertEquals(true, $this->authorization->getStatus()); + $this->assertEquals(true, Authorization::$status); } } diff --git a/tests/unit/Validator/DateTimeTest.php b/tests/unit/Validator/DateTimeTest.php index d8ababb6f..106080c29 100644 --- a/tests/unit/Validator/DateTimeTest.php +++ b/tests/unit/Validator/DateTimeTest.php @@ -8,6 +8,19 @@ class DateTimeTest extends TestCase { + private \DateTime $minAllowed; + private \DateTime $maxAllowed; + private string $minString = '0000-01-01 00:00:00'; + private string $maxString = '9999-12-31 23:59:59'; + + public function __construct() + { + parent::__construct(); + + $this->minAllowed = new \DateTime($this->minString); + $this->maxAllowed = new \DateTime($this->maxString); + } + public function setUp(): void { } @@ -18,7 +31,7 @@ public function tearDown(): void public function testCreateDatetime(): void { - $dateValidator = new DatetimeValidator(); + $dateValidator = new DatetimeValidator($this->minAllowed, $this->maxAllowed); $this->assertGreaterThan(DateTime::addSeconds(new \DateTime(), -3), DateTime::now()); $this->assertEquals(true, $dateValidator->isValid("2022-12-04")); @@ -29,7 +42,7 @@ public function testCreateDatetime(): void $now = DateTime::now(); $this->assertEquals(23, strlen($now)); $this->assertGreaterThan('2020-1-1 11:31:52.680', $now); - $this->assertEquals('Value must be valid date.', $dateValidator->getDescription()); + $this->assertEquals("Value must be valid date between {$this->minString} and {$this->maxString}.", $dateValidator->getDescription()); $date = '2022-07-02 18:31:52.680'; $dateObject = new \DateTime($date); @@ -51,63 +64,100 @@ public function testCreateDatetime(): void * Test for Failure */ $this->assertEquals(false, $dateValidator->isValid("2022-13-04 11:31:52.680")); + $this->assertEquals(false, $dateValidator->isValid("-0001-13-04 00:00:00")); + $this->assertEquals(false, $dateValidator->isValid("0000-00-00 00:00:00")); + $this->assertEquals(false, $dateValidator->isValid("10000-01-01 00:00:00")); } public function testPastDateValidation(): void { - $dateValidator = new DatetimeValidator(requireDateInFuture: true); + $dateValidator = new DatetimeValidator( + $this->minAllowed, + $this->maxAllowed, + requireDateInFuture: true, + ); + $this->assertEquals(false, $dateValidator->isValid(DateTime::addSeconds(new \DateTime(), -3))); $this->assertEquals(true, $dateValidator->isValid(DateTime::addSeconds(new \DateTime(), 5))); - $this->assertEquals('Value must be valid date in future.', $dateValidator->getDescription()); + $this->assertEquals("Value must be valid date in the future and between {$this->minString} and {$this->maxString}.", $dateValidator->getDescription()); + + $dateValidator = new DatetimeValidator( + $this->minAllowed, + $this->maxAllowed, + requireDateInFuture: false + ); - $dateValidator = new DatetimeValidator(requireDateInFuture: false); $this->assertEquals(true, $dateValidator->isValid(DateTime::addSeconds(new \DateTime(), -3))); $this->assertEquals(true, $dateValidator->isValid(DateTime::addSeconds(new \DateTime(), 5))); - $this->assertEquals('Value must be valid date.', $dateValidator->getDescription()); + $this->assertEquals("Value must be valid date between {$this->minString} and {$this->maxString}.", $dateValidator->getDescription()); } public function testDatePrecision(): void { - $dateValidator = new DatetimeValidator(precision: DatetimeValidator::PRECISION_SECONDS); + $dateValidator = new DatetimeValidator( + $this->minAllowed, + $this->maxAllowed, + precision: DatetimeValidator::PRECISION_SECONDS + ); $this->assertEquals(false, $dateValidator->isValid(DateTime::format(new \DateTime('2019-04-08 19:36:26.255')))); $this->assertEquals(true, $dateValidator->isValid(DateTime::format(new \DateTime('2019-04-08 19:36:26.000')))); $this->assertEquals(true, $dateValidator->isValid(DateTime::format(new \DateTime('2019-04-08 19:36:26')))); - $this->assertEquals('Value must be valid date with seconds precision.', $dateValidator->getDescription()); + $this->assertEquals("Value must be valid date with seconds precision between {$this->minString} and {$this->maxString}.", $dateValidator->getDescription()); - $dateValidator = new DatetimeValidator(precision: DatetimeValidator::PRECISION_MINUTES); + $dateValidator = new DatetimeValidator( + $this->minAllowed, + $this->maxAllowed, + precision: DatetimeValidator::PRECISION_MINUTES + ); $this->assertEquals(false, $dateValidator->isValid(DateTime::format(new \DateTime('2019-04-08 19:36:26.255')))); $this->assertEquals(false, $dateValidator->isValid(DateTime::format(new \DateTime('2019-04-08 19:36:26.000')))); $this->assertEquals(false, $dateValidator->isValid(DateTime::format(new \DateTime('2019-04-08 19:36:26')))); $this->assertEquals(true, $dateValidator->isValid(DateTime::format(new \DateTime('2019-04-08 19:36:00')))); - $this->assertEquals('Value must be valid date with minutes precision.', $dateValidator->getDescription()); + $this->assertEquals("Value must be valid date with minutes precision between {$this->minString} and {$this->maxString}.", $dateValidator->getDescription()); - $dateValidator = new DatetimeValidator(precision: DatetimeValidator::PRECISION_HOURS); + $dateValidator = new DatetimeValidator( + $this->minAllowed, + $this->maxAllowed, + precision: DatetimeValidator::PRECISION_HOURS + ); $this->assertEquals(false, $dateValidator->isValid(DateTime::format(new \DateTime('2019-04-08 19:36:26.255')))); $this->assertEquals(false, $dateValidator->isValid(DateTime::format(new \DateTime('2019-04-08 19:36:26.000')))); $this->assertEquals(false, $dateValidator->isValid(DateTime::format(new \DateTime('2019-04-08 19:36:26')))); $this->assertEquals(false, $dateValidator->isValid(DateTime::format(new \DateTime('2019-04-08 19:36:00')))); $this->assertEquals(true, $dateValidator->isValid(DateTime::format(new \DateTime('2019-04-08 19:00:00')))); - $this->assertEquals('Value must be valid date with hours precision.', $dateValidator->getDescription()); + $this->assertEquals("Value must be valid date with hours precision between {$this->minString} and {$this->maxString}.", $dateValidator->getDescription()); - $dateValidator = new DatetimeValidator(precision: DatetimeValidator::PRECISION_DAYS); + $dateValidator = new DatetimeValidator( + $this->minAllowed, + $this->maxAllowed, + precision: DatetimeValidator::PRECISION_DAYS + ); $this->assertEquals(false, $dateValidator->isValid(DateTime::format(new \DateTime('2019-04-08 19:36:26.255')))); $this->assertEquals(false, $dateValidator->isValid(DateTime::format(new \DateTime('2019-04-08 19:36:26.000')))); $this->assertEquals(false, $dateValidator->isValid(DateTime::format(new \DateTime('2019-04-08 19:36:26')))); $this->assertEquals(false, $dateValidator->isValid(DateTime::format(new \DateTime('2019-04-08 19:36:00')))); $this->assertEquals(false, $dateValidator->isValid(DateTime::format(new \DateTime('2019-04-08 19:00:00')))); $this->assertEquals(true, $dateValidator->isValid(DateTime::format(new \DateTime('2019-04-08 00:00:00')))); - $this->assertEquals('Value must be valid date with days precision.', $dateValidator->getDescription()); + $this->assertEquals("Value must be valid date with days precision between {$this->minString} and {$this->maxString}.", $dateValidator->getDescription()); - $dateValidator = new DatetimeValidator(true, DatetimeValidator::PRECISION_MINUTES); + $dateValidator = new DatetimeValidator( + $this->minAllowed, + $this->maxAllowed, + precision: DatetimeValidator::PRECISION_MINUTES + ); $this->assertEquals(false, $dateValidator->isValid(DateTime::format(new \DateTime('2019-04-08 19:36:26.255')))); $this->assertEquals(false, $dateValidator->isValid(DateTime::format(new \DateTime('2100-04-08 19:36:26.255')))); $this->assertEquals(true, $dateValidator->isValid(DateTime::format(new \DateTime('2100-04-08 19:36:00')))); - $this->assertEquals('Value must be valid date in future with minutes precision.', $dateValidator->getDescription()); + $this->assertEquals("Value must be valid date with minutes precision between {$this->minString} and {$this->maxString}.", $dateValidator->getDescription()); } public function testOffset(): void { - $dateValidator = new DatetimeValidator(offset: 60); + $dateValidator = new DatetimeValidator( + $this->minAllowed, + $this->maxAllowed, + offset: 60 + ); $time = (new \DateTime()); $this->assertEquals(false, $dateValidator->isValid(DateTime::format($time))); @@ -115,22 +165,30 @@ public function testOffset(): void $this->assertEquals(false, $dateValidator->isValid(DateTime::format($time))); $time = $time->add(new \DateInterval('PT20S')); $this->assertEquals(true, $dateValidator->isValid(DateTime::format($time))); - $this->assertEquals('Value must be valid date at least 60 seconds in future.', $dateValidator->getDescription()); + $this->assertEquals("Value must be valid date at least 60 seconds in the future and between {$this->minString} and {$this->maxString}.", $dateValidator->getDescription()); - $dateValidator = new DatetimeValidator(requireDateInFuture: true, offset: 60); + $dateValidator = new DatetimeValidator( + $this->minAllowed, + $this->maxAllowed, + requireDateInFuture: true, + offset: 60 + ); $time = (new \DateTime()); $time = $time->add(new \DateInterval('PT50S')); $time = $time->add(new \DateInterval('PT20S')); $this->assertEquals(true, $dateValidator->isValid(DateTime::format($time))); - $this->assertEquals('Value must be valid date at least 60 seconds in future.', $dateValidator->getDescription()); + $this->assertEquals("Value must be valid date at least 60 seconds in the future and between {$this->minString} and {$this->maxString}.", $dateValidator->getDescription()); - $threwException = false; try { - $dateValidator = new DatetimeValidator(offset: -60); + new DatetimeValidator( + $this->minAllowed, + $this->maxAllowed, + offset: -60 + ); + $this->fail('Failed to throw exception when offset is negative.'); } catch (\Exception $e) { - $threwException = true; + $this->assertEquals('Offset must be a positive integer.', $e->getMessage()); } - $this->assertTrue($threwException); } } diff --git a/tests/unit/Validator/IndexTest.php b/tests/unit/Validator/IndexTest.php index 5464d470a..a2862830c 100644 --- a/tests/unit/Validator/IndexTest.php +++ b/tests/unit/Validator/IndexTest.php @@ -310,6 +310,43 @@ public function testDuplicatedAttributesDifferentOrder(): void $validator = new Index($collection->getAttribute('attributes'), 768); $index = $collection->getAttribute('indexes')[0]; - $this->assertTrue($validator->isValid($index)); + $this->assertFalse($validator->isValid($index)); + } + + /** + * @throws Exception + */ + public function testReservedIndexKey(): void + { + $collection = new Document([ + '$id' => ID::custom('test'), + 'name' => 'test', + 'attributes' => [ + new Document([ + '$id' => ID::custom('title'), + 'type' => Database::VAR_STRING, + 'format' => '', + 'size' => 255, + 'signed' => true, + 'required' => false, + 'default' => null, + 'array' => false, + 'filters' => [], + ]) + ], + 'indexes' => [ + new Document([ + '$id' => ID::custom('primary'), + 'type' => Database::INDEX_FULLTEXT, + 'attributes' => ['title'], + 'lengths' => [], + 'orders' => [], + ]), + ], + ]); + + $validator = new Index($collection->getAttribute('attributes'), 768, ['PRIMARY']); + $index = $collection->getAttribute('indexes')[0]; + $this->assertFalse($validator->isValid($index)); } } diff --git a/tests/unit/Validator/Query/FilterTest.php b/tests/unit/Validator/Query/FilterTest.php index d9a2dbb38..1388dbd7c 100644 --- a/tests/unit/Validator/Query/FilterTest.php +++ b/tests/unit/Validator/Query/FilterTest.php @@ -103,4 +103,15 @@ public function testEmptyValues(): void $this->assertFalse($this->validator->isValid(Query::equal('string', []))); $this->assertEquals('Equal queries require at least one value.', $this->validator->getDescription()); } + + public function testMaxValuesCount(): void + { + $values = []; + for ($i = 1; $i <= 200; $i++) { + $values[] = $i; + } + + $this->assertFalse($this->validator->isValid(Query::equal('integer', $values))); + $this->assertEquals('Query on attribute has greater than 100 values: integer', $this->validator->getDescription()); + } }