From 1164dc7cc5cd966c20c941bce018ccd9bc5e45b9 Mon Sep 17 00:00:00 2001 From: "Daniel J. Summers" Date: Mon, 3 Jun 2024 19:46:39 -0400 Subject: [PATCH 01/25] Add classes and tests from common project --- .gitignore | 2 + composer.json | 22 + composer.lock | 1702 ++++++++++++++++++++++++ src/Configuration.php | 32 + src/DocumentException.php | 30 + src/DocumentList.php | 36 + src/Field.php | 176 +++ src/Mapper/ArrayMapper.php | 17 + src/Mapper/JsonMapper.php | 43 + src/Mapper/Mapper.php | 19 + src/Mapper/StringMapper.php | 30 + src/Op.php | 48 + src/Query.php | 77 ++ src/Query/Count.php | 36 + src/Query/Definition.php | 66 + src/Query/Delete.php | 36 + src/Query/Exists.php | 48 + src/Query/Find.php | 36 + tests/integration/.gitkeep | 0 tests/unit/ConfigurationTest.php | 28 + tests/unit/DocumentExceptionTest.php | 46 + tests/unit/FieldTest.php | 257 ++++ tests/unit/Mapper/ArrayMapperTest.php | 19 + tests/unit/Mapper/JsonMapperTest.php | 57 + tests/unit/Mapper/StringMapperTest.php | 29 + tests/unit/OpTest.php | 67 + tests/unit/Query/CountTest.php | 26 + tests/unit/Query/DefinitionTest.php | 38 + tests/unit/Query/DeleteTest.php | 26 + tests/unit/Query/ExistsTest.php | 32 + tests/unit/Query/FindTest.php | 26 + tests/unit/QueryTest.php | 68 + 32 files changed, 3175 insertions(+) create mode 100644 .gitignore create mode 100644 composer.json create mode 100644 composer.lock create mode 100644 src/Configuration.php create mode 100644 src/DocumentException.php create mode 100644 src/DocumentList.php create mode 100644 src/Field.php create mode 100644 src/Mapper/ArrayMapper.php create mode 100644 src/Mapper/JsonMapper.php create mode 100644 src/Mapper/Mapper.php create mode 100644 src/Mapper/StringMapper.php create mode 100644 src/Op.php create mode 100644 src/Query.php create mode 100644 src/Query/Count.php create mode 100644 src/Query/Definition.php create mode 100644 src/Query/Delete.php create mode 100644 src/Query/Exists.php create mode 100644 src/Query/Find.php create mode 100644 tests/integration/.gitkeep create mode 100644 tests/unit/ConfigurationTest.php create mode 100644 tests/unit/DocumentExceptionTest.php create mode 100644 tests/unit/FieldTest.php create mode 100644 tests/unit/Mapper/ArrayMapperTest.php create mode 100644 tests/unit/Mapper/JsonMapperTest.php create mode 100644 tests/unit/Mapper/StringMapperTest.php create mode 100644 tests/unit/OpTest.php create mode 100644 tests/unit/Query/CountTest.php create mode 100644 tests/unit/Query/DefinitionTest.php create mode 100644 tests/unit/Query/DeleteTest.php create mode 100644 tests/unit/Query/ExistsTest.php create mode 100644 tests/unit/Query/FindTest.php create mode 100644 tests/unit/QueryTest.php diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3ce5adb --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.idea +vendor diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..9781acb --- /dev/null +++ b/composer.json @@ -0,0 +1,22 @@ +{ + "name": "bit-badger/pdo-document", + "require": { + "netresearch/jsonmapper": "^4" + }, + "require-dev": { + "phpunit/phpunit": "^11" + }, + "autoload": { + "psr-4": { + "BitBadger\\PDODocument\\": "./src", + "BitBadger\\PDODocument\\Mapper\\": "./src/Mapper", + "BitBadger\\PDODocument\\Query\\": "./src/Query" + } + }, + "autoload-dev": { + "psr-4": { + "Test\\Unit\\": "./tests/unit", + "Test\\Integration\\": "./tests/integration" + } + } +} \ No newline at end of file diff --git a/composer.lock b/composer.lock new file mode 100644 index 0000000..56df984 --- /dev/null +++ b/composer.lock @@ -0,0 +1,1702 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "38b71eefd32cb528da22dd5908fb8d02", + "packages": [ + { + "name": "netresearch/jsonmapper", + "version": "v4.4.1", + "source": { + "type": "git", + "url": "https://github.com/cweiske/jsonmapper.git", + "reference": "132c75c7dd83e45353ebb9c6c9f591952995bbf0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/cweiske/jsonmapper/zipball/132c75c7dd83e45353ebb9c6c9f591952995bbf0", + "reference": "132c75c7dd83e45353ebb9c6c9f591952995bbf0", + "shasum": "" + }, + "require": { + "ext-json": "*", + "ext-pcre": "*", + "ext-reflection": "*", + "ext-spl": "*", + "php": ">=7.1" + }, + "require-dev": { + "phpunit/phpunit": "~7.5 || ~8.0 || ~9.0 || ~10.0", + "squizlabs/php_codesniffer": "~3.5" + }, + "type": "library", + "autoload": { + "psr-0": { + "JsonMapper": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "OSL-3.0" + ], + "authors": [ + { + "name": "Christian Weiske", + "email": "cweiske@cweiske.de", + "homepage": "http://github.com/cweiske/jsonmapper/", + "role": "Developer" + } + ], + "description": "Map nested JSON structures onto PHP classes", + "support": { + "email": "cweiske@cweiske.de", + "issues": "https://github.com/cweiske/jsonmapper/issues", + "source": "https://github.com/cweiske/jsonmapper/tree/v4.4.1" + }, + "time": "2024-01-31T06:18:54+00:00" + } + ], + "packages-dev": [ + { + "name": "myclabs/deep-copy", + "version": "1.11.1", + "source": { + "type": "git", + "url": "https://github.com/myclabs/DeepCopy.git", + "reference": "7284c22080590fb39f2ffa3e9057f10a4ddd0e0c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/7284c22080590fb39f2ffa3e9057f10a4ddd0e0c", + "reference": "7284c22080590fb39f2ffa3e9057f10a4ddd0e0c", + "shasum": "" + }, + "require": { + "php": "^7.1 || ^8.0" + }, + "conflict": { + "doctrine/collections": "<1.6.8", + "doctrine/common": "<2.13.3 || >=3,<3.2.2" + }, + "require-dev": { + "doctrine/collections": "^1.6.8", + "doctrine/common": "^2.13.3 || ^3.2.2", + "phpunit/phpunit": "^7.5.20 || ^8.5.23 || ^9.5.13" + }, + "type": "library", + "autoload": { + "files": [ + "src/DeepCopy/deep_copy.php" + ], + "psr-4": { + "DeepCopy\\": "src/DeepCopy/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Create deep copies (clones) of your objects", + "keywords": [ + "clone", + "copy", + "duplicate", + "object", + "object graph" + ], + "support": { + "issues": "https://github.com/myclabs/DeepCopy/issues", + "source": "https://github.com/myclabs/DeepCopy/tree/1.11.1" + }, + "funding": [ + { + "url": "https://tidelift.com/funding/github/packagist/myclabs/deep-copy", + "type": "tidelift" + } + ], + "time": "2023-03-08T13:26:56+00:00" + }, + { + "name": "nikic/php-parser", + "version": "v5.0.2", + "source": { + "type": "git", + "url": "https://github.com/nikic/PHP-Parser.git", + "reference": "139676794dc1e9231bf7bcd123cfc0c99182cb13" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/139676794dc1e9231bf7bcd123cfc0c99182cb13", + "reference": "139676794dc1e9231bf7bcd123cfc0c99182cb13", + "shasum": "" + }, + "require": { + "ext-ctype": "*", + "ext-json": "*", + "ext-tokenizer": "*", + "php": ">=7.4" + }, + "require-dev": { + "ircmaxell/php-yacc": "^0.0.7", + "phpunit/phpunit": "^7.0 || ^8.0 || ^9.0" + }, + "bin": [ + "bin/php-parse" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "5.0-dev" + } + }, + "autoload": { + "psr-4": { + "PhpParser\\": "lib/PhpParser" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Nikita Popov" + } + ], + "description": "A PHP parser written in PHP", + "keywords": [ + "parser", + "php" + ], + "support": { + "issues": "https://github.com/nikic/PHP-Parser/issues", + "source": "https://github.com/nikic/PHP-Parser/tree/v5.0.2" + }, + "time": "2024-03-05T20:51:40+00:00" + }, + { + "name": "phar-io/manifest", + "version": "2.0.4", + "source": { + "type": "git", + "url": "https://github.com/phar-io/manifest.git", + "reference": "54750ef60c58e43759730615a392c31c80e23176" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phar-io/manifest/zipball/54750ef60c58e43759730615a392c31c80e23176", + "reference": "54750ef60c58e43759730615a392c31c80e23176", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-libxml": "*", + "ext-phar": "*", + "ext-xmlwriter": "*", + "phar-io/version": "^3.0.1", + "php": "^7.2 || ^8.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Arne Blankerts", + "email": "arne@blankerts.de", + "role": "Developer" + }, + { + "name": "Sebastian Heuer", + "email": "sebastian@phpeople.de", + "role": "Developer" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "Developer" + } + ], + "description": "Component for reading phar.io manifest information from a PHP Archive (PHAR)", + "support": { + "issues": "https://github.com/phar-io/manifest/issues", + "source": "https://github.com/phar-io/manifest/tree/2.0.4" + }, + "funding": [ + { + "url": "https://github.com/theseer", + "type": "github" + } + ], + "time": "2024-03-03T12:33:53+00:00" + }, + { + "name": "phar-io/version", + "version": "3.2.1", + "source": { + "type": "git", + "url": "https://github.com/phar-io/version.git", + "reference": "4f7fd7836c6f332bb2933569e566a0d6c4cbed74" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phar-io/version/zipball/4f7fd7836c6f332bb2933569e566a0d6c4cbed74", + "reference": "4f7fd7836c6f332bb2933569e566a0d6c4cbed74", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "type": "library", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Arne Blankerts", + "email": "arne@blankerts.de", + "role": "Developer" + }, + { + "name": "Sebastian Heuer", + "email": "sebastian@phpeople.de", + "role": "Developer" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "Developer" + } + ], + "description": "Library for handling version information and constraints", + "support": { + "issues": "https://github.com/phar-io/version/issues", + "source": "https://github.com/phar-io/version/tree/3.2.1" + }, + "time": "2022-02-21T01:04:05+00:00" + }, + { + "name": "phpunit/php-code-coverage", + "version": "11.0.3", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-code-coverage.git", + "reference": "7e35a2cbcabac0e6865fd373742ea432a3c34f92" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/7e35a2cbcabac0e6865fd373742ea432a3c34f92", + "reference": "7e35a2cbcabac0e6865fd373742ea432a3c34f92", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-libxml": "*", + "ext-xmlwriter": "*", + "nikic/php-parser": "^5.0", + "php": ">=8.2", + "phpunit/php-file-iterator": "^5.0", + "phpunit/php-text-template": "^4.0", + "sebastian/code-unit-reverse-lookup": "^4.0", + "sebastian/complexity": "^4.0", + "sebastian/environment": "^7.0", + "sebastian/lines-of-code": "^3.0", + "sebastian/version": "^5.0", + "theseer/tokenizer": "^1.2.0" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "suggest": { + "ext-pcov": "PHP extension that provides line coverage", + "ext-xdebug": "PHP extension that provides line coverage as well as branch and path coverage" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "11.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library that provides collection, processing, and rendering functionality for PHP code coverage information.", + "homepage": "https://github.com/sebastianbergmann/php-code-coverage", + "keywords": [ + "coverage", + "testing", + "xunit" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-code-coverage/issues", + "security": "https://github.com/sebastianbergmann/php-code-coverage/security/policy", + "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/11.0.3" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-03-12T15:35:40+00:00" + }, + { + "name": "phpunit/php-file-iterator", + "version": "5.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-file-iterator.git", + "reference": "99e95c94ad9500daca992354fa09d7b99abe2210" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/99e95c94ad9500daca992354fa09d7b99abe2210", + "reference": "99e95c94ad9500daca992354fa09d7b99abe2210", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "5.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "FilterIterator implementation that filters files based on a list of suffixes.", + "homepage": "https://github.com/sebastianbergmann/php-file-iterator/", + "keywords": [ + "filesystem", + "iterator" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-file-iterator/issues", + "security": "https://github.com/sebastianbergmann/php-file-iterator/security/policy", + "source": "https://github.com/sebastianbergmann/php-file-iterator/tree/5.0.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-02-02T06:05:04+00:00" + }, + { + "name": "phpunit/php-invoker", + "version": "5.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-invoker.git", + "reference": "5d8d9355a16d8cc5a1305b0a85342cfa420612be" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-invoker/zipball/5d8d9355a16d8cc5a1305b0a85342cfa420612be", + "reference": "5d8d9355a16d8cc5a1305b0a85342cfa420612be", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "ext-pcntl": "*", + "phpunit/phpunit": "^11.0" + }, + "suggest": { + "ext-pcntl": "*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "5.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Invoke callables with a timeout", + "homepage": "https://github.com/sebastianbergmann/php-invoker/", + "keywords": [ + "process" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-invoker/issues", + "security": "https://github.com/sebastianbergmann/php-invoker/security/policy", + "source": "https://github.com/sebastianbergmann/php-invoker/tree/5.0.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-02-02T06:05:50+00:00" + }, + { + "name": "phpunit/php-text-template", + "version": "4.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-text-template.git", + "reference": "d38f6cbff1cdb6f40b03c9811421561668cc133e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/d38f6cbff1cdb6f40b03c9811421561668cc133e", + "reference": "d38f6cbff1cdb6f40b03c9811421561668cc133e", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "4.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Simple template engine.", + "homepage": "https://github.com/sebastianbergmann/php-text-template/", + "keywords": [ + "template" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-text-template/issues", + "security": "https://github.com/sebastianbergmann/php-text-template/security/policy", + "source": "https://github.com/sebastianbergmann/php-text-template/tree/4.0.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-02-02T06:06:56+00:00" + }, + { + "name": "phpunit/php-timer", + "version": "7.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-timer.git", + "reference": "8a59d9e25720482ee7fcdf296595e08795b84dc5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/8a59d9e25720482ee7fcdf296595e08795b84dc5", + "reference": "8a59d9e25720482ee7fcdf296595e08795b84dc5", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "7.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Utility class for timing", + "homepage": "https://github.com/sebastianbergmann/php-timer/", + "keywords": [ + "timer" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-timer/issues", + "security": "https://github.com/sebastianbergmann/php-timer/security/policy", + "source": "https://github.com/sebastianbergmann/php-timer/tree/7.0.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-02-02T06:08:01+00:00" + }, + { + "name": "phpunit/phpunit", + "version": "11.1.3", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/phpunit.git", + "reference": "d475be032238173ca3b0a516f5cc291d174708ae" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/d475be032238173ca3b0a516f5cc291d174708ae", + "reference": "d475be032238173ca3b0a516f5cc291d174708ae", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-json": "*", + "ext-libxml": "*", + "ext-mbstring": "*", + "ext-xml": "*", + "ext-xmlwriter": "*", + "myclabs/deep-copy": "^1.10.1", + "phar-io/manifest": "^2.0.3", + "phar-io/version": "^3.0.2", + "php": ">=8.2", + "phpunit/php-code-coverage": "^11.0", + "phpunit/php-file-iterator": "^5.0", + "phpunit/php-invoker": "^5.0", + "phpunit/php-text-template": "^4.0", + "phpunit/php-timer": "^7.0", + "sebastian/cli-parser": "^3.0", + "sebastian/code-unit": "^3.0", + "sebastian/comparator": "^6.0", + "sebastian/diff": "^6.0", + "sebastian/environment": "^7.0", + "sebastian/exporter": "^6.0", + "sebastian/global-state": "^7.0", + "sebastian/object-enumerator": "^6.0", + "sebastian/type": "^5.0", + "sebastian/version": "^5.0" + }, + "suggest": { + "ext-soap": "To be able to generate mocks based on WSDL files" + }, + "bin": [ + "phpunit" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "11.1-dev" + } + }, + "autoload": { + "files": [ + "src/Framework/Assert/Functions.php" + ], + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "The PHP Unit Testing framework.", + "homepage": "https://phpunit.de/", + "keywords": [ + "phpunit", + "testing", + "xunit" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/phpunit/issues", + "security": "https://github.com/sebastianbergmann/phpunit/security/policy", + "source": "https://github.com/sebastianbergmann/phpunit/tree/11.1.3" + }, + "funding": [ + { + "url": "https://phpunit.de/sponsors.html", + "type": "custom" + }, + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/phpunit/phpunit", + "type": "tidelift" + } + ], + "time": "2024-04-24T06:34:25+00:00" + }, + { + "name": "sebastian/cli-parser", + "version": "3.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/cli-parser.git", + "reference": "00a74d5568694711f0222e54fb281e1d15fdf04a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/cli-parser/zipball/00a74d5568694711f0222e54fb281e1d15fdf04a", + "reference": "00a74d5568694711f0222e54fb281e1d15fdf04a", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library for parsing CLI options", + "homepage": "https://github.com/sebastianbergmann/cli-parser", + "support": { + "issues": "https://github.com/sebastianbergmann/cli-parser/issues", + "security": "https://github.com/sebastianbergmann/cli-parser/security/policy", + "source": "https://github.com/sebastianbergmann/cli-parser/tree/3.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-03-02T07:26:58+00:00" + }, + { + "name": "sebastian/code-unit", + "version": "3.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/code-unit.git", + "reference": "6634549cb8d702282a04a774e36a7477d2bd9015" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/code-unit/zipball/6634549cb8d702282a04a774e36a7477d2bd9015", + "reference": "6634549cb8d702282a04a774e36a7477d2bd9015", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Collection of value objects that represent the PHP code units", + "homepage": "https://github.com/sebastianbergmann/code-unit", + "support": { + "issues": "https://github.com/sebastianbergmann/code-unit/issues", + "security": "https://github.com/sebastianbergmann/code-unit/security/policy", + "source": "https://github.com/sebastianbergmann/code-unit/tree/3.0.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-02-02T05:50:41+00:00" + }, + { + "name": "sebastian/code-unit-reverse-lookup", + "version": "4.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/code-unit-reverse-lookup.git", + "reference": "df80c875d3e459b45c6039e4d9b71d4fbccae25d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/code-unit-reverse-lookup/zipball/df80c875d3e459b45c6039e4d9b71d4fbccae25d", + "reference": "df80c875d3e459b45c6039e4d9b71d4fbccae25d", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "4.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Looks up which function or method a line of code belongs to", + "homepage": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/", + "support": { + "issues": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/issues", + "security": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/security/policy", + "source": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/tree/4.0.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-02-02T05:52:17+00:00" + }, + { + "name": "sebastian/comparator", + "version": "6.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/comparator.git", + "reference": "bd0f2fa5b9257c69903537b266ccb80fcf940db8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/bd0f2fa5b9257c69903537b266ccb80fcf940db8", + "reference": "bd0f2fa5b9257c69903537b266ccb80fcf940db8", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-mbstring": "*", + "php": ">=8.2", + "sebastian/diff": "^6.0", + "sebastian/exporter": "^6.0" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "6.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, + { + "name": "Volker Dusch", + "email": "github@wallbash.com" + }, + { + "name": "Bernhard Schussek", + "email": "bschussek@2bepublished.at" + } + ], + "description": "Provides the functionality to compare PHP values for equality", + "homepage": "https://github.com/sebastianbergmann/comparator", + "keywords": [ + "comparator", + "compare", + "equality" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/comparator/issues", + "security": "https://github.com/sebastianbergmann/comparator/security/policy", + "source": "https://github.com/sebastianbergmann/comparator/tree/6.0.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-02-02T05:53:45+00:00" + }, + { + "name": "sebastian/complexity", + "version": "4.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/complexity.git", + "reference": "88a434ad86150e11a606ac4866b09130712671f0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/complexity/zipball/88a434ad86150e11a606ac4866b09130712671f0", + "reference": "88a434ad86150e11a606ac4866b09130712671f0", + "shasum": "" + }, + "require": { + "nikic/php-parser": "^5.0", + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "4.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library for calculating the complexity of PHP code units", + "homepage": "https://github.com/sebastianbergmann/complexity", + "support": { + "issues": "https://github.com/sebastianbergmann/complexity/issues", + "security": "https://github.com/sebastianbergmann/complexity/security/policy", + "source": "https://github.com/sebastianbergmann/complexity/tree/4.0.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-02-02T05:55:19+00:00" + }, + { + "name": "sebastian/diff", + "version": "6.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/diff.git", + "reference": "ab83243ecc233de5655b76f577711de9f842e712" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/ab83243ecc233de5655b76f577711de9f842e712", + "reference": "ab83243ecc233de5655b76f577711de9f842e712", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0", + "symfony/process": "^4.2 || ^5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "6.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Kore Nordmann", + "email": "mail@kore-nordmann.de" + } + ], + "description": "Diff implementation", + "homepage": "https://github.com/sebastianbergmann/diff", + "keywords": [ + "diff", + "udiff", + "unidiff", + "unified diff" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/diff/issues", + "security": "https://github.com/sebastianbergmann/diff/security/policy", + "source": "https://github.com/sebastianbergmann/diff/tree/6.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-03-02T07:30:33+00:00" + }, + { + "name": "sebastian/environment", + "version": "7.1.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/environment.git", + "reference": "4eb3a442574d0e9d141aab209cd4aaf25701b09a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/4eb3a442574d0e9d141aab209cd4aaf25701b09a", + "reference": "4eb3a442574d0e9d141aab209cd4aaf25701b09a", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "suggest": { + "ext-posix": "*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "7.1-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Provides functionality to handle HHVM/PHP environments", + "homepage": "https://github.com/sebastianbergmann/environment", + "keywords": [ + "Xdebug", + "environment", + "hhvm" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/environment/issues", + "security": "https://github.com/sebastianbergmann/environment/security/policy", + "source": "https://github.com/sebastianbergmann/environment/tree/7.1.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-03-23T08:56:34+00:00" + }, + { + "name": "sebastian/exporter", + "version": "6.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/exporter.git", + "reference": "f291e5a317c321c0381fa9ecc796fa2d21b186da" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/f291e5a317c321c0381fa9ecc796fa2d21b186da", + "reference": "f291e5a317c321c0381fa9ecc796fa2d21b186da", + "shasum": "" + }, + "require": { + "ext-mbstring": "*", + "php": ">=8.2", + "sebastian/recursion-context": "^6.0" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "6.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, + { + "name": "Volker Dusch", + "email": "github@wallbash.com" + }, + { + "name": "Adam Harvey", + "email": "aharvey@php.net" + }, + { + "name": "Bernhard Schussek", + "email": "bschussek@gmail.com" + } + ], + "description": "Provides the functionality to export PHP variables for visualization", + "homepage": "https://www.github.com/sebastianbergmann/exporter", + "keywords": [ + "export", + "exporter" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/exporter/issues", + "security": "https://github.com/sebastianbergmann/exporter/security/policy", + "source": "https://github.com/sebastianbergmann/exporter/tree/6.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-03-02T07:28:20+00:00" + }, + { + "name": "sebastian/global-state", + "version": "7.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/global-state.git", + "reference": "c3a307e832f2e69c7ef869e31fc644fde0e7cb3e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/c3a307e832f2e69c7ef869e31fc644fde0e7cb3e", + "reference": "c3a307e832f2e69c7ef869e31fc644fde0e7cb3e", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "sebastian/object-reflector": "^4.0", + "sebastian/recursion-context": "^6.0" + }, + "require-dev": { + "ext-dom": "*", + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "7.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Snapshotting of global state", + "homepage": "https://www.github.com/sebastianbergmann/global-state", + "keywords": [ + "global state" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/global-state/issues", + "security": "https://github.com/sebastianbergmann/global-state/security/policy", + "source": "https://github.com/sebastianbergmann/global-state/tree/7.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-03-02T07:32:10+00:00" + }, + { + "name": "sebastian/lines-of-code", + "version": "3.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/lines-of-code.git", + "reference": "376c5b3f6b43c78fdc049740bca76a7c846706c0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/lines-of-code/zipball/376c5b3f6b43c78fdc049740bca76a7c846706c0", + "reference": "376c5b3f6b43c78fdc049740bca76a7c846706c0", + "shasum": "" + }, + "require": { + "nikic/php-parser": "^5.0", + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library for counting the lines of code in PHP source code", + "homepage": "https://github.com/sebastianbergmann/lines-of-code", + "support": { + "issues": "https://github.com/sebastianbergmann/lines-of-code/issues", + "security": "https://github.com/sebastianbergmann/lines-of-code/security/policy", + "source": "https://github.com/sebastianbergmann/lines-of-code/tree/3.0.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-02-02T06:00:36+00:00" + }, + { + "name": "sebastian/object-enumerator", + "version": "6.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/object-enumerator.git", + "reference": "f75f6c460da0bbd9668f43a3dde0ec0ba7faa678" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/object-enumerator/zipball/f75f6c460da0bbd9668f43a3dde0ec0ba7faa678", + "reference": "f75f6c460da0bbd9668f43a3dde0ec0ba7faa678", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "sebastian/object-reflector": "^4.0", + "sebastian/recursion-context": "^6.0" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "6.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Traverses array structures and object graphs to enumerate all referenced objects", + "homepage": "https://github.com/sebastianbergmann/object-enumerator/", + "support": { + "issues": "https://github.com/sebastianbergmann/object-enumerator/issues", + "security": "https://github.com/sebastianbergmann/object-enumerator/security/policy", + "source": "https://github.com/sebastianbergmann/object-enumerator/tree/6.0.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-02-02T06:01:29+00:00" + }, + { + "name": "sebastian/object-reflector", + "version": "4.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/object-reflector.git", + "reference": "bb2a6255d30853425fd38f032eb64ced9f7f132d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/object-reflector/zipball/bb2a6255d30853425fd38f032eb64ced9f7f132d", + "reference": "bb2a6255d30853425fd38f032eb64ced9f7f132d", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "4.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Allows reflection of object attributes, including inherited and non-public ones", + "homepage": "https://github.com/sebastianbergmann/object-reflector/", + "support": { + "issues": "https://github.com/sebastianbergmann/object-reflector/issues", + "security": "https://github.com/sebastianbergmann/object-reflector/security/policy", + "source": "https://github.com/sebastianbergmann/object-reflector/tree/4.0.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-02-02T06:02:18+00:00" + }, + { + "name": "sebastian/recursion-context", + "version": "6.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/recursion-context.git", + "reference": "b75224967b5a466925c6d54e68edd0edf8dd4ed4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/b75224967b5a466925c6d54e68edd0edf8dd4ed4", + "reference": "b75224967b5a466925c6d54e68edd0edf8dd4ed4", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "6.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, + { + "name": "Adam Harvey", + "email": "aharvey@php.net" + } + ], + "description": "Provides functionality to recursively process PHP variables", + "homepage": "https://github.com/sebastianbergmann/recursion-context", + "support": { + "issues": "https://github.com/sebastianbergmann/recursion-context/issues", + "security": "https://github.com/sebastianbergmann/recursion-context/security/policy", + "source": "https://github.com/sebastianbergmann/recursion-context/tree/6.0.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-02-02T06:08:48+00:00" + }, + { + "name": "sebastian/type", + "version": "5.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/type.git", + "reference": "b8502785eb3523ca0dd4afe9ca62235590020f3f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/type/zipball/b8502785eb3523ca0dd4afe9ca62235590020f3f", + "reference": "b8502785eb3523ca0dd4afe9ca62235590020f3f", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "5.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Collection of value objects that represent the types of the PHP type system", + "homepage": "https://github.com/sebastianbergmann/type", + "support": { + "issues": "https://github.com/sebastianbergmann/type/issues", + "security": "https://github.com/sebastianbergmann/type/security/policy", + "source": "https://github.com/sebastianbergmann/type/tree/5.0.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-02-02T06:09:34+00:00" + }, + { + "name": "sebastian/version", + "version": "5.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/version.git", + "reference": "13999475d2cb1ab33cb73403ba356a814fdbb001" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/13999475d2cb1ab33cb73403ba356a814fdbb001", + "reference": "13999475d2cb1ab33cb73403ba356a814fdbb001", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "5.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library that helps with managing the version number of Git-hosted PHP projects", + "homepage": "https://github.com/sebastianbergmann/version", + "support": { + "issues": "https://github.com/sebastianbergmann/version/issues", + "security": "https://github.com/sebastianbergmann/version/security/policy", + "source": "https://github.com/sebastianbergmann/version/tree/5.0.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-02-02T06:10:47+00:00" + }, + { + "name": "theseer/tokenizer", + "version": "1.2.3", + "source": { + "type": "git", + "url": "https://github.com/theseer/tokenizer.git", + "reference": "737eda637ed5e28c3413cb1ebe8bb52cbf1ca7a2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/theseer/tokenizer/zipball/737eda637ed5e28c3413cb1ebe8bb52cbf1ca7a2", + "reference": "737eda637ed5e28c3413cb1ebe8bb52cbf1ca7a2", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-tokenizer": "*", + "ext-xmlwriter": "*", + "php": "^7.2 || ^8.0" + }, + "type": "library", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Arne Blankerts", + "email": "arne@blankerts.de", + "role": "Developer" + } + ], + "description": "A small library for converting tokenized PHP source code into XML and potentially other formats", + "support": { + "issues": "https://github.com/theseer/tokenizer/issues", + "source": "https://github.com/theseer/tokenizer/tree/1.2.3" + }, + "funding": [ + { + "url": "https://github.com/theseer", + "type": "github" + } + ], + "time": "2024-03-03T12:36:25+00:00" + } + ], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": [], + "prefer-stable": false, + "prefer-lowest": false, + "platform": [], + "platform-dev": [], + "plugin-api-version": "2.6.0" +} diff --git a/src/Configuration.php b/src/Configuration.php new file mode 100644 index 0000000..dc54040 --- /dev/null +++ b/src/Configuration.php @@ -0,0 +1,32 @@ +code == 0 ? '' : "[$this->code] "; + return __CLASS__ . ": $codeStr$this->message\n"; + } +} diff --git a/src/DocumentList.php b/src/DocumentList.php new file mode 100644 index 0000000..7d5d872 --- /dev/null +++ b/src/DocumentList.php @@ -0,0 +1,36 @@ + The query results as a lazily-iterated generator + */ + public function items(): Generator; + + /** + * Construct a new document list + * + * @param string $query The query to run to retrieve results + * @param array $parameters An associative array of parameters for the query + * @param Mapper $mapper A mapper to deserialize JSON documents + * @return static The `DocumentList`-implementing instance + */ + public static function create(string $query, array $parameters, Mapper $mapper): static; + + /** + * Clean up database connection resources + */ + public function __destruct(); +} diff --git a/src/Field.php b/src/Field.php new file mode 100644 index 0000000..38c7f10 --- /dev/null +++ b/src/Field.php @@ -0,0 +1,176 @@ +op) { + case Op::EX: + case Op::NEX: + break; + case Op::BT: + $existing["{$this->paramName}min"] = $this->value[0]; + $existing["{$this->paramName}max"] = $this->value[1]; + break; + default: + $existing[$this->paramName] = $this->value; + } + return $existing; + } + + /** + * Get the WHERE clause fragment for this parameter + * + * @return string The WHERE clause fragment for this parameter + */ + public function toWhere(): string + { + $criteria = match ($this->op) { + Op::EX, Op::NEX => '', + Op::BT => " {$this->paramName}min AND {$this->paramName}max", + default => " $this->paramName" + }; + $prefix = $this->qualifier == '' ? '' : "$this->qualifier."; + return "{$prefix}data->>'$this->fieldName' " . $this->op->toString() . $criteria; + } + + /** + * Create an equals (=) field criterion + * + * @param string $fieldName The name of the field against which the value will be compared + * @param mixed $value The value for which equality will be checked + * @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank) + * @return static The field with the requested criterion + */ + public static function EQ(string $fieldName, mixed $value, string $paramName = ''): static + { + return new static($fieldName, Op::EQ, $value, $paramName); + } + + /** + * Create a greater than (>) field criterion + * + * @param string $fieldName The name of the field against which the value will be compared + * @param mixed $value The value for the greater than comparison + * @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank) + * @return static The field with the requested criterion + */ + public static function GT(string $fieldName, mixed $value, string $paramName = ''): static + { + return new static($fieldName, Op::GT, $value, $paramName); + } + + /** + * Create a greater than or equal to (>=) field criterion + * + * @param string $fieldName The name of the field against which the value will be compared + * @param mixed $value The value for the greater than or equal to comparison + * @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank) + * @return static The field with the requested criterion + */ + public static function GE(string $fieldName, mixed $value, string $paramName = ''): static + { + return new static($fieldName, Op::GE, $value, $paramName); + } + + /** + * Create a less than (<) field criterion + * + * @param string $fieldName The name of the field against which the value will be compared + * @param mixed $value The value for the less than comparison + * @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank) + * @return static The field with the requested criterion + */ + public static function LT(string $fieldName, mixed $value, string $paramName = ''): static + { + return new static($fieldName, Op::LT, $value, $paramName); + } + + /** + * Create a less than or equal to (<=) field criterion + * + * @param string $fieldName The name of the field against which the value will be compared + * @param mixed $value The value for the less than or equal to comparison + * @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank) + * @return static The field with the requested criterion + */ + public static function LE(string $fieldName, mixed $value, string $paramName = ''): static + { + return new static($fieldName, Op::LE, $value, $paramName); + } + + /** + * Create a not equals (<>) field criterion + * + * @param string $fieldName The name of the field against which the value will be compared + * @param mixed $value The value for the not equals comparison + * @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank) + * @return static The field with the requested criterion + */ + public static function NE(string $fieldName, mixed $value, string $paramName = ''): static + { + return new static($fieldName, Op::NE, $value, $paramName); + } + + /** + * Create a BETWEEN field criterion + * + * @param string $fieldName The name of the field against which the value will be compared + * @param mixed $minValue The lower value for range + * @param mixed $maxValue The upper value for the range + * @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank) + * @return static The field with the requested criterion + */ + public static function BT(string $fieldName, mixed $minValue, mixed $maxValue, string $paramName = ''): static + { + return new static($fieldName, Op::BT, [$minValue, $maxValue], $paramName); + } + + /** + * Create an exists (IS NOT NULL) field criterion + * + * @param string $fieldName The name of the field for which existence will be checked + * @return static The field with the requested criterion + */ + public static function EX(string $fieldName): static + { + return new static($fieldName, Op::EX, '', ''); + } + + /** + * Create a not exists (IS NULL) field criterion + * + * @param string $fieldName The name of the field for which non-existence will be checked + * @return static The field with the requested criterion + */ + public static function NEX(string $fieldName): static + { + return new static($fieldName, Op::NEX, '', ''); + } +} diff --git a/src/Mapper/ArrayMapper.php b/src/Mapper/ArrayMapper.php new file mode 100644 index 0000000..62f1286 --- /dev/null +++ b/src/Mapper/ArrayMapper.php @@ -0,0 +1,17 @@ + Provide a mapping from JSON + */ +class JsonMapper implements Mapper +{ + /** + * Constructor + * + * @param class-string $className The type of class to be returned by this mapping + * @param string $fieldName The name of the field (optional; defaults to `data`) + */ + public function __construct(public string $className, public string $fieldName = 'data') { } + + /** + * Map a result to a domain class instance + * + * @param array $result An associative array representing a single database result + * @return TDoc The document, deserialized from its JSON representation + * @throws DocumentException If the JSON cannot be deserialized + */ + public function map(array $result): mixed + { + try { + $json = json_decode($result[$this->fieldName]); + if (is_null($json)) { + throw new DocumentException("Could not map document for $this->className: " . json_last_error_msg()); + } + return (new \JsonMapper())->map($json, $this->className); + } catch (JsonMapper_Exception $ex) { + throw new DocumentException("Could not map document for $this->className", previous: $ex); + } + } +} diff --git a/src/Mapper/Mapper.php b/src/Mapper/Mapper.php new file mode 100644 index 0000000..5ed0ff2 --- /dev/null +++ b/src/Mapper/Mapper.php @@ -0,0 +1,19 @@ + + */ +class StringMapper implements Mapper +{ + /** + * Constructor + * + * @param string $fieldName The name of the field to be retrieved as a string + */ + public function __construct(public string $fieldName) { } + + /** + * @inheritDoc + */ + public function map(array $result): ?string + { + return match (false) { + key_exists($this->fieldName, $result) => null, + is_string($result[$this->fieldName]) => "{$result[$this->fieldName]}", + default => $result[$this->fieldName] + }; + } +} diff --git a/src/Op.php b/src/Op.php new file mode 100644 index 0000000..9352fb9 --- /dev/null +++ b/src/Op.php @@ -0,0 +1,48 @@ +) */ + case GT; + /** Greater Than or Equal To (>=) */ + case GE; + /** Less Than (<) */ + case LT; + /** Less Than or Equal To (<=) */ + case LE; + /** Not Equal to (<>) */ + case NE; + /** Between (BETWEEN) */ + case BT; + /** Exists (IS NOT NULL) */ + case EX; + /** Does Not Exist (IS NULL) */ + case NEX; + + /** + * Get the string representation of this operator + * + * @return string The operator to use in SQL statements + */ + public function toString(): string + { + return match ($this) { + Op::EQ => "=", + Op::GT => ">", + Op::GE => ">=", + Op::LT => "<", + Op::LE => "<=", + Op::NE => "<>", + Op::BT => "BETWEEN", + Op::EX => "IS NOT NULL", + Op::NEX => "IS NULL" + }; + } +} diff --git a/src/Query.php b/src/Query.php new file mode 100644 index 0000000..d9a265f --- /dev/null +++ b/src/Query.php @@ -0,0 +1,77 @@ + $it->toWhere(), $fields)); + } + + /** + * Create a WHERE clause fragment to implement an ID-based query + * + * @param string $paramName The parameter name where the value of the ID will be provided (optional; default @id) + * @return string The WHERE clause fragment to match by ID + */ + public static function whereById(string $paramName = '@id'): string + { + return self::whereByFields([Field::EQ(Configuration::idField(), 0, $paramName)]); + } + + /** + * Query to insert a document + * + * @param string $tableName The name of the table into which a document should be inserted + * @return string The INSERT statement for the given table + */ + public static function insert(string $tableName): string + { + return "INSERT INTO $tableName VALUES (@data)"; + } + + /** + * Query to save a document, inserting it if it does not exist and updating it if it does (AKA "upsert") + * + * @param string $tableName The name of the table into which a document should be saved + * @return string The INSERT...ON CONFLICT query for the document + */ + public static function save(string $tableName): string + { + return self::insert($tableName) + . " ON CONFLICT ((data->>'" . Configuration::idField() . "')) DO UPDATE SET data = EXCLUDED.data"; + } + + /** + * Query to update a document + * + * @param string $tableName The name of the table in which the document should be updated + * @return string The UPDATE query for the document + */ + public static function update(string $tableName): string + { + return "UPDATE $tableName SET data = @data WHERE " . self::whereById(); + } +} diff --git a/src/Query/Count.php b/src/Query/Count.php new file mode 100644 index 0000000..cc112f0 --- /dev/null +++ b/src/Query/Count.php @@ -0,0 +1,36 @@ +>'$fieldName')$direction"; + }, $fields)); + return "CREATE INDEX IF NOT EXISTS idx_{$tbl}_$indexName ON $tableName ($jsonFields)"; + } + + /** + * SQL statement to create a key index for a document table + * + * @param string $tableName The name of the table whose key should be ensured + * @return string The CREATE INDEX statement to ensure the key index exists + */ + public static function ensureKey(string $tableName): string + { + return str_replace('INDEX', 'UNIQUE INDEX', self::ensureIndexOn($tableName, 'key', [Configuration::idField()])); + } +} diff --git a/src/Query/Delete.php b/src/Query/Delete.php new file mode 100644 index 0000000..d171bb7 --- /dev/null +++ b/src/Query/Delete.php @@ -0,0 +1,36 @@ +assertEquals('id', Configuration::idField(), 'Default ID field should be "id"'); + } + + public function testUseIdFieldSucceeds() + { + try { + Configuration::useIdField('EyeDee'); + $this->assertEquals('EyeDee', Configuration::idField(), 'ID field should have been updated'); + } finally { + Configuration::useIdField('id'); + $this->assertEquals('id', Configuration::idField(), 'Default ID value should have been restored'); + } + } +} diff --git a/tests/unit/DocumentExceptionTest.php b/tests/unit/DocumentExceptionTest.php new file mode 100644 index 0000000..7103575 --- /dev/null +++ b/tests/unit/DocumentExceptionTest.php @@ -0,0 +1,46 @@ +assertNotNull($ex, 'The exception should not have been null'); + $this->assertEquals('Test Exception', $ex->getMessage(), 'Message not filled properly'); + $this->assertEquals(17, $ex->getCode(), 'Code not filled properly'); + $this->assertSame($priorEx, $ex->getPrevious(), 'Prior exception not filled properly'); + } + + public function testConstructorSucceedsWithoutCodeAndPriorException() + { + $ex = new DocumentException('Oops'); + $this->assertNotNull($ex, 'The exception should not have been null'); + $this->assertEquals('Oops', $ex->getMessage(), 'Message not filled properly'); + $this->assertEquals(0, $ex->getCode(), 'Code not filled properly'); + $this->assertNull($ex->getPrevious(), 'Prior exception should have been null'); + } + + public function testToStringSucceedsWithoutCode() + { + $ex = new DocumentException('Test failure'); + $this->assertEquals("BitBadger\PDODocument\DocumentException: Test failure\n", "$ex", + 'toString not generated correctly'); + } + + public function testToStringSucceedsWithCode() + { + $ex = new DocumentException('Oof', -6); + $this->assertEquals("BitBadger\PDODocument\DocumentException: [-6] Oof\n", "$ex", + 'toString not generated correctly'); + } +} diff --git a/tests/unit/FieldTest.php b/tests/unit/FieldTest.php new file mode 100644 index 0000000..8294534 --- /dev/null +++ b/tests/unit/FieldTest.php @@ -0,0 +1,257 @@ +assertEquals([], Field::EX('exists')->appendParameter([]), 'EX should not have appended a parameter'); + } + + #[TestDox('Append parameter succeeds for NEX')] + public function testAppendParameterSucceedsForNEX(): void + { + $this->assertEquals([], Field::NEX('absent')->appendParameter([]), 'NEX should not have appended a parameter'); + } + + #[TestDox('Append parameter succeeds for BT')] + public function testAppendParameterSucceedsForBT(): void + { + $this->assertEquals(['@nummin' => 5, '@nummax' => 9], Field::BT('exists', 5, 9, '@num')->appendParameter([]), + 'BT should have appended min and max parameters'); + } + + public function testAppendParameterSucceedsForOthers(): void + { + $this->assertEquals(['@test' => 33], Field::EQ('the_field', 33, '@test')->appendParameter([]), + 'Field parameter not returned correctly'); + } + + #[TestDox('To where succeeds for EX without qualifier')] + public function testToWhereSucceedsForEXWithoutQualifier(): void + { + $this->assertEquals("data->>'that_field' IS NOT NULL", Field::EX('that_field')->toWhere(), + 'WHERE fragment not generated correctly'); + } + + #[TestDox('To where succeeds for NEX without qualifier')] + public function testToWhereSucceedsForNEXWithoutQualifier(): void + { + $this->assertEquals("data->>'a_field' IS NULL", Field::NEX('a_field')->toWhere(), + 'WHERE fragment not generated correctly'); + } + + #[TestDox('To where succeeds for BT without qualifier')] + public function testToWhereSucceedsForBTWithoutQualifier(): void + { + $this->assertEquals("data->>'age' BETWEEN @agemin AND @agemax", Field::BT('age', 13, 17, '@age')->toWhere(), + 'WHERE fragment not generated correctly'); + } + + public function testToWhereSucceedsForOthersWithoutQualifier(): void + { + $this->assertEquals("data->>'some_field' = @value", Field::EQ('some_field', '', '@value')->toWhere(), + 'WHERE fragment not generated correctly'); + } + + public function testToWhereSucceedsWithQualifierNoParameter(): void + { + $field = Field::EX('no_field'); + $field->qualifier = 'test'; + $this->assertEquals("test.data->>'no_field' IS NOT NULL", $field->toWhere(), + 'WHERE fragment not generated correctly'); + } + + public function testToWhereSucceedsWithQualifierAndParameter(): void + { + $field = Field::LE('le_field', 18, '@it'); + $field->qualifier = 'q'; + $this->assertEquals("q.data->>'le_field' <= @it", $field->toWhere(), 'WHERE fragment not generated correctly'); + } + + #[TestDox('EQ succeeds without parameter')] + public function testEQSucceedsWithoutParameter(): void + { + $field = Field::EQ('my_test', 9); + $this->assertNotNull($field, 'The field should not have been null'); + $this->assertEquals('my_test', $field->fieldName, 'Field name not filled correctly'); + $this->assertEquals(Op::EQ, $field->op, 'Operation not filled correctly'); + $this->assertEquals(9, $field->value, 'Value not filled correctly'); + $this->assertEquals('', $field->paramName, 'Parameter name should have been blank'); + } + + #[TestDox('EQ succeeds with parameter')] + public function testEQSucceedsWithParameter(): void + { + $field = Field::EQ('another_test', 'turkey', '@test'); + $this->assertNotNull($field, 'The field should not have been null'); + $this->assertEquals('another_test', $field->fieldName, 'Field name not filled correctly'); + $this->assertEquals(Op::EQ, $field->op, 'Operation not filled correctly'); + $this->assertEquals('turkey', $field->value, 'Value not filled correctly'); + $this->assertEquals('@test', $field->paramName, 'Parameter name not filled correctly'); + } + + #[TestDox('GT succeeds without parameter')] + public function testGTSucceedsWithoutParameter(): void + { + $field = Field::GT('your_test', 4); + $this->assertNotNull($field, 'The field should not have been null'); + $this->assertEquals('your_test', $field->fieldName, 'Field name not filled correctly'); + $this->assertEquals(Op::GT, $field->op, 'Operation not filled correctly'); + $this->assertEquals(4, $field->value, 'Value not filled correctly'); + $this->assertEquals('', $field->paramName, 'Parameter name should have been blank'); + } + + #[TestDox('GT succeeds with parameter')] + public function testGTSucceedsWithParameter(): void + { + $field = Field::GT('more_test', 'chicken', '@value'); + $this->assertNotNull($field, 'The field should not have been null'); + $this->assertEquals('more_test', $field->fieldName, 'Field name not filled correctly'); + $this->assertEquals(Op::GT, $field->op, 'Operation not filled correctly'); + $this->assertEquals('chicken', $field->value, 'Value not filled correctly'); + $this->assertEquals('@value', $field->paramName, 'Parameter name not filled correctly'); + } + + #[TestDox('GE succeeds without parameter')] + public function testGESucceedsWithoutParameter(): void + { + $field = Field::GE('their_test', 6); + $this->assertNotNull($field, 'The field should not have been null'); + $this->assertEquals('their_test', $field->fieldName, 'Field name not filled correctly'); + $this->assertEquals(Op::GE, $field->op, 'Operation not filled correctly'); + $this->assertEquals(6, $field->value, 'Value not filled correctly'); + $this->assertEquals('', $field->paramName, 'Parameter name should have been blank'); + } + + #[TestDox('GE succeeds with parameter')] + public function testGESucceedsWithParameter(): void + { + $field = Field::GE('greater_test', 'poultry', '@cluck'); + $this->assertNotNull($field, 'The field should not have been null'); + $this->assertEquals('greater_test', $field->fieldName, 'Field name not filled correctly'); + $this->assertEquals(Op::GE, $field->op, 'Operation not filled correctly'); + $this->assertEquals('poultry', $field->value, 'Value not filled correctly'); + $this->assertEquals('@cluck', $field->paramName, 'Parameter name not filled correctly'); + } + + #[TestDox('LT succeeds without parameter')] + public function testLTSucceedsWithoutParameter(): void + { + $field = Field::LT('z', 32); + $this->assertNotNull($field, 'The field should not have been null'); + $this->assertEquals('z', $field->fieldName, 'Field name not filled correctly'); + $this->assertEquals(Op::LT, $field->op, 'Operation not filled correctly'); + $this->assertEquals(32, $field->value, 'Value not filled correctly'); + $this->assertEquals('', $field->paramName, 'Parameter name should have been blank'); + } + + #[TestDox('LT succeeds with parameter')] + public function testLTSucceedsWithParameter(): void + { + $field = Field::LT('additional_test', 'fowl', '@boo'); + $this->assertNotNull($field, 'The field should not have been null'); + $this->assertEquals('additional_test', $field->fieldName, 'Field name not filled correctly'); + $this->assertEquals(Op::LT, $field->op, 'Operation not filled correctly'); + $this->assertEquals('fowl', $field->value, 'Value not filled correctly'); + $this->assertEquals('@boo', $field->paramName, 'Parameter name not filled correctly'); + } + + #[TestDox('LE succeeds without parameter')] + public function testLESucceedsWithoutParameter(): void + { + $field = Field::LE('g', 87); + $this->assertNotNull($field, 'The field should not have been null'); + $this->assertEquals('g', $field->fieldName, 'Field name not filled correctly'); + $this->assertEquals(Op::LE, $field->op, 'Operation not filled correctly'); + $this->assertEquals(87, $field->value, 'Value not filled correctly'); + $this->assertEquals('', $field->paramName, 'Parameter name should have been blank'); + } + + #[TestDox('LE succeeds with parameter')] + public function testLESucceedsWithParameter(): void + { + $field = Field::LE('lesser_test', 'hen', '@woo'); + $this->assertNotNull($field, 'The field should not have been null'); + $this->assertEquals('lesser_test', $field->fieldName, 'Field name not filled correctly'); + $this->assertEquals(Op::LE, $field->op, 'Operation not filled correctly'); + $this->assertEquals('hen', $field->value, 'Value not filled correctly'); + $this->assertEquals('@woo', $field->paramName, 'Parameter name not filled correctly'); + } + + #[TestDox('NE succeeds without parameter')] + public function testNESucceedsWithoutParameter(): void + { + $field = Field::NE('j', 65); + $this->assertNotNull($field, 'The field should not have been null'); + $this->assertEquals('j', $field->fieldName, 'Field name not filled correctly'); + $this->assertEquals(Op::NE, $field->op, 'Operation not filled correctly'); + $this->assertEquals(65, $field->value, 'Value not filled correctly'); + $this->assertEquals('', $field->paramName, 'Parameter name should have been blank'); + } + + #[TestDox('NE succeeds with parameter')] + public function testNESucceedsWithParameter(): void + { + $field = Field::NE('unequal_test', 'egg', '@zoo'); + $this->assertNotNull($field, 'The field should not have been null'); + $this->assertEquals('unequal_test', $field->fieldName, 'Field name not filled correctly'); + $this->assertEquals(Op::NE, $field->op, 'Operation not filled correctly'); + $this->assertEquals('egg', $field->value, 'Value not filled correctly'); + $this->assertEquals('@zoo', $field->paramName, 'Parameter name not filled correctly'); + } + + #[TestDox('BT succeeds without parameter')] + public function testBTSucceedsWithoutParameter(): void + { + $field = Field::BT('k', 'alpha', 'zed'); + $this->assertNotNull($field, 'The field should not have been null'); + $this->assertEquals('k', $field->fieldName, 'Field name not filled correctly'); + $this->assertEquals(Op::BT, $field->op, 'Operation not filled correctly'); + $this->assertEquals(['alpha', 'zed'], $field->value, 'Value not filled correctly'); + $this->assertEquals('', $field->paramName, 'Parameter name should have been blank'); + } + + #[TestDox('BT succeeds with parameter')] + public function testBTSucceedsWithParameter(): void + { + $field = Field::BT('between_test', 18, 49, '@count'); + $this->assertNotNull($field, 'The field should not have been null'); + $this->assertEquals('between_test', $field->fieldName, 'Field name not filled correctly'); + $this->assertEquals(Op::BT, $field->op, 'Operation not filled correctly'); + $this->assertEquals([18, 49], $field->value, 'Value not filled correctly'); + $this->assertEquals('@count', $field->paramName, 'Parameter name not filled correctly'); + } + + #[TestDox('EX succeeds')] + public function testEXSucceeds(): void + { + $field = Field::EX('be_there'); + $this->assertNotNull($field, 'The field should not have been null'); + $this->assertEquals('be_there', $field->fieldName, 'Field name not filled correctly'); + $this->assertEquals(Op::EX, $field->op, 'Operation not filled correctly'); + $this->assertEquals('', $field->value, 'Value should have been blank'); + $this->assertEquals('', $field->paramName, 'Parameter name should have been blank'); + } + + #[TestDox('NEX succeeds')] + public function testNEXSucceeds(): void + { + $field = Field::NEX('be_absent'); + $this->assertNotNull($field, 'The field should not have been null'); + $this->assertEquals('be_absent', $field->fieldName, 'Field name not filled correctly'); + $this->assertEquals(Op::NEX, $field->op, 'Operation not filled correctly'); + $this->assertEquals('', $field->value, 'Value should have been blank'); + $this->assertEquals('', $field->paramName, 'Parameter name should have been blank'); + } +} diff --git a/tests/unit/Mapper/ArrayMapperTest.php b/tests/unit/Mapper/ArrayMapperTest.php new file mode 100644 index 0000000..51a8603 --- /dev/null +++ b/tests/unit/Mapper/ArrayMapperTest.php @@ -0,0 +1,19 @@ + 2, 'three' => 4, 'eight' => 'five']; + $mapped = (new ArrayMapper())->map($result); + $this->assertSame($result, $mapped, 'The array mapper should return the parameter given to it'); + } +} diff --git a/tests/unit/Mapper/JsonMapperTest.php b/tests/unit/Mapper/JsonMapperTest.php new file mode 100644 index 0000000..14e84ce --- /dev/null +++ b/tests/unit/Mapper/JsonMapperTest.php @@ -0,0 +1,57 @@ +assertEquals('data', $mapper->fieldName, 'Default field name should have been "data"'); + } + + public function testConstructorSucceedsWithSpecifiedField(): void + { + $mapper = new JsonMapper(Field::class, 'json'); + $this->assertEquals('json', $mapper->fieldName, 'Field name not recorded correctly'); + } + + #[TestDox('Map succeeds with valid JSON')] + public function testMapSucceedsWithValidJSON(): void + { + $doc = (new JsonMapper(TestDocument::class))->map(['data' => '{"id":7,"subDoc":{"id":22,"name":"tester"}}']); + $this->assertNotNull($doc, 'The document should not have been null'); + $this->assertEquals(7, $doc->id, 'ID not filled correctly'); + $this->assertNotNull($doc->subDoc, 'The sub-document should not have been null'); + $this->assertEquals(22, $doc->subDoc->id, 'Sub-document ID not filled correctly'); + $this->assertEquals('tester', $doc->subDoc->name, 'Sub-document name not filled correctly'); + } + + #[TestDox('Map fails with invalid JSON')] + public function testMapFailsWithInvalidJSON(): void + { + $this->expectException(DocumentException::class); + (new JsonMapper(TestDocument::class))->map(['data' => 'this is not valid']); + } +} diff --git a/tests/unit/Mapper/StringMapperTest.php b/tests/unit/Mapper/StringMapperTest.php new file mode 100644 index 0000000..57c1c0a --- /dev/null +++ b/tests/unit/Mapper/StringMapperTest.php @@ -0,0 +1,29 @@ + 'test_value']; + $mapper = new StringMapper('test_field'); + $this->assertEquals('test_value', $mapper->map($result), 'String value not returned correctly'); + } + + public function testMapSucceedsWhenFieldIsPresentAndNotString() + { + $result = ['a_number' => 6.7]; + $mapper = new StringMapper('a_number'); + $this->assertEquals('6.7', $mapper->map($result), 'Number value not returned correctly'); + } + + public function testMapSucceedsWhenFieldIsNotPresent() + { + $mapper = new StringMapper('something_else'); + $this->assertNull($mapper->map([]), 'Missing value not returned correctly'); + } +} diff --git a/tests/unit/OpTest.php b/tests/unit/OpTest.php new file mode 100644 index 0000000..3cb3106 --- /dev/null +++ b/tests/unit/OpTest.php @@ -0,0 +1,67 @@ +assertEquals('=', Op::EQ->toString(), 'EQ operator incorrect'); + } + + #[TestDox('To string succeeds for GT')] + public function testToStringSucceedsForGT(): void + { + $this->assertEquals('>', Op::GT->toString(), 'GT operator incorrect'); + } + + #[TestDox('To string succeeds for GE')] + public function testToStringSucceedsForGE(): void + { + $this->assertEquals('>=', Op::GE->toString(), 'GE operator incorrect'); + } + + #[TestDox('To string succeeds for LT')] + public function testToStringSucceedsForLT(): void + { + $this->assertEquals('<', Op::LT->toString(), 'LT operator incorrect'); + } + + #[TestDox('To string succeeds for LE')] + public function testToStringSucceedsForLE(): void + { + $this->assertEquals('<=', Op::LE->toString(), 'LE operator incorrect'); + } + + #[TestDox('To string succeeds for NE')] + public function testToStringSucceedsForNE(): void + { + $this->assertEquals('<>', Op::NE->toString(), 'NE operator incorrect'); + } + + #[TestDox('To string succeeds for BT')] + public function testToStringSucceedsForBT(): void + { + $this->assertEquals('BETWEEN', Op::BT->toString(), 'BT operator incorrect'); + } + + #[TestDox('To string succeeds for EX')] + public function testToStringSucceedsForEX(): void + { + $this->assertEquals('IS NOT NULL', Op::EX->toString(), 'EX operator incorrect'); + } + + #[TestDox('To string succeeds for NEX')] + public function testToStringSucceedsForNEX(): void + { + $this->assertEquals('IS NULL', Op::NEX->toString(), 'NEX operator incorrect'); + } +} diff --git a/tests/unit/Query/CountTest.php b/tests/unit/Query/CountTest.php new file mode 100644 index 0000000..d0b6223 --- /dev/null +++ b/tests/unit/Query/CountTest.php @@ -0,0 +1,26 @@ +assertEquals('SELECT COUNT(*) FROM a_table', Count::all('a_table'), + 'SELECT statement not generated correctly'); + } + + public function testByFieldsSucceeds() + { + $this->assertEquals("SELECT COUNT(*) FROM somewhere WHERE data->>'errors' > @errors", + Count::byFields('somewhere', [Field::GT('errors', 10, '@errors')])); + } +} diff --git a/tests/unit/Query/DefinitionTest.php b/tests/unit/Query/DefinitionTest.php new file mode 100644 index 0000000..680b2e1 --- /dev/null +++ b/tests/unit/Query/DefinitionTest.php @@ -0,0 +1,38 @@ +assertEquals('CREATE TABLE IF NOT EXISTS documents (data JSON NOT NULL)', + Definition::ensureTableFor('documents', 'JSON'), 'CREATE TABLE statement not generated correctly'); + } + + public function testEnsureIndexOnSucceedsWithoutSchemaSingleAscendingField(): void + { + $this->assertEquals("CREATE INDEX IF NOT EXISTS idx_test_fields ON test ((data->>'details'))", + Definition::ensureIndexOn('test', 'fields', ['details']), 'CREATE INDEX statement not generated correctly'); + } + + public function testEnsureIndexOnSucceedsWithSchemaMultipleFields(): void + { + $this->assertEquals( + "CREATE INDEX IF NOT EXISTS idx_testing_json ON sch.testing ((data->>'group'), (data->>'sub_group') DESC)", + Definition::ensureIndexOn('sch.testing', 'json', ['group', 'sub_group DESC']), + 'CREATE INDEX statement not generated correctly'); + } + + public function testEnsureKey(): void + { + $this->assertEquals("CREATE UNIQUE INDEX IF NOT EXISTS idx_tbl_key ON tbl ((data->>'id'))", + Definition::ensureKey('tbl'), 'CREATE INDEX statement for document key not generated correctly'); + } +} diff --git a/tests/unit/Query/DeleteTest.php b/tests/unit/Query/DeleteTest.php new file mode 100644 index 0000000..7921631 --- /dev/null +++ b/tests/unit/Query/DeleteTest.php @@ -0,0 +1,26 @@ +assertEquals("DELETE FROM over_there WHERE data->>'id' = @id", Delete::byId('over_there'), + 'DELETE statement not constructed correctly'); + } + + public function testByFieldsSucceeds(): void + { + $this->assertEquals("DELETE FROM my_table WHERE data->>'value' < @max AND data->>'value' >= @min", + Delete::byFields('my_table', [Field::LT('value', 99, '@max'), Field::GE('value', 18, '@min')]), + 'DELETE statement not constructed correctly'); + } +} diff --git a/tests/unit/Query/ExistsTest.php b/tests/unit/Query/ExistsTest.php new file mode 100644 index 0000000..dcbf023 --- /dev/null +++ b/tests/unit/Query/ExistsTest.php @@ -0,0 +1,32 @@ +assertEquals('SELECT EXISTS (SELECT 1 FROM abc WHERE def)', Exists::query('abc', 'def'), + 'Existence query not generated correctly'); + } + + public function testByIdSucceeds(): void + { + $this->assertEquals("SELECT EXISTS (SELECT 1 FROM dox WHERE data->>'id' = @id)", Exists::byId('dox'), + 'Existence query not generated correctly'); + } + + public function testByFieldsSucceeds(): void + { + $this->assertEquals("SELECT EXISTS (SELECT 1 FROM box WHERE data->>'status' <> @status)", + Exists::byFields('box', [Field::NE('status', 'occupied', '@status')]), + 'Existence query not generated correctly'); + } +} diff --git a/tests/unit/Query/FindTest.php b/tests/unit/Query/FindTest.php new file mode 100644 index 0000000..1811caf --- /dev/null +++ b/tests/unit/Query/FindTest.php @@ -0,0 +1,26 @@ +assertEquals("SELECT data FROM here WHERE data->>'id' = @id", Find::byId('here'), + 'SELECT query not generated correctly'); + } + + public function testByFieldsSucceeds(): void + { + $this->assertEquals("SELECT data FROM there WHERE data->>'active' = @act OR data->>'locked' = @lock", + Find::byFields('there', [Field::EQ('active', true, '@act'), Field::EQ('locked', true, '@lock')], 'OR'), + 'SELECT query not generated correctly'); + } +} diff --git a/tests/unit/QueryTest.php b/tests/unit/QueryTest.php new file mode 100644 index 0000000..afdd261 --- /dev/null +++ b/tests/unit/QueryTest.php @@ -0,0 +1,68 @@ +assertEquals('SELECT data FROM testing', Query::selectFromTable('testing'), + 'Query not constructed correctly'); + } + + public function testWhereByFieldsSucceedsForSingleField(): void + { + $this->assertEquals("data->>'test_field' <= @it", + Query::whereByFields([Field::LE('test_field', '', '@it')]), 'WHERE fragment not constructed correctly'); + } + + public function testWhereByFieldsSucceedsForMultipleFields(): void + { + $this->assertEquals("data->>'test_field' <= @it AND data->>'other_field' = @other", + Query::whereByFields([Field::LE('test_field', '', '@it'), Field::EQ('other_field', '', '@other')]), + 'WHERE fragment not constructed correctly'); + } + + public function testWhereByFieldsSucceedsForMultipleFieldsWithOr(): void + { + $this->assertEquals("data->>'test_field' <= @it OR data->>'other_field' = @other", + Query::whereByFields([Field::LE('test_field', '', '@it'), Field::EQ('other_field', '', '@other')], 'OR'), + 'WHERE fragment not constructed correctly'); + } + + public function testWhereByIdSucceedsWithDefaultParameter(): void + { + $this->assertEquals("data->>'id' = @id", Query::whereById(), 'WHERE fragment not constructed correctly'); + } + + public function testWhereByIdSucceedsWithSpecificParameter(): void + { + $this->assertEquals("data->>'id' = @di", Query::whereById('@di'), 'WHERE fragment not constructed correctly'); + } + + public function testInsertSucceeds(): void + { + $this->assertEquals('INSERT INTO my_table VALUES (@data)', Query::insert('my_table'), + 'INSERT statement not constructed correctly'); + } + + public function testSaveSucceeds(): void + { + $this->assertEquals( + "INSERT INTO test_tbl VALUES (@data) ON CONFLICT ((data->>'id')) DO UPDATE SET data = EXCLUDED.data", + Query::save('test_tbl'), 'INSERT ON CONFLICT statement not constructed correctly'); + } + + public function testUpdateSucceeds() + { + $this->assertEquals("UPDATE testing SET data = @data WHERE data->>'id' = @id", Query::update('testing'), + 'UPDATE statement not constructed correctly'); + } +} -- 2.45.1 From ecc13a30cff488297d3dedc4d4f00334081b6bdb Mon Sep 17 00:00:00 2001 From: "Daniel J. Summers" Date: Mon, 3 Jun 2024 20:13:45 -0400 Subject: [PATCH 02/25] Add PDO connection config --- src/Configuration.php | 41 +++++++++++++++++++++----------- src/Query.php | 4 ++-- src/Query/Definition.php | 2 +- tests/unit/ConfigurationTest.php | 21 +++++++++++----- 4 files changed, 45 insertions(+), 23 deletions(-) diff --git a/src/Configuration.php b/src/Configuration.php index dc54040..5d44172 100644 --- a/src/Configuration.php +++ b/src/Configuration.php @@ -2,31 +2,44 @@ namespace BitBadger\PDODocument; +use PDO; + /** * Common configuration for the document library */ class Configuration { /** @var string The name of the ID field used in the database (will be treated as the primary key) */ - private static string $_idField = 'id'; + public static string $idField = 'id'; + + /** @var string The data source name (DSN) of the connection string */ + public static string $pdoDSN = ''; + + /** @var string|null The username to use to establish a data connection (use env PDO_DOC_USERNAME if possible) */ + public static ?string $username = null; + + /** @var string|null The password to use to establish a data connection (use env PDO_DOC_PASSWORD if possible) */ + public static ?string $password = null; + + /** @var array|null Options to use for connections (driver-specific) */ + public static ?array $options = null; /** - * Configure the ID field used by the library + * Retrieve a new connection to the database * - * @param string $name The name of the ID field within each document + * @return PDO A new connection to the SQLite database with foreign key support enabled + * @throws DocumentException If this is called before a connection string is set */ - public static function useIdField(string $name): void + public static function dbConn(): PDO { - self::$_idField = $name; - } + if (empty(self::$pdoDSN)) { + throw new DocumentException('Please provide a data source name (DSN) before attempting data access'); + } + $db = new PDO(self::$pdoDSN, $_ENV['PDO_DOC_USERNAME'] ?? self::$username, + $_ENV['PDO_DOC_PASSWORD'] ?? self::$password, self::$options); - /** - * Retrieve the ID field for documents within this library - * - * @return string The configured ID field - */ - public static function idField(): string - { - return self::$_idField; + // TODO: determine driver, set mode for other queries + echo $db->getAttribute(PDO::ATTR_DRIVER_NAME); + return $db; } } diff --git a/src/Query.php b/src/Query.php index d9a265f..a1facbc 100644 --- a/src/Query.php +++ b/src/Query.php @@ -38,7 +38,7 @@ class Query */ public static function whereById(string $paramName = '@id'): string { - return self::whereByFields([Field::EQ(Configuration::idField(), 0, $paramName)]); + return self::whereByFields([Field::EQ(Configuration::$idField, 0, $paramName)]); } /** @@ -61,7 +61,7 @@ class Query public static function save(string $tableName): string { return self::insert($tableName) - . " ON CONFLICT ((data->>'" . Configuration::idField() . "')) DO UPDATE SET data = EXCLUDED.data"; + . " ON CONFLICT ((data->>'" . Configuration::$idField . "')) DO UPDATE SET data = EXCLUDED.data"; } /** diff --git a/src/Query/Definition.php b/src/Query/Definition.php index 802ec7a..730d8a6 100644 --- a/src/Query/Definition.php +++ b/src/Query/Definition.php @@ -61,6 +61,6 @@ class Definition */ public static function ensureKey(string $tableName): string { - return str_replace('INDEX', 'UNIQUE INDEX', self::ensureIndexOn($tableName, 'key', [Configuration::idField()])); + return str_replace('INDEX', 'UNIQUE INDEX', self::ensureIndexOn($tableName, 'key', [Configuration::$idField])); } } diff --git a/tests/unit/ConfigurationTest.php b/tests/unit/ConfigurationTest.php index c493a89..2efbf6d 100644 --- a/tests/unit/ConfigurationTest.php +++ b/tests/unit/ConfigurationTest.php @@ -3,6 +3,8 @@ namespace Test\Unit; use BitBadger\PDODocument\Configuration; +use BitBadger\PDODocument\DocumentException; +use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; /** @@ -12,17 +14,24 @@ class ConfigurationTest extends TestCase { public function testIdFieldDefaultSucceeds(): void { - $this->assertEquals('id', Configuration::idField(), 'Default ID field should be "id"'); + $this->assertEquals('id', Configuration::$idField, 'Default ID field should be "id"'); } - public function testUseIdFieldSucceeds() + public function testIdFieldChangeSucceeds() { try { - Configuration::useIdField('EyeDee'); - $this->assertEquals('EyeDee', Configuration::idField(), 'ID field should have been updated'); + Configuration::$idField = 'EyeDee'; + $this->assertEquals('EyeDee', Configuration::$idField, 'ID field should have been updated'); } finally { - Configuration::useIdField('id'); - $this->assertEquals('id', Configuration::idField(), 'Default ID value should have been restored'); + Configuration::$idField = 'id'; + $this->assertEquals('id', Configuration::$idField, 'Default ID value should have been restored'); } } + + #[TestDox("Db conn fails when no DSN specified")] + public function testDbConnFailsWhenNoDSNSpecified(): void + { + $this->expectException(DocumentException::class); + Configuration::dbConn(); + } } -- 2.45.1 From 98bfceb7c9a08de8eedb0fa306dee71885b3976e Mon Sep 17 00:00:00 2001 From: "Daniel J. Summers" Date: Mon, 3 Jun 2024 21:09:03 -0400 Subject: [PATCH 03/25] Add mode, bring in definition/patch queries --- src/Configuration.php | 14 ++++- src/Mode.php | 15 ++++++ src/Query/Definition.php | 11 +++- src/Query/Patch.php | 59 ++++++++++++++++++++ tests/unit/Query/DefinitionTest.php | 35 ++++++++++-- tests/unit/Query/DeleteTest.php | 2 + tests/unit/Query/ExistsTest.php | 2 + tests/unit/Query/FindTest.php | 2 + tests/unit/Query/PatchTest.php | 83 +++++++++++++++++++++++++++++ tests/unit/QueryTest.php | 3 ++ 10 files changed, 219 insertions(+), 7 deletions(-) create mode 100644 src/Mode.php create mode 100644 src/Query/Patch.php create mode 100644 tests/unit/Query/PatchTest.php diff --git a/src/Configuration.php b/src/Configuration.php index 5d44172..e214aa8 100644 --- a/src/Configuration.php +++ b/src/Configuration.php @@ -24,6 +24,9 @@ class Configuration /** @var array|null Options to use for connections (driver-specific) */ public static ?array $options = null; + /** @var Mode|null The mode in which the library is operating (filled after first connection if not configured) */ + public static ?Mode $mode = null; + /** * Retrieve a new connection to the database * @@ -38,8 +41,15 @@ class Configuration $db = new PDO(self::$pdoDSN, $_ENV['PDO_DOC_USERNAME'] ?? self::$username, $_ENV['PDO_DOC_PASSWORD'] ?? self::$password, self::$options); - // TODO: determine driver, set mode for other queries - echo $db->getAttribute(PDO::ATTR_DRIVER_NAME); + if (is_null(self::$mode)) { + $driver = $db->getAttribute(PDO::ATTR_DRIVER_NAME); + self::$mode = match ($driver) { + 'pgsql' => Mode::PgSQL, + 'sqlite' => Mode::SQLite, + default => throw new DocumentException( + "Unsupported driver $driver: this library currently supports PostgreSQL and SQLite") + }; + } return $db; } } diff --git a/src/Mode.php b/src/Mode.php new file mode 100644 index 0000000..f6e21c7 --- /dev/null +++ b/src/Mode.php @@ -0,0 +1,15 @@ + 'JSONB', + Mode::SQLite => 'TEXT', + default => throw new DocumentException('Database mode not set; cannot make create table statement') + }; return "CREATE TABLE IF NOT EXISTS $name (data $dataType NOT NULL)"; } diff --git a/src/Query/Patch.php b/src/Query/Patch.php new file mode 100644 index 0000000..5811647 --- /dev/null +++ b/src/Query/Patch.php @@ -0,0 +1,59 @@ + 'data || @data', + Mode::SQLite => 'json_patch(data, json(@data))', + default => throw new DocumentException('Database mode not set; cannot make patch statement') + }; + return "UPDATE $tableName SET data = $setValue WHERE $whereClause"; + } + + /** + * Query to patch (partially update) a document by its ID + * + * @param string $tableName The name of the table in which a document should be patched + * @return string The query to patch a document by its ID + * @throws DocumentException If the database mode has not been set + */ + public static function byId(string $tableName): string + { + return self::update($tableName, Query::whereById()); + } + + /** + * Query to patch (partially update) a document via a comparison on a JSON field + * + * @param string $tableName The name of the table in which documents should be patched + * @param array|Field[] $field The field comparison to match + * @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`) + * @return string The query to patch documents via field comparison + * @throws DocumentException If the database mode has not been set + */ + public static function byFields(string $tableName, array $field, string $conjunction = 'AND'): string + { + return self::update($tableName, Query::whereByFields($field, $conjunction)); + } +} diff --git a/tests/unit/Query/DefinitionTest.php b/tests/unit/Query/DefinitionTest.php index 680b2e1..dbdcb02 100644 --- a/tests/unit/Query/DefinitionTest.php +++ b/tests/unit/Query/DefinitionTest.php @@ -2,7 +2,11 @@ namespace Test\Unit\Query; +use BitBadger\PDODocument\Configuration; +use BitBadger\PDODocument\DocumentException; +use BitBadger\PDODocument\Mode; use BitBadger\PDODocument\Query\Definition; +use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; /** @@ -10,10 +14,35 @@ use PHPUnit\Framework\TestCase; */ class DefinitionTest extends TestCase { - public function testEnsureTableForSucceeds(): void + #[TestDox('Ensure table succeeds for PosgtreSQL')] + public function testEnsureTableSucceedsForPostgreSQL(): void { - $this->assertEquals('CREATE TABLE IF NOT EXISTS documents (data JSON NOT NULL)', - Definition::ensureTableFor('documents', 'JSON'), 'CREATE TABLE statement not generated correctly'); + try { + Configuration::$mode = Mode::PgSQL; + $this->assertEquals('CREATE TABLE IF NOT EXISTS documents (data JSONB NOT NULL)', + Definition::ensureTable('documents'), 'CREATE TABLE statement not generated correctly'); + } finally { + Configuration::$mode = null; + } + } + + #[TestDox('Ensure table succeeds for SQLite')] + public function testEnsureTableSucceedsForSQLite(): void + { + try { + Configuration::$mode = Mode::SQLite; + $this->assertEquals('CREATE TABLE IF NOT EXISTS dox (data TEXT NOT NULL)', Definition::ensureTable('dox'), + 'CREATE TABLE statement not generated correctly'); + } finally { + Configuration::$mode = null; + } + } + + public function testEnsureTableFailsWhenModeNotSet(): void + { + $this->expectException(DocumentException::class); + Configuration::$mode = null; + Definition::ensureTable('boom'); } public function testEnsureIndexOnSucceedsWithoutSchemaSingleAscendingField(): void diff --git a/tests/unit/Query/DeleteTest.php b/tests/unit/Query/DeleteTest.php index 7921631..8636713 100644 --- a/tests/unit/Query/DeleteTest.php +++ b/tests/unit/Query/DeleteTest.php @@ -4,6 +4,7 @@ namespace Test\Unit\Query; use BitBadger\PDODocument\Field; use BitBadger\PDODocument\Query\Delete; +use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; /** @@ -11,6 +12,7 @@ use PHPUnit\Framework\TestCase; */ class DeleteTest extends TestCase { + #[TestDox('By ID succeeds')] public function testByIdSucceeds(): void { $this->assertEquals("DELETE FROM over_there WHERE data->>'id' = @id", Delete::byId('over_there'), diff --git a/tests/unit/Query/ExistsTest.php b/tests/unit/Query/ExistsTest.php index dcbf023..60d1093 100644 --- a/tests/unit/Query/ExistsTest.php +++ b/tests/unit/Query/ExistsTest.php @@ -4,6 +4,7 @@ namespace Test\Unit\Query; use BitBadger\PDODocument\Field; use BitBadger\PDODocument\Query\Exists; +use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; /** @@ -17,6 +18,7 @@ class ExistsTest extends TestCase 'Existence query not generated correctly'); } + #[TestDox('By ID succeeds')] public function testByIdSucceeds(): void { $this->assertEquals("SELECT EXISTS (SELECT 1 FROM dox WHERE data->>'id' = @id)", Exists::byId('dox'), diff --git a/tests/unit/Query/FindTest.php b/tests/unit/Query/FindTest.php index 1811caf..5a92241 100644 --- a/tests/unit/Query/FindTest.php +++ b/tests/unit/Query/FindTest.php @@ -4,6 +4,7 @@ namespace Test\Unit\Query; use BitBadger\PDODocument\Field; use BitBadger\PDODocument\Query\Find; +use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; /** @@ -11,6 +12,7 @@ use PHPUnit\Framework\TestCase; */ class FindTest extends TestCase { + #[TestDox('By ID succeeds')] public function testByIdSucceeds(): void { $this->assertEquals("SELECT data FROM here WHERE data->>'id' = @id", Find::byId('here'), diff --git a/tests/unit/Query/PatchTest.php b/tests/unit/Query/PatchTest.php new file mode 100644 index 0000000..81c5fd8 --- /dev/null +++ b/tests/unit/Query/PatchTest.php @@ -0,0 +1,83 @@ +assertEquals("UPDATE doc_table SET data = data || @data WHERE data->>'id' = @id", + Patch::byId('doc_table'), 'Patch UPDATE statement is not correct'); + } finally { + Configuration::$mode = null; + } + } + + #[TestDox('By ID succeeds for SQLite')] + public function testByIdSucceedsForSQLite(): void + { + try { + Configuration::$mode = Mode::SQLite; + $this->assertEquals("UPDATE my_table SET data = json_patch(data, json(@data)) WHERE data->>'id' = @id", + Patch::byId('my_table'), 'Patch UPDATE statement is not correct'); + } finally { + Configuration::$mode = null; + } + } + + #[TestDox('By ID fails when mode not set')] + public function testByIdFailsWhenModeNotSet(): void + { + $this->expectException(DocumentException::class); + Configuration::$mode = null; + Patch::byId('oof'); + } + + #[TestDox('By fields succeeds for PostgreSQL')] + public function testByFieldsSucceedsForPostgreSQL(): void + { + try { + Configuration::$mode = Mode::PgSQL; + $this->assertEquals("UPDATE that SET data = data || @data WHERE data->>'something' < @some", + Patch::byFields('that', [Field::LT('something', 17, '@some')]), + 'Patch UPDATE statement is not correct'); + } finally { + Configuration::$mode = null; + } + } + + #[TestDox('By fields succeeds for SQLite')] + public function testByFieldsSucceedsForSQLite(): void + { + try { + Configuration::$mode = Mode::SQLite; + $this->assertEquals( + "UPDATE a_table SET data = json_patch(data, json(@data)) WHERE data->>'something' > @it", + Patch::byFields('a_table', [Field::GT('something', 17, '@it')]), + 'Patch UPDATE statement is not correct'); + } finally { + Configuration::$mode = null; + } + } + + public function testByFieldsFailsWhenModeNotSet(): void + { + $this->expectException(DocumentException::class); + Configuration::$mode = null; + Patch::byFields('oops', []); + } +} diff --git a/tests/unit/QueryTest.php b/tests/unit/QueryTest.php index afdd261..3ed215e 100644 --- a/tests/unit/QueryTest.php +++ b/tests/unit/QueryTest.php @@ -4,6 +4,7 @@ namespace Test\Unit; use BitBadger\PDODocument\Field; use BitBadger\PDODocument\Query; +use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; /** @@ -37,11 +38,13 @@ class QueryTest extends TestCase 'WHERE fragment not constructed correctly'); } + #[TestDox('Where by ID succeeds with default parameter')] public function testWhereByIdSucceedsWithDefaultParameter(): void { $this->assertEquals("data->>'id' = @id", Query::whereById(), 'WHERE fragment not constructed correctly'); } + #[TestDox('Where by ID succeeds with specific parameter')] public function testWhereByIdSucceedsWithSpecificParameter(): void { $this->assertEquals("data->>'id' = @di", Query::whereById('@di'), 'WHERE fragment not constructed correctly'); -- 2.45.1 From b70513062452abd8527b60212bffa1c676ab571b Mon Sep 17 00:00:00 2001 From: "Daniel J. Summers" Date: Mon, 3 Jun 2024 23:10:12 -0400 Subject: [PATCH 04/25] Add support, custom, and other queries --- src/Count.php | 43 +++++++++ src/Custom.php | 117 +++++++++++++++++++++++++ src/Definition.php | 38 ++++++++ src/Delete.php | 41 +++++++++ src/Document.php | 37 ++++++++ src/DocumentList.php | 37 ++++++-- src/Mapper/CountMapper.php | 17 ++++ src/Mapper/ExistsMapper.php | 26 ++++++ src/Parameters.php | 81 +++++++++++++++++ tests/unit/ConfigurationTest.php | 2 + tests/unit/Mapper/CountMapperTest.php | 17 ++++ tests/unit/Mapper/ExistsMapperTest.php | 45 ++++++++++ tests/unit/ParametersTest.php | 83 ++++++++++++++++++ 13 files changed, 576 insertions(+), 8 deletions(-) create mode 100644 src/Count.php create mode 100644 src/Custom.php create mode 100644 src/Definition.php create mode 100644 src/Delete.php create mode 100644 src/Document.php create mode 100644 src/Mapper/CountMapper.php create mode 100644 src/Mapper/ExistsMapper.php create mode 100644 src/Parameters.php create mode 100644 tests/unit/Mapper/CountMapperTest.php create mode 100644 tests/unit/Mapper/ExistsMapperTest.php create mode 100644 tests/unit/ParametersTest.php diff --git a/src/Count.php b/src/Count.php new file mode 100644 index 0000000..ca945b2 --- /dev/null +++ b/src/Count.php @@ -0,0 +1,43 @@ +prepare($query); + foreach ($parameters as $key => $value) { + if ($debug) echo "
Binding $value to $key\n
"; + $stmt->bindValue($key, $value); + } + if ($debug) echo '
SQL: ' . $stmt->queryString . '
'; + $stmt->execute(); + return $stmt; + } + + /** + * Execute a query that returns a list of results (lazy) + * + * @template TDoc The domain type of the document to retrieve + * @param string $query The query to be executed + * @param array $parameters Parameters to use in executing the query + * @param Mapper $mapper Mapper to deserialize the result + * @return DocumentList The items matching the query + * @throws DocumentException If any is encountered + */ + public static function list(string $query, array $parameters, Mapper $mapper): DocumentList + { + return DocumentList::create($query, $parameters, $mapper); + } + + /** + * Execute a query that returns an array of results (eager) + * + * @template TDoc The domain type of the document to retrieve + * @param string $query The query to be executed + * @param array $parameters Parameters to use in executing the query + * @param Mapper $mapper Mapper to deserialize the result + * @return TDoc[] The items matching the query + * @throws DocumentException If any is encountered + */ + public static function array(string $query, array $parameters, Mapper $mapper): array + { + return iterator_to_array(self::list($query, $parameters, $mapper)->items()); + } + + /** + * Execute a query that returns one or no results (returns false if not found) + * + * @template TDoc The domain type of the document to retrieve + * @param string $query The query to be executed (will have "LIMIT 1" appended) + * @param array $parameters Parameters to use in executing the query + * @param Mapper $mapper Mapper to deserialize the result + * @return false|TDoc The item if it is found, false if not + * @throws DocumentException If any is encountered + */ + public static function single(string $query, array $parameters, Mapper $mapper): mixed + { + return empty($results = self::array("$query LIMIT 1", $parameters, $mapper)) ? false : $results[0]; + } + + /** + * Execute a query that does not return a value + * + * @param string $query The query to execute + * @param array $parameters Parameters to use in executing the query + * @param PDO|null $pdo The database connection to use (optional; will obtain one if not provided) + * @throws DocumentException If any is encountered + */ + public static function nonQuery(string $query, array $parameters, ?PDO $pdo = null): void + { + $stmt = self::runQuery($query, $parameters, $pdo ?? Configuration::dbConn()); + if ($stmt->errorCode()) throw new DocumentException('Error executing command: ' . $stmt->errorCode()); + } + + /** + * Execute a query that returns a scalar value + * + * @template T The scalar type to return + * @param string $query The query to retrieve the value + * @param array $parameters Parameters to use in executing the query + * @param Mapper $mapper The mapper to obtain the result + * @param PDO|null $pdo The database connection to use (optional; will obtain one if not provided) + * @return mixed|false|T The scalar value if found, false if not + * @throws DocumentException If any is encountered + */ + public static function scalar(string $query, array $parameters, Mapper $mapper, ?PDO $pdo = null): mixed + { + $stmt = self::runQuery($query, $parameters, $pdo ?? Configuration::dbConn()); + if ($stmt->errorCode()) { + throw new DocumentException('Error retrieving scalar value: ' . $stmt->errorCode()); + } + if ($stmt->rowCount() > 0) { + $first = $stmt->fetch(PDO::FETCH_NUM); + return $first ? $mapper->map($first) : false; + } + return false; + } +} diff --git a/src/Definition.php b/src/Definition.php new file mode 100644 index 0000000..85b0169 --- /dev/null +++ b/src/Definition.php @@ -0,0 +1,38 @@ + The query results as a lazily-iterated generator + * @param PDO $pdo The database connection against which the query was opened + * @param PDOStatement $result The result of the query + * @param Mapper $mapper The mapper to deserialize JSON */ - public function items(): Generator; + private function __construct(private PDO $pdo, private PDOStatement $result, private Mapper $mapper) { } /** * Construct a new document list @@ -25,12 +30,28 @@ interface DocumentList * @param string $query The query to run to retrieve results * @param array $parameters An associative array of parameters for the query * @param Mapper $mapper A mapper to deserialize JSON documents - * @return static The `DocumentList`-implementing instance + * @return static The document list instance + * @throws DocumentException If any is encountered */ - public static function create(string $query, array $parameters, Mapper $mapper): static; + public static function create(string $query, array $parameters, Mapper $mapper): static + { + $pdo = Configuration::dbConn(); + $stmt = Custom::runQuery($query, $parameters, $pdo); + if ($stmt->errorCode()) { + throw new DocumentException('Error retrieving data: ' . $stmt->errorCode()); + } + return new static($pdo, $stmt, $mapper); + } /** - * Clean up database connection resources + * The items from the query result + * + * @return Generator The items from the document list */ - public function __destruct(); + public function items(): Generator + { + if ($this->result) { + while ($row = $this->result->fetch(PDO::FETCH_ASSOC)) yield $this->mapper->map($row); + } + } } diff --git a/src/Mapper/CountMapper.php b/src/Mapper/CountMapper.php new file mode 100644 index 0000000..a2922a7 --- /dev/null +++ b/src/Mapper/CountMapper.php @@ -0,0 +1,17 @@ + (bool)$result[0], + Mode::SQLite => (int)$result[0] > 0, + default => throw new DocumentException('Database mode not set; cannot map existence result'), + }; + } +} diff --git a/src/Parameters.php b/src/Parameters.php new file mode 100644 index 0000000..592b135 --- /dev/null +++ b/src/Parameters.php @@ -0,0 +1,81 @@ + is_string($key) ? $key : "$key"]; + } + + /** + * Create a parameter with a JSON value + * + * @param string $name The name of the JSON parameter + * @param object|array $document The value that should be passed as a JSON string + * @return array An associative array with the named parameter/value pair + */ + public static function json(string $name, object|array $document): array + { + return [$name => json_encode($document, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)]; + } + + /** + * Fill in parameter names for any fields missing one + * + * @param array|Field[] $fields The fields for the query + * @return array|Field[] The fields, all with non-blank parameter names + */ + public static function nameFields(array $fields): array + { + for ($idx = 0; $idx < sizeof($fields); $idx++) { + if ($fields[$idx]->paramName == '') $fields[$idx]->paramName = "@field$idx"; + } + return $fields; + } + + /** + * Add field parameters to the given set of parameters + * + * @param array|Field[] $fields The fields being compared in the query + * @param array $parameters An associative array of parameters to which the fields should be added + * @return array An associative array of parameter names and values with the fields added + */ + public static function addFields(array $fields, array $parameters): array + { + return array_reduce($fields, fn($carry, $item) => $item->appendParameter($carry), $parameters); + } + + /** + * Create JSON field name parameters for the given field names to the given parameter + * + * @param string $paramName The name of the parameter for the field names + * @param array|string[] $fieldNames The names of the fields for the parameter + * @return array An associative array of parameter/value pairs for the field names + * @throws DocumentException If the database mode has not been set + */ + public static function fieldNames(string $paramName, array $fieldNames): array + { + switch (Configuration::$mode) { + case Mode::PgSQL: + return [$paramName => "ARRAY['" . implode("','", $fieldNames) . "']"]; + case Mode::SQLite: + $it = []; + $idx = 0; + foreach ($fieldNames as $field) $it[$paramName . $idx++] = $field; + return $it; + default: + throw new DocumentException('Database mode not set; cannot generate field name parameters'); + } + } +} diff --git a/tests/unit/ConfigurationTest.php b/tests/unit/ConfigurationTest.php index 2efbf6d..6ff0c09 100644 --- a/tests/unit/ConfigurationTest.php +++ b/tests/unit/ConfigurationTest.php @@ -12,11 +12,13 @@ use PHPUnit\Framework\TestCase; */ class ConfigurationTest extends TestCase { + #[TestDox('ID field default succeeds')] public function testIdFieldDefaultSucceeds(): void { $this->assertEquals('id', Configuration::$idField, 'Default ID field should be "id"'); } + #[TestDox('ID field change succeeds')] public function testIdFieldChangeSucceeds() { try { diff --git a/tests/unit/Mapper/CountMapperTest.php b/tests/unit/Mapper/CountMapperTest.php new file mode 100644 index 0000000..130763a --- /dev/null +++ b/tests/unit/Mapper/CountMapperTest.php @@ -0,0 +1,17 @@ +assertEquals(5, (new CountMapper())->map([5, 8, 10]), 'Count not correct'); + } +} diff --git a/tests/unit/Mapper/ExistsMapperTest.php b/tests/unit/Mapper/ExistsMapperTest.php new file mode 100644 index 0000000..ce68908 --- /dev/null +++ b/tests/unit/Mapper/ExistsMapperTest.php @@ -0,0 +1,45 @@ +assertFalse((new ExistsMapper())->map([false, 'nope']), 'Result should have been false'); + } finally { + Configuration::$mode = null; + } + } + + #[TestDox('Map succeeds for SQLite')] + public function testMapSucceedsForSQLite(): void + { + try { + Configuration::$mode = Mode::SQLite; + $this->assertTrue((new ExistsMapper())->map([1, 'yep']), 'Result should have been true'); + } finally { + Configuration::$mode = null; + } + } + + public function testMapFailsWhenModeNotSet(): void + { + $this->expectException(DocumentException::class); + Configuration::$mode = null; + (new ExistsMapper())->map(['0']); + } +} diff --git a/tests/unit/ParametersTest.php b/tests/unit/ParametersTest.php new file mode 100644 index 0000000..1a0627c --- /dev/null +++ b/tests/unit/ParametersTest.php @@ -0,0 +1,83 @@ +assertEquals(['@id' => 'key'], Parameters::id('key'), 'ID parameter not constructed correctly'); + } + + #[TestDox('ID succeeds with non string')] + public function testIdSucceedsWithNonString(): void + { + $this->assertEquals(['@id' => '7'], Parameters::id(7), 'ID parameter not constructed correctly'); + } + + public function testJsonSucceeds(): void + { + $this->assertEquals(['@it' => '{"id":18,"url":"https://www.unittest.com"}'], + Parameters::json('@it', ['id' => 18, 'url' => 'https://www.unittest.com']), + 'JSON parameter not constructed correctly'); + } + + public function testNameFieldsSucceeds(): void + { + $named = Parameters::nameFields([Field::EQ('it', 17), Field::EQ('also', 22, '@also'), Field::EQ('other', 24)]); + $this->assertCount(3, $named, 'There should be 3 parameters in the array'); + $this->assertEquals('@field0', $named[0]->paramName, 'Parameter 1 not named correctly'); + $this->assertEquals('@also', $named[1]->paramName, 'Parameter 2 not named correctly'); + $this->assertEquals('@field2', $named[2]->paramName, 'Parameter 3 not named correctly'); + } + + public function testAddFieldsSucceeds(): void + { + $this->assertEquals(['@a' => 1, '@b' => 'two', '@z' => 18], + Parameters::addFields([Field::EQ('b', 'two', '@b'), Field::EQ('z', 18, '@z')], ['@a' => 1]), + 'Field parameters not added correctly'); + } + + #[TestDox('Field names succeeds for PostgreSQL')] + public function testFieldNamesSucceedsForPostgreSQL(): void + { + try { + Configuration::$mode = Mode::PgSQL; + $this->assertEquals(['@names' => "ARRAY['one','two','seven']"], + Parameters::fieldNames('@names', ['one', 'two', 'seven']), 'Field name parameters not correct'); + } finally { + Configuration::$mode = null; + } + } + + #[TestDox('Field names succeeds for SQLite')] + public function testFieldNamesSucceedsForSQLite(): void + { + try { + Configuration::$mode = Mode::SQLite; + $this->assertEquals(['@it0' => 'test', '@it1' => 'unit', '@it2' => 'wow'], + Parameters::fieldNames('@it', ['test', 'unit', 'wow']), 'Field name parameters not correct'); + } finally { + Configuration::$mode = null; + } + } + + public function testFieldNamesFailsWhenModeNotSet(): void + { + $this->expectException(DocumentException::class); + Configuration::$mode = null; + Parameters::fieldNames('', []); + } +} -- 2.45.1 From afc5d8009507a297c8169be93aee1085e652eedc Mon Sep 17 00:00:00 2001 From: "Daniel J. Summers" Date: Tue, 4 Jun 2024 08:10:57 -0400 Subject: [PATCH 05/25] Migrate remaining implementation --- composer.json | 3 +- composer.lock | 6 +- src/Document.php | 15 ++++ src/Exists.php | 44 +++++++++++ src/Find.php | 78 +++++++++++++++++++ .../{JsonMapper.php => DocumentMapper.php} | 5 +- src/Patch.php | 44 +++++++++++ src/Query/RemoveFields.php | 70 +++++++++++++++++ src/RemoveFields.php | 46 +++++++++++ ...nMapperTest.php => DocumentMapperTest.php} | 14 ++-- 10 files changed, 313 insertions(+), 12 deletions(-) create mode 100644 src/Exists.php create mode 100644 src/Find.php rename src/Mapper/{JsonMapper.php => DocumentMapper.php} (91%) create mode 100644 src/Patch.php create mode 100644 src/Query/RemoveFields.php create mode 100644 src/RemoveFields.php rename tests/unit/Mapper/{JsonMapperTest.php => DocumentMapperTest.php} (77%) diff --git a/composer.json b/composer.json index 9781acb..a792038 100644 --- a/composer.json +++ b/composer.json @@ -1,7 +1,8 @@ { "name": "bit-badger/pdo-document", "require": { - "netresearch/jsonmapper": "^4" + "netresearch/jsonmapper": "^4", + "ext-pdo": "*" }, "require-dev": { "phpunit/phpunit": "^11" diff --git a/composer.lock b/composer.lock index 56df984..50d47e2 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "38b71eefd32cb528da22dd5908fb8d02", + "content-hash": "eada4b7eb6f976e0aaf0b54b92e2ca32", "packages": [ { "name": "netresearch/jsonmapper", @@ -1696,7 +1696,9 @@ "stability-flags": [], "prefer-stable": false, "prefer-lowest": false, - "platform": [], + "platform": { + "ext-pdo": "*" + }, "platform-dev": [], "plugin-api-version": "2.6.0" } diff --git a/src/Document.php b/src/Document.php index 663eed0..cb56cd7 100644 --- a/src/Document.php +++ b/src/Document.php @@ -34,4 +34,19 @@ class Document { Custom::nonQuery(Query::save($tableName), Parameters::json('@data', $document), $pdo); } + + /** + * Update (replace) an entire document by its ID + * + * @param string $tableName The table in which the document should be updated + * @param mixed $docId The ID of the document to be updated + * @param array|object $document The document to be updated + * @param PDO|null $pdo The database connection to use (optional; will obtain one if not provided) + * @throws DocumentException If any is encountered + */ + public static function update(string $tableName, mixed $docId, array|object $document, ?PDO $pdo = null): void + { + Custom::nonQuery(Query::update($tableName), + array_merge(Parameters::id($docId), Parameters::json('@data', $document)), $pdo); + } } diff --git a/src/Exists.php b/src/Exists.php new file mode 100644 index 0000000..5b4e6cd --- /dev/null +++ b/src/Exists.php @@ -0,0 +1,44 @@ + $className The name of the class to be retrieved + * @return DocumentList A list of all documents from the table + * @throws DocumentException If any is encountered + */ + public static function all(string $tableName, string $className): DocumentList + { + return Custom::list(Query::selectFromTable($tableName), [], new DocumentMapper($className)); + } + + /** + * Retrieve a document by its ID (returns false if not found) + * + * @template TDoc The type of document to be retrieved + * @param string $tableName The table from which the document should be retrieved + * @param mixed $docId The ID of the document to retrieve + * @param class-string $className The name of the class to be retrieved + * @return false|TDoc The document if it exists, false if not + * @throws DocumentException If any is encountered + */ + public static function byId(string $tableName, mixed $docId, string $className): mixed + { + return Custom::single(Query\Find::byId($tableName), Parameters::id($docId), new DocumentMapper($className)); + } + + /** + * Retrieve documents via a comparison on JSON fields + * + * @template TDoc The type of document to be retrieved + * @param string $tableName The table from which documents should be retrieved + * @param array|Field[] $fields The field comparison to match + * @param class-string $className The name of the class to be retrieved + * @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`) + * @return DocumentList A list of documents matching the given field comparison + * @throws DocumentException If any is encountered + */ + public static function byFields(string $tableName, array $fields, string $className, + string $conjunction = 'AND'): DocumentList + { + $namedFields = Parameters::nameFields($fields); + return Custom::list(Query\Find::byFields($tableName, $namedFields, $conjunction), + Parameters::addFields($namedFields, []), new DocumentMapper($className)); + } + + /** + * Retrieve documents via a comparison on JSON fields, returning only the first result + * + * @template TDoc The type of document to be retrieved + * @param string $tableName The table from which the document should be retrieved + * @param array|Field[] $fields The field comparison to match + * @param class-string $className The name of the class to be retrieved + * @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`) + * @return false|TDoc The first document if any matches are found, false otherwise + * @throws DocumentException If any is encountered + */ + public static function firstByFields(string $tableName, array $fields, string $className, + string $conjunction = 'AND'): mixed + { + $namedFields = Parameters::nameFields($fields); + return Custom::single(Query\Find::byFields($tableName, $namedFields, $conjunction), + Parameters::addFields($namedFields, []), new DocumentMapper($className)); + } +} diff --git a/src/Mapper/JsonMapper.php b/src/Mapper/DocumentMapper.php similarity index 91% rename from src/Mapper/JsonMapper.php rename to src/Mapper/DocumentMapper.php index 10919b4..a4d20ac 100644 --- a/src/Mapper/JsonMapper.php +++ b/src/Mapper/DocumentMapper.php @@ -3,6 +3,7 @@ namespace BitBadger\PDODocument\Mapper; use BitBadger\PDODocument\DocumentException; +use JsonMapper; use JsonMapper_Exception; /** @@ -11,7 +12,7 @@ use JsonMapper_Exception; * @template TDoc The type of document returned by this mapper * @implements Mapper Provide a mapping from JSON */ -class JsonMapper implements Mapper +class DocumentMapper implements Mapper { /** * Constructor @@ -35,7 +36,7 @@ class JsonMapper implements Mapper if (is_null($json)) { throw new DocumentException("Could not map document for $this->className: " . json_last_error_msg()); } - return (new \JsonMapper())->map($json, $this->className); + return (new JsonMapper())->map($json, $this->className); } catch (JsonMapper_Exception $ex) { throw new DocumentException("Could not map document for $this->className", previous: $ex); } diff --git a/src/Patch.php b/src/Patch.php new file mode 100644 index 0000000..40afa7e --- /dev/null +++ b/src/Patch.php @@ -0,0 +1,44 @@ +assertEquals('data', $mapper->fieldName, 'Default field name should have been "data"'); } public function testConstructorSucceedsWithSpecifiedField(): void { - $mapper = new JsonMapper(Field::class, 'json'); + $mapper = new DocumentMapper(Field::class, 'json'); $this->assertEquals('json', $mapper->fieldName, 'Field name not recorded correctly'); } #[TestDox('Map succeeds with valid JSON')] public function testMapSucceedsWithValidJSON(): void { - $doc = (new JsonMapper(TestDocument::class))->map(['data' => '{"id":7,"subDoc":{"id":22,"name":"tester"}}']); + $doc = (new DocumentMapper(TestDocument::class))->map(['data' => '{"id":7,"subDoc":{"id":22,"name":"tester"}}']); $this->assertNotNull($doc, 'The document should not have been null'); $this->assertEquals(7, $doc->id, 'ID not filled correctly'); $this->assertNotNull($doc->subDoc, 'The sub-document should not have been null'); @@ -52,6 +52,6 @@ class JsonMapperTest extends TestCase public function testMapFailsWithInvalidJSON(): void { $this->expectException(DocumentException::class); - (new JsonMapper(TestDocument::class))->map(['data' => 'this is not valid']); + (new DocumentMapper(TestDocument::class))->map(['data' => 'this is not valid']); } } -- 2.45.1 From c2dc111dcecc6e5f1db71b6e6f403db4a27c7220 Mon Sep 17 00:00:00 2001 From: "Daniel J. Summers" Date: Tue, 4 Jun 2024 19:55:22 -0400 Subject: [PATCH 06/25] WIP on connection management --- src/Custom.php | 17 ++++++++++------- src/DocumentList.php | 18 ++++++++---------- 2 files changed, 18 insertions(+), 17 deletions(-) diff --git a/src/Custom.php b/src/Custom.php index ae75ac8..572ac51 100644 --- a/src/Custom.php +++ b/src/Custom.php @@ -18,6 +18,7 @@ class Custom * @param array $parameters The parameters for the query * @param PDO $pdo The database connection on which the query should be run * @return PDOStatement The result of executing the query + * @throws DocumentException If the query execution is unsuccessful */ public static function runQuery(string $query, array $parameters, PDO $pdo): PDOStatement { @@ -28,8 +29,9 @@ class Custom $stmt->bindValue($key, $value); } if ($debug) echo '
SQL: ' . $stmt->queryString . '
'; - $stmt->execute(); - return $stmt; + if ($stmt->execute()) return $stmt; + $keyword = explode(' ', $query, 2)[0]; + throw new DocumentException("Error executing $keyword statement: " . $stmt->errorCode()); } /** @@ -87,8 +89,12 @@ class Custom */ public static function nonQuery(string $query, array $parameters, ?PDO $pdo = null): void { - $stmt = self::runQuery($query, $parameters, $pdo ?? Configuration::dbConn()); - if ($stmt->errorCode()) throw new DocumentException('Error executing command: ' . $stmt->errorCode()); + try { + $stmt = self::runQuery($query, $parameters, is_null($pdo) ? $actualPDO = Configuration::dbConn() : $pdo); + $stmt = null; + } finally { + if (isset($actualPDO)) $actualPDO = null; + } } /** @@ -105,9 +111,6 @@ class Custom public static function scalar(string $query, array $parameters, Mapper $mapper, ?PDO $pdo = null): mixed { $stmt = self::runQuery($query, $parameters, $pdo ?? Configuration::dbConn()); - if ($stmt->errorCode()) { - throw new DocumentException('Error retrieving scalar value: ' . $stmt->errorCode()); - } if ($stmt->rowCount() > 0) { $first = $stmt->fetch(PDO::FETCH_NUM); return $first ? $mapper->map($first) : false; diff --git a/src/DocumentList.php b/src/DocumentList.php index 58eb9a7..60a7658 100644 --- a/src/DocumentList.php +++ b/src/DocumentList.php @@ -13,16 +13,16 @@ use PDOStatement; * * @template TDoc The domain class for items returned by this list */ -readonly class DocumentList +class DocumentList { /** * Constructor * - * @param PDO $pdo The database connection against which the query was opened - * @param PDOStatement $result The result of the query + * @param PDO|null $pdo The database connection against which the query was opened + * @param PDOStatement|null $result The result of the query * @param Mapper $mapper The mapper to deserialize JSON */ - private function __construct(private PDO $pdo, private PDOStatement $result, private Mapper $mapper) { } + private function __construct(private ?PDO $pdo, private ?PDOStatement $result, private Mapper $mapper) { } /** * Construct a new document list @@ -35,12 +35,8 @@ readonly class DocumentList */ public static function create(string $query, array $parameters, Mapper $mapper): static { - $pdo = Configuration::dbConn(); - $stmt = Custom::runQuery($query, $parameters, $pdo); - if ($stmt->errorCode()) { - throw new DocumentException('Error retrieving data: ' . $stmt->errorCode()); - } - return new static($pdo, $stmt, $mapper); + $pdo = Configuration::dbConn(); + return new static($pdo, Custom::runQuery($query, $parameters, $pdo), $mapper); } /** @@ -53,5 +49,7 @@ readonly class DocumentList if ($this->result) { while ($row = $this->result->fetch(PDO::FETCH_ASSOC)) yield $this->mapper->map($row); } + $this->result = null; + $this->pdo = null; } } -- 2.45.1 From cecbb51414492ba45e869180284251cf21404e2a Mon Sep 17 00:00:00 2001 From: "Daniel J. Summers" Date: Tue, 4 Jun 2024 20:12:42 -0400 Subject: [PATCH 07/25] Fix scalar, add conn mgt --- src/Custom.php | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/Custom.php b/src/Custom.php index 572ac51..24371b0 100644 --- a/src/Custom.php +++ b/src/Custom.php @@ -91,8 +91,8 @@ class Custom { try { $stmt = self::runQuery($query, $parameters, is_null($pdo) ? $actualPDO = Configuration::dbConn() : $pdo); - $stmt = null; } finally { + $stmt = null; if (isset($actualPDO)) $actualPDO = null; } } @@ -110,11 +110,12 @@ class Custom */ public static function scalar(string $query, array $parameters, Mapper $mapper, ?PDO $pdo = null): mixed { - $stmt = self::runQuery($query, $parameters, $pdo ?? Configuration::dbConn()); - if ($stmt->rowCount() > 0) { - $first = $stmt->fetch(PDO::FETCH_NUM); - return $first ? $mapper->map($first) : false; + try { + $stmt = self::runQuery($query, $parameters, is_null($pdo) ? $actualPDO = Configuration::dbConn() : $pdo); + return ($first = $stmt->fetch(PDO::FETCH_NUM)) ? $mapper->map($first) : false; + } finally { + $stmt = null; + if (isset($actualPDO)) $actualPDO = null; } - return false; } } -- 2.45.1 From 7390ae0f6198f41b4e0913ed362af82bd767ce6b Mon Sep 17 00:00:00 2001 From: "Daniel J. Summers" Date: Tue, 4 Jun 2024 20:18:38 -0400 Subject: [PATCH 08/25] Do not construct a list for a single item query --- src/Custom.php | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/Custom.php b/src/Custom.php index 24371b0..b3ce240 100644 --- a/src/Custom.php +++ b/src/Custom.php @@ -71,12 +71,20 @@ class Custom * @param string $query The query to be executed (will have "LIMIT 1" appended) * @param array $parameters Parameters to use in executing the query * @param Mapper $mapper Mapper to deserialize the result + * @param PDO|null $pdo The database connection to use (optional; will obtain one if not provided) * @return false|TDoc The item if it is found, false if not * @throws DocumentException If any is encountered */ - public static function single(string $query, array $parameters, Mapper $mapper): mixed + public static function single(string $query, array $parameters, Mapper $mapper, ?PDO $pdo = null): mixed { - return empty($results = self::array("$query LIMIT 1", $parameters, $mapper)) ? false : $results[0]; + try { + $stmt = self::runQuery("$query LIMIT 1", $parameters, + is_null($pdo) ? $actualPDO = Configuration::dbConn() : $pdo); + return ($first = $stmt->fetch(PDO::FETCH_ASSOC)) ? $mapper->map($first) : false; + } finally { + $stmt = null; + if (isset($actualPDO)) $actualPDO = null; + } } /** -- 2.45.1 From 3d45bbcabc43f9801e4aaccd705b8582ba0d9d99 Mon Sep 17 00:00:00 2001 From: "Daniel J. Summers" Date: Tue, 4 Jun 2024 20:59:24 -0400 Subject: [PATCH 09/25] Change param prefix from @ to : --- src/Parameters.php | 6 +- src/Patch.php | 4 +- src/Query.php | 6 +- src/Query/Patch.php | 4 +- src/RemoveFields.php | 4 +- tests/unit/ParametersTest.php | 28 +++--- tests/unit/Query/CountTest.php | 4 +- tests/unit/Query/DeleteTest.php | 6 +- tests/unit/Query/ExistsTest.php | 6 +- tests/unit/Query/FindTest.php | 6 +- tests/unit/Query/PatchTest.php | 12 +-- tests/unit/Query/RemoveFieldsTest.php | 121 ++++++++++++++++++++++++++ tests/unit/QueryTest.php | 22 ++--- 13 files changed, 175 insertions(+), 54 deletions(-) create mode 100644 tests/unit/Query/RemoveFieldsTest.php diff --git a/src/Parameters.php b/src/Parameters.php index 592b135..0d32fab 100644 --- a/src/Parameters.php +++ b/src/Parameters.php @@ -8,14 +8,14 @@ namespace BitBadger\PDODocument; class Parameters { /** - * Create an ID parameter (name "@id", key will be treated as a string) + * Create an ID parameter (name ":id", key will be treated as a string) * * @param mixed $key The key representing the ID of the document * @return array|string[] An associative array with an "@id" parameter/value pair */ public static function id(mixed $key): array { - return ['@id' => is_string($key) ? $key : "$key"]; + return [':id' => is_string($key) ? $key : "$key"]; } /** @@ -39,7 +39,7 @@ class Parameters public static function nameFields(array $fields): array { for ($idx = 0; $idx < sizeof($fields); $idx++) { - if ($fields[$idx]->paramName == '') $fields[$idx]->paramName = "@field$idx"; + if ($fields[$idx]->paramName == '') $fields[$idx]->paramName = ":field$idx"; } return $fields; } diff --git a/src/Patch.php b/src/Patch.php index 40afa7e..9bbbaa9 100644 --- a/src/Patch.php +++ b/src/Patch.php @@ -21,7 +21,7 @@ class Patch public static function byId(string $tableName, mixed $docId, array|object $patch, ?PDO $pdo = null): void { Custom::nonQuery(Query\Patch::byId($tableName), - array_merge(Parameters::id($docId), Parameters::json('@data', $patch)), $pdo); + array_merge(Parameters::id($docId), Parameters::json(':data', $patch)), $pdo); } /** @@ -39,6 +39,6 @@ class Patch { $namedFields = Parameters::nameFields($fields); Custom::nonQuery(Query\Patch::byFields($tableName, $namedFields, $conjunction), - Parameters::addFields($namedFields, Parameters::json('@data', $patch)), $pdo); + Parameters::addFields($namedFields, Parameters::json(':data', $patch)), $pdo); } } diff --git a/src/Query.php b/src/Query.php index a1facbc..495315a 100644 --- a/src/Query.php +++ b/src/Query.php @@ -36,7 +36,7 @@ class Query * @param string $paramName The parameter name where the value of the ID will be provided (optional; default @id) * @return string The WHERE clause fragment to match by ID */ - public static function whereById(string $paramName = '@id'): string + public static function whereById(string $paramName = ':id'): string { return self::whereByFields([Field::EQ(Configuration::$idField, 0, $paramName)]); } @@ -49,7 +49,7 @@ class Query */ public static function insert(string $tableName): string { - return "INSERT INTO $tableName VALUES (@data)"; + return "INSERT INTO $tableName VALUES (:data)"; } /** @@ -72,6 +72,6 @@ class Query */ public static function update(string $tableName): string { - return "UPDATE $tableName SET data = @data WHERE " . self::whereById(); + return "UPDATE $tableName SET data = :data WHERE " . self::whereById(); } } diff --git a/src/Query/Patch.php b/src/Query/Patch.php index 5811647..7f63253 100644 --- a/src/Query/Patch.php +++ b/src/Query/Patch.php @@ -24,8 +24,8 @@ class Patch public static function update(string $tableName, string $whereClause): string { $setValue = match (Configuration::$mode) { - Mode::PgSQL => 'data || @data', - Mode::SQLite => 'json_patch(data, json(@data))', + Mode::PgSQL => 'data || :data', + Mode::SQLite => 'json_patch(data, json(:data))', default => throw new DocumentException('Database mode not set; cannot make patch statement') }; return "UPDATE $tableName SET data = $setValue WHERE $whereClause"; diff --git a/src/RemoveFields.php b/src/RemoveFields.php index 236ea99..4432c0f 100644 --- a/src/RemoveFields.php +++ b/src/RemoveFields.php @@ -20,7 +20,7 @@ class RemoveFields */ public static function byId(string $tableName, mixed $docId, array $fieldNames, ?PDO $pdo = null): void { - $nameParams = Parameters::fieldNames('@name', $fieldNames); + $nameParams = Parameters::fieldNames(':name', $fieldNames); Custom::nonQuery(Query\RemoveFields::byId($tableName, $nameParams), array_merge(Parameters::id($docId), $nameParams), $pdo); } @@ -38,7 +38,7 @@ class RemoveFields public static function byFields(string $tableName, array $fields, array $fieldNames, ?PDO $pdo = null, string $conjunction = 'AND'): void { - $nameParams = Parameters::fieldNames('@name', $fieldNames); + $nameParams = Parameters::fieldNames(':name', $fieldNames); $namedFields = Parameters::nameFields($fields); Custom::nonQuery(Query\RemoveFields::byFields($tableName, $namedFields, $nameParams, $conjunction), Parameters::addFields($namedFields, $nameParams), $pdo); diff --git a/tests/unit/ParametersTest.php b/tests/unit/ParametersTest.php index 1a0627c..1bf0ec0 100644 --- a/tests/unit/ParametersTest.php +++ b/tests/unit/ParametersTest.php @@ -18,35 +18,35 @@ class ParametersTest extends TestCase #[TestDox('ID succeeds with string')] public function testIdSucceedsWithString(): void { - $this->assertEquals(['@id' => 'key'], Parameters::id('key'), 'ID parameter not constructed correctly'); + $this->assertEquals([':id' => 'key'], Parameters::id('key'), 'ID parameter not constructed correctly'); } #[TestDox('ID succeeds with non string')] public function testIdSucceedsWithNonString(): void { - $this->assertEquals(['@id' => '7'], Parameters::id(7), 'ID parameter not constructed correctly'); + $this->assertEquals([':id' => '7'], Parameters::id(7), 'ID parameter not constructed correctly'); } public function testJsonSucceeds(): void { - $this->assertEquals(['@it' => '{"id":18,"url":"https://www.unittest.com"}'], - Parameters::json('@it', ['id' => 18, 'url' => 'https://www.unittest.com']), + $this->assertEquals([':it' => '{"id":18,"url":"https://www.unittest.com"}'], + Parameters::json(':it', ['id' => 18, 'url' => 'https://www.unittest.com']), 'JSON parameter not constructed correctly'); } public function testNameFieldsSucceeds(): void { - $named = Parameters::nameFields([Field::EQ('it', 17), Field::EQ('also', 22, '@also'), Field::EQ('other', 24)]); + $named = Parameters::nameFields([Field::EQ('it', 17), Field::EQ('also', 22, ':also'), Field::EQ('other', 24)]); $this->assertCount(3, $named, 'There should be 3 parameters in the array'); - $this->assertEquals('@field0', $named[0]->paramName, 'Parameter 1 not named correctly'); - $this->assertEquals('@also', $named[1]->paramName, 'Parameter 2 not named correctly'); - $this->assertEquals('@field2', $named[2]->paramName, 'Parameter 3 not named correctly'); + $this->assertEquals(':field0', $named[0]->paramName, 'Parameter 1 not named correctly'); + $this->assertEquals(':also', $named[1]->paramName, 'Parameter 2 not named correctly'); + $this->assertEquals(':field2', $named[2]->paramName, 'Parameter 3 not named correctly'); } public function testAddFieldsSucceeds(): void { - $this->assertEquals(['@a' => 1, '@b' => 'two', '@z' => 18], - Parameters::addFields([Field::EQ('b', 'two', '@b'), Field::EQ('z', 18, '@z')], ['@a' => 1]), + $this->assertEquals([':a' => 1, ':b' => 'two', ':z' => 18], + Parameters::addFields([Field::EQ('b', 'two', ':b'), Field::EQ('z', 18, ':z')], [':a' => 1]), 'Field parameters not added correctly'); } @@ -55,8 +55,8 @@ class ParametersTest extends TestCase { try { Configuration::$mode = Mode::PgSQL; - $this->assertEquals(['@names' => "ARRAY['one','two','seven']"], - Parameters::fieldNames('@names', ['one', 'two', 'seven']), 'Field name parameters not correct'); + $this->assertEquals([':names' => "ARRAY['one','two','seven']"], + Parameters::fieldNames(':names', ['one', 'two', 'seven']), 'Field name parameters not correct'); } finally { Configuration::$mode = null; } @@ -67,8 +67,8 @@ class ParametersTest extends TestCase { try { Configuration::$mode = Mode::SQLite; - $this->assertEquals(['@it0' => 'test', '@it1' => 'unit', '@it2' => 'wow'], - Parameters::fieldNames('@it', ['test', 'unit', 'wow']), 'Field name parameters not correct'); + $this->assertEquals([':it0' => 'test', ':it1' => 'unit', ':it2' => 'wow'], + Parameters::fieldNames(':it', ['test', 'unit', 'wow']), 'Field name parameters not correct'); } finally { Configuration::$mode = null; } diff --git a/tests/unit/Query/CountTest.php b/tests/unit/Query/CountTest.php index d0b6223..0a70527 100644 --- a/tests/unit/Query/CountTest.php +++ b/tests/unit/Query/CountTest.php @@ -20,7 +20,7 @@ class CountTest extends TestCase public function testByFieldsSucceeds() { - $this->assertEquals("SELECT COUNT(*) FROM somewhere WHERE data->>'errors' > @errors", - Count::byFields('somewhere', [Field::GT('errors', 10, '@errors')])); + $this->assertEquals("SELECT COUNT(*) FROM somewhere WHERE data->>'errors' > :errors", + Count::byFields('somewhere', [Field::GT('errors', 10, ':errors')])); } } diff --git a/tests/unit/Query/DeleteTest.php b/tests/unit/Query/DeleteTest.php index 8636713..edf21bc 100644 --- a/tests/unit/Query/DeleteTest.php +++ b/tests/unit/Query/DeleteTest.php @@ -15,14 +15,14 @@ class DeleteTest extends TestCase #[TestDox('By ID succeeds')] public function testByIdSucceeds(): void { - $this->assertEquals("DELETE FROM over_there WHERE data->>'id' = @id", Delete::byId('over_there'), + $this->assertEquals("DELETE FROM over_there WHERE data->>'id' = :id", Delete::byId('over_there'), 'DELETE statement not constructed correctly'); } public function testByFieldsSucceeds(): void { - $this->assertEquals("DELETE FROM my_table WHERE data->>'value' < @max AND data->>'value' >= @min", - Delete::byFields('my_table', [Field::LT('value', 99, '@max'), Field::GE('value', 18, '@min')]), + $this->assertEquals("DELETE FROM my_table WHERE data->>'value' < :max AND data->>'value' >= :min", + Delete::byFields('my_table', [Field::LT('value', 99, ':max'), Field::GE('value', 18, ':min')]), 'DELETE statement not constructed correctly'); } } diff --git a/tests/unit/Query/ExistsTest.php b/tests/unit/Query/ExistsTest.php index 60d1093..32fbae2 100644 --- a/tests/unit/Query/ExistsTest.php +++ b/tests/unit/Query/ExistsTest.php @@ -21,14 +21,14 @@ class ExistsTest extends TestCase #[TestDox('By ID succeeds')] public function testByIdSucceeds(): void { - $this->assertEquals("SELECT EXISTS (SELECT 1 FROM dox WHERE data->>'id' = @id)", Exists::byId('dox'), + $this->assertEquals("SELECT EXISTS (SELECT 1 FROM dox WHERE data->>'id' = :id)", Exists::byId('dox'), 'Existence query not generated correctly'); } public function testByFieldsSucceeds(): void { - $this->assertEquals("SELECT EXISTS (SELECT 1 FROM box WHERE data->>'status' <> @status)", - Exists::byFields('box', [Field::NE('status', 'occupied', '@status')]), + $this->assertEquals("SELECT EXISTS (SELECT 1 FROM box WHERE data->>'status' <> :status)", + Exists::byFields('box', [Field::NE('status', 'occupied', ':status')]), 'Existence query not generated correctly'); } } diff --git a/tests/unit/Query/FindTest.php b/tests/unit/Query/FindTest.php index 5a92241..65bc571 100644 --- a/tests/unit/Query/FindTest.php +++ b/tests/unit/Query/FindTest.php @@ -15,14 +15,14 @@ class FindTest extends TestCase #[TestDox('By ID succeeds')] public function testByIdSucceeds(): void { - $this->assertEquals("SELECT data FROM here WHERE data->>'id' = @id", Find::byId('here'), + $this->assertEquals("SELECT data FROM here WHERE data->>'id' = :id", Find::byId('here'), 'SELECT query not generated correctly'); } public function testByFieldsSucceeds(): void { - $this->assertEquals("SELECT data FROM there WHERE data->>'active' = @act OR data->>'locked' = @lock", - Find::byFields('there', [Field::EQ('active', true, '@act'), Field::EQ('locked', true, '@lock')], 'OR'), + $this->assertEquals("SELECT data FROM there WHERE data->>'active' = :act OR data->>'locked' = :lock", + Find::byFields('there', [Field::EQ('active', true, ':act'), Field::EQ('locked', true, ':lock')], 'OR'), 'SELECT query not generated correctly'); } } diff --git a/tests/unit/Query/PatchTest.php b/tests/unit/Query/PatchTest.php index 81c5fd8..1e338a1 100644 --- a/tests/unit/Query/PatchTest.php +++ b/tests/unit/Query/PatchTest.php @@ -20,7 +20,7 @@ class PatchTest extends TestCase { try { Configuration::$mode = Mode::PgSQL; - $this->assertEquals("UPDATE doc_table SET data = data || @data WHERE data->>'id' = @id", + $this->assertEquals("UPDATE doc_table SET data = data || :data WHERE data->>'id' = :id", Patch::byId('doc_table'), 'Patch UPDATE statement is not correct'); } finally { Configuration::$mode = null; @@ -32,7 +32,7 @@ class PatchTest extends TestCase { try { Configuration::$mode = Mode::SQLite; - $this->assertEquals("UPDATE my_table SET data = json_patch(data, json(@data)) WHERE data->>'id' = @id", + $this->assertEquals("UPDATE my_table SET data = json_patch(data, json(:data)) WHERE data->>'id' = :id", Patch::byId('my_table'), 'Patch UPDATE statement is not correct'); } finally { Configuration::$mode = null; @@ -52,8 +52,8 @@ class PatchTest extends TestCase { try { Configuration::$mode = Mode::PgSQL; - $this->assertEquals("UPDATE that SET data = data || @data WHERE data->>'something' < @some", - Patch::byFields('that', [Field::LT('something', 17, '@some')]), + $this->assertEquals("UPDATE that SET data = data || :data WHERE data->>'something' < :some", + Patch::byFields('that', [Field::LT('something', 17, ':some')]), 'Patch UPDATE statement is not correct'); } finally { Configuration::$mode = null; @@ -66,8 +66,8 @@ class PatchTest extends TestCase try { Configuration::$mode = Mode::SQLite; $this->assertEquals( - "UPDATE a_table SET data = json_patch(data, json(@data)) WHERE data->>'something' > @it", - Patch::byFields('a_table', [Field::GT('something', 17, '@it')]), + "UPDATE a_table SET data = json_patch(data, json(:data)) WHERE data->>'something' > :it", + Patch::byFields('a_table', [Field::GT('something', 17, ':it')]), 'Patch UPDATE statement is not correct'); } finally { Configuration::$mode = null; diff --git a/tests/unit/Query/RemoveFieldsTest.php b/tests/unit/Query/RemoveFieldsTest.php new file mode 100644 index 0000000..bd79858 --- /dev/null +++ b/tests/unit/Query/RemoveFieldsTest.php @@ -0,0 +1,121 @@ +assertEquals('UPDATE taco SET data = data - :names WHERE it = true', + RemoveFields::update('taco', [':names' => "ARRAY['one','two']"], 'it = true'), + 'UPDATE statement not correct'); + } finally { + Configuration::$mode = null; + } + } + + #[TestDox('Update succeeds for SQLite')] + public function testUpdateSucceedsForSQLite(): void + { + try { + Configuration::$mode = Mode::SQLite; + $this->assertEquals('UPDATE burrito SET data = json_remove(data, :name0, :name1, :name2) WHERE a = b', + RemoveFields::update('burrito', Parameters::fieldNames(':name', ['one', 'two', 'ten']), 'a = b'), + 'UPDATE statement not correct'); + } finally { + Configuration::$mode = null; + } + } + + public function testUpdateFailsWhenModeNotSet(): void + { + $this->expectException(DocumentException::class); + Configuration::$mode = null; + RemoveFields::update('wow', [], ''); + } + + #[TestDox('By ID succeeds for PostgreSQL')] + public function testByIdSucceedsForPostgreSQL() + { + try { + Configuration::$mode = Mode::PgSQL; + $this->assertEquals("UPDATE churro SET data = data - :bite WHERE data->>'id' = :id", + RemoveFields::byId('churro', Parameters::fieldNames(':bite', ['byte'])), + 'UPDATE statement not correct'); + } finally { + Configuration::$mode = null; + } + } + + #[TestDox('By ID succeeds for SQLite')] + public function testByIdSucceedsForSQLite() + { + try { + Configuration::$mode = Mode::SQLite; + $this->assertEquals("UPDATE quesadilla SET data = json_remove(data, :bite0) WHERE data->>'id' = :id", + RemoveFields::byId('quesadilla', Parameters::fieldNames(':bite', ['byte'])), + 'UPDATE statement not correct'); + } finally { + Configuration::$mode = null; + } + } + + #[TestDox('By ID fails when mode not set')] + public function testByIdFailsWhenModeNotSet(): void + { + $this->expectException(DocumentException::class); + Configuration::$mode = null; + RemoveFields::byId('oof', []); + } + + #[TestDox('By fields succeeds for PostgreSQL')] + public function testByFieldsSucceedsForPostgreSQL() + { + try { + Configuration::$mode = Mode::PgSQL; + $this->assertEquals("UPDATE enchilada SET data = data - :sauce WHERE data->>'cheese' = :queso", + RemoveFields::byFields('enchilada', [Field::EQ('cheese', 'jack', ':queso')], + Parameters::fieldNames(':sauce', ['white'])), + 'UPDATE statement not correct'); + } finally { + Configuration::$mode = null; + } + } + + #[TestDox('By fields succeeds for SQLite')] + public function testByFieldsSucceedsForSQLite() + { + try { + Configuration::$mode = Mode::SQLite; + $this->assertEquals( + "UPDATE chimichanga SET data = json_remove(data, :filling0) WHERE data->>'side' = :rice", + RemoveFields::byFields('chimichanga', [Field::EQ('side', 'beans', ':rice')], + Parameters::fieldNames(':filling', ['beef'])), + 'UPDATE statement not correct'); + } finally { + Configuration::$mode = null; + } + } + + public function testByFieldsFailsWhenModeNotSet(): void + { + $this->expectException(DocumentException::class); + Configuration::$mode = null; + RemoveFields::byFields('boing', [], []); + } +} diff --git a/tests/unit/QueryTest.php b/tests/unit/QueryTest.php index 3ed215e..894a700 100644 --- a/tests/unit/QueryTest.php +++ b/tests/unit/QueryTest.php @@ -20,52 +20,52 @@ class QueryTest extends TestCase public function testWhereByFieldsSucceedsForSingleField(): void { - $this->assertEquals("data->>'test_field' <= @it", - Query::whereByFields([Field::LE('test_field', '', '@it')]), 'WHERE fragment not constructed correctly'); + $this->assertEquals("data->>'test_field' <= :it", + Query::whereByFields([Field::LE('test_field', '', ':it')]), 'WHERE fragment not constructed correctly'); } public function testWhereByFieldsSucceedsForMultipleFields(): void { - $this->assertEquals("data->>'test_field' <= @it AND data->>'other_field' = @other", - Query::whereByFields([Field::LE('test_field', '', '@it'), Field::EQ('other_field', '', '@other')]), + $this->assertEquals("data->>'test_field' <= :it AND data->>'other_field' = :other", + Query::whereByFields([Field::LE('test_field', '', ':it'), Field::EQ('other_field', '', ':other')]), 'WHERE fragment not constructed correctly'); } public function testWhereByFieldsSucceedsForMultipleFieldsWithOr(): void { - $this->assertEquals("data->>'test_field' <= @it OR data->>'other_field' = @other", - Query::whereByFields([Field::LE('test_field', '', '@it'), Field::EQ('other_field', '', '@other')], 'OR'), + $this->assertEquals("data->>'test_field' <= :it OR data->>'other_field' = :other", + Query::whereByFields([Field::LE('test_field', '', ':it'), Field::EQ('other_field', '', ':other')], 'OR'), 'WHERE fragment not constructed correctly'); } #[TestDox('Where by ID succeeds with default parameter')] public function testWhereByIdSucceedsWithDefaultParameter(): void { - $this->assertEquals("data->>'id' = @id", Query::whereById(), 'WHERE fragment not constructed correctly'); + $this->assertEquals("data->>'id' = :id", Query::whereById(), 'WHERE fragment not constructed correctly'); } #[TestDox('Where by ID succeeds with specific parameter')] public function testWhereByIdSucceedsWithSpecificParameter(): void { - $this->assertEquals("data->>'id' = @di", Query::whereById('@di'), 'WHERE fragment not constructed correctly'); + $this->assertEquals("data->>'id' = :di", Query::whereById(':di'), 'WHERE fragment not constructed correctly'); } public function testInsertSucceeds(): void { - $this->assertEquals('INSERT INTO my_table VALUES (@data)', Query::insert('my_table'), + $this->assertEquals('INSERT INTO my_table VALUES (:data)', Query::insert('my_table'), 'INSERT statement not constructed correctly'); } public function testSaveSucceeds(): void { $this->assertEquals( - "INSERT INTO test_tbl VALUES (@data) ON CONFLICT ((data->>'id')) DO UPDATE SET data = EXCLUDED.data", + "INSERT INTO test_tbl VALUES (:data) ON CONFLICT ((data->>'id')) DO UPDATE SET data = EXCLUDED.data", Query::save('test_tbl'), 'INSERT ON CONFLICT statement not constructed correctly'); } public function testUpdateSucceeds() { - $this->assertEquals("UPDATE testing SET data = @data WHERE data->>'id' = @id", Query::update('testing'), + $this->assertEquals("UPDATE testing SET data = :data WHERE data->>'id' = :id", Query::update('testing'), 'UPDATE statement not constructed correctly'); } } -- 2.45.1 From 4342d1ac503df7def805f40beb27f717df73361b Mon Sep 17 00:00:00 2001 From: "Daniel J. Summers" Date: Tue, 4 Jun 2024 21:28:12 -0400 Subject: [PATCH 10/25] Add debug to document list --- src/DocumentList.php | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/DocumentList.php b/src/DocumentList.php index 60a7658..6aafba2 100644 --- a/src/DocumentList.php +++ b/src/DocumentList.php @@ -46,8 +46,15 @@ class DocumentList */ public function items(): Generator { + $debug = defined('PDO_DOC_DEBUG_SQL'); + if ($this->result) { - while ($row = $this->result->fetch(PDO::FETCH_ASSOC)) yield $this->mapper->map($row); + while ($row = $this->result->fetch(PDO::FETCH_ASSOC)) { + if ($debug) echo "
Returning an item\n
"; + yield $this->mapper->map($row); + } + } else { + if ($debug) echo 'Nothing to return'; } $this->result = null; $this->pdo = null; -- 2.45.1 From b871d3e03fed5bd4e678d4b6e23a21598d90054c Mon Sep 17 00:00:00 2001 From: "Daniel J. Summers" Date: Tue, 4 Jun 2024 21:34:17 -0400 Subject: [PATCH 11/25] Add more debug --- src/DocumentList.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/DocumentList.php b/src/DocumentList.php index 6aafba2..02ada88 100644 --- a/src/DocumentList.php +++ b/src/DocumentList.php @@ -47,6 +47,7 @@ class DocumentList public function items(): Generator { $debug = defined('PDO_DOC_DEBUG_SQL'); + if ($debug) echo '*** CALLED GENERATOR ***'; if ($this->result) { while ($row = $this->result->fetch(PDO::FETCH_ASSOC)) { -- 2.45.1 From 259247464a61a60a366cdfd3c8b9881a4d223a94 Mon Sep 17 00:00:00 2001 From: "Daniel J. Summers" Date: Tue, 4 Jun 2024 21:36:36 -0400 Subject: [PATCH 12/25] Even more debug --- src/DocumentList.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/DocumentList.php b/src/DocumentList.php index 02ada88..de3dd32 100644 --- a/src/DocumentList.php +++ b/src/DocumentList.php @@ -50,6 +50,7 @@ class DocumentList if ($debug) echo '*** CALLED GENERATOR ***'; if ($this->result) { + if ($debug) echo 'There are results'; while ($row = $this->result->fetch(PDO::FETCH_ASSOC)) { if ($debug) echo "
Returning an item\n
"; yield $this->mapper->map($row); -- 2.45.1 From 71ae46fac7d0101cd255371d0bf6259b5f3b352a Mon Sep 17 00:00:00 2001 From: "Daniel J. Summers" Date: Tue, 4 Jun 2024 21:49:30 -0400 Subject: [PATCH 13/25] Make properties public --- src/DocumentList.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/DocumentList.php b/src/DocumentList.php index de3dd32..da5d0f3 100644 --- a/src/DocumentList.php +++ b/src/DocumentList.php @@ -22,7 +22,7 @@ class DocumentList * @param PDOStatement|null $result The result of the query * @param Mapper $mapper The mapper to deserialize JSON */ - private function __construct(private ?PDO $pdo, private ?PDOStatement $result, private Mapper $mapper) { } + private function __construct(private ?PDO $pdo, public ?PDOStatement $result, public Mapper $mapper) { } /** * Construct a new document list -- 2.45.1 From 85786fa1138414f8a85cef3df1b69a548b00dd2e Mon Sep 17 00:00:00 2001 From: "Daniel J. Summers" Date: Tue, 4 Jun 2024 21:53:02 -0400 Subject: [PATCH 14/25] where are the results --- src/DocumentList.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/DocumentList.php b/src/DocumentList.php index da5d0f3..e1ff4aa 100644 --- a/src/DocumentList.php +++ b/src/DocumentList.php @@ -22,7 +22,9 @@ class DocumentList * @param PDOStatement|null $result The result of the query * @param Mapper $mapper The mapper to deserialize JSON */ - private function __construct(private ?PDO $pdo, public ?PDOStatement $result, public Mapper $mapper) { } + private function __construct(private ?PDO $pdo, public ?PDOStatement $result, public Mapper $mapper) { + var_dump($this->result->fetch(PDO::FETCH_ASSOC)); + } /** * Construct a new document list -- 2.45.1 From 50b4104e02e2822f31d5c640c61cd58b428b74da Mon Sep 17 00:00:00 2001 From: "Daniel J. Summers" Date: Tue, 4 Jun 2024 22:00:00 -0400 Subject: [PATCH 15/25] undo last commit --- src/DocumentList.php | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/DocumentList.php b/src/DocumentList.php index e1ff4aa..da5d0f3 100644 --- a/src/DocumentList.php +++ b/src/DocumentList.php @@ -22,9 +22,7 @@ class DocumentList * @param PDOStatement|null $result The result of the query * @param Mapper $mapper The mapper to deserialize JSON */ - private function __construct(private ?PDO $pdo, public ?PDOStatement $result, public Mapper $mapper) { - var_dump($this->result->fetch(PDO::FETCH_ASSOC)); - } + private function __construct(private ?PDO $pdo, public ?PDOStatement $result, public Mapper $mapper) { } /** * Construct a new document list -- 2.45.1 From 1e7c41eaa2010def86bef67575fc9c55d8de78b5 Mon Sep 17 00:00:00 2001 From: "Daniel J. Summers" Date: Tue, 4 Jun 2024 22:24:27 -0400 Subject: [PATCH 16/25] Derive data type for bindValue call Remove debugging in document list --- src/Custom.php | 8 +++++++- src/DocumentList.php | 13 ++----------- 2 files changed, 9 insertions(+), 12 deletions(-) diff --git a/src/Custom.php b/src/Custom.php index b3ce240..fc1a068 100644 --- a/src/Custom.php +++ b/src/Custom.php @@ -26,7 +26,13 @@ class Custom $stmt = $pdo->prepare($query); foreach ($parameters as $key => $value) { if ($debug) echo "
Binding $value to $key\n
"; - $stmt->bindValue($key, $value); + $dataType = match (true) { + is_bool($value) => PDO::PARAM_BOOL, + is_int($value) => PDO::PARAM_INT, + is_null($value) => PDO::PARAM_NULL, + default => PDO::PARAM_STR + }; + $stmt->bindValue($key, $value, $dataType); } if ($debug) echo '
SQL: ' . $stmt->queryString . '
'; if ($stmt->execute()) return $stmt; diff --git a/src/DocumentList.php b/src/DocumentList.php index da5d0f3..60a7658 100644 --- a/src/DocumentList.php +++ b/src/DocumentList.php @@ -22,7 +22,7 @@ class DocumentList * @param PDOStatement|null $result The result of the query * @param Mapper $mapper The mapper to deserialize JSON */ - private function __construct(private ?PDO $pdo, public ?PDOStatement $result, public Mapper $mapper) { } + private function __construct(private ?PDO $pdo, private ?PDOStatement $result, private Mapper $mapper) { } /** * Construct a new document list @@ -46,17 +46,8 @@ class DocumentList */ public function items(): Generator { - $debug = defined('PDO_DOC_DEBUG_SQL'); - if ($debug) echo '*** CALLED GENERATOR ***'; - if ($this->result) { - if ($debug) echo 'There are results'; - while ($row = $this->result->fetch(PDO::FETCH_ASSOC)) { - if ($debug) echo "
Returning an item\n
"; - yield $this->mapper->map($row); - } - } else { - if ($debug) echo 'Nothing to return'; + while ($row = $this->result->fetch(PDO::FETCH_ASSOC)) yield $this->mapper->map($row); } $this->result = null; $this->pdo = null; -- 2.45.1 From bcca9f5ace2ba32c24412e284ff4789480d9619d Mon Sep 17 00:00:00 2001 From: "Daniel J. Summers" Date: Tue, 4 Jun 2024 22:36:58 -0400 Subject: [PATCH 17/25] Missed document param prefix updates --- src/Document.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Document.php b/src/Document.php index cb56cd7..e6c209d 100644 --- a/src/Document.php +++ b/src/Document.php @@ -19,7 +19,7 @@ class Document */ public static function insert(string $tableName, array|object $document, ?PDO $pdo = null): void { - Custom::nonQuery(Query::insert($tableName), Parameters::json('@data', $document), $pdo); + Custom::nonQuery(Query::insert($tableName), Parameters::json(':data', $document), $pdo); } /** @@ -32,7 +32,7 @@ class Document */ public static function save(string $tableName, array|object $document, ?PDO $pdo = null): void { - Custom::nonQuery(Query::save($tableName), Parameters::json('@data', $document), $pdo); + Custom::nonQuery(Query::save($tableName), Parameters::json(':data', $document), $pdo); } /** @@ -47,6 +47,6 @@ class Document public static function update(string $tableName, mixed $docId, array|object $document, ?PDO $pdo = null): void { Custom::nonQuery(Query::update($tableName), - array_merge(Parameters::id($docId), Parameters::json('@data', $document)), $pdo); + array_merge(Parameters::id($docId), Parameters::json(':data', $document)), $pdo); } } -- 2.45.1 From d9ffc36fe6d07ff1927a09fe9fbec1ea647e1d41 Mon Sep 17 00:00:00 2001 From: "Daniel J. Summers" Date: Fri, 7 Jun 2024 20:57:12 -0400 Subject: [PATCH 18/25] Use PDO singleton --- src/Configuration.php | 34 ++++++++++++++++++++-------------- src/Count.php | 12 ++++-------- src/Custom.php | 22 +++++++--------------- src/Definition.php | 14 +++++--------- src/Delete.php | 13 ++++--------- src/Document.php | 17 ++++++----------- src/DocumentList.php | 8 +++----- src/Exists.php | 12 ++++-------- src/Patch.php | 12 ++++-------- src/RemoveFields.php | 12 ++++-------- 10 files changed, 61 insertions(+), 95 deletions(-) diff --git a/src/Configuration.php b/src/Configuration.php index e214aa8..b562e7b 100644 --- a/src/Configuration.php +++ b/src/Configuration.php @@ -27,6 +27,9 @@ class Configuration /** @var Mode|null The mode in which the library is operating (filled after first connection if not configured) */ public static ?Mode $mode = null; + /** @var PDO|null The PDO instance to use for database commands */ + private static ?PDO $_pdo = null; + /** * Retrieve a new connection to the database * @@ -35,21 +38,24 @@ class Configuration */ public static function dbConn(): PDO { - if (empty(self::$pdoDSN)) { - throw new DocumentException('Please provide a data source name (DSN) before attempting data access'); - } - $db = new PDO(self::$pdoDSN, $_ENV['PDO_DOC_USERNAME'] ?? self::$username, - $_ENV['PDO_DOC_PASSWORD'] ?? self::$password, self::$options); + if (is_null(self::$_pdo)) { + if (empty(self::$pdoDSN)) { + throw new DocumentException('Please provide a data source name (DSN) before attempting data access'); + } + self::$_pdo = new PDO(self::$pdoDSN, $_ENV['PDO_DOC_USERNAME'] ?? self::$username, + $_ENV['PDO_DOC_PASSWORD'] ?? self::$password, self::$options); - if (is_null(self::$mode)) { - $driver = $db->getAttribute(PDO::ATTR_DRIVER_NAME); - self::$mode = match ($driver) { - 'pgsql' => Mode::PgSQL, - 'sqlite' => Mode::SQLite, - default => throw new DocumentException( - "Unsupported driver $driver: this library currently supports PostgreSQL and SQLite") - }; + if (is_null(self::$mode)) { + $driver = self::$_pdo->getAttribute(PDO::ATTR_DRIVER_NAME); + self::$mode = match ($driver) { + 'pgsql' => Mode::PgSQL, + 'sqlite' => Mode::SQLite, + default => throw new DocumentException( + "Unsupported driver $driver: this library currently supports PostgreSQL and SQLite") + }; + } } - return $db; + + return self::$_pdo; } } diff --git a/src/Count.php b/src/Count.php index ca945b2..df91c72 100644 --- a/src/Count.php +++ b/src/Count.php @@ -3,7 +3,6 @@ namespace BitBadger\PDODocument; use BitBadger\PDODocument\Mapper\CountMapper; -use PDO; /** * Functions to count documents @@ -14,13 +13,12 @@ class Count * Count all documents in a table * * @param string $tableName The name of the table in which documents should be counted - * @param PDO|null $pdo The database connection to use (optional; will obtain one if not provided) * @return int The count of documents in the table * @throws DocumentException If one is encountered */ - public static function all(string $tableName, ?PDO $pdo = null): int + public static function all(string $tableName): int { - return Custom::scalar(Query\Count::all($tableName), [], new CountMapper(), $pdo); + return Custom::scalar(Query\Count::all($tableName), [], new CountMapper()); } /** @@ -28,16 +26,14 @@ class Count * * @param string $tableName The name of the table in which documents should be counted * @param array|Field[] $fields The field comparison to match - * @param PDO|null $pdo The database connection to use (optional; will obtain one if not provided) * @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`) * @return int The count of documents matching the field comparison * @throws DocumentException If one is encountered */ - public static function byFields(string $tableName, array $fields, ?PDO $pdo = null, - string $conjunction = 'AND'): int + public static function byFields(string $tableName, array $fields, string $conjunction = 'AND'): int { $namedFields = Parameters::nameFields($fields); return Custom::scalar(Query\Count::byFields($tableName, $namedFields, $conjunction), - Parameters::addFields($namedFields, []), new CountMapper(), $pdo); + Parameters::addFields($namedFields, []), new CountMapper()); } } diff --git a/src/Custom.php b/src/Custom.php index fc1a068..5ba6663 100644 --- a/src/Custom.php +++ b/src/Custom.php @@ -16,14 +16,13 @@ class Custom * * @param string $query The query to be run * @param array $parameters The parameters for the query - * @param PDO $pdo The database connection on which the query should be run * @return PDOStatement The result of executing the query * @throws DocumentException If the query execution is unsuccessful */ - public static function runQuery(string $query, array $parameters, PDO $pdo): PDOStatement + public static function &runQuery(string $query, array $parameters): PDOStatement { $debug = defined('PDO_DOC_DEBUG_SQL'); - $stmt = $pdo->prepare($query); + $stmt = Configuration::dbConn()->prepare($query); foreach ($parameters as $key => $value) { if ($debug) echo "
Binding $value to $key\n
"; $dataType = match (true) { @@ -77,19 +76,16 @@ class Custom * @param string $query The query to be executed (will have "LIMIT 1" appended) * @param array $parameters Parameters to use in executing the query * @param Mapper $mapper Mapper to deserialize the result - * @param PDO|null $pdo The database connection to use (optional; will obtain one if not provided) * @return false|TDoc The item if it is found, false if not * @throws DocumentException If any is encountered */ - public static function single(string $query, array $parameters, Mapper $mapper, ?PDO $pdo = null): mixed + public static function single(string $query, array $parameters, Mapper $mapper): mixed { try { - $stmt = self::runQuery("$query LIMIT 1", $parameters, - is_null($pdo) ? $actualPDO = Configuration::dbConn() : $pdo); + $stmt = &self::runQuery("$query LIMIT 1", $parameters); return ($first = $stmt->fetch(PDO::FETCH_ASSOC)) ? $mapper->map($first) : false; } finally { $stmt = null; - if (isset($actualPDO)) $actualPDO = null; } } @@ -98,16 +94,14 @@ class Custom * * @param string $query The query to execute * @param array $parameters Parameters to use in executing the query - * @param PDO|null $pdo The database connection to use (optional; will obtain one if not provided) * @throws DocumentException If any is encountered */ - public static function nonQuery(string $query, array $parameters, ?PDO $pdo = null): void + public static function nonQuery(string $query, array $parameters): void { try { - $stmt = self::runQuery($query, $parameters, is_null($pdo) ? $actualPDO = Configuration::dbConn() : $pdo); + $stmt = &self::runQuery($query, $parameters); } finally { $stmt = null; - if (isset($actualPDO)) $actualPDO = null; } } @@ -118,18 +112,16 @@ class Custom * @param string $query The query to retrieve the value * @param array $parameters Parameters to use in executing the query * @param Mapper $mapper The mapper to obtain the result - * @param PDO|null $pdo The database connection to use (optional; will obtain one if not provided) * @return mixed|false|T The scalar value if found, false if not * @throws DocumentException If any is encountered */ public static function scalar(string $query, array $parameters, Mapper $mapper, ?PDO $pdo = null): mixed { try { - $stmt = self::runQuery($query, $parameters, is_null($pdo) ? $actualPDO = Configuration::dbConn() : $pdo); + $stmt = &self::runQuery($query, $parameters); return ($first = $stmt->fetch(PDO::FETCH_NUM)) ? $mapper->map($first) : false; } finally { $stmt = null; - if (isset($actualPDO)) $actualPDO = null; } } } diff --git a/src/Definition.php b/src/Definition.php index 85b0169..be87c3a 100644 --- a/src/Definition.php +++ b/src/Definition.php @@ -2,8 +2,6 @@ namespace BitBadger\PDODocument; -use PDO; - /** * Functions to create tables and indexes */ @@ -13,13 +11,12 @@ class Definition * Ensure a document table exists * * @param string $name The name of the table to be created if it does not exist - * @param PDO|null $pdo The database connection to use (optional; will obtain one if not provided) * @throws DocumentException If any is encountered */ - public static function ensureTable(string $name, ?PDO $pdo = null): void + public static function ensureTable(string $name): void { - Custom::nonQuery(Query\Definition::ensureTable($name), [], $pdo); - Custom::nonQuery(Query\Definition::ensureKey($name), [], $pdo); + Custom::nonQuery(Query\Definition::ensureTable($name), []); + Custom::nonQuery(Query\Definition::ensureKey($name), []); } /** @@ -28,11 +25,10 @@ class Definition * @param string $tableName The name of the table which should be indexed * @param string $indexName The name of the index * @param array $fields Fields which should be a part of this index - * @param PDO|null $pdo The database connection to use (optional; will obtain one if not provided) * @throws DocumentException If any is encountered */ - public static function ensureFieldIndex(string $tableName, string $indexName, array $fields, ?PDO $pdo = null): void + public static function ensureFieldIndex(string $tableName, string $indexName, array $fields): void { - Custom::nonQuery(Query\Definition::ensureIndexOn($tableName, $indexName, $fields), [], $pdo); + Custom::nonQuery(Query\Definition::ensureIndexOn($tableName, $indexName, $fields), []); } } diff --git a/src/Delete.php b/src/Delete.php index 477bb26..00a408f 100644 --- a/src/Delete.php +++ b/src/Delete.php @@ -2,8 +2,6 @@ namespace BitBadger\PDODocument; -use PDO; - /** * Functions to delete documents */ @@ -14,12 +12,11 @@ class Delete * * @param string $tableName The table from which the document should be deleted * @param mixed $docId The ID of the document to be deleted - * @param PDO|null $pdo The database connection to use (optional; will obtain one if not provided) * @throws DocumentException If any is encountered */ - public static function byId(string $tableName, mixed $docId, ?PDO $pdo = null): void + public static function byId(string $tableName, mixed $docId): void { - Custom::nonQuery(Query\Delete::byId($tableName), Parameters::id($docId), $pdo); + Custom::nonQuery(Query\Delete::byId($tableName), Parameters::id($docId)); } /** @@ -27,15 +24,13 @@ class Delete * * @param string $tableName The table from which documents should be deleted * @param array|Field[] $fields The field comparison to match - * @param PDO|null $pdo The database connection to use (optional; will obtain one if not provided) * @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`) * @throws DocumentException If any is encountered */ - public static function byFields(string $tableName, array $fields, ?PDO $pdo = null, - string $conjunction = 'AND'): void + public static function byFields(string $tableName, array $fields, string $conjunction = 'AND'): void { $namedFields = Parameters::nameFields($fields); Custom::nonQuery(Query\Delete::byFields($tableName, $namedFields, $conjunction), - Parameters::addFields($namedFields, []), $pdo); + Parameters::addFields($namedFields, [])); } } diff --git a/src/Document.php b/src/Document.php index e6c209d..5f14323 100644 --- a/src/Document.php +++ b/src/Document.php @@ -2,8 +2,6 @@ namespace BitBadger\PDODocument; -use PDO; - /** * Functions that apply at a whole document level */ @@ -14,12 +12,11 @@ class Document * * @param string $tableName The name of the table into which the document should be inserted * @param array|object $document The document to be inserted - * @param PDO|null $pdo The database connection to use (optional; will obtain one if not provided) * @throws DocumentException If any is encountered */ - public static function insert(string $tableName, array|object $document, ?PDO $pdo = null): void + public static function insert(string $tableName, array|object $document): void { - Custom::nonQuery(Query::insert($tableName), Parameters::json(':data', $document), $pdo); + Custom::nonQuery(Query::insert($tableName), Parameters::json(':data', $document)); } /** @@ -27,12 +24,11 @@ class Document * * @param string $tableName The name of the table to which the document should be saved * @param array|object $document The document to be saved - * @param PDO|null $pdo The database connection to use (optional; will obtain one if not provided) * @throws DocumentException If any is encountered */ - public static function save(string $tableName, array|object $document, ?PDO $pdo = null): void + public static function save(string $tableName, array|object $document): void { - Custom::nonQuery(Query::save($tableName), Parameters::json(':data', $document), $pdo); + Custom::nonQuery(Query::save($tableName), Parameters::json(':data', $document)); } /** @@ -41,12 +37,11 @@ class Document * @param string $tableName The table in which the document should be updated * @param mixed $docId The ID of the document to be updated * @param array|object $document The document to be updated - * @param PDO|null $pdo The database connection to use (optional; will obtain one if not provided) * @throws DocumentException If any is encountered */ - public static function update(string $tableName, mixed $docId, array|object $document, ?PDO $pdo = null): void + public static function update(string $tableName, mixed $docId, array|object $document): void { Custom::nonQuery(Query::update($tableName), - array_merge(Parameters::id($docId), Parameters::json(':data', $document)), $pdo); + array_merge(Parameters::id($docId), Parameters::json(':data', $document))); } } diff --git a/src/DocumentList.php b/src/DocumentList.php index 60a7658..44ec060 100644 --- a/src/DocumentList.php +++ b/src/DocumentList.php @@ -18,11 +18,10 @@ class DocumentList /** * Constructor * - * @param PDO|null $pdo The database connection against which the query was opened * @param PDOStatement|null $result The result of the query * @param Mapper $mapper The mapper to deserialize JSON */ - private function __construct(private ?PDO $pdo, private ?PDOStatement $result, private Mapper $mapper) { } + private function __construct(private ?PDOStatement &$result, private readonly Mapper $mapper) { } /** * Construct a new document list @@ -35,8 +34,8 @@ class DocumentList */ public static function create(string $query, array $parameters, Mapper $mapper): static { - $pdo = Configuration::dbConn(); - return new static($pdo, Custom::runQuery($query, $parameters, $pdo), $mapper); + $stmt = &Custom::runQuery($query, $parameters); + return new static($stmt, $mapper); } /** @@ -50,6 +49,5 @@ class DocumentList while ($row = $this->result->fetch(PDO::FETCH_ASSOC)) yield $this->mapper->map($row); } $this->result = null; - $this->pdo = null; } } diff --git a/src/Exists.php b/src/Exists.php index 5b4e6cd..11548d4 100644 --- a/src/Exists.php +++ b/src/Exists.php @@ -3,7 +3,6 @@ namespace BitBadger\PDODocument; use BitBadger\PDODocument\Mapper\ExistsMapper; -use PDO; /** * Functions to determine if documents exist @@ -15,13 +14,12 @@ class Exists * * @param string $tableName The name of the table in which document existence should be determined * @param mixed $docId The ID of the document whose existence should be determined - * @param PDO|null $pdo The database connection to use (optional; will obtain one if not provided) * @return bool True if the document exists, false if not * @throws DocumentException If any is encountered */ - public static function byId(string $tableName, mixed $docId, ?PDO $pdo = null): bool + public static function byId(string $tableName, mixed $docId): bool { - return Custom::scalar(Query\Exists::byId($tableName), Parameters::id($docId), new ExistsMapper(), $pdo); + return Custom::scalar(Query\Exists::byId($tableName), Parameters::id($docId), new ExistsMapper()); } /** @@ -29,16 +27,14 @@ class Exists * * @param string $tableName The name of the table in which document existence should be determined * @param Field[] $fields The field comparison to match - * @param PDO|null $pdo The database connection to use (optional; will obtain one if not provided) * @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`) * @return bool True if any documents match the field comparison, false if not * @throws DocumentException If any is encountered */ - public static function byFields(string $tableName, array $fields, ?PDO $pdo = null, - string $conjunction = 'AND'): bool + public static function byFields(string $tableName, array $fields, string $conjunction = 'AND'): bool { $namedFields = Parameters::nameFields($fields); return Custom::scalar(Query\Exists::byFields($tableName, $namedFields, $conjunction), - Parameters::addFields($namedFields, []), new ExistsMapper(), $pdo); + Parameters::addFields($namedFields, []), new ExistsMapper()); } } diff --git a/src/Patch.php b/src/Patch.php index 9bbbaa9..98e5378 100644 --- a/src/Patch.php +++ b/src/Patch.php @@ -2,8 +2,6 @@ namespace BitBadger\PDODocument; -use PDO; - /** * Functions to patch (partially update) documents */ @@ -15,13 +13,12 @@ class Patch * @param string $tableName The table in which the document should be patched * @param mixed $docId The ID of the document to be patched * @param array|object $patch The object with which the document should be patched (will be JSON-encoded) - * @param PDO|null $pdo The database connection to use (optional; will obtain one if not provided) * @throws DocumentException If any is encountered (database mode must be set) */ - public static function byId(string $tableName, mixed $docId, array|object $patch, ?PDO $pdo = null): void + public static function byId(string $tableName, mixed $docId, array|object $patch): void { Custom::nonQuery(Query\Patch::byId($tableName), - array_merge(Parameters::id($docId), Parameters::json(':data', $patch)), $pdo); + array_merge(Parameters::id($docId), Parameters::json(':data', $patch))); } /** @@ -30,15 +27,14 @@ class Patch * @param string $tableName The table in which documents should be patched * @param array|Field[] $fields The field comparison to match * @param array|object $patch The object with which the documents should be patched (will be JSON-encoded) - * @param PDO|null $pdo The database connection to use (optional; will obtain one if not provided) * @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`) * @throws DocumentException If any is encountered */ - public static function byFields(string $tableName, array $fields, array|object $patch, ?PDO $pdo = null, + public static function byFields(string $tableName, array $fields, array|object $patch, string $conjunction = 'AND'): void { $namedFields = Parameters::nameFields($fields); Custom::nonQuery(Query\Patch::byFields($tableName, $namedFields, $conjunction), - Parameters::addFields($namedFields, Parameters::json(':data', $patch)), $pdo); + Parameters::addFields($namedFields, Parameters::json(':data', $patch))); } } diff --git a/src/RemoveFields.php b/src/RemoveFields.php index 4432c0f..b32e2f4 100644 --- a/src/RemoveFields.php +++ b/src/RemoveFields.php @@ -2,8 +2,6 @@ namespace BitBadger\PDODocument; -use PDO; - /** * Functions to remove fields from documents */ @@ -15,14 +13,13 @@ class RemoveFields * @param string $tableName The table in which the document should have fields removed * @param mixed $docId The ID of the document from which fields should be removed * @param array|string[] $fieldNames The names of the fields to be removed - * @param PDO|null $pdo The database connection to use (optional; will obtain one if not provided) * @throws DocumentException If any is encountered */ - public static function byId(string $tableName, mixed $docId, array $fieldNames, ?PDO $pdo = null): void + public static function byId(string $tableName, mixed $docId, array $fieldNames): void { $nameParams = Parameters::fieldNames(':name', $fieldNames); Custom::nonQuery(Query\RemoveFields::byId($tableName, $nameParams), - array_merge(Parameters::id($docId), $nameParams), $pdo); + array_merge(Parameters::id($docId), $nameParams)); } /** @@ -31,16 +28,15 @@ class RemoveFields * @param string $tableName The table in which documents should have fields removed * @param array|Field[] $fields The field comparison to match * @param array|string[] $fieldNames The names of the fields to be removed - * @param PDO|null $pdo The database connection to use (optional; will obtain one if not provided) * @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`) * @throws DocumentException If any is encountered */ - public static function byFields(string $tableName, array $fields, array $fieldNames, ?PDO $pdo = null, + public static function byFields(string $tableName, array $fields, array $fieldNames, string $conjunction = 'AND'): void { $nameParams = Parameters::fieldNames(':name', $fieldNames); $namedFields = Parameters::nameFields($fields); Custom::nonQuery(Query\RemoveFields::byFields($tableName, $namedFields, $nameParams, $conjunction), - Parameters::addFields($namedFields, $nameParams), $pdo); + Parameters::addFields($namedFields, $nameParams)); } } -- 2.45.1 From 1ab961e35a1b2c07113c1903967f294251b37689 Mon Sep 17 00:00:00 2001 From: "Daniel J. Summers" Date: Fri, 7 Jun 2024 22:14:17 -0400 Subject: [PATCH 19/25] Change PDO to singleton instance - Add SQLite throwaway DB implementation - Add integration tests for Custom class --- composer.json | 3 +- composer.lock | 14 +-- src/Configuration.php | 6 ++ src/Custom.php | 11 +- src/Mapper/StringMapper.php | 2 +- tests/integration/.gitkeep | 0 tests/integration/SubDocument.php | 11 ++ tests/integration/TestDocument.php | 9 ++ tests/integration/sqlite/CustomTest.php | 128 +++++++++++++++++++++++ tests/integration/sqlite/ThrowawayDb.php | 71 +++++++++++++ 10 files changed, 244 insertions(+), 11 deletions(-) delete mode 100644 tests/integration/.gitkeep create mode 100644 tests/integration/SubDocument.php create mode 100644 tests/integration/TestDocument.php create mode 100644 tests/integration/sqlite/CustomTest.php create mode 100644 tests/integration/sqlite/ThrowawayDb.php diff --git a/composer.json b/composer.json index a792038..3650240 100644 --- a/composer.json +++ b/composer.json @@ -17,7 +17,8 @@ "autoload-dev": { "psr-4": { "Test\\Unit\\": "./tests/unit", - "Test\\Integration\\": "./tests/integration" + "Test\\Integration\\": "./tests/integration", + "Test\\Integration\\SQLite\\": "./tests/integration/sqlite" } } } \ No newline at end of file diff --git a/composer.lock b/composer.lock index 50d47e2..3f0b880 100644 --- a/composer.lock +++ b/composer.lock @@ -619,16 +619,16 @@ }, { "name": "phpunit/phpunit", - "version": "11.1.3", + "version": "11.2.0", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/phpunit.git", - "reference": "d475be032238173ca3b0a516f5cc291d174708ae" + "reference": "705eba0190afe04bc057f565ad843267717cf109" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/d475be032238173ca3b0a516f5cc291d174708ae", - "reference": "d475be032238173ca3b0a516f5cc291d174708ae", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/705eba0190afe04bc057f565ad843267717cf109", + "reference": "705eba0190afe04bc057f565ad843267717cf109", "shasum": "" }, "require": { @@ -667,7 +667,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-main": "11.1-dev" + "dev-main": "11.2-dev" } }, "autoload": { @@ -699,7 +699,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/phpunit/issues", "security": "https://github.com/sebastianbergmann/phpunit/security/policy", - "source": "https://github.com/sebastianbergmann/phpunit/tree/11.1.3" + "source": "https://github.com/sebastianbergmann/phpunit/tree/11.2.0" }, "funding": [ { @@ -715,7 +715,7 @@ "type": "tidelift" } ], - "time": "2024-04-24T06:34:25+00:00" + "time": "2024-06-07T04:48:50+00:00" }, { "name": "sebastian/cli-parser", diff --git a/src/Configuration.php b/src/Configuration.php index b562e7b..c12a6ae 100644 --- a/src/Configuration.php +++ b/src/Configuration.php @@ -58,4 +58,10 @@ class Configuration return self::$_pdo; } + + + public static function resetPDO(): void + { + self::$_pdo = null; + } } diff --git a/src/Custom.php b/src/Custom.php index 5ba6663..740868b 100644 --- a/src/Custom.php +++ b/src/Custom.php @@ -4,6 +4,7 @@ namespace BitBadger\PDODocument; use BitBadger\PDODocument\Mapper\Mapper; use PDO; +use PDOException; use PDOStatement; /** @@ -22,7 +23,13 @@ class Custom public static function &runQuery(string $query, array $parameters): PDOStatement { $debug = defined('PDO_DOC_DEBUG_SQL'); - $stmt = Configuration::dbConn()->prepare($query); + try { + $stmt = Configuration::dbConn()->prepare($query); + } catch (PDOException $ex) { + $keyword = explode(' ', $query, 2)[0]; + throw new DocumentException("Error executing $keyword statement: " . Configuration::dbConn()->errorCode(), + previous: $ex); + } foreach ($parameters as $key => $value) { if ($debug) echo "
Binding $value to $key\n
"; $dataType = match (true) { @@ -115,7 +122,7 @@ class Custom * @return mixed|false|T The scalar value if found, false if not * @throws DocumentException If any is encountered */ - public static function scalar(string $query, array $parameters, Mapper $mapper, ?PDO $pdo = null): mixed + public static function scalar(string $query, array $parameters, Mapper $mapper): mixed { try { $stmt = &self::runQuery($query, $parameters); diff --git a/src/Mapper/StringMapper.php b/src/Mapper/StringMapper.php index 3ed781f..c923fc5 100644 --- a/src/Mapper/StringMapper.php +++ b/src/Mapper/StringMapper.php @@ -3,7 +3,7 @@ namespace BitBadger\PDODocument\Mapper; /** - * Map a string result from the given + * Map a string result from the * * @implements Mapper */ diff --git a/tests/integration/.gitkeep b/tests/integration/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/tests/integration/SubDocument.php b/tests/integration/SubDocument.php new file mode 100644 index 0000000..3c5eb58 --- /dev/null +++ b/tests/integration/SubDocument.php @@ -0,0 +1,11 @@ +dbName = ThrowawayDb::create(); + } + + public function tearDown(): void + { + ThrowawayDb::destroy($this->dbName); + } + + public function testRunQuerySucceedsWithAValidQuery() + { + $stmt = &Custom::runQuery('SELECT data FROM ' . ThrowawayDb::TABLE . ' LIMIT 1', []); + try { + $this->assertNotNull($stmt, 'The statement should not have been null'); + } finally { + $stmt = null; + } + } + + public function testRunQueryFailsWithAnInvalidQuery() + { + $this->expectException(DocumentException::class); + $stmt = &Custom::runQuery('GRAB stuff FROM over_there UNTIL done', []); + try { + $this->assertTrue(false, 'This code should not be reached'); + } finally { + $stmt = null; + } + } + + public function testListSucceedsWhenDataIsFound() + { + $list = Custom::list(Query::selectFromTable(ThrowawayDb::TABLE), [], new DocumentMapper(TestDocument::class)); + $this->assertNotNull($list, 'The document list should not be null'); + $count = 0; + foreach ($list->items() as $ignored) $count++; + $this->assertEquals(5, $count, 'There should have been 5 documents in the list'); + } + + public function testListSucceedsWhenNoDataIsFound() + { + $list = Custom::list(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'num_value' > :value", + [':value' => 100], new DocumentMapper(TestDocument::class)); + $this->assertNotNull($list, 'The document list should not be null'); + $count = 0; + foreach ($list->items() as $ignored) $count++; + $this->assertEquals(0, $count, 'There should have been no documents in the list'); + } + + public function testArraySucceedsWhenDataIsFound() + { + $array = Custom::array(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'sub' IS NOT NULL", [], + new DocumentMapper(TestDocument::class)); + $this->assertNotNull($array, 'The document array should not be null'); + $this->assertCount(2, $array, 'There should have been 2 documents in the array'); + } + + public function testArraySucceedsWhenNoDataIsFound() + { + $array = Custom::array(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'value' = :value", + [':value' => 'not there'], new DocumentMapper(TestDocument::class)); + $this->assertNotNull($array, 'The document array should not be null'); + $this->assertCount(0, $array, 'There should have been no documents in the array'); + } + + public function testSingleSucceedsWhenARowIsFound(): void + { + $doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id", [':id' => 'one'], + new DocumentMapper(TestDocument::class)); + $this->assertNotNull($doc, 'There should have been a document returned'); + $this->assertEquals('one', $doc->id, 'The incorrect document was returned'); + } + + public function testSingleSucceedsWhenARowIsNotFound(): void + { + $doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id", + [':id' => 'eighty'], new DocumentMapper(TestDocument::class)); + $this->assertFalse($doc, 'There should not have been a document returned'); + } + + public function testNonQuerySucceedsWhenOperatingOnData() + { + Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []); + try { + $remaining = Count::all(ThrowawayDb::TABLE); + $this->assertEquals(0, $remaining, 'There should be no documents remaining in the table'); + } finally { + $this->dbName = ThrowawayDb::exchange($this->dbName); + } + } + + public function testNonQuerySucceedsWhenNoDataMatchesWhereClause() + { + Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE . " WHERE data->>'num_value' > :value", [':value' => 100]); + $remaining = Count::all(ThrowawayDb::TABLE); + $this->assertEquals(5, $remaining, 'There should be 5 documents remaining in the table'); + } + + public function testScalarSucceeds() + { + $value = Custom::scalar("SELECT 5 AS it", [], new CountMapper()); + $this->assertEquals(5, $value, 'The scalar value was not returned correctly'); + } +} diff --git a/tests/integration/sqlite/ThrowawayDb.php b/tests/integration/sqlite/ThrowawayDb.php new file mode 100644 index 0000000..5a3ab64 --- /dev/null +++ b/tests/integration/sqlite/ThrowawayDb.php @@ -0,0 +1,71 @@ + Date: Fri, 7 Jun 2024 23:06:31 -0400 Subject: [PATCH 20/25] Add SQLite Patch integration tests - Use multiple-class use statements --- src/Custom.php | 4 +- src/Mapper/ExistsMapper.php | 4 +- src/Query/Count.php | 3 +- src/Query/Definition.php | 4 +- src/Query/Delete.php | 3 +- src/Query/Exists.php | 3 +- src/Query/Find.php | 3 +- src/Query/Patch.php | 6 +-- src/Query/RemoveFields.php | 6 +-- tests/integration/sqlite/CustomTest.php | 17 ++---- tests/integration/sqlite/DefinitionTest.php | 58 ++++++++++++++++++++ tests/integration/sqlite/PatchTest.php | 59 +++++++++++++++++++++ tests/unit/ConfigurationTest.php | 4 +- tests/unit/FieldTest.php | 3 +- tests/unit/Mapper/DocumentMapperTest.php | 3 +- tests/unit/Mapper/ExistsMapperTest.php | 4 +- tests/unit/ParametersTest.php | 8 +-- tests/unit/Query/DefinitionTest.php | 4 +- tests/unit/Query/PatchTest.php | 5 +- tests/unit/Query/RemoveFieldsTest.php | 6 +-- tests/unit/QueryTest.php | 3 +- 21 files changed, 143 insertions(+), 67 deletions(-) create mode 100644 tests/integration/sqlite/DefinitionTest.php create mode 100644 tests/integration/sqlite/PatchTest.php diff --git a/src/Custom.php b/src/Custom.php index 740868b..00494e0 100644 --- a/src/Custom.php +++ b/src/Custom.php @@ -27,7 +27,9 @@ class Custom $stmt = Configuration::dbConn()->prepare($query); } catch (PDOException $ex) { $keyword = explode(' ', $query, 2)[0]; - throw new DocumentException("Error executing $keyword statement: " . Configuration::dbConn()->errorCode(), + throw new DocumentException( + sprintf("Error executing %s statement: [%s] %s", $keyword, Configuration::dbConn()->errorCode(), + Configuration::dbConn()->errorInfo()[2]), previous: $ex); } foreach ($parameters as $key => $value) { diff --git a/src/Mapper/ExistsMapper.php b/src/Mapper/ExistsMapper.php index 4f7ec2c..7668318 100644 --- a/src/Mapper/ExistsMapper.php +++ b/src/Mapper/ExistsMapper.php @@ -2,9 +2,7 @@ namespace BitBadger\PDODocument\Mapper; -use BitBadger\PDODocument\Configuration; -use BitBadger\PDODocument\DocumentException; -use BitBadger\PDODocument\Mode; +use BitBadger\PDODocument\{Configuration, DocumentException, Mode}; /** * Map an EXISTS result to a boolean value diff --git a/src/Query/Count.php b/src/Query/Count.php index cc112f0..87c47e3 100644 --- a/src/Query/Count.php +++ b/src/Query/Count.php @@ -2,8 +2,7 @@ namespace BitBadger\PDODocument\Query; -use BitBadger\PDODocument\Field; -use BitBadger\PDODocument\Query; +use BitBadger\PDODocument\{Field, Query}; /** * Queries for counting documents diff --git a/src/Query/Definition.php b/src/Query/Definition.php index 4399310..6e584f5 100644 --- a/src/Query/Definition.php +++ b/src/Query/Definition.php @@ -2,9 +2,7 @@ namespace BitBadger\PDODocument\Query; -use BitBadger\PDODocument\Configuration; -use BitBadger\PDODocument\DocumentException; -use BitBadger\PDODocument\Mode; +use BitBadger\PDODocument\{Configuration, DocumentException, Mode}; /** * Queries to define tables and indexes diff --git a/src/Query/Delete.php b/src/Query/Delete.php index d171bb7..84bd2a0 100644 --- a/src/Query/Delete.php +++ b/src/Query/Delete.php @@ -2,8 +2,7 @@ namespace BitBadger\PDODocument\Query; -use BitBadger\PDODocument\Field; -use BitBadger\PDODocument\Query; +use BitBadger\PDODocument\{Field, Query}; /** * Queries to delete documents diff --git a/src/Query/Exists.php b/src/Query/Exists.php index ba6d47d..a7750b1 100644 --- a/src/Query/Exists.php +++ b/src/Query/Exists.php @@ -2,8 +2,7 @@ namespace BitBadger\PDODocument\Query; -use BitBadger\PDODocument\Field; -use BitBadger\PDODocument\Query; +use BitBadger\PDODocument\{Field, Query}; /** * Queries to determine document existence diff --git a/src/Query/Find.php b/src/Query/Find.php index dcc08be..2e65385 100644 --- a/src/Query/Find.php +++ b/src/Query/Find.php @@ -2,8 +2,7 @@ namespace BitBadger\PDODocument\Query; -use BitBadger\PDODocument\Field; -use BitBadger\PDODocument\Query; +use BitBadger\PDODocument\{Field, Query}; /** * Queries for retrieving documents diff --git a/src/Query/Patch.php b/src/Query/Patch.php index 7f63253..6b1ab76 100644 --- a/src/Query/Patch.php +++ b/src/Query/Patch.php @@ -2,11 +2,7 @@ namespace BitBadger\PDODocument\Query; -use BitBadger\PDODocument\Configuration; -use BitBadger\PDODocument\DocumentException; -use BitBadger\PDODocument\Field; -use BitBadger\PDODocument\Mode; -use BitBadger\PDODocument\Query; +use BitBadger\PDODocument\{Configuration, DocumentException, Field, Mode, Query}; /** * Queries to perform partial updates on documents diff --git a/src/Query/RemoveFields.php b/src/Query/RemoveFields.php index 46c1bcb..0e3fea0 100644 --- a/src/Query/RemoveFields.php +++ b/src/Query/RemoveFields.php @@ -2,11 +2,7 @@ namespace BitBadger\PDODocument\Query; -use BitBadger\PDODocument\Configuration; -use BitBadger\PDODocument\DocumentException; -use BitBadger\PDODocument\Field; -use BitBadger\PDODocument\Mode; -use BitBadger\PDODocument\Query; +use BitBadger\PDODocument\{Configuration, DocumentException, Field, Mode, Query}; /** * Queries to remove fields from documents diff --git a/tests/integration/sqlite/CustomTest.php b/tests/integration/sqlite/CustomTest.php index 3155e72..31c1d74 100644 --- a/tests/integration/sqlite/CustomTest.php +++ b/tests/integration/sqlite/CustomTest.php @@ -2,13 +2,8 @@ namespace Test\Integration\SQLite; -use BitBadger\PDODocument\Count; -use BitBadger\PDODocument\Custom; -use BitBadger\PDODocument\DocumentException; -use BitBadger\PDODocument\Mapper\CountMapper; -use BitBadger\PDODocument\Mapper\DocumentMapper; -use BitBadger\PDODocument\Mapper\StringMapper; -use BitBadger\PDODocument\Query; +use BitBadger\PDODocument\{Count, Custom, DocumentException, Query}; +use BitBadger\PDODocument\Mapper\{CountMapper, DocumentMapper}; use PHPUnit\Framework\TestCase; use Test\Integration\TestDocument; @@ -105,12 +100,8 @@ class CustomTest extends TestCase public function testNonQuerySucceedsWhenOperatingOnData() { Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []); - try { - $remaining = Count::all(ThrowawayDb::TABLE); - $this->assertEquals(0, $remaining, 'There should be no documents remaining in the table'); - } finally { - $this->dbName = ThrowawayDb::exchange($this->dbName); - } + $remaining = Count::all(ThrowawayDb::TABLE); + $this->assertEquals(0, $remaining, 'There should be no documents remaining in the table'); } public function testNonQuerySucceedsWhenNoDataMatchesWhereClause() diff --git a/tests/integration/sqlite/DefinitionTest.php b/tests/integration/sqlite/DefinitionTest.php new file mode 100644 index 0000000..44f248e --- /dev/null +++ b/tests/integration/sqlite/DefinitionTest.php @@ -0,0 +1,58 @@ +dbName = ThrowawayDb::create(withData: false); + } + + protected function tearDown(): void + { + ThrowawayDb::destroy($this->dbName); + parent::tearDown(); + } + + /** + * Does the given named object exist in the database? + * + * @param string $name The name of the object whose existence should be verified + * @return bool True if the object exists, false if not + * @throws DocumentException If any is encountered + */ + private function itExists(string $name): bool + { + return Custom::scalar('SELECT EXISTS (SELECT 1 FROM sqlite_master WHERE name = :name)', + [':name' => $name], new ExistsMapper()); + } + + public function testEnsureTableSucceeds() + { + $this->assertFalse($this->itExists('ensured'), 'The table should not exist already'); + $this->assertFalse($this->itExists('idx_ensured_key'), 'The key index should not exist already'); + Definition::ensureTable('ensured'); + $this->assertTrue($this->itExists('ensured'), 'The table should now exist'); + $this->assertTrue($this->itExists('idx_ensured_key'), 'The key index should now exist'); + } + + public function testEnsureFieldIndexSucceeds() + { + $this->assertFalse($this->itExists('idx_ensured_test'), 'The index should not exist already'); + Definition::ensureTable('ensured'); + Definition::ensureFieldIndex('ensured', 'test', ['name', 'age']); + $this->assertTrue($this->itExists('idx_ensured_test'), 'The index should now exist'); + } +} diff --git a/tests/integration/sqlite/PatchTest.php b/tests/integration/sqlite/PatchTest.php new file mode 100644 index 0000000..b891501 --- /dev/null +++ b/tests/integration/sqlite/PatchTest.php @@ -0,0 +1,59 @@ +dbName = ThrowawayDb::create(); + } + + protected function tearDown(): void + { + ThrowawayDb::destroy($this->dbName); + parent::tearDown(); + } + + #[TestDox('By ID succeeds when a document is updated')] + public function testByIdSucceedsWhenADocumentIsUpdated(): void + { + Patch::byId(ThrowawayDb::TABLE, 'one', ['num_value' => 44]); + $doc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class); + $this->assertNotFalse($doc, 'There should have been a document returned'); + $this->assertEquals(44, $doc->num_value, 'The updated document is not correct'); + } + + #[TestDox('By ID succeeds when no document is updated')] + public function testByIdSucceedsWhenNoDocumentIsUpdated(): void + { + Patch::byId(ThrowawayDb::TABLE, 'forty-seven', ['foo' => 'green']); + $this->assertTrue(true, 'The above not throwing an exception is the test'); + } + + + public function testByFieldsSucceedsWhenADocumentIsUpdated(): void + { + Patch::byFields(ThrowawayDb::TABLE, [Field::EQ('value', 'purple')], ['num_value' => 77]); + $after = Count::byFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 77)]); + $this->assertEquals(2, $after, 'There should have been 2 documents updated'); + } + + public function testByFieldsSucceedsWhenNoDocumentIsUpdated(): void + { + Patch::byFields(ThrowawayDb::TABLE, [Field::EQ('value', 'burgundy')], ['foo' => 'green']); + $this->assertTrue(true, 'The above not throwing an exception is the test'); + } +} diff --git a/tests/unit/ConfigurationTest.php b/tests/unit/ConfigurationTest.php index 6ff0c09..1416ceb 100644 --- a/tests/unit/ConfigurationTest.php +++ b/tests/unit/ConfigurationTest.php @@ -2,8 +2,7 @@ namespace Test\Unit; -use BitBadger\PDODocument\Configuration; -use BitBadger\PDODocument\DocumentException; +use BitBadger\PDODocument\{Configuration, DocumentException}; use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; @@ -34,6 +33,7 @@ class ConfigurationTest extends TestCase public function testDbConnFailsWhenNoDSNSpecified(): void { $this->expectException(DocumentException::class); + Configuration::$pdoDSN = ''; Configuration::dbConn(); } } diff --git a/tests/unit/FieldTest.php b/tests/unit/FieldTest.php index 8294534..f2f76e3 100644 --- a/tests/unit/FieldTest.php +++ b/tests/unit/FieldTest.php @@ -2,8 +2,7 @@ namespace Test\Unit; -use BitBadger\PDODocument\Field; -use BitBadger\PDODocument\Op; +use BitBadger\PDODocument\{Field, Op}; use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; diff --git a/tests/unit/Mapper/DocumentMapperTest.php b/tests/unit/Mapper/DocumentMapperTest.php index 2fa3af5..5213312 100644 --- a/tests/unit/Mapper/DocumentMapperTest.php +++ b/tests/unit/Mapper/DocumentMapperTest.php @@ -2,8 +2,7 @@ namespace Test\Unit\Mapper; -use BitBadger\PDODocument\DocumentException; -use BitBadger\PDODocument\Field; +use BitBadger\PDODocument\{DocumentException, Field}; use BitBadger\PDODocument\Mapper\DocumentMapper; use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; diff --git a/tests/unit/Mapper/ExistsMapperTest.php b/tests/unit/Mapper/ExistsMapperTest.php index ce68908..1dbaf02 100644 --- a/tests/unit/Mapper/ExistsMapperTest.php +++ b/tests/unit/Mapper/ExistsMapperTest.php @@ -2,10 +2,8 @@ namespace Test\Unit\Mapper; -use BitBadger\PDODocument\Configuration; -use BitBadger\PDODocument\DocumentException; +use BitBadger\PDODocument\{Configuration, DocumentException, Mode}; use BitBadger\PDODocument\Mapper\ExistsMapper; -use BitBadger\PDODocument\Mode; use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; diff --git a/tests/unit/ParametersTest.php b/tests/unit/ParametersTest.php index 1bf0ec0..be9d236 100644 --- a/tests/unit/ParametersTest.php +++ b/tests/unit/ParametersTest.php @@ -1,12 +1,8 @@ Date: Fri, 7 Jun 2024 23:35:48 -0400 Subject: [PATCH 21/25] Add Count and Document SQLite integration tests --- src/Custom.php | 7 +- tests/integration/sqlite/CountTest.php | 42 ++++++++++++ tests/integration/sqlite/DocumentTest.php | 82 +++++++++++++++++++++++ 3 files changed, 130 insertions(+), 1 deletion(-) create mode 100644 tests/integration/sqlite/CountTest.php create mode 100644 tests/integration/sqlite/DocumentTest.php diff --git a/src/Custom.php b/src/Custom.php index 00494e0..e4d2300 100644 --- a/src/Custom.php +++ b/src/Custom.php @@ -43,7 +43,12 @@ class Custom $stmt->bindValue($key, $value, $dataType); } if ($debug) echo '
SQL: ' . $stmt->queryString . '
'; - if ($stmt->execute()) return $stmt; + try { + if ($stmt->execute()) return $stmt; + } catch (PDOException $ex) { + $keyword = explode(' ', $query, 2)[0]; + throw new DocumentException("Error executing $keyword statement: " . $stmt->errorCode(), previous: $ex); + } $keyword = explode(' ', $query, 2)[0]; throw new DocumentException("Error executing $keyword statement: " . $stmt->errorCode()); } diff --git a/tests/integration/sqlite/CountTest.php b/tests/integration/sqlite/CountTest.php new file mode 100644 index 0000000..30e3c0d --- /dev/null +++ b/tests/integration/sqlite/CountTest.php @@ -0,0 +1,42 @@ +dbName = ThrowawayDb::create(); + } + + protected function tearDown(): void + { + ThrowawayDb::destroy($this->dbName); + parent::tearDown(); + } + + public function testAllSucceeds(): void + { + $count = Count::all(ThrowawayDb::TABLE); + $this->assertEquals(5, $count, 'There should have been 5 matching documents'); + } + + public function testByFieldsSucceedsForANumericRange(): void + { + $count = Count::byFields(ThrowawayDb::TABLE, [Field::BT('num_value', 10, 20)]); + $this->assertEquals(3, $count, 'There should have been 3 matching documents'); + } + + public function testByFieldsSucceedsForANonNumericRange(): void + { + $count = Count::byFields(ThrowawayDb::TABLE, [Field::BT('value', 'aardvark', 'apple')]); + $this->assertEquals(1, $count, 'There should have been 1 matching document'); + } +} diff --git a/tests/integration/sqlite/DocumentTest.php b/tests/integration/sqlite/DocumentTest.php new file mode 100644 index 0000000..ca5309b --- /dev/null +++ b/tests/integration/sqlite/DocumentTest.php @@ -0,0 +1,82 @@ +dbName = ThrowawayDb::create(); + } + + protected function tearDown(): void + { + ThrowawayDb::destroy($this->dbName); + parent::tearDown(); + } + + public function testInsertSucceeds(): void + { + Document::insert(ThrowawayDb::TABLE, new TestDocument('turkey', sub: new SubDocument('gobble', 'gobble'))); + $doc = Find::byId(ThrowawayDb::TABLE, 'turkey', TestDocument::class); + $this->assertNotFalse($doc, 'There should have been a document inserted'); + $this->assertEquals('turkey', $doc->id, 'The ID was incorrect'); + $this->assertEquals('', $doc->value, 'The value was incorrect'); + $this->assertEquals(0, $doc->num_value, 'The numeric value was incorrect'); + $this->assertNotNull($doc->sub, 'The sub-document should not have been null'); + $this->assertEquals('gobble', $doc->sub->foo, 'The sub-document foo property was incorrect'); + $this->assertEquals('gobble', $doc->sub->bar, 'The sub-document bar property was incorrect'); + } + + public function testInsertFailsForDuplicateKey(): void + { + $this->expectException(DocumentException::class); + Document::insert(ThrowawayDb::TABLE, new TestDocument('one')); + } + + public function testSaveSucceedsWhenADocumentIsInserted(): void + { + Document::save(ThrowawayDb::TABLE, new TestDocument('test', sub: new SubDocument('a', 'b'))); + $doc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class); + $this->assertNotFalse($doc, 'There should have been a document returned'); + } + + public function testSaveSucceedsWhenADocumentIsUpdated(): void + { + Document::save(ThrowawayDb::TABLE, new TestDocument('two', num_value: 44)); + $doc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class); + $this->assertNotFalse($doc, 'There should have been a document returned'); + $this->assertEquals(44, $doc->num_value, 'The numeric value was not updated'); + $this->assertNull($doc->sub, 'The sub-document should have been null'); + } + + public function testUpdateSucceedsWhenReplacingADocument(): void + { + Document::update(ThrowawayDb::TABLE, 'one', new TestDocument('one', 'howdy', 8, new SubDocument('y', 'z'))); + $doc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class); + $this->assertNotFalse($doc, 'There should have been a document returned'); + $this->assertEquals('howdy', $doc->value, 'The value was incorrect'); + $this->assertEquals(8, $doc->num_value, 'The numeric value was incorrect'); + $this->assertNotNull($doc->sub, 'The sub-document should not have been null'); + $this->assertEquals('y', $doc->sub->foo, 'The sub-document foo property was incorrect'); + $this->assertEquals('z', $doc->sub->bar, 'The sub-document bar property was incorrect'); + } + + public function testUpdateSucceedsWhenNoDocumentIsReplaced(): void + { + Document::update(ThrowawayDb::TABLE, 'two-hundred', new TestDocument('200')); + $doc = Find::byId(ThrowawayDb::TABLE, 'two-hundred', TestDocument::class); + $this->assertFalse($doc, 'There should not have been a document returned'); + } +} -- 2.45.1 From 2d8f8b6e8728f8fbe0d801e2bc529a678f65ad9b Mon Sep 17 00:00:00 2001 From: "Daniel J. Summers" Date: Sat, 8 Jun 2024 10:49:52 -0400 Subject: [PATCH 22/25] Finish tests - Add sub-doc handling for SQLite fields - Add casting for PostgreSQL BT on numeric value - Add hasItems() to DocumentList - Fix SQL syntax problems exposed by tests --- src/Custom.php | 4 +- src/DocumentList.php | 36 ++- src/Field.php | 14 +- src/Parameters.php | 2 +- tests/integration/sqlite/CountTest.php | 5 + tests/integration/sqlite/CustomTest.php | 6 +- tests/integration/sqlite/DefinitionTest.php | 2 + tests/integration/sqlite/DeleteTest.php | 59 +++++ tests/integration/sqlite/DocumentListTest.php | 73 ++++++ tests/integration/sqlite/DocumentTest.php | 2 + tests/integration/sqlite/ExistsTest.php | 54 ++++ tests/integration/sqlite/FindTest.php | 100 ++++++++ tests/integration/sqlite/PatchTest.php | 1 + tests/integration/sqlite/RemoveFieldsTest.php | 74 ++++++ tests/unit/FieldTest.php | 240 ++++++++++++++++-- tests/unit/ParametersTest.php | 2 +- tests/unit/Query/CountTest.php | 11 +- tests/unit/Query/DeleteTest.php | 12 +- tests/unit/Query/ExistsTest.php | 12 +- tests/unit/Query/FindTest.php | 12 +- tests/unit/QueryTest.php | 12 +- 21 files changed, 691 insertions(+), 42 deletions(-) create mode 100644 tests/integration/sqlite/DeleteTest.php create mode 100644 tests/integration/sqlite/DocumentListTest.php create mode 100644 tests/integration/sqlite/ExistsTest.php create mode 100644 tests/integration/sqlite/FindTest.php create mode 100644 tests/integration/sqlite/RemoveFieldsTest.php diff --git a/src/Custom.php b/src/Custom.php index e4d2300..8644cda 100644 --- a/src/Custom.php +++ b/src/Custom.php @@ -47,7 +47,9 @@ class Custom if ($stmt->execute()) return $stmt; } catch (PDOException $ex) { $keyword = explode(' ', $query, 2)[0]; - throw new DocumentException("Error executing $keyword statement: " . $stmt->errorCode(), previous: $ex); + throw new DocumentException( + sprintf("Error executing %s statement: [%s] %s", $keyword, $stmt->errorCode(), $stmt->errorInfo()[2]), + previous: $ex); } $keyword = explode(' ', $query, 2)[0]; throw new DocumentException("Error executing $keyword statement: " . $stmt->errorCode()); diff --git a/src/DocumentList.php b/src/DocumentList.php index 44ec060..5c4c011 100644 --- a/src/DocumentList.php +++ b/src/DocumentList.php @@ -15,13 +15,23 @@ use PDOStatement; */ class DocumentList { + /** @var TDoc|null $_first The first item from the results */ + private mixed $_first = null; + /** * Constructor * * @param PDOStatement|null $result The result of the query * @param Mapper $mapper The mapper to deserialize JSON */ - private function __construct(private ?PDOStatement &$result, private readonly Mapper $mapper) { } + private function __construct(private ?PDOStatement &$result, private readonly Mapper $mapper) + { + if ($row = $this->result->fetch(PDO::FETCH_ASSOC)) { + $this->_first = $this->mapper->map($row); + } else { + $this->result = null; + } + } /** * Construct a new document list @@ -45,9 +55,29 @@ class DocumentList */ public function items(): Generator { - if ($this->result) { - while ($row = $this->result->fetch(PDO::FETCH_ASSOC)) yield $this->mapper->map($row); + if (!$this->result) return; + yield $this->_first; + while ($row = $this->result->fetch(PDO::FETCH_ASSOC)) { + yield $this->mapper->map($row); } $this->result = null; } + + /** + * Does this list have items remaining? + * + * @return bool True if there are items still to be retrieved from the list, false if not + */ + public function hasItems(): bool + { + return !is_null($this->result); + } + + /** + * Ensure the statement is destroyed if the generator is not exhausted + */ + public function __destruct() + { + if (!is_null($this->result)) $this->result = null; + } } diff --git a/src/Field.php b/src/Field.php index 38c7f10..04c4f68 100644 --- a/src/Field.php +++ b/src/Field.php @@ -48,6 +48,7 @@ class Field * Get the WHERE clause fragment for this parameter * * @return string The WHERE clause fragment for this parameter + * @throws DocumentException If the database mode has not been set */ public function toWhere(): string { @@ -57,7 +58,18 @@ class Field default => " $this->paramName" }; $prefix = $this->qualifier == '' ? '' : "$this->qualifier."; - return "{$prefix}data->>'$this->fieldName' " . $this->op->toString() . $criteria; + $fieldPath = match (Configuration::$mode) { + Mode::SQLite => "{$prefix}data->>'" + . (str_contains($this->fieldName, '.') + ? implode("'->>'", explode('.', $this->fieldName)) + : $this->fieldName) + . "'", + Mode::PgSQL => $this->op == Op::BT && is_numeric($this->value[0]) + ? "({$prefix}data->>'$this->fieldName')::numeric" + : "{$prefix}data->>'$this->fieldName'", + default => throw new DocumentException('Database mode not set; cannot make field WHERE clause') + }; + return $fieldPath . ' ' . $this->op->toString() . $criteria; } /** diff --git a/src/Parameters.php b/src/Parameters.php index 0d32fab..2e13830 100644 --- a/src/Parameters.php +++ b/src/Parameters.php @@ -72,7 +72,7 @@ class Parameters case Mode::SQLite: $it = []; $idx = 0; - foreach ($fieldNames as $field) $it[$paramName . $idx++] = $field; + foreach ($fieldNames as $field) $it[$paramName . $idx++] = "$.$field"; return $it; default: throw new DocumentException('Database mode not set; cannot generate field name parameters'); diff --git a/tests/integration/sqlite/CountTest.php b/tests/integration/sqlite/CountTest.php index 30e3c0d..259bf28 100644 --- a/tests/integration/sqlite/CountTest.php +++ b/tests/integration/sqlite/CountTest.php @@ -3,8 +3,13 @@ namespace Test\Integration\SQLite; use BitBadger\PDODocument\{Count, Field}; +use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; +/** + * SQLite integration tests for the Count class + */ +#[TestDox('Count (SQLite integration)')] class CountTest extends TestCase { /** @var string Database name for throwaway database */ diff --git a/tests/integration/sqlite/CustomTest.php b/tests/integration/sqlite/CustomTest.php index 31c1d74..bf83bdd 100644 --- a/tests/integration/sqlite/CustomTest.php +++ b/tests/integration/sqlite/CustomTest.php @@ -4,12 +4,14 @@ namespace Test\Integration\SQLite; use BitBadger\PDODocument\{Count, Custom, DocumentException, Query}; use BitBadger\PDODocument\Mapper\{CountMapper, DocumentMapper}; +use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; use Test\Integration\TestDocument; /** * SQLite Integration tests for the Custom class */ +#[TestDox('Custom (SQLite integration)')] class CustomTest extends TestCase { /** @var string Database name for throwaway database */ @@ -61,9 +63,7 @@ class CustomTest extends TestCase $list = Custom::list(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'num_value' > :value", [':value' => 100], new DocumentMapper(TestDocument::class)); $this->assertNotNull($list, 'The document list should not be null'); - $count = 0; - foreach ($list->items() as $ignored) $count++; - $this->assertEquals(0, $count, 'There should have been no documents in the list'); + $this->assertFalse($list->hasItems(), 'There should have been no documents in the list'); } public function testArraySucceedsWhenDataIsFound() diff --git a/tests/integration/sqlite/DefinitionTest.php b/tests/integration/sqlite/DefinitionTest.php index 44f248e..59b192f 100644 --- a/tests/integration/sqlite/DefinitionTest.php +++ b/tests/integration/sqlite/DefinitionTest.php @@ -4,11 +4,13 @@ namespace Test\Integration\SQLite; use BitBadger\PDODocument\{Custom, Definition, DocumentException}; use BitBadger\PDODocument\Mapper\ExistsMapper; +use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; /** * SQLite integration tests for the Definition class */ +#[TestDox('Definition (SQLite integration)')] class DefinitionTest extends TestCase { /** @var string Database name for throwaway database */ diff --git a/tests/integration/sqlite/DeleteTest.php b/tests/integration/sqlite/DeleteTest.php new file mode 100644 index 0000000..58a664a --- /dev/null +++ b/tests/integration/sqlite/DeleteTest.php @@ -0,0 +1,59 @@ +dbName = ThrowawayDb::create(); + } + + protected function tearDown(): void + { + ThrowawayDb::destroy($this->dbName); + parent::tearDown(); + } + + #[TestDox('By ID succeeds when a document is deleted')] + public function testByIdSucceedsWhenADocumentIsDeleted(): void + { + $this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start'); + Delete::byId(ThrowawayDb::TABLE, 'four'); + $this->assertEquals(4, Count::all(ThrowawayDb::TABLE), 'There should have been 4 documents remaining'); + } + + #[TestDox('By ID succeeds when a document is not deleted')] + public function testByIdSucceedsWhenADocumentIsNotDeleted(): void + { + $this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start'); + Delete::byId(ThrowawayDb::TABLE, 'negative four'); + $this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents remaining'); + } + + public function testByFieldsSucceedsWhenDocumentsAreDeleted(): void + { + $this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start'); + Delete::byFields(ThrowawayDb::TABLE, [Field::NE('value', 'purple')]); + $this->assertEquals(2, Count::all(ThrowawayDb::TABLE), 'There should have been 2 documents remaining'); + } + + public function testByFieldsSucceedsWhenDocumentsAreNotDeleted(): void + { + $this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start'); + Delete::byFields(ThrowawayDb::TABLE, [Field::EQ('value', 'crimson')]); + $this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents remaining'); + } +} diff --git a/tests/integration/sqlite/DocumentListTest.php b/tests/integration/sqlite/DocumentListTest.php new file mode 100644 index 0000000..08ff618 --- /dev/null +++ b/tests/integration/sqlite/DocumentListTest.php @@ -0,0 +1,73 @@ +dbName = ThrowawayDb::create(); + } + + protected function tearDown(): void + { + ThrowawayDb::destroy($this->dbName); + parent::tearDown(); + } + + public function testCreateSucceeds(): void + { + $list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [], + new DocumentMapper(TestDocument::class)); + $this->assertNotNull($list, 'There should have been a document list created'); + $list = null; + } + + public function testItems(): void + { + $list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [], + new DocumentMapper(TestDocument::class)); + $this->assertNotNull($list, 'There should have been a document list created'); + $count = 0; + foreach ($list->items() as $item) { + $this->assertContains($item->id, ['one', 'two', 'three', 'four', 'five'], + 'An unexpected document ID was returned'); + $count++; + } + $this->assertEquals(5, $count, 'There should have been 5 documents returned'); + } + + public function testHasItemsSucceedsWithEmptyResults(): void + { + $list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'num_value' < 0", [], + new DocumentMapper(TestDocument::class)); + $this->assertNotNull($list, 'There should have been a document list created'); + $this->assertFalse($list->hasItems(), 'There should be no items in the list'); + } + + public function testHasItemsSucceedsWithNonEmptyResults(): void + { + $list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [], + new DocumentMapper(TestDocument::class)); + $this->assertNotNull($list, 'There should have been a document list created'); + $this->assertTrue($list->hasItems(), 'There should be items in the list'); + foreach ($list->items() as $ignored) { + $this->assertTrue($list->hasItems(), 'There should be items remaining in the list'); + } + $this->assertFalse($list->hasItems(), 'There should be no remaining items in the list'); + } +} diff --git a/tests/integration/sqlite/DocumentTest.php b/tests/integration/sqlite/DocumentTest.php index ca5309b..2616633 100644 --- a/tests/integration/sqlite/DocumentTest.php +++ b/tests/integration/sqlite/DocumentTest.php @@ -3,12 +3,14 @@ namespace Test\Integration\SQLite; use BitBadger\PDODocument\{Document, DocumentException, Find}; +use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; use Test\Integration\{SubDocument, TestDocument}; /** * SQLite integration tests for the Document class */ +#[TestDox('Document (SQLite integration)')] class DocumentTest extends TestCase { /** @var string Database name for throwaway database */ diff --git a/tests/integration/sqlite/ExistsTest.php b/tests/integration/sqlite/ExistsTest.php new file mode 100644 index 0000000..0454b10 --- /dev/null +++ b/tests/integration/sqlite/ExistsTest.php @@ -0,0 +1,54 @@ +dbName = ThrowawayDb::create(); + } + + protected function tearDown(): void + { + ThrowawayDb::destroy($this->dbName); + parent::tearDown(); + } + + #[TestDox('By ID succeeds when a document exists')] + public function testByIdSucceedsWhenADocumentExists(): void + { + $this->assertTrue(Exists::byId(ThrowawayDb::TABLE, 'three'), 'There should have been an existing document'); + } + + #[TestDox('By ID succeeds when a document does not exist')] + public function testByIdSucceedsWhenADocumentDoesNotExist(): void + { + $this->assertFalse(Exists::byId(ThrowawayDb::TABLE, 'seven'), + 'There should not have been an existing document'); + } + + public function testByFieldsSucceedsWhenDocumentsExist(): void + { + $this->assertTrue(Exists::byFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 10)]), + 'There should have been existing documents'); + } + + public function testByFieldsSucceedsWhenNoMatchingDocumentsExist(): void + { + $this->assertFalse(Exists::byFields(ThrowawayDb::TABLE, [Field::LT('nothing', 'none')]), + 'There should not have been any existing documents'); + } +} diff --git a/tests/integration/sqlite/FindTest.php b/tests/integration/sqlite/FindTest.php new file mode 100644 index 0000000..7552a51 --- /dev/null +++ b/tests/integration/sqlite/FindTest.php @@ -0,0 +1,100 @@ +dbName = ThrowawayDb::create(); + } + + protected function tearDown(): void + { + ThrowawayDb::destroy($this->dbName); + parent::tearDown(); + } + + public function testAllSucceedsWhenThereIsData(): void + { + $docs = Find::all(ThrowawayDb::TABLE, TestDocument::class); + $this->assertNotNull($docs, 'There should have been a document list returned'); + $count = 0; + foreach ($docs->items() as $ignored) $count++; + $this->assertEquals(5, $count, 'There should have been 5 documents in the list'); + } + + public function testAllSucceedsWhenThereIsNoData(): void + { + Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []); + $docs = Find::all(ThrowawayDb::TABLE, TestDocument::class); + $this->assertNotNull($docs, 'There should have been a document list returned'); + $this->assertFalse($docs->hasItems(), 'There should have been no documents in the list'); + } + + #[TestDox('By ID succeeds when a document is found')] + public function testByIdSucceedsWhenADocumentIsFound(): void + { + $doc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class); + $this->assertNotFalse($doc, 'There should have been a document returned'); + $this->assertEquals('two', $doc->id, 'An incorrect document was returned'); + } + + #[TestDox('By ID succeeds when a document is not found')] + public function testByIdSucceedsWhenADocumentIsNotFound(): void + { + $doc = Find::byId(ThrowawayDb::TABLE, 'seventy-five', TestDocument::class); + $this->assertFalse($doc, 'There should not have been a document returned'); + } + + public function testByFieldsSucceedsWhenDocumentsAreFound(): void + { + $docs = Find::byFields(ThrowawayDb::TABLE, [Field::GT('num_value', 15)], TestDocument::class); + $this->assertNotNull($docs, 'There should have been a document list returned'); + $count = 0; + foreach ($docs->items() as $ignored) $count++; + $this->assertEquals(2, $count, 'There should have been 2 documents in the list'); + } + + public function testByFieldsSucceedsWhenNoDocumentsAreFound(): void + { + $docs = Find::byFields(ThrowawayDb::TABLE, [Field::GT('num_value', 100)], TestDocument::class); + $this->assertNotNull($docs, 'There should have been a document list returned'); + $count = 0; + foreach ($docs->items() as $ignored) $count++; + $this->assertFalse($docs->hasItems(), 'There should have been no documents in the list'); + } + + public function testFirstByFieldsSucceedsWhenADocumentIsFound(): void + { + $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'another')], TestDocument::class); + $this->assertNotFalse($doc, 'There should have been a document returned'); + $this->assertEquals('two', $doc->id, 'The incorrect document was returned'); + } + + public function testFirstByFieldsSucceedsWhenMultipleDocumentsAreFound(): void + { + $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('sub.foo', 'green')], TestDocument::class); + $this->assertNotFalse($doc, 'There should have been a document returned'); + $this->assertContains($doc->id, ['two', 'four'], 'An incorrect document was returned'); + } + + public function testFirstByFieldsSucceedsWhenADocumentIsNotFound(): void + { + $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'absent')], TestDocument::class); + $this->assertFalse($doc, 'There should not have been a document returned'); + } +} diff --git a/tests/integration/sqlite/PatchTest.php b/tests/integration/sqlite/PatchTest.php index b891501..ce64f24 100644 --- a/tests/integration/sqlite/PatchTest.php +++ b/tests/integration/sqlite/PatchTest.php @@ -10,6 +10,7 @@ use Test\Integration\TestDocument; /** * SQLite integration tests for the Patch class */ +#[TestDox('Patch (SQLite integration)')] class PatchTest extends TestCase { /** @var string Database name for throwaway database */ diff --git a/tests/integration/sqlite/RemoveFieldsTest.php b/tests/integration/sqlite/RemoveFieldsTest.php new file mode 100644 index 0000000..e1b3cf1 --- /dev/null +++ b/tests/integration/sqlite/RemoveFieldsTest.php @@ -0,0 +1,74 @@ +dbName = ThrowawayDb::create(); + } + + protected function tearDown(): void + { + ThrowawayDb::destroy($this->dbName); + parent::tearDown(); + } + + #[TestDox('By ID succeeds when fields are removed')] + public function testByIdSucceedsWhenFieldsAreRemoved(): void + { + RemoveFields::byId(ThrowawayDb::TABLE, 'two', ['sub', 'value']); + $doc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class); + $this->assertNotFalse($doc, 'There should have been a document returned'); + $this->assertEquals('', $doc->value, 'Value should have been blank (its default value)'); + $this->assertNull($doc->sub, 'Sub-document should have been null'); + } + + #[TestDox('By ID succeeds when a field is not removed')] + public function testByIdSucceedsWhenAFieldIsNotRemoved(): void + { + RemoveFields::byId(ThrowawayDb::TABLE, 'one', ['a_field_that_does_not_exist']); + $this->assertTrue(true, 'The above not throwing an exception is the test'); + } + + #[TestDox('By ID succeeds when no document is matched')] + public function testByIdSucceedsWhenNoDocumentIsMatched(): void + { + RemoveFields::byId(ThrowawayDb::TABLE, 'fifty', ['sub']); + $this->assertTrue(true, 'The above not throwing an exception is the test'); + } + + public function testByFieldsSucceedsWhenAFieldIsRemoved(): void + { + RemoveFields::byFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 17)], ['sub']); + $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 17)], TestDocument::class); + $this->assertNotFalse($doc, 'There should have been a document returned'); + $this->assertNull($doc->sub, 'Sub-document should have been null'); + } + + public function testByFieldsSucceedsWhenAFieldIsNotRemoved(): void + { + RemoveFields::byFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 17)], ['nada']); + $this->assertTrue(true, 'The above not throwing an exception is the test'); + } + + public function testByFieldsSucceedsWhenNoDocumentIsMatched(): void + { + RemoveFields::byFields(ThrowawayDb::TABLE, [Field::NE('missing', 'nope')], ['value']); + $this->assertTrue(true, 'The above not throwing an exception is the test'); + } +} diff --git a/tests/unit/FieldTest.php b/tests/unit/FieldTest.php index f2f76e3..421d131 100644 --- a/tests/unit/FieldTest.php +++ b/tests/unit/FieldTest.php @@ -2,7 +2,7 @@ namespace Test\Unit; -use BitBadger\PDODocument\{Field, Op}; +use BitBadger\PDODocument\{Configuration, Field, Mode, Op}; use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; @@ -36,46 +36,236 @@ class FieldTest extends TestCase 'Field parameter not returned correctly'); } - #[TestDox('To where succeeds for EX without qualifier')] - public function testToWhereSucceedsForEXWithoutQualifier(): void + #[TestDox('To where succeeds for EX without qualifier for PostgreSQL')] + public function testToWhereSucceedsForEXWithoutQualifierForPostgreSQL(): void { - $this->assertEquals("data->>'that_field' IS NOT NULL", Field::EX('that_field')->toWhere(), - 'WHERE fragment not generated correctly'); + Configuration::$mode = Mode::PgSQL; + try { + $this->assertEquals("data->>'that_field' IS NOT NULL", Field::EX('that_field')->toWhere(), + 'WHERE fragment not generated correctly'); + } finally { + Configuration::$mode = null; + } } - #[TestDox('To where succeeds for NEX without qualifier')] - public function testToWhereSucceedsForNEXWithoutQualifier(): void + #[TestDox('To where succeeds for EX without qualifier for SQLite')] + public function testToWhereSucceedsForEXWithoutQualifierForSQLite(): void { - $this->assertEquals("data->>'a_field' IS NULL", Field::NEX('a_field')->toWhere(), - 'WHERE fragment not generated correctly'); + Configuration::$mode = Mode::SQLite; + try { + $this->assertEquals("data->>'that_field' IS NOT NULL", Field::EX('that_field')->toWhere(), + 'WHERE fragment not generated correctly'); + } finally { + Configuration::$mode = null; + } } - #[TestDox('To where succeeds for BT without qualifier')] - public function testToWhereSucceedsForBTWithoutQualifier(): void + #[TestDox('To where succeeds for NEX without qualifier for PostgreSQL')] + public function testToWhereSucceedsForNEXWithoutQualifierForPostgreSQL(): void { - $this->assertEquals("data->>'age' BETWEEN @agemin AND @agemax", Field::BT('age', 13, 17, '@age')->toWhere(), - 'WHERE fragment not generated correctly'); + Configuration::$mode = Mode::PgSQL; + try { + $this->assertEquals("data->>'a_field' IS NULL", Field::NEX('a_field')->toWhere(), + 'WHERE fragment not generated correctly'); + } finally { + Configuration::$mode = null; + } } - public function testToWhereSucceedsForOthersWithoutQualifier(): void + #[TestDox('To where succeeds for NEX without qualifier for SQLite')] + public function testToWhereSucceedsForNEXWithoutQualifierForSQLite(): void { - $this->assertEquals("data->>'some_field' = @value", Field::EQ('some_field', '', '@value')->toWhere(), - 'WHERE fragment not generated correctly'); + Configuration::$mode = Mode::SQLite; + try { + $this->assertEquals("data->>'a_field' IS NULL", Field::NEX('a_field')->toWhere(), + 'WHERE fragment not generated correctly'); + } finally { + Configuration::$mode = null; + } } - public function testToWhereSucceedsWithQualifierNoParameter(): void + #[TestDox('To where succeeds for BT without qualifier for SQLite')] + public function testToWhereSucceedsForBTWithoutQualifierForSQLite(): void { - $field = Field::EX('no_field'); - $field->qualifier = 'test'; - $this->assertEquals("test.data->>'no_field' IS NOT NULL", $field->toWhere(), - 'WHERE fragment not generated correctly'); + Configuration::$mode = Mode::SQLite; + try { + $this->assertEquals("data->>'age' BETWEEN @agemin AND @agemax", Field::BT('age', 13, 17, '@age')->toWhere(), + 'WHERE fragment not generated correctly'); + } finally { + Configuration::$mode = null; + } } - public function testToWhereSucceedsWithQualifierAndParameter(): void + #[TestDox('To where succeeds for BT without qualifier for PostgreSQL with numeric range')] + public function testToWhereSucceedsForBTWithoutQualifierForPostgreSQLWithNumericRange(): void { - $field = Field::LE('le_field', 18, '@it'); - $field->qualifier = 'q'; - $this->assertEquals("q.data->>'le_field' <= @it", $field->toWhere(), 'WHERE fragment not generated correctly'); + Configuration::$mode = Mode::PgSQL; + try { + $this->assertEquals("(data->>'age')::numeric BETWEEN @agemin AND @agemax", + Field::BT('age', 13, 17, '@age')->toWhere(), 'WHERE fragment not generated correctly'); + } finally { + Configuration::$mode = null; + } + } + + #[TestDox('To where succeeds for BT without qualifier for PostgreSQL with non-numeric range')] + public function testToWhereSucceedsForBTWithoutQualifierForPostgreSQLWithNonNumericRange(): void + { + Configuration::$mode = Mode::PgSQL; + try { + $this->assertEquals("data->>'city' BETWEEN :citymin AND :citymax", + Field::BT('city', 'Atlanta', 'Chicago', ':city')->toWhere(), 'WHERE fragment not generated correctly'); + } finally { + Configuration::$mode = null; + } + } + + #[TestDox('To where succeeds for BT with qualifier for SQLite')] + public function testToWhereSucceedsForBTWithQualifierForSQLite(): void + { + Configuration::$mode = Mode::SQLite; + try { + $field = Field::BT('age', 13, 17, '@age'); + $field->qualifier = 'me'; + $this->assertEquals("me.data->>'age' BETWEEN @agemin AND @agemax", $field->toWhere(), + 'WHERE fragment not generated correctly'); + } finally { + Configuration::$mode = null; + } + } + + #[TestDox('To where succeeds for BT with qualifier for PostgreSQL with numeric range')] + public function testToWhereSucceedsForBTWithQualifierForPostgreSQLWithNumericRange(): void + { + Configuration::$mode = Mode::PgSQL; + try { + $field = Field::BT('age', 13, 17, '@age'); + $field->qualifier = 'me'; + $this->assertEquals("(me.data->>'age')::numeric BETWEEN @agemin AND @agemax", $field->toWhere(), + 'WHERE fragment not generated correctly'); + } finally { + Configuration::$mode = null; + } + } + + #[TestDox('To where succeeds for BT with qualifier for PostgreSQL with non-numeric range')] + public function testToWhereSucceedsForBTWithQualifierForPostgreSQLWithNonNumericRange(): void + { + Configuration::$mode = Mode::PgSQL; + try { + $field = Field::BT('city', 'Atlanta', 'Chicago', ':city'); + $field->qualifier = 'me'; + $this->assertEquals("me.data->>'city' BETWEEN :citymin AND :citymax", $field->toWhere(), + 'WHERE fragment not generated correctly'); + } finally { + Configuration::$mode = null; + } + } + + #[TestDox('To where succeeds for others without qualifier for PostgreSQL')] + public function testToWhereSucceedsForOthersWithoutQualifierForPostgreSQL(): void + { + Configuration::$mode = Mode::PgSQL; + try { + $this->assertEquals("data->>'some_field' = @value", Field::EQ('some_field', '', '@value')->toWhere(), + 'WHERE fragment not generated correctly'); + } finally { + Configuration::$mode = null; + } + } + + #[TestDox('To where succeeds for others without qualifier for SQLite')] + public function testToWhereSucceedsForOthersWithoutQualifierForSQLite(): void + { + Configuration::$mode = Mode::SQLite; + try { + $this->assertEquals("data->>'some_field' = @value", Field::EQ('some_field', '', '@value')->toWhere(), + 'WHERE fragment not generated correctly'); + } finally { + Configuration::$mode = null; + } + } + + #[TestDox('To where succeeds with qualifier no parameter for PostgreSQL')] + public function testToWhereSucceedsWithQualifierNoParameterForPostgreSQL(): void + { + Configuration::$mode = Mode::PgSQL; + try { + $field = Field::EX('no_field'); + $field->qualifier = 'test'; + $this->assertEquals("test.data->>'no_field' IS NOT NULL", $field->toWhere(), + 'WHERE fragment not generated correctly'); + } finally { + Configuration::$mode = null; + } + } + + #[TestDox('To where succeeds with qualifier no parameter for SQLite')] + public function testToWhereSucceedsWithQualifierNoParameterForSQLite(): void + { + Configuration::$mode = Mode::SQLite; + try { + $field = Field::EX('no_field'); + $field->qualifier = 'test'; + $this->assertEquals("test.data->>'no_field' IS NOT NULL", $field->toWhere(), + 'WHERE fragment not generated correctly'); + } finally { + Configuration::$mode = null; + } + } + + #[TestDox('To where succeeds with qualifier and parameter for PostgreSQL')] + public function testToWhereSucceedsWithQualifierAndParameterForPostgreSQL(): void + { + Configuration::$mode = Mode::PgSQL; + try { + $field = Field::LE('le_field', 18, '@it'); + $field->qualifier = 'q'; + $this->assertEquals("q.data->>'le_field' <= @it", $field->toWhere(), + 'WHERE fragment not generated correctly'); + } finally { + Configuration::$mode = null; + } + } + + #[TestDox('To where succeeds with qualifier and parameter for SQLite')] + public function testToWhereSucceedsWithQualifierAndParameterForSQLite(): void + { + Configuration::$mode = Mode::SQLite; + try { + $field = Field::LE('le_field', 18, '@it'); + $field->qualifier = 'q'; + $this->assertEquals("q.data->>'le_field' <= @it", $field->toWhere(), + 'WHERE fragment not generated correctly'); + } finally { + Configuration::$mode = null; + } + } + + #[TestDox('To where succeeds with sub-document for PostgreSQL')] + public function testToWhereSucceedsWithSubDocumentForPostgreSQL(): void + { + Configuration::$mode = Mode::PgSQL; + try { + $field = Field::EQ('sub.foo.bar', 22, '@it'); + $this->assertEquals("data->>'sub.foo.bar' = @it", $field->toWhere(), + 'WHERE fragment not generated correctly'); + } finally { + Configuration::$mode = null; + } + } + + #[TestDox('To where succeeds with sub-document for SQLite')] + public function testToWhereSucceedsWithSubDocumentForSQLite(): void + { + Configuration::$mode = Mode::SQLite; + try { + $field = Field::EQ('sub.foo.bar', 22, '@it'); + $this->assertEquals("data->>'sub'->>'foo'->>'bar' = @it", $field->toWhere(), + 'WHERE fragment not generated correctly'); + } finally { + Configuration::$mode = null; + } } #[TestDox('EQ succeeds without parameter')] diff --git a/tests/unit/ParametersTest.php b/tests/unit/ParametersTest.php index be9d236..a633124 100644 --- a/tests/unit/ParametersTest.php +++ b/tests/unit/ParametersTest.php @@ -63,7 +63,7 @@ class ParametersTest extends TestCase { try { Configuration::$mode = Mode::SQLite; - $this->assertEquals([':it0' => 'test', ':it1' => 'unit', ':it2' => 'wow'], + $this->assertEquals([':it0' => '$.test', ':it1' => '$.unit', ':it2' => '$.wow'], Parameters::fieldNames(':it', ['test', 'unit', 'wow']), 'Field name parameters not correct'); } finally { Configuration::$mode = null; diff --git a/tests/unit/Query/CountTest.php b/tests/unit/Query/CountTest.php index 0a70527..69eb6a7 100644 --- a/tests/unit/Query/CountTest.php +++ b/tests/unit/Query/CountTest.php @@ -2,7 +2,7 @@ namespace Test\Unit\Query; -use BitBadger\PDODocument\Field; +use BitBadger\PDODocument\{Configuration, Field, Mode}; use BitBadger\PDODocument\Query\Count; use PHPUnit\Framework\TestCase; @@ -20,7 +20,12 @@ class CountTest extends TestCase public function testByFieldsSucceeds() { - $this->assertEquals("SELECT COUNT(*) FROM somewhere WHERE data->>'errors' > :errors", - Count::byFields('somewhere', [Field::GT('errors', 10, ':errors')])); + Configuration::$mode = Mode::SQLite; + try { + $this->assertEquals("SELECT COUNT(*) FROM somewhere WHERE data->>'errors' > :errors", + Count::byFields('somewhere', [Field::GT('errors', 10, ':errors')])); + } finally { + Configuration::$mode = null; + } } } diff --git a/tests/unit/Query/DeleteTest.php b/tests/unit/Query/DeleteTest.php index edf21bc..1ac3c7b 100644 --- a/tests/unit/Query/DeleteTest.php +++ b/tests/unit/Query/DeleteTest.php @@ -2,7 +2,7 @@ namespace Test\Unit\Query; -use BitBadger\PDODocument\Field; +use BitBadger\PDODocument\{Configuration, Field, Mode}; use BitBadger\PDODocument\Query\Delete; use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; @@ -12,6 +12,16 @@ use PHPUnit\Framework\TestCase; */ class DeleteTest extends TestCase { + protected function setUp(): void + { + Configuration::$mode = Mode::SQLite; + } + + protected function tearDown(): void + { + Configuration::$mode = null; + } + #[TestDox('By ID succeeds')] public function testByIdSucceeds(): void { diff --git a/tests/unit/Query/ExistsTest.php b/tests/unit/Query/ExistsTest.php index 32fbae2..416c9dd 100644 --- a/tests/unit/Query/ExistsTest.php +++ b/tests/unit/Query/ExistsTest.php @@ -2,7 +2,7 @@ namespace Test\Unit\Query; -use BitBadger\PDODocument\Field; +use BitBadger\PDODocument\{Configuration, Field, Mode}; use BitBadger\PDODocument\Query\Exists; use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; @@ -12,6 +12,16 @@ use PHPUnit\Framework\TestCase; */ class ExistsTest extends TestCase { + protected function setUp(): void + { + Configuration::$mode = Mode::SQLite; + } + + protected function tearDown(): void + { + Configuration::$mode = null; + } + public function testQuerySucceeds(): void { $this->assertEquals('SELECT EXISTS (SELECT 1 FROM abc WHERE def)', Exists::query('abc', 'def'), diff --git a/tests/unit/Query/FindTest.php b/tests/unit/Query/FindTest.php index 65bc571..5b2fb9a 100644 --- a/tests/unit/Query/FindTest.php +++ b/tests/unit/Query/FindTest.php @@ -2,7 +2,7 @@ namespace Test\Unit\Query; -use BitBadger\PDODocument\Field; +use BitBadger\PDODocument\{Configuration, Field, Mode}; use BitBadger\PDODocument\Query\Find; use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; @@ -12,6 +12,16 @@ use PHPUnit\Framework\TestCase; */ class FindTest extends TestCase { + protected function setUp(): void + { + Configuration::$mode = Mode::SQLite; + } + + protected function tearDown(): void + { + Configuration::$mode = null; + } + #[TestDox('By ID succeeds')] public function testByIdSucceeds(): void { diff --git a/tests/unit/QueryTest.php b/tests/unit/QueryTest.php index 6e00cab..b3ac80b 100644 --- a/tests/unit/QueryTest.php +++ b/tests/unit/QueryTest.php @@ -2,7 +2,7 @@ namespace Test\Unit; -use BitBadger\PDODocument\{Field, Query}; +use BitBadger\PDODocument\{Configuration, Field, Mode, Query}; use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; @@ -11,6 +11,16 @@ use PHPUnit\Framework\TestCase; */ class QueryTest extends TestCase { + protected function setUp(): void + { + Configuration::$mode = Mode::SQLite; + } + + protected function tearDown(): void + { + Configuration::$mode = null; + } + public function testSelectFromTableSucceeds(): void { $this->assertEquals('SELECT data FROM testing', Query::selectFromTable('testing'), -- 2.45.1 From a10ecbb1cdfdf6dd8ab3c1884b09d9ba987b7ff5 Mon Sep 17 00:00:00 2001 From: "Daniel J. Summers" Date: Sat, 8 Jun 2024 12:57:13 -0400 Subject: [PATCH 23/25] Pass integer IDs as-is --- src/Parameters.php | 2 +- tests/integration/sqlite/FindTest.php | 11 ++++++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/Parameters.php b/src/Parameters.php index 2e13830..e6dffad 100644 --- a/src/Parameters.php +++ b/src/Parameters.php @@ -15,7 +15,7 @@ class Parameters */ public static function id(mixed $key): array { - return [':id' => is_string($key) ? $key : "$key"]; + return [':id' => is_int($key) || is_string($key) ? $key : "$key"]; } /** diff --git a/tests/integration/sqlite/FindTest.php b/tests/integration/sqlite/FindTest.php index 7552a51..c3b7ced 100644 --- a/tests/integration/sqlite/FindTest.php +++ b/tests/integration/sqlite/FindTest.php @@ -2,7 +2,7 @@ namespace Test\Integration\SQLite; -use BitBadger\PDODocument\{Custom, Field, Find}; +use BitBadger\PDODocument\{Custom, Document, Field, Find}; use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\TestCase; use Test\Integration\TestDocument; @@ -53,6 +53,15 @@ class FindTest extends TestCase $this->assertEquals('two', $doc->id, 'An incorrect document was returned'); } + #[TestDox('By ID succeeds when a document is found with numeric ID')] + public function testByIdSucceedsWhenADocumentIsFoundWithNumericId(): void + { + Document::insert(ThrowawayDb::TABLE, ['id' => 18, 'value' => 'howdy']); + $doc = Find::byId(ThrowawayDb::TABLE, 18, TestDocument::class); + $this->assertNotFalse($doc, 'There should have been a document returned'); + $this->assertEquals('18', $doc->id, 'An incorrect document was returned'); + } + #[TestDox('By ID succeeds when a document is not found')] public function testByIdSucceedsWhenADocumentIsNotFound(): void { -- 2.45.1 From 3f038b02fda6ae2c408ea6f9be41132724171079 Mon Sep 17 00:00:00 2001 From: "Daniel J. Summers" Date: Sat, 8 Jun 2024 16:58:53 -0400 Subject: [PATCH 24/25] Add attributes prior to publishing --- .gitattributes | 1 + composer.json | 17 +++++++++++++++++ composer.lock | 3 ++- 3 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..a929ee8 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +/test export-ignore diff --git a/composer.json b/composer.json index 3650240..f3c3323 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,23 @@ { "name": "bit-badger/pdo-document", + "description": "Treat SQLite (and soon PostgreSQL) as a document store", + "keywords": ["database", "document", "sqlite", "pdo"], + "license": "MIT", + "authors": [ + { + "name": "Daniel J. Summers", + "email": "daniel@bitbadger.solutions", + "homepage": "https://bitbadger.solutions", + "role": "Developer" + } + ], + "support": { + "email": "daniel@bitbadger.solutions", + "source": "https://git.bitbadger.solutions/bit-badger/pdo-document", + "rss": "https://git.bitbadger.solutions/bit-badger/pdo-document.rss" + }, "require": { + "php": ">=8.3", "netresearch/jsonmapper": "^4", "ext-pdo": "*" }, diff --git a/composer.lock b/composer.lock index 3f0b880..c9a364a 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "eada4b7eb6f976e0aaf0b54b92e2ca32", + "content-hash": "ca79f450e8e715ad61ba3581734c0fe7", "packages": [ { "name": "netresearch/jsonmapper", @@ -1697,6 +1697,7 @@ "prefer-stable": false, "prefer-lowest": false, "platform": { + "php": ">=8.3", "ext-pdo": "*" }, "platform-dev": [], -- 2.45.1 From ac78d3718c6973af9ae68f5bea57ded4f971e1de Mon Sep 17 00:00:00 2001 From: "Daniel J. Summers" Date: Sat, 8 Jun 2024 19:57:37 -0400 Subject: [PATCH 25/25] Add instructions to README --- .gitattributes | 5 ++++- README.md | 12 ++++++++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/.gitattributes b/.gitattributes index a929ee8..cd43aad 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,4 @@ -/test export-ignore +.gitignore export-ignore +.gitattributes export-ignore +composer.lock export-ignore +tests/**/* export-ignore diff --git a/README.md b/README.md index f77d860..174f327 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,11 @@ -# pdo-document +# PDODocument -Bit Badger Documents PHP implementation with PDO \ No newline at end of file +This library allows SQLite (and, by v1.0.0-beta1, PostgreSQL) to be treated as a document database. It is a PHP implementation of the .NET [BitBadger.Documents](https://git.bitbadger.solutions/bit-badger/BitBadger.Documents) library. + +## Add via Composer + +`compose require bit-badger/pdo-document` + +## Usage + +Documentation for this library is not complete; however, its structure is very similar to the .NET version, so [its documentation will help](https://bitbadger.solutions/open-source/relational-documents/basic-usage.html) until its project specific documentation is developed. Things like `Count.All()` become `Count::all`, and all the `byField` operations are named `byFields` and take an array of fields. -- 2.45.1