Compare commits
7 Commits
v1.0.0-alp
...
v1.0.0-bet
| Author | SHA1 | Date | |
|---|---|---|---|
| 50854275a8 | |||
| 0c9490e394 | |||
| 124426fa12 | |||
| 330e272187 | |||
| 1f1f06679f | |||
| 2902059cd4 | |||
| 17748354c4 |
8
.gitattributes
vendored
8
.gitattributes
vendored
@@ -1,4 +1,4 @@
|
|||||||
.gitignore export-ignore
|
/.gitignore export-ignore
|
||||||
.gitattributes export-ignore
|
/.gitattributes export-ignore
|
||||||
composer.lock export-ignore
|
/composer.lock export-ignore
|
||||||
tests/**/* export-ignore
|
/tests/**/* export-ignore
|
||||||
|
|||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,2 +1,3 @@
|
|||||||
.idea
|
.idea
|
||||||
vendor
|
vendor
|
||||||
|
*-tests.txt
|
||||||
|
|||||||
27
README.md
27
README.md
@@ -1,11 +1,32 @@
|
|||||||
# PDODocument
|
# PDODocument
|
||||||
|
|
||||||
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.
|
This library allows SQLite and PostgreSQL to be treated as document databases. It is a PHP implementation of the .NET [BitBadger.Documents](https://git.bitbadger.solutions/bit-badger/BitBadger.Documents) library.
|
||||||
|
|
||||||
## Add via Composer
|
## Add via Composer
|
||||||
|
|
||||||
`compose require bit-badger/pdo-document`
|
[](https://packagist.org/packages/bit-badger/pdo-document)
|
||||||
|
|
||||||
|
`composer require bit-badger/pdo-document`
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
### Connection Details
|
||||||
|
|
||||||
|
The static variable `Configuration::$pdoDSN` must be set to the [PDO data source name](https://www.php.net/manual/en/pdo.construct.php#refsect1-pdo.construct-parameters) for your database. `Configuration` also has `$username`, `$password`, and `$options` variables that will be used to construct the PDO object it will use for data access.
|
||||||
|
|
||||||
|
### Document Identifiers
|
||||||
|
|
||||||
|
Each document must have a unique identifier. By default, the library assumes that this is a property or array key named `id`, but this can be controlled by setting `Configuration::$idField`. Once documents exist, this should not be changed.
|
||||||
|
|
||||||
|
IDs can be generated automatically on insert. The `AutoId` enumeration has 4 values:
|
||||||
|
|
||||||
|
- `AutoId::None` is the default; no IDs will be generated
|
||||||
|
- `AutoId::Number` will assign max-ID-plus-one to documents with an ID of 0
|
||||||
|
- `AutoId::UUID` will generate a v4 <abbr title="Universally Unique Identifier">UUID</abbr> for documents with an empty `string` ID
|
||||||
|
- `AutoId::RandomString` will generate a string of letters and numbers for documents with an empty `string` ID; `Configuration::$idStringLength` controls the length of the generated string, and defaults to 16 characters
|
||||||
|
|
||||||
|
In all generated scenarios, if the ID value is not 0 or blank, that ID will be used instead of a generated one.
|
||||||
|
|
||||||
## Usage
|
## 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.
|
Documentation for this library is not complete (writing it is one of the goals before the “beta” tag is dropped); 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.
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "bit-badger/pdo-document",
|
"name": "bit-badger/pdo-document",
|
||||||
"description": "Treat SQLite (and soon PostgreSQL) as a document store",
|
"description": "Treat SQLite and PostgreSQL as document stores",
|
||||||
"keywords": ["database", "document", "sqlite", "pdo"],
|
"keywords": ["database", "document", "sqlite", "pdo", "postgresql"],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
@@ -17,9 +17,10 @@
|
|||||||
"rss": "https://git.bitbadger.solutions/bit-badger/pdo-document.rss"
|
"rss": "https://git.bitbadger.solutions/bit-badger/pdo-document.rss"
|
||||||
},
|
},
|
||||||
"require": {
|
"require": {
|
||||||
"php": ">=8.3",
|
"php": ">=8.2",
|
||||||
"netresearch/jsonmapper": "^4",
|
"netresearch/jsonmapper": "^4",
|
||||||
"ext-pdo": "*"
|
"ext-pdo": "*",
|
||||||
|
"phpoption/phpoption": "^1.9"
|
||||||
},
|
},
|
||||||
"require-dev": {
|
"require-dev": {
|
||||||
"phpunit/phpunit": "^11"
|
"phpunit/phpunit": "^11"
|
||||||
@@ -35,7 +36,11 @@
|
|||||||
"psr-4": {
|
"psr-4": {
|
||||||
"Test\\Unit\\": "./tests/unit",
|
"Test\\Unit\\": "./tests/unit",
|
||||||
"Test\\Integration\\": "./tests/integration",
|
"Test\\Integration\\": "./tests/integration",
|
||||||
|
"Test\\Integration\\PostgreSQL\\": "./tests/integration/postgresql",
|
||||||
"Test\\Integration\\SQLite\\": "./tests/integration/sqlite"
|
"Test\\Integration\\SQLite\\": "./tests/integration/sqlite"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"archive": {
|
||||||
|
"exclude": [ "/tests", "/.gitattributes", "/.gitignore", "/.git", "/composer.lock" ]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
136
composer.lock
generated
136
composer.lock
generated
@@ -4,7 +4,7 @@
|
|||||||
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
||||||
"This file is @generated automatically"
|
"This file is @generated automatically"
|
||||||
],
|
],
|
||||||
"content-hash": "ca79f450e8e715ad61ba3581734c0fe7",
|
"content-hash": "71593fca8aa32b0cd963eb52bad1a34e",
|
||||||
"packages": [
|
"packages": [
|
||||||
{
|
{
|
||||||
"name": "netresearch/jsonmapper",
|
"name": "netresearch/jsonmapper",
|
||||||
@@ -56,21 +56,96 @@
|
|||||||
"source": "https://github.com/cweiske/jsonmapper/tree/v4.4.1"
|
"source": "https://github.com/cweiske/jsonmapper/tree/v4.4.1"
|
||||||
},
|
},
|
||||||
"time": "2024-01-31T06:18:54+00:00"
|
"time": "2024-01-31T06:18:54+00:00"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "phpoption/phpoption",
|
||||||
|
"version": "1.9.2",
|
||||||
|
"source": {
|
||||||
|
"type": "git",
|
||||||
|
"url": "https://github.com/schmittjoh/php-option.git",
|
||||||
|
"reference": "80735db690fe4fc5c76dfa7f9b770634285fa820"
|
||||||
|
},
|
||||||
|
"dist": {
|
||||||
|
"type": "zip",
|
||||||
|
"url": "https://api.github.com/repos/schmittjoh/php-option/zipball/80735db690fe4fc5c76dfa7f9b770634285fa820",
|
||||||
|
"reference": "80735db690fe4fc5c76dfa7f9b770634285fa820",
|
||||||
|
"shasum": ""
|
||||||
|
},
|
||||||
|
"require": {
|
||||||
|
"php": "^7.2.5 || ^8.0"
|
||||||
|
},
|
||||||
|
"require-dev": {
|
||||||
|
"bamarni/composer-bin-plugin": "^1.8.2",
|
||||||
|
"phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2"
|
||||||
|
},
|
||||||
|
"type": "library",
|
||||||
|
"extra": {
|
||||||
|
"bamarni-bin": {
|
||||||
|
"bin-links": true,
|
||||||
|
"forward-command": true
|
||||||
|
},
|
||||||
|
"branch-alias": {
|
||||||
|
"dev-master": "1.9-dev"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"autoload": {
|
||||||
|
"psr-4": {
|
||||||
|
"PhpOption\\": "src/PhpOption/"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"notification-url": "https://packagist.org/downloads/",
|
||||||
|
"license": [
|
||||||
|
"Apache-2.0"
|
||||||
|
],
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "Johannes M. Schmitt",
|
||||||
|
"email": "schmittjoh@gmail.com",
|
||||||
|
"homepage": "https://github.com/schmittjoh"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Graham Campbell",
|
||||||
|
"email": "hello@gjcampbell.co.uk",
|
||||||
|
"homepage": "https://github.com/GrahamCampbell"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Option Type for PHP",
|
||||||
|
"keywords": [
|
||||||
|
"language",
|
||||||
|
"option",
|
||||||
|
"php",
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"support": {
|
||||||
|
"issues": "https://github.com/schmittjoh/php-option/issues",
|
||||||
|
"source": "https://github.com/schmittjoh/php-option/tree/1.9.2"
|
||||||
|
},
|
||||||
|
"funding": [
|
||||||
|
{
|
||||||
|
"url": "https://github.com/GrahamCampbell",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://tidelift.com/funding/github/packagist/phpoption/phpoption",
|
||||||
|
"type": "tidelift"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"time": "2023-11-12T21:59:55+00:00"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"packages-dev": [
|
"packages-dev": [
|
||||||
{
|
{
|
||||||
"name": "myclabs/deep-copy",
|
"name": "myclabs/deep-copy",
|
||||||
"version": "1.11.1",
|
"version": "1.12.0",
|
||||||
"source": {
|
"source": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "https://github.com/myclabs/DeepCopy.git",
|
"url": "https://github.com/myclabs/DeepCopy.git",
|
||||||
"reference": "7284c22080590fb39f2ffa3e9057f10a4ddd0e0c"
|
"reference": "3a6b9a42cd8f8771bd4295d13e1423fa7f3d942c"
|
||||||
},
|
},
|
||||||
"dist": {
|
"dist": {
|
||||||
"type": "zip",
|
"type": "zip",
|
||||||
"url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/7284c22080590fb39f2ffa3e9057f10a4ddd0e0c",
|
"url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/3a6b9a42cd8f8771bd4295d13e1423fa7f3d942c",
|
||||||
"reference": "7284c22080590fb39f2ffa3e9057f10a4ddd0e0c",
|
"reference": "3a6b9a42cd8f8771bd4295d13e1423fa7f3d942c",
|
||||||
"shasum": ""
|
"shasum": ""
|
||||||
},
|
},
|
||||||
"require": {
|
"require": {
|
||||||
@@ -78,11 +153,12 @@
|
|||||||
},
|
},
|
||||||
"conflict": {
|
"conflict": {
|
||||||
"doctrine/collections": "<1.6.8",
|
"doctrine/collections": "<1.6.8",
|
||||||
"doctrine/common": "<2.13.3 || >=3,<3.2.2"
|
"doctrine/common": "<2.13.3 || >=3 <3.2.2"
|
||||||
},
|
},
|
||||||
"require-dev": {
|
"require-dev": {
|
||||||
"doctrine/collections": "^1.6.8",
|
"doctrine/collections": "^1.6.8",
|
||||||
"doctrine/common": "^2.13.3 || ^3.2.2",
|
"doctrine/common": "^2.13.3 || ^3.2.2",
|
||||||
|
"phpspec/prophecy": "^1.10",
|
||||||
"phpunit/phpunit": "^7.5.20 || ^8.5.23 || ^9.5.13"
|
"phpunit/phpunit": "^7.5.20 || ^8.5.23 || ^9.5.13"
|
||||||
},
|
},
|
||||||
"type": "library",
|
"type": "library",
|
||||||
@@ -108,7 +184,7 @@
|
|||||||
],
|
],
|
||||||
"support": {
|
"support": {
|
||||||
"issues": "https://github.com/myclabs/DeepCopy/issues",
|
"issues": "https://github.com/myclabs/DeepCopy/issues",
|
||||||
"source": "https://github.com/myclabs/DeepCopy/tree/1.11.1"
|
"source": "https://github.com/myclabs/DeepCopy/tree/1.12.0"
|
||||||
},
|
},
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
@@ -116,7 +192,7 @@
|
|||||||
"type": "tidelift"
|
"type": "tidelift"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"time": "2023-03-08T13:26:56+00:00"
|
"time": "2024-06-12T14:39:25+00:00"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "nikic/php-parser",
|
"name": "nikic/php-parser",
|
||||||
@@ -619,16 +695,16 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "phpunit/phpunit",
|
"name": "phpunit/phpunit",
|
||||||
"version": "11.2.0",
|
"version": "11.2.5",
|
||||||
"source": {
|
"source": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "https://github.com/sebastianbergmann/phpunit.git",
|
"url": "https://github.com/sebastianbergmann/phpunit.git",
|
||||||
"reference": "705eba0190afe04bc057f565ad843267717cf109"
|
"reference": "be9e3ed32a1287a9bfda15936cc86fef4e4cf591"
|
||||||
},
|
},
|
||||||
"dist": {
|
"dist": {
|
||||||
"type": "zip",
|
"type": "zip",
|
||||||
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/705eba0190afe04bc057f565ad843267717cf109",
|
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/be9e3ed32a1287a9bfda15936cc86fef4e4cf591",
|
||||||
"reference": "705eba0190afe04bc057f565ad843267717cf109",
|
"reference": "be9e3ed32a1287a9bfda15936cc86fef4e4cf591",
|
||||||
"shasum": ""
|
"shasum": ""
|
||||||
},
|
},
|
||||||
"require": {
|
"require": {
|
||||||
@@ -652,7 +728,7 @@
|
|||||||
"sebastian/comparator": "^6.0",
|
"sebastian/comparator": "^6.0",
|
||||||
"sebastian/diff": "^6.0",
|
"sebastian/diff": "^6.0",
|
||||||
"sebastian/environment": "^7.0",
|
"sebastian/environment": "^7.0",
|
||||||
"sebastian/exporter": "^6.0",
|
"sebastian/exporter": "^6.1.2",
|
||||||
"sebastian/global-state": "^7.0",
|
"sebastian/global-state": "^7.0",
|
||||||
"sebastian/object-enumerator": "^6.0",
|
"sebastian/object-enumerator": "^6.0",
|
||||||
"sebastian/type": "^5.0",
|
"sebastian/type": "^5.0",
|
||||||
@@ -699,7 +775,7 @@
|
|||||||
"support": {
|
"support": {
|
||||||
"issues": "https://github.com/sebastianbergmann/phpunit/issues",
|
"issues": "https://github.com/sebastianbergmann/phpunit/issues",
|
||||||
"security": "https://github.com/sebastianbergmann/phpunit/security/policy",
|
"security": "https://github.com/sebastianbergmann/phpunit/security/policy",
|
||||||
"source": "https://github.com/sebastianbergmann/phpunit/tree/11.2.0"
|
"source": "https://github.com/sebastianbergmann/phpunit/tree/11.2.5"
|
||||||
},
|
},
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
@@ -715,7 +791,7 @@
|
|||||||
"type": "tidelift"
|
"type": "tidelift"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"time": "2024-06-07T04:48:50+00:00"
|
"time": "2024-06-20T13:11:31+00:00"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "sebastian/cli-parser",
|
"name": "sebastian/cli-parser",
|
||||||
@@ -1155,16 +1231,16 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "sebastian/exporter",
|
"name": "sebastian/exporter",
|
||||||
"version": "6.0.1",
|
"version": "6.1.2",
|
||||||
"source": {
|
"source": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "https://github.com/sebastianbergmann/exporter.git",
|
"url": "https://github.com/sebastianbergmann/exporter.git",
|
||||||
"reference": "f291e5a317c321c0381fa9ecc796fa2d21b186da"
|
"reference": "507d2333cbc4e6ea248fbda2d45ee1511e03da13"
|
||||||
},
|
},
|
||||||
"dist": {
|
"dist": {
|
||||||
"type": "zip",
|
"type": "zip",
|
||||||
"url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/f291e5a317c321c0381fa9ecc796fa2d21b186da",
|
"url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/507d2333cbc4e6ea248fbda2d45ee1511e03da13",
|
||||||
"reference": "f291e5a317c321c0381fa9ecc796fa2d21b186da",
|
"reference": "507d2333cbc4e6ea248fbda2d45ee1511e03da13",
|
||||||
"shasum": ""
|
"shasum": ""
|
||||||
},
|
},
|
||||||
"require": {
|
"require": {
|
||||||
@@ -1173,12 +1249,12 @@
|
|||||||
"sebastian/recursion-context": "^6.0"
|
"sebastian/recursion-context": "^6.0"
|
||||||
},
|
},
|
||||||
"require-dev": {
|
"require-dev": {
|
||||||
"phpunit/phpunit": "^11.0"
|
"phpunit/phpunit": "^11.2"
|
||||||
},
|
},
|
||||||
"type": "library",
|
"type": "library",
|
||||||
"extra": {
|
"extra": {
|
||||||
"branch-alias": {
|
"branch-alias": {
|
||||||
"dev-main": "6.0-dev"
|
"dev-main": "6.1-dev"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"autoload": {
|
"autoload": {
|
||||||
@@ -1221,7 +1297,7 @@
|
|||||||
"support": {
|
"support": {
|
||||||
"issues": "https://github.com/sebastianbergmann/exporter/issues",
|
"issues": "https://github.com/sebastianbergmann/exporter/issues",
|
||||||
"security": "https://github.com/sebastianbergmann/exporter/security/policy",
|
"security": "https://github.com/sebastianbergmann/exporter/security/policy",
|
||||||
"source": "https://github.com/sebastianbergmann/exporter/tree/6.0.1"
|
"source": "https://github.com/sebastianbergmann/exporter/tree/6.1.2"
|
||||||
},
|
},
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
@@ -1229,7 +1305,7 @@
|
|||||||
"type": "github"
|
"type": "github"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"time": "2024-03-02T07:28:20+00:00"
|
"time": "2024-06-18T11:19:56+00:00"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "sebastian/global-state",
|
"name": "sebastian/global-state",
|
||||||
@@ -1467,16 +1543,16 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "sebastian/recursion-context",
|
"name": "sebastian/recursion-context",
|
||||||
"version": "6.0.0",
|
"version": "6.0.1",
|
||||||
"source": {
|
"source": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "https://github.com/sebastianbergmann/recursion-context.git",
|
"url": "https://github.com/sebastianbergmann/recursion-context.git",
|
||||||
"reference": "b75224967b5a466925c6d54e68edd0edf8dd4ed4"
|
"reference": "2f15508e17af4ea35129bbc32ce28a814d9c7426"
|
||||||
},
|
},
|
||||||
"dist": {
|
"dist": {
|
||||||
"type": "zip",
|
"type": "zip",
|
||||||
"url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/b75224967b5a466925c6d54e68edd0edf8dd4ed4",
|
"url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/2f15508e17af4ea35129bbc32ce28a814d9c7426",
|
||||||
"reference": "b75224967b5a466925c6d54e68edd0edf8dd4ed4",
|
"reference": "2f15508e17af4ea35129bbc32ce28a814d9c7426",
|
||||||
"shasum": ""
|
"shasum": ""
|
||||||
},
|
},
|
||||||
"require": {
|
"require": {
|
||||||
@@ -1519,7 +1595,7 @@
|
|||||||
"support": {
|
"support": {
|
||||||
"issues": "https://github.com/sebastianbergmann/recursion-context/issues",
|
"issues": "https://github.com/sebastianbergmann/recursion-context/issues",
|
||||||
"security": "https://github.com/sebastianbergmann/recursion-context/security/policy",
|
"security": "https://github.com/sebastianbergmann/recursion-context/security/policy",
|
||||||
"source": "https://github.com/sebastianbergmann/recursion-context/tree/6.0.0"
|
"source": "https://github.com/sebastianbergmann/recursion-context/tree/6.0.1"
|
||||||
},
|
},
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
@@ -1527,7 +1603,7 @@
|
|||||||
"type": "github"
|
"type": "github"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"time": "2024-02-02T06:08:48+00:00"
|
"time": "2024-06-17T05:22:57+00:00"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "sebastian/type",
|
"name": "sebastian/type",
|
||||||
@@ -1697,7 +1773,7 @@
|
|||||||
"prefer-stable": false,
|
"prefer-stable": false,
|
||||||
"prefer-lowest": false,
|
"prefer-lowest": false,
|
||||||
"platform": {
|
"platform": {
|
||||||
"php": ">=8.3",
|
"php": ">=8.2",
|
||||||
"ext-pdo": "*"
|
"ext-pdo": "*"
|
||||||
},
|
},
|
||||||
"platform-dev": [],
|
"platform-dev": [],
|
||||||
|
|||||||
52
src/AutoId.php
Normal file
52
src/AutoId.php
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
use Random\RandomException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How automatic ID generation should be performed
|
||||||
|
*/
|
||||||
|
enum AutoId
|
||||||
|
{
|
||||||
|
/** Do not automatically generate IDs */
|
||||||
|
case None;
|
||||||
|
|
||||||
|
/** New documents with a 0 ID should receive max ID plus one */
|
||||||
|
case Number;
|
||||||
|
|
||||||
|
/** New documents with a blank ID should receive a v4 UUID (Universally Unique Identifier) */
|
||||||
|
case UUID;
|
||||||
|
|
||||||
|
/** New documents with a blank ID should receive a random string (set `Configuration::$idStringLength`) */
|
||||||
|
case RandomString;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate a v4 UUID
|
||||||
|
*
|
||||||
|
* @return string The v4 UUID
|
||||||
|
* @throws RandomException If an appropriate source of randomness cannot be found
|
||||||
|
*/
|
||||||
|
public static function generateUUID(): string
|
||||||
|
{
|
||||||
|
// hat tip: https://stackoverflow.com/a/15875555/276707
|
||||||
|
$bytes = random_bytes(16);
|
||||||
|
|
||||||
|
$bytes[6] = chr(ord($bytes[6]) & 0x0f | 0x40); // set version to 0100
|
||||||
|
$bytes[8] = chr(ord($bytes[8]) & 0x3f | 0x80); // set bits 6-7 to 10
|
||||||
|
|
||||||
|
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate a random string ID
|
||||||
|
*
|
||||||
|
* @param int|null $length The length of string to generate (optional; defaults to configured ID string length)
|
||||||
|
* @return string A string filled with the hexadecimal representation of random bytes
|
||||||
|
* @throws RandomException If an appropriate source of randomness cannot be found
|
||||||
|
*/
|
||||||
|
public static function generateRandom(?int $length = null): string
|
||||||
|
{
|
||||||
|
return bin2hex(random_bytes(($length ?? Configuration::$idStringLength) / 2));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,6 +12,14 @@ class Configuration
|
|||||||
/** @var string The name of the ID field used in the database (will be treated as the primary key) */
|
/** @var string The name of the ID field used in the database (will be treated as the primary key) */
|
||||||
public static string $idField = 'id';
|
public static string $idField = 'id';
|
||||||
|
|
||||||
|
/** @var AutoId The automatic ID generation process to use */
|
||||||
|
public static AutoId $autoId = AutoId::None;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var int The number of characters a string generated by `AutoId::RandomString` will have (must be an even number)
|
||||||
|
*/
|
||||||
|
public static int $idStringLength = 16;
|
||||||
|
|
||||||
/** @var string The data source name (DSN) of the connection string */
|
/** @var string The data source name (DSN) of the connection string */
|
||||||
public static string $pdoDSN = '';
|
public static string $pdoDSN = '';
|
||||||
|
|
||||||
@@ -59,7 +67,9 @@ class Configuration
|
|||||||
return self::$_pdo;
|
return self::$_pdo;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clear the current PDO instance
|
||||||
|
*/
|
||||||
public static function resetPDO(): void
|
public static function resetPDO(): void
|
||||||
{
|
{
|
||||||
self::$_pdo = null;
|
self::$_pdo = null;
|
||||||
|
|||||||
@@ -26,14 +26,41 @@ class Count
|
|||||||
*
|
*
|
||||||
* @param string $tableName The name of the table in which documents should be counted
|
* @param string $tableName The name of the table in which documents should be counted
|
||||||
* @param array|Field[] $fields The field comparison to match
|
* @param array|Field[] $fields The field comparison to match
|
||||||
* @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
|
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
|
||||||
* @return int The count of documents matching the field comparison
|
* @return int The count of documents matching the field comparison
|
||||||
* @throws DocumentException If one is encountered
|
* @throws DocumentException If one is encountered
|
||||||
*/
|
*/
|
||||||
public static function byFields(string $tableName, array $fields, string $conjunction = 'AND'): int
|
public static function byFields(string $tableName, array $fields, ?FieldMatch $match = null): int
|
||||||
{
|
{
|
||||||
$namedFields = Parameters::nameFields($fields);
|
$namedFields = Parameters::nameFields($fields);
|
||||||
return Custom::scalar(Query\Count::byFields($tableName, $namedFields, $conjunction),
|
return Custom::scalar(Query\Count::byFields($tableName, $namedFields, $match),
|
||||||
Parameters::addFields($namedFields, []), new CountMapper());
|
Parameters::addFields($namedFields, []), new CountMapper());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Count matching documents using a JSON containment query (`@>`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which documents should be counted
|
||||||
|
* @param array|object $criteria The criteria for the JSON containment query
|
||||||
|
* @return int The number of documents matching the JSON containment query
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function byContains(string $tableName, array|object $criteria): int
|
||||||
|
{
|
||||||
|
return Custom::scalar(Query\Count::byContains($tableName), Parameters::json(':criteria', $criteria),
|
||||||
|
new CountMapper());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Count matching documents using a JSON Path match query (`@?`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which documents should be counted
|
||||||
|
* @param string $path The JSON Path match string
|
||||||
|
* @return int The number of documents matching the given JSON Path criteria
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function byJsonPath(string $tableName, string $path): int
|
||||||
|
{
|
||||||
|
return Custom::scalar(Query\Count::byJsonPath($tableName), [':path' => $path], new CountMapper());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ use BitBadger\PDODocument\Mapper\Mapper;
|
|||||||
use PDO;
|
use PDO;
|
||||||
use PDOException;
|
use PDOException;
|
||||||
use PDOStatement;
|
use PDOStatement;
|
||||||
|
use PhpOption\{None, Option, Some};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functions to execute custom queries
|
* Functions to execute custom queries
|
||||||
@@ -92,14 +93,14 @@ class Custom
|
|||||||
* @param string $query The query to be executed (will have "LIMIT 1" appended)
|
* @param string $query The query to be executed (will have "LIMIT 1" appended)
|
||||||
* @param array $parameters Parameters to use in executing the query
|
* @param array $parameters Parameters to use in executing the query
|
||||||
* @param Mapper<TDoc> $mapper Mapper to deserialize the result
|
* @param Mapper<TDoc> $mapper Mapper to deserialize the result
|
||||||
* @return false|TDoc The item if it is found, false if not
|
* @return Option<TDoc> A `Some` instance if the item is found, `None` otherwise
|
||||||
* @throws DocumentException If any is encountered
|
* @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): Option
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
$stmt = &self::runQuery("$query LIMIT 1", $parameters);
|
$stmt = &self::runQuery("$query LIMIT 1", $parameters);
|
||||||
return ($first = $stmt->fetch(PDO::FETCH_ASSOC)) ? $mapper->map($first) : false;
|
return ($first = $stmt->fetch(PDO::FETCH_ASSOC)) ? Some::create($mapper->map($first)) : None::create();
|
||||||
} finally {
|
} finally {
|
||||||
$stmt = null;
|
$stmt = null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,4 +31,16 @@ class Definition
|
|||||||
{
|
{
|
||||||
Custom::nonQuery(Query\Definition::ensureIndexOn($tableName, $indexName, $fields), []);
|
Custom::nonQuery(Query\Definition::ensureIndexOn($tableName, $indexName, $fields), []);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a full-document index on a table (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table on which the document index should be created
|
||||||
|
* @param DocumentIndex $indexType The type of document index to create
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL or if an error occurs creating the index
|
||||||
|
*/
|
||||||
|
public static function ensureDocumentIndex(string $tableName, DocumentIndex $indexType): void
|
||||||
|
{
|
||||||
|
Custom::nonQuery(Query\Definition::ensureDocumentIndexOn($tableName, $indexType), []);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ class Delete
|
|||||||
*/
|
*/
|
||||||
public static function byId(string $tableName, mixed $docId): void
|
public static function byId(string $tableName, mixed $docId): void
|
||||||
{
|
{
|
||||||
Custom::nonQuery(Query\Delete::byId($tableName), Parameters::id($docId));
|
Custom::nonQuery(Query\Delete::byId($tableName, $docId), Parameters::id($docId));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -24,13 +24,37 @@ class Delete
|
|||||||
*
|
*
|
||||||
* @param string $tableName The table from which documents should be deleted
|
* @param string $tableName The table from which documents should be deleted
|
||||||
* @param array|Field[] $fields The field comparison to match
|
* @param array|Field[] $fields The field comparison to match
|
||||||
* @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
|
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
|
||||||
* @throws DocumentException If any is encountered
|
* @throws DocumentException If any is encountered
|
||||||
*/
|
*/
|
||||||
public static function byFields(string $tableName, array $fields, string $conjunction = 'AND'): void
|
public static function byFields(string $tableName, array $fields, ?FieldMatch $match = null): void
|
||||||
{
|
{
|
||||||
$namedFields = Parameters::nameFields($fields);
|
$namedFields = Parameters::nameFields($fields);
|
||||||
Custom::nonQuery(Query\Delete::byFields($tableName, $namedFields, $conjunction),
|
Custom::nonQuery(Query\Delete::byFields($tableName, $namedFields, $match),
|
||||||
Parameters::addFields($namedFields, []));
|
Parameters::addFields($namedFields, []));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete documents matching a JSON containment query (`@>`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The table from which documents should be deleted
|
||||||
|
* @param array|object $criteria The JSON containment query values
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function byContains(string $tableName, array|object $criteria): void
|
||||||
|
{
|
||||||
|
Custom::nonQuery(Query\Delete::byContains($tableName), Parameters::json(':criteria', $criteria));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete documents matching a JSON Path match query (`@?`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The table from which documents should be deleted
|
||||||
|
* @param string $path The JSON Path match string
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function byJsonPath(string $tableName, string $path): void
|
||||||
|
{
|
||||||
|
Custom::nonQuery(Query\Delete::byJsonPath($tableName), [':path' => $path]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,7 +16,25 @@ class Document
|
|||||||
*/
|
*/
|
||||||
public static function insert(string $tableName, array|object $document): void
|
public static function insert(string $tableName, array|object $document): void
|
||||||
{
|
{
|
||||||
Custom::nonQuery(Query::insert($tableName), Parameters::json(':data', $document));
|
$doInsert = fn() => Custom::nonQuery(Query::insert($tableName), Parameters::json(':data', $document));
|
||||||
|
|
||||||
|
if (Configuration::$autoId == AutoId::None) {
|
||||||
|
$doInsert();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$id = Configuration::$idField;
|
||||||
|
$idProvided =
|
||||||
|
(is_array( $document) && is_int( $document[$id]) && $document[$id] <> 0)
|
||||||
|
|| (is_array( $document) && is_string($document[$id]) && $document[$id] <> '')
|
||||||
|
|| (is_object($document) && is_int( $document->{$id}) && $document->{$id} <> 0)
|
||||||
|
|| (is_object($document) && is_string($document->{$id}) && $document->{$id} <> '');
|
||||||
|
|
||||||
|
if ($idProvided) {
|
||||||
|
$doInsert();
|
||||||
|
} else {
|
||||||
|
Custom::nonQuery(Query::insert($tableName, Configuration::$autoId), Parameters::json(':data', $document));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
15
src/DocumentIndex.php
Normal file
15
src/DocumentIndex.php
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The type of index to generate for the document
|
||||||
|
*/
|
||||||
|
enum DocumentIndex
|
||||||
|
{
|
||||||
|
/** A GIN index with standard operations (all operators supported) */
|
||||||
|
case Full;
|
||||||
|
|
||||||
|
/** A GIN index with JSONPath operations (optimized for @>, @?, @@ operators) */
|
||||||
|
case Optimized;
|
||||||
|
}
|
||||||
@@ -19,7 +19,7 @@ class Exists
|
|||||||
*/
|
*/
|
||||||
public static function byId(string $tableName, mixed $docId): bool
|
public static function byId(string $tableName, mixed $docId): bool
|
||||||
{
|
{
|
||||||
return Custom::scalar(Query\Exists::byId($tableName), Parameters::id($docId), new ExistsMapper());
|
return Custom::scalar(Query\Exists::byId($tableName, $docId), Parameters::id($docId), new ExistsMapper());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -27,14 +27,41 @@ class Exists
|
|||||||
*
|
*
|
||||||
* @param string $tableName The name of the table in which document existence should be determined
|
* @param string $tableName The name of the table in which document existence should be determined
|
||||||
* @param Field[] $fields The field comparison to match
|
* @param Field[] $fields The field comparison to match
|
||||||
* @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
|
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
|
||||||
* @return bool True if any documents match the field comparison, false if not
|
* @return bool True if any documents match the field comparison, false if not
|
||||||
* @throws DocumentException If any is encountered
|
* @throws DocumentException If any is encountered
|
||||||
*/
|
*/
|
||||||
public static function byFields(string $tableName, array $fields, string $conjunction = 'AND'): bool
|
public static function byFields(string $tableName, array $fields, ?FieldMatch $match = null): bool
|
||||||
{
|
{
|
||||||
$namedFields = Parameters::nameFields($fields);
|
$namedFields = Parameters::nameFields($fields);
|
||||||
return Custom::scalar(Query\Exists::byFields($tableName, $namedFields, $conjunction),
|
return Custom::scalar(Query\Exists::byFields($tableName, $namedFields, $match),
|
||||||
Parameters::addFields($namedFields, []), new ExistsMapper());
|
Parameters::addFields($namedFields, []), new ExistsMapper());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determine if documents exist by a JSON containment query (`@>`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which document existence should be determined
|
||||||
|
* @param array|object $criteria The criteria for the JSON containment query
|
||||||
|
* @return bool True if any documents match the JSON containment query, false if not
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function byContains(string $tableName, array|object $criteria): bool
|
||||||
|
{
|
||||||
|
return Custom::scalar(Query\Exists::byContains($tableName), Parameters::json(':criteria', $criteria),
|
||||||
|
new ExistsMapper());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determine if documents exist by a JSON Path match query (`@?`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which document existence should be determined
|
||||||
|
* @param string $path The JSON Path match string
|
||||||
|
* @return bool True if any documents match the JSON Path string, false if not
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function byJsonPath(string $tableName, string $path): bool
|
||||||
|
{
|
||||||
|
return Custom::scalar(Query\Exists::byJsonPath($tableName), [':path' => $path], new ExistsMapper());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -52,23 +52,25 @@ class Field
|
|||||||
*/
|
*/
|
||||||
public function toWhere(): string
|
public function toWhere(): string
|
||||||
{
|
{
|
||||||
|
$fieldName = ($this->qualifier == '' ? '' : "$this->qualifier.") . 'data' . match (true) {
|
||||||
|
!str_contains($this->fieldName, '.') => "->>'$this->fieldName'",
|
||||||
|
Configuration::$mode == Mode::PgSQL => "#>>'{" . implode(',', explode('.', $this->fieldName)) . "}'",
|
||||||
|
Configuration::$mode == Mode::SQLite => "->>'" . implode("'->>'", explode('.', $this->fieldName)) . "'",
|
||||||
|
default => throw new DocumentException('Database mode not set; cannot make field WHERE clause')
|
||||||
|
};
|
||||||
|
$fieldPath = match (Configuration::$mode) {
|
||||||
|
Mode::PgSQL => match (true) {
|
||||||
|
$this->op == Op::BT => is_numeric($this->value[0]) ? "($fieldName)::numeric" : $fieldName,
|
||||||
|
is_numeric($this->value) => "($fieldName)::numeric",
|
||||||
|
default => $fieldName
|
||||||
|
},
|
||||||
|
default => $fieldName
|
||||||
|
};
|
||||||
$criteria = match ($this->op) {
|
$criteria = match ($this->op) {
|
||||||
Op::EX, Op::NEX => '',
|
Op::EX, Op::NEX => '',
|
||||||
Op::BT => " {$this->paramName}min AND {$this->paramName}max",
|
Op::BT => " {$this->paramName}min AND {$this->paramName}max",
|
||||||
default => " $this->paramName"
|
default => " $this->paramName"
|
||||||
};
|
};
|
||||||
$prefix = $this->qualifier == '' ? '' : "$this->qualifier.";
|
|
||||||
$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;
|
return $fieldPath . ' ' . $this->op->toString() . $criteria;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
28
src/FieldMatch.php
Normal file
28
src/FieldMatch.php
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How multiple fields should be matched
|
||||||
|
*/
|
||||||
|
enum FieldMatch
|
||||||
|
{
|
||||||
|
/** Match all provided fields (`AND`) */
|
||||||
|
case All;
|
||||||
|
|
||||||
|
/** Match any provided fields (`OR`) */
|
||||||
|
case Any;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the SQL keyword for this enumeration value
|
||||||
|
*
|
||||||
|
* @return string The SQL keyword for this enumeration value
|
||||||
|
*/
|
||||||
|
public function toString(): string
|
||||||
|
{
|
||||||
|
return match ($this) {
|
||||||
|
FieldMatch::All => 'AND',
|
||||||
|
FieldMatch::Any => 'OR'
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
84
src/Find.php
84
src/Find.php
@@ -3,6 +3,7 @@
|
|||||||
namespace BitBadger\PDODocument;
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
use BitBadger\PDODocument\Mapper\DocumentMapper;
|
use BitBadger\PDODocument\Mapper\DocumentMapper;
|
||||||
|
use PhpOption\Option;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functions to find documents
|
* Functions to find documents
|
||||||
@@ -30,12 +31,13 @@ class Find
|
|||||||
* @param string $tableName The table from which the document should 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 mixed $docId The ID of the document to retrieve
|
||||||
* @param class-string<TDoc> $className The name of the class to be retrieved
|
* @param class-string<TDoc> $className The name of the class to be retrieved
|
||||||
* @return false|TDoc The document if it exists, false if not
|
* @return Option<TDoc> A `Some` instance if the document is found, `None` otherwise
|
||||||
* @throws DocumentException If any is encountered
|
* @throws DocumentException If any is encountered
|
||||||
*/
|
*/
|
||||||
public static function byId(string $tableName, mixed $docId, string $className): mixed
|
public static function byId(string $tableName, mixed $docId, string $className): Option
|
||||||
{
|
{
|
||||||
return Custom::single(Query\Find::byId($tableName), Parameters::id($docId), new DocumentMapper($className));
|
return Custom::single(Query\Find::byId($tableName, $docId), Parameters::id($docId),
|
||||||
|
new DocumentMapper($className));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -45,18 +47,49 @@ class Find
|
|||||||
* @param string $tableName The table from which documents should be retrieved
|
* @param string $tableName The table from which documents should be retrieved
|
||||||
* @param array|Field[] $fields The field comparison to match
|
* @param array|Field[] $fields The field comparison to match
|
||||||
* @param class-string<TDoc> $className The name of the class to be retrieved
|
* @param class-string<TDoc> $className The name of the class to be retrieved
|
||||||
* @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
|
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
|
||||||
* @return DocumentList<TDoc> A list of documents matching the given field comparison
|
* @return DocumentList<TDoc> A list of documents matching the given field comparison
|
||||||
* @throws DocumentException If any is encountered
|
* @throws DocumentException If any is encountered
|
||||||
*/
|
*/
|
||||||
public static function byFields(string $tableName, array $fields, string $className,
|
public static function byFields(string $tableName, array $fields, string $className,
|
||||||
string $conjunction = 'AND'): DocumentList
|
?FieldMatch $match = null): DocumentList
|
||||||
{
|
{
|
||||||
$namedFields = Parameters::nameFields($fields);
|
$namedFields = Parameters::nameFields($fields);
|
||||||
return Custom::list(Query\Find::byFields($tableName, $namedFields, $conjunction),
|
return Custom::list(Query\Find::byFields($tableName, $namedFields, $match),
|
||||||
Parameters::addFields($namedFields, []), new DocumentMapper($className));
|
Parameters::addFields($namedFields, []), new DocumentMapper($className));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve documents via a JSON containment query (`@>`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @template TDoc The type of document to be retrieved
|
||||||
|
* @param string $tableName The name of the table from which documents should be retrieved
|
||||||
|
* @param array|object $criteria The criteria for the JSON containment query
|
||||||
|
* @param class-string<TDoc> $className The name of the class to be retrieved
|
||||||
|
* @return DocumentList<TDoc> A list of documents matching the JSON containment query
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function byContains(string $tableName, array|object $criteria, string $className): DocumentList
|
||||||
|
{
|
||||||
|
return Custom::list(Query\Find::byContains($tableName), Parameters::json(':criteria', $criteria),
|
||||||
|
new DocumentMapper($className));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve documents via a JSON Path match query (`@?`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @template TDoc The type of document to be retrieved
|
||||||
|
* @param string $tableName The name of the table from which documents should be retrieved
|
||||||
|
* @param string $path The JSON Path match string
|
||||||
|
* @param class-string<TDoc> $className The name of the class to be retrieved
|
||||||
|
* @return DocumentList<TDoc> A list of documents matching the JSON Path
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function byJsonPath(string $tableName, string $path, string $className): DocumentList
|
||||||
|
{
|
||||||
|
return Custom::list(Query\Find::byJsonPath($tableName), [':path' => $path], new DocumentMapper($className));
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieve documents via a comparison on JSON fields, returning only the first result
|
* Retrieve documents via a comparison on JSON fields, returning only the first result
|
||||||
*
|
*
|
||||||
@@ -64,15 +97,46 @@ class Find
|
|||||||
* @param string $tableName The table from which the document should be retrieved
|
* @param string $tableName The table from which the document should be retrieved
|
||||||
* @param array|Field[] $fields The field comparison to match
|
* @param array|Field[] $fields The field comparison to match
|
||||||
* @param class-string<TDoc> $className The name of the class to be retrieved
|
* @param class-string<TDoc> $className The name of the class to be retrieved
|
||||||
* @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
|
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
|
||||||
* @return false|TDoc The first document if any matches are found, false otherwise
|
* @return Option<TDoc> A `Some` instance with the first document if any matches are found, `None` otherwise
|
||||||
* @throws DocumentException If any is encountered
|
* @throws DocumentException If any is encountered
|
||||||
*/
|
*/
|
||||||
public static function firstByFields(string $tableName, array $fields, string $className,
|
public static function firstByFields(string $tableName, array $fields, string $className,
|
||||||
string $conjunction = 'AND'): mixed
|
?FieldMatch $match = null): Option
|
||||||
{
|
{
|
||||||
$namedFields = Parameters::nameFields($fields);
|
$namedFields = Parameters::nameFields($fields);
|
||||||
return Custom::single(Query\Find::byFields($tableName, $namedFields, $conjunction),
|
return Custom::single(Query\Find::byFields($tableName, $namedFields, $match),
|
||||||
Parameters::addFields($namedFields, []), new DocumentMapper($className));
|
Parameters::addFields($namedFields, []), new DocumentMapper($className));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve documents via a JSON containment query (`@>`), returning only the first result (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @template TDoc The type of document to be retrieved
|
||||||
|
* @param string $tableName The name of the table from which documents should be retrieved
|
||||||
|
* @param array|object $criteria The criteria for the JSON containment query
|
||||||
|
* @param class-string<TDoc> $className The name of the class to be retrieved
|
||||||
|
* @return Option<TDoc> A `Some` instance with the first document if any matches are found, `None` otherwise
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function firstByContains(string $tableName, array|object $criteria, string $className): Option
|
||||||
|
{
|
||||||
|
return Custom::single(Query\Find::byContains($tableName), Parameters::json(':criteria', $criteria),
|
||||||
|
new DocumentMapper($className));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve documents via a JSON Path match query (`@?`), returning only the first result (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @template TDoc The type of document to be retrieved
|
||||||
|
* @param string $tableName The name of the table from which documents should be retrieved
|
||||||
|
* @param string $path The JSON Path match string
|
||||||
|
* @param class-string<TDoc> $className The name of the class to be retrieved
|
||||||
|
* @return Option<TDoc> A `Some` instance with the first document if any matches are found, `None` otherwise
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function firstByJsonPath(string $tableName, string $path, string $className): Option
|
||||||
|
{
|
||||||
|
return Custom::single(Query\Find::byJsonPath($tableName), [':path' => $path], new DocumentMapper($className));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -68,7 +68,7 @@ class Parameters
|
|||||||
{
|
{
|
||||||
switch (Configuration::$mode) {
|
switch (Configuration::$mode) {
|
||||||
case Mode::PgSQL:
|
case Mode::PgSQL:
|
||||||
return [$paramName => "ARRAY['" . implode("','", $fieldNames) . "']"];
|
return [$paramName => "{" . implode(",", $fieldNames) . "}"];
|
||||||
case Mode::SQLite:
|
case Mode::SQLite:
|
||||||
$it = [];
|
$it = [];
|
||||||
$idx = 0;
|
$idx = 0;
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ class Patch
|
|||||||
*/
|
*/
|
||||||
public static function byId(string $tableName, mixed $docId, array|object $patch): void
|
public static function byId(string $tableName, mixed $docId, array|object $patch): void
|
||||||
{
|
{
|
||||||
Custom::nonQuery(Query\Patch::byId($tableName),
|
Custom::nonQuery(Query\Patch::byId($tableName, $docId),
|
||||||
array_merge(Parameters::id($docId), Parameters::json(':data', $patch)));
|
array_merge(Parameters::id($docId), Parameters::json(':data', $patch)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -27,14 +27,42 @@ class Patch
|
|||||||
* @param string $tableName The table in which documents should be patched
|
* @param string $tableName The table in which documents should be patched
|
||||||
* @param array|Field[] $fields The field comparison to match
|
* @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 array|object $patch The object with which the documents should be patched (will be JSON-encoded)
|
||||||
* @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
|
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
|
||||||
* @throws DocumentException If any is encountered
|
* @throws DocumentException If any is encountered
|
||||||
*/
|
*/
|
||||||
public static function byFields(string $tableName, array $fields, array|object $patch,
|
public static function byFields(string $tableName, array $fields, array|object $patch,
|
||||||
string $conjunction = 'AND'): void
|
?FieldMatch $match = null): void
|
||||||
{
|
{
|
||||||
$namedFields = Parameters::nameFields($fields);
|
$namedFields = Parameters::nameFields($fields);
|
||||||
Custom::nonQuery(Query\Patch::byFields($tableName, $namedFields, $conjunction),
|
Custom::nonQuery(Query\Patch::byFields($tableName, $namedFields, $match),
|
||||||
Parameters::addFields($namedFields, Parameters::json(':data', $patch)));
|
Parameters::addFields($namedFields, Parameters::json(':data', $patch)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Patch documents using a JSON containment query (`@>`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The table in which documents should be patched
|
||||||
|
* @param array|object $criteria The JSON containment query values to match
|
||||||
|
* @param array|object $patch The object with which the documents should be patched (will be JSON-encoded)
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function byContains(string $tableName, array|object $criteria, array|object $patch): void
|
||||||
|
{
|
||||||
|
Custom::nonQuery(Query\Patch::byContains($tableName),
|
||||||
|
array_merge(Parameters::json(':criteria', $criteria), Parameters::json(':data', $patch)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Patch documents using a JSON Path match query (`@?`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The table in which documents should be patched
|
||||||
|
* @param string $path The JSON Path match string
|
||||||
|
* @param array|object $patch The object with which the documents should be patched (will be JSON-encoded)
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function byJsonPath(string $tableName, string $path, array|object $patch): void
|
||||||
|
{
|
||||||
|
Custom::nonQuery(Query\Patch::byJsonPath($tableName),
|
||||||
|
array_merge([':path' => $path], Parameters::json(':data', $patch)));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
namespace BitBadger\PDODocument;
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
use Random\RandomException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Query construction functions
|
* Query construction functions
|
||||||
*/
|
*/
|
||||||
@@ -22,34 +24,95 @@ class Query
|
|||||||
* Create a WHERE clause fragment to implement a comparison on fields in a JSON document
|
* Create a WHERE clause fragment to implement a comparison on fields in a JSON document
|
||||||
*
|
*
|
||||||
* @param Field[] $fields The field comparison to generate
|
* @param Field[] $fields The field comparison to generate
|
||||||
* @param string $conjunction How to join multiple conditions (optional; defaults to AND)
|
* @param FieldMatch|null $match How to join multiple conditions (optional; defaults to All)
|
||||||
* @return string The WHERE clause fragment matching the given fields and parameter
|
* @return string The WHERE clause fragment matching the given fields and parameter
|
||||||
|
* @throws DocumentException If the database mode has not been set
|
||||||
*/
|
*/
|
||||||
public static function whereByFields(array $fields, string $conjunction = 'AND'): string
|
public static function whereByFields(array $fields, ?FieldMatch $match = null): string
|
||||||
{
|
{
|
||||||
return implode(" $conjunction ", array_map(fn($it) => $it->toWhere(), $fields));
|
return implode(' ' . ($match ?? FieldMatch::All)->toString() . ' ',
|
||||||
|
array_map(fn($it) => $it->toWhere(), $fields));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a WHERE clause fragment to implement an ID-based query
|
* 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)
|
* @param string $paramName The parameter name where the value of the ID will be provided (optional; default @id)
|
||||||
|
* @param mixed $docId The ID of the document to be retrieved; used to determine type for potential JSON field
|
||||||
|
* casts (optional; string ID assumed if no value is provided)
|
||||||
* @return string The WHERE clause fragment to match by ID
|
* @return string The WHERE clause fragment to match by ID
|
||||||
|
* @throws DocumentException If the database mode has not been set
|
||||||
*/
|
*/
|
||||||
public static function whereById(string $paramName = ':id'): string
|
public static function whereById(string $paramName = ':id', mixed $docId = null): string
|
||||||
{
|
{
|
||||||
return self::whereByFields([Field::EQ(Configuration::$idField, 0, $paramName)]);
|
return self::whereByFields([Field::EQ(Configuration::$idField, $docId ?? '', $paramName)]);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Query to insert a document
|
* Create a WHERE clause fragment to implement a JSON containment query (PostgreSQL only)
|
||||||
*
|
*
|
||||||
* @param string $tableName The name of the table into which a document should be inserted
|
* @param string $paramName The name of the parameter (optional; defaults to `:criteria`)
|
||||||
* @return string The INSERT statement for the given table
|
* @return string The WHERE clause fragment for a JSON containment query
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL
|
||||||
*/
|
*/
|
||||||
public static function insert(string $tableName): string
|
public static function whereDataContains(string $paramName = ':criteria'): string
|
||||||
{
|
{
|
||||||
return "INSERT INTO $tableName VALUES (:data)";
|
if (Configuration::$mode <> Mode::PgSQL) {
|
||||||
|
throw new DocumentException('JSON containment is only supported on PostgreSQL');
|
||||||
|
}
|
||||||
|
return "data @> $paramName";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a WHERE clause fragment to implement a JSON Path match query (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $paramName The name of the parameter (optional; defaults to `:path`)
|
||||||
|
* @return string The WHERE clause fragment for a JSON Path match query
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL
|
||||||
|
*/
|
||||||
|
public static function whereJsonPathMatches(string $paramName = ':path'): string
|
||||||
|
{
|
||||||
|
if (Configuration::$mode <> Mode::PgSQL) {
|
||||||
|
throw new DocumentException('JSON Path matching is only supported on PostgreSQL');
|
||||||
|
}
|
||||||
|
return "jsonb_path_exists(data, $paramName::jsonpath)";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create an `INSERT` statement for a document
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table into which the document will be inserted
|
||||||
|
* @param AutoId|null $autoId The version of automatic ID query to generate (optional, defaults to None)
|
||||||
|
* @return string The `INSERT` statement to insert a document
|
||||||
|
* @throws DocumentException If the database mode is not set
|
||||||
|
*/
|
||||||
|
public static function insert(string $tableName, ?AutoId $autoId = null): string
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$id = Configuration::$idField;
|
||||||
|
$values = match (Configuration::$mode) {
|
||||||
|
Mode::SQLite => match ($autoId ?? AutoId::None) {
|
||||||
|
AutoId::None => ':data',
|
||||||
|
AutoId::Number => "json_set(:data, '$.$id', "
|
||||||
|
. "(SELECT coalesce(max(data->>'$id'), 0) + 1 FROM $tableName))",
|
||||||
|
AutoId::UUID => "json_set(:data, '$.$id', '" . AutoId::generateUUID() . "')",
|
||||||
|
AutoId::RandomString => "json_set(:data, '$.$id', '" . AutoId::generateRandom() ."')"
|
||||||
|
},
|
||||||
|
Mode::PgSQL => match ($autoId ?? AutoId::None) {
|
||||||
|
AutoId::None => ':data',
|
||||||
|
AutoId::Number => ":data::jsonb || ('{\"$id\":' || "
|
||||||
|
. "(SELECT COALESCE(MAX((data->>'$id')::numeric), 0) + 1 "
|
||||||
|
. "FROM $tableName) || '}')::jsonb",
|
||||||
|
AutoId::UUID => ":data::jsonb || '{\"$id\":\"" . AutoId::generateUUID() . "\"}'",
|
||||||
|
AutoId::RandomString => ":data::jsonb || '{\"$id\":\"" . AutoId::generateRandom() . "\"}'",
|
||||||
|
},
|
||||||
|
default =>
|
||||||
|
throw new DocumentException('Database mode not set; cannot generate auto-ID INSERT statement'),
|
||||||
|
};
|
||||||
|
return "INSERT INTO $tableName VALUES ($values)";
|
||||||
|
} catch (RandomException $ex) {
|
||||||
|
throw new DocumentException('Unable to generate ID: ' . $ex->getMessage(), previous: $ex);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -60,8 +123,8 @@ class Query
|
|||||||
*/
|
*/
|
||||||
public static function save(string $tableName): string
|
public static function save(string $tableName): string
|
||||||
{
|
{
|
||||||
return self::insert($tableName)
|
$id = Configuration::$idField;
|
||||||
. " ON CONFLICT ((data->>'" . Configuration::$idField . "')) DO UPDATE SET data = EXCLUDED.data";
|
return "INSERT INTO $tableName VALUES (:data) ON CONFLICT ((data->>'$id')) DO UPDATE SET data = EXCLUDED.data";
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -69,6 +132,7 @@ class Query
|
|||||||
*
|
*
|
||||||
* @param string $tableName The name of the table in which the document should be updated
|
* @param string $tableName The name of the table in which the document should be updated
|
||||||
* @return string The UPDATE query for the document
|
* @return string The UPDATE query for the document
|
||||||
|
* @throws DocumentException If the database mode has not been set
|
||||||
*/
|
*/
|
||||||
public static function update(string $tableName): string
|
public static function update(string $tableName): string
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
namespace BitBadger\PDODocument\Query;
|
namespace BitBadger\PDODocument\Query;
|
||||||
|
|
||||||
use BitBadger\PDODocument\{Field, Query};
|
use BitBadger\PDODocument\{DocumentException, Field, FieldMatch, Query};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Queries for counting documents
|
* Queries for counting documents
|
||||||
@@ -25,11 +25,36 @@ class Count
|
|||||||
*
|
*
|
||||||
* @param string $tableName The name of the table in which documents should be counted
|
* @param string $tableName The name of the table in which documents should be counted
|
||||||
* @param Field[] $fields The field comparison to match
|
* @param Field[] $fields The field comparison to match
|
||||||
* @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
|
* @param FieldMatch|null $match How to join multiple conditions (optional; defaults to All)
|
||||||
* @return string The query to count documents using a field comparison
|
* @return string The query to count documents using a field comparison
|
||||||
|
* @throws DocumentException If the database mode has not been set
|
||||||
*/
|
*/
|
||||||
public static function byFields(string $tableName, array $fields, string $conjunction = 'AND'): string
|
public static function byFields(string $tableName, array $fields, ?FieldMatch $match = null): string
|
||||||
{
|
{
|
||||||
return self::all($tableName) . ' WHERE ' . Query::whereByFields($fields, $conjunction);
|
return self::all($tableName) . ' WHERE ' . Query::whereByFields($fields, $match);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to count matching documents using a JSON containment query (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which documents should be counted
|
||||||
|
* @return string The query to count documents using a JSON containment query
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL
|
||||||
|
*/
|
||||||
|
public static function byContains(string $tableName): string
|
||||||
|
{
|
||||||
|
return self::all($tableName) . ' WHERE ' . Query::whereDataContains();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to count matching documents using a JSON Path match (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which documents should be counted
|
||||||
|
* @return string The query to count documents using a JSON Path match
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL
|
||||||
|
*/
|
||||||
|
public static function byJsonPath(string $tableName): string
|
||||||
|
{
|
||||||
|
return self::all($tableName) . ' WHERE ' . Query::whereJsonPathMatches();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
namespace BitBadger\PDODocument\Query;
|
namespace BitBadger\PDODocument\Query;
|
||||||
|
|
||||||
use BitBadger\PDODocument\{Configuration, DocumentException, Mode};
|
use BitBadger\PDODocument\{Configuration, DocumentException, DocumentIndex, Mode};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Queries to define tables and indexes
|
* Queries to define tables and indexes
|
||||||
@@ -68,4 +68,25 @@ class Definition
|
|||||||
{
|
{
|
||||||
return str_replace('INDEX', 'UNIQUE INDEX', self::ensureIndexOn($tableName, 'key', [Configuration::$idField]));
|
return str_replace('INDEX', 'UNIQUE INDEX', self::ensureIndexOn($tableName, 'key', [Configuration::$idField]));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a document-wide index on a table (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table on which the document index should be created
|
||||||
|
* @param DocumentIndex $indexType The type of index to be created
|
||||||
|
* @return string The SQL statement to create an index on JSON documents in the specified table
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL
|
||||||
|
*/
|
||||||
|
public static function ensureDocumentIndexOn(string $tableName, DocumentIndex $indexType): string
|
||||||
|
{
|
||||||
|
if (Configuration::$mode <> Mode::PgSQL) {
|
||||||
|
throw new DocumentException('Document indexes are only supported on PostgreSQL');
|
||||||
|
}
|
||||||
|
[, $tbl] = self::splitSchemaAndTable($tableName);
|
||||||
|
$extraOps = match ($indexType) {
|
||||||
|
DocumentIndex::Full => '',
|
||||||
|
DocumentIndex::Optimized => ' jsonb_path_ops'
|
||||||
|
};
|
||||||
|
return "CREATE INDEX IF NOT EXISTS idx_{$tbl}_document ON $tableName USING GIN (data$extraOps)";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
namespace BitBadger\PDODocument\Query;
|
namespace BitBadger\PDODocument\Query;
|
||||||
|
|
||||||
use BitBadger\PDODocument\{Field, Query};
|
use BitBadger\PDODocument\{DocumentException, Field, FieldMatch, Query};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Queries to delete documents
|
* Queries to delete documents
|
||||||
@@ -13,11 +13,13 @@ class Delete
|
|||||||
* Query to delete a document by its ID
|
* Query to delete a document by its ID
|
||||||
*
|
*
|
||||||
* @param string $tableName The name of the table from which a document should be deleted
|
* @param string $tableName The name of the table from which a document should be deleted
|
||||||
|
* @param mixed $docId The ID of the document to be deleted (optional; string ID assumed)
|
||||||
* @return string The DELETE statement to delete a document by its ID
|
* @return string The DELETE statement to delete a document by its ID
|
||||||
|
* @throws DocumentException If the database mode has not been set
|
||||||
*/
|
*/
|
||||||
public static function byId(string $tableName): string
|
public static function byId(string $tableName, mixed $docId = null): string
|
||||||
{
|
{
|
||||||
return "DELETE FROM $tableName WHERE " . Query::whereById();
|
return "DELETE FROM $tableName WHERE " . Query::whereById(docId: $docId);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -25,11 +27,36 @@ class Delete
|
|||||||
*
|
*
|
||||||
* @param string $tableName The name of the table from which documents should be deleted
|
* @param string $tableName The name of the table from which documents should be deleted
|
||||||
* @param Field[] $fields The field comparison to match
|
* @param Field[] $fields The field comparison to match
|
||||||
* @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
|
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
|
||||||
* @return string The DELETE statement to delete documents via field comparison
|
* @return string The DELETE statement to delete documents via field comparison
|
||||||
|
* @throws DocumentException If the database mode has not been set
|
||||||
*/
|
*/
|
||||||
public static function byFields(string $tableName, array $fields, string $conjunction = 'AND'): string
|
public static function byFields(string $tableName, array $fields, ?FieldMatch $match = null): string
|
||||||
{
|
{
|
||||||
return "DELETE FROM $tableName WHERE " . Query::whereByFields($fields, $conjunction);
|
return "DELETE FROM $tableName WHERE " . Query::whereByFields($fields, $match);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to delete documents using a JSON containment query (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table from which documents should be deleted
|
||||||
|
* @return string The DELETE statement to delete documents via a JSON containment query
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL
|
||||||
|
*/
|
||||||
|
public static function byContains(string $tableName): string
|
||||||
|
{
|
||||||
|
return "DELETE FROM $tableName WHERE " . Query::whereDataContains();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to delete documents using a JSON Path match query (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table from which documents should be deleted
|
||||||
|
* @return string The DELETE statement to delete documents via a JSON Path match
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL
|
||||||
|
*/
|
||||||
|
public static function byJsonPath(string $tableName): string
|
||||||
|
{
|
||||||
|
return "DELETE FROM $tableName WHERE " . Query::whereJsonPathMatches();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
namespace BitBadger\PDODocument\Query;
|
namespace BitBadger\PDODocument\Query;
|
||||||
|
|
||||||
use BitBadger\PDODocument\{Field, Query};
|
use BitBadger\PDODocument\{DocumentException, Field, FieldMatch, Query};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Queries to determine document existence
|
* Queries to determine document existence
|
||||||
@@ -25,11 +25,13 @@ class Exists
|
|||||||
* Query to determine if a document exists for the given ID
|
* Query to determine if a document exists for the given ID
|
||||||
*
|
*
|
||||||
* @param string $tableName The name of the table in which document existence should be checked
|
* @param string $tableName The name of the table in which document existence should be checked
|
||||||
|
* @param mixed $docId The ID of the document whose existence should be checked (optional; string ID assumed)
|
||||||
* @return string The query to determine document existence by ID
|
* @return string The query to determine document existence by ID
|
||||||
|
* @throws DocumentException If the database mode has not been set
|
||||||
*/
|
*/
|
||||||
public static function byId(string $tableName): string
|
public static function byId(string $tableName, mixed $docId = null): string
|
||||||
{
|
{
|
||||||
return self::query($tableName, Query::whereById());
|
return self::query($tableName, Query::whereById(docId: $docId));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -37,11 +39,36 @@ class Exists
|
|||||||
*
|
*
|
||||||
* @param string $tableName The name of the table in which document existence should be checked
|
* @param string $tableName The name of the table in which document existence should be checked
|
||||||
* @param Field[] $fields The field comparison to match
|
* @param Field[] $fields The field comparison to match
|
||||||
* @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
|
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
|
||||||
* @return string The query to determine document existence by field comparison
|
* @return string The query to determine document existence by field comparison
|
||||||
|
* @throws DocumentException If the database mode has not been set
|
||||||
*/
|
*/
|
||||||
public static function byFields(string $tableName, array $fields, string $conjunction = 'AND'): string
|
public static function byFields(string $tableName, array $fields, ?FieldMatch $match = null): string
|
||||||
{
|
{
|
||||||
return self::query($tableName, Query::whereByFields($fields, $conjunction));
|
return self::query($tableName, Query::whereByFields($fields, $match));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to determine if documents exist using a JSON containment query (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which document existence should be checked
|
||||||
|
* @return string The query to determine document existence by a JSON containment query
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL
|
||||||
|
*/
|
||||||
|
public static function byContains(string $tableName): string
|
||||||
|
{
|
||||||
|
return self::query($tableName, Query::whereDataContains());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to determine if documents exist using a JSON Path match query (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which document existence should be checked
|
||||||
|
* @return string The query to determine document existence by a JSON Path match
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL
|
||||||
|
*/
|
||||||
|
public static function byJsonPath(string $tableName): string
|
||||||
|
{
|
||||||
|
return self::query($tableName, Query::whereJsonPathMatches());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
namespace BitBadger\PDODocument\Query;
|
namespace BitBadger\PDODocument\Query;
|
||||||
|
|
||||||
use BitBadger\PDODocument\{Field, Query};
|
use BitBadger\PDODocument\{DocumentException, Field, FieldMatch, Query};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Queries for retrieving documents
|
* Queries for retrieving documents
|
||||||
@@ -13,11 +13,13 @@ class Find
|
|||||||
* Query to retrieve a document by its ID
|
* Query to retrieve a document by its ID
|
||||||
*
|
*
|
||||||
* @param string $tableName The name of the table from which a document should be retrieved
|
* @param string $tableName The name of the table from which a document should be retrieved
|
||||||
|
* @param mixed $docId The ID of the document to be retrieved (optional; string ID assumed)
|
||||||
* @return string The SELECT statement to retrieve a document by its ID
|
* @return string The SELECT statement to retrieve a document by its ID
|
||||||
|
* @throws DocumentException If the database mode has not been set
|
||||||
*/
|
*/
|
||||||
public static function byId(string $tableName): string
|
public static function byId(string $tableName, mixed $docId = null): string
|
||||||
{
|
{
|
||||||
return Query::selectFromTable($tableName) . ' WHERE ' . Query::whereById();
|
return Query::selectFromTable($tableName) . ' WHERE ' . Query::whereById(docId: $docId);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -25,11 +27,36 @@ class Find
|
|||||||
*
|
*
|
||||||
* @param string $tableName The name of the table from which documents should be retrieved
|
* @param string $tableName The name of the table from which documents should be retrieved
|
||||||
* @param Field[] $fields The field comparison to match
|
* @param Field[] $fields The field comparison to match
|
||||||
* @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
|
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
|
||||||
* @return string The SELECT statement to retrieve documents by field comparison
|
* @return string The SELECT statement to retrieve documents by field comparison
|
||||||
|
* @throws DocumentException If the database mode has not been set
|
||||||
*/
|
*/
|
||||||
public static function byFields(string $tableName, array $fields, string $conjunction = 'AND'): string
|
public static function byFields(string $tableName, array $fields, ?FieldMatch $match = null): string
|
||||||
{
|
{
|
||||||
return Query::selectFromTable($tableName) . ' WHERE ' . Query::whereByFields($fields, $conjunction);
|
return Query::selectFromTable($tableName) . ' WHERE ' . Query::whereByFields($fields, $match);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to retrieve documents using a JSON containment query (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table from which documents should be retrieved
|
||||||
|
* @return string The SELECT statement to retrieve documents by a JSON containment query
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL
|
||||||
|
*/
|
||||||
|
public static function byContains(string $tableName): string
|
||||||
|
{
|
||||||
|
return Query::selectFromTable($tableName) . ' WHERE ' . Query::whereDataContains();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to retrieve documents using a JSON Path match query (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table from which documents should be retrieved
|
||||||
|
* @return string The SELECT statement to retrieve documents by a JSON Path match
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL
|
||||||
|
*/
|
||||||
|
public static function byJsonPath(string $tableName): string
|
||||||
|
{
|
||||||
|
return Query::selectFromTable($tableName) . ' WHERE ' . Query::whereJsonPathMatches();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
namespace BitBadger\PDODocument\Query;
|
namespace BitBadger\PDODocument\Query;
|
||||||
|
|
||||||
use BitBadger\PDODocument\{Configuration, DocumentException, Field, Mode, Query};
|
use BitBadger\PDODocument\{Configuration, DocumentException, Field, FieldMatch, Mode, Query};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Queries to perform partial updates on documents
|
* Queries to perform partial updates on documents
|
||||||
@@ -31,12 +31,13 @@ class Patch
|
|||||||
* Query to patch (partially update) a document by its ID
|
* 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
|
* @param string $tableName The name of the table in which a document should be patched
|
||||||
|
* @param mixed $docId The ID of the document to be patched (optional; string ID assumed)
|
||||||
* @return string The query to patch a document by its ID
|
* @return string The query to patch a document by its ID
|
||||||
* @throws DocumentException If the database mode has not been set
|
* @throws DocumentException If the database mode has not been set
|
||||||
*/
|
*/
|
||||||
public static function byId(string $tableName): string
|
public static function byId(string $tableName, mixed $docId = null): string
|
||||||
{
|
{
|
||||||
return self::update($tableName, Query::whereById());
|
return self::update($tableName, Query::whereById(docId: $docId));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -44,12 +45,36 @@ class Patch
|
|||||||
*
|
*
|
||||||
* @param string $tableName The name of the table in which documents should be patched
|
* @param string $tableName The name of the table in which documents should be patched
|
||||||
* @param array|Field[] $field The field comparison to match
|
* @param array|Field[] $field The field comparison to match
|
||||||
* @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
|
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
|
||||||
* @return string The query to patch documents via field comparison
|
* @return string The query to patch documents via field comparison
|
||||||
* @throws DocumentException If the database mode has not been set
|
* @throws DocumentException If the database mode has not been set
|
||||||
*/
|
*/
|
||||||
public static function byFields(string $tableName, array $field, string $conjunction = 'AND'): string
|
public static function byFields(string $tableName, array $field, ?FieldMatch $match = null): string
|
||||||
{
|
{
|
||||||
return self::update($tableName, Query::whereByFields($field, $conjunction));
|
return self::update($tableName, Query::whereByFields($field, $match));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to patch (partially update) a document via a JSON containment query (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which documents should be patched
|
||||||
|
* @return string The query to patch documents via a JSON containment query
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL
|
||||||
|
*/
|
||||||
|
public static function byContains(string $tableName): string
|
||||||
|
{
|
||||||
|
return self::update($tableName, Query::whereDataContains());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to patch (partially update) a document via a JSON Path match query (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which documents should be patched
|
||||||
|
* @return string The query to patch documents via a JSON Path match
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL
|
||||||
|
*/
|
||||||
|
public static function byJsonPath(string $tableName): string
|
||||||
|
{
|
||||||
|
return self::update($tableName, Query::whereJsonPathMatches());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
namespace BitBadger\PDODocument\Query;
|
namespace BitBadger\PDODocument\Query;
|
||||||
|
|
||||||
use BitBadger\PDODocument\{Configuration, DocumentException, Field, Mode, Query};
|
use BitBadger\PDODocument\{Configuration, DocumentException, Field, FieldMatch, Mode, Query};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Queries to remove fields from documents
|
* Queries to remove fields from documents
|
||||||
@@ -26,7 +26,8 @@ class RemoveFields
|
|||||||
{
|
{
|
||||||
switch (Configuration::$mode) {
|
switch (Configuration::$mode) {
|
||||||
case Mode::PgSQL:
|
case Mode::PgSQL:
|
||||||
return "UPDATE $tableName SET data = data - " . array_keys($parameters)[0] . " WHERE $whereClause";
|
return "UPDATE $tableName SET data = data - " . array_keys($parameters)[0]
|
||||||
|
. "::text[] WHERE $whereClause";
|
||||||
case Mode::SQLite:
|
case Mode::SQLite:
|
||||||
$paramNames = implode(', ', array_keys($parameters));
|
$paramNames = implode(', ', array_keys($parameters));
|
||||||
return "UPDATE $tableName SET data = json_remove(data, $paramNames) WHERE $whereClause";
|
return "UPDATE $tableName SET data = json_remove(data, $paramNames) WHERE $whereClause";
|
||||||
@@ -40,12 +41,13 @@ class RemoveFields
|
|||||||
*
|
*
|
||||||
* @param string $tableName The name of the table in which the document should be manipulated
|
* @param string $tableName The name of the table in which the document should be manipulated
|
||||||
* @param array $parameters The parameter list for the query
|
* @param array $parameters The parameter list for the query
|
||||||
|
* @param mixed $docId The ID of the document from which fields should be removed (optional; string ID assumed)
|
||||||
* @return string The UPDATE statement to remove fields from a document by its ID
|
* @return string The UPDATE statement to remove fields from a document by its ID
|
||||||
* @throws DocumentException If the database mode has not been set
|
* @throws DocumentException If the database mode has not been set
|
||||||
*/
|
*/
|
||||||
public static function byId(string $tableName, array $parameters): string
|
public static function byId(string $tableName, array $parameters, mixed $docId = null): string
|
||||||
{
|
{
|
||||||
return self::update($tableName, $parameters, Query::whereById());
|
return self::update($tableName, $parameters, Query::whereById(docId: $docId));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -54,13 +56,39 @@ class RemoveFields
|
|||||||
* @param string $tableName The name of the table in which documents should be manipulated
|
* @param string $tableName The name of the table in which documents should be manipulated
|
||||||
* @param array|Field[] $fields The field comparison to match
|
* @param array|Field[] $fields The field comparison to match
|
||||||
* @param array $parameters The parameter list for the query
|
* @param array $parameters The parameter list for the query
|
||||||
* @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
|
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
|
||||||
* @return string The UPDATE statement to remove fields from documents via field comparison
|
* @return string The UPDATE statement to remove fields from documents via field comparison
|
||||||
* @throws DocumentException If the database mode has not been set
|
* @throws DocumentException If the database mode has not been set
|
||||||
*/
|
*/
|
||||||
public static function byFields(string $tableName, array $fields, array $parameters,
|
public static function byFields(string $tableName, array $fields, array $parameters,
|
||||||
string $conjunction = 'AND'): string
|
?FieldMatch $match = null): string
|
||||||
{
|
{
|
||||||
return self::update($tableName, $parameters, Query::whereByFields($fields, $conjunction));
|
return self::update($tableName, $parameters, Query::whereByFields($fields, $match));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to remove fields from documents via a JSON containment query (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which documents should be manipulated
|
||||||
|
* @param array $parameters The parameter list for the query
|
||||||
|
* @return string The UPDATE statement to remove fields from documents via a JSON containment query
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL
|
||||||
|
*/
|
||||||
|
public static function byContains(string $tableName, array $parameters): string
|
||||||
|
{
|
||||||
|
return self::update($tableName, $parameters, Query::whereDataContains());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to remove fields from documents via a JSON Path match query (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which documents should be manipulated
|
||||||
|
* @param array $parameters The parameter list for the query
|
||||||
|
* @return string The UPDATE statement to remove fields from documents via a JSON Path match
|
||||||
|
* @throws DocumentException
|
||||||
|
*/
|
||||||
|
public static function byJsonPath(string $tableName, array $parameters): string
|
||||||
|
{
|
||||||
|
return self::update($tableName, $parameters, Query::whereJsonPathMatches());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ class RemoveFields
|
|||||||
public static function byId(string $tableName, mixed $docId, array $fieldNames): void
|
public static function byId(string $tableName, mixed $docId, array $fieldNames): void
|
||||||
{
|
{
|
||||||
$nameParams = Parameters::fieldNames(':name', $fieldNames);
|
$nameParams = Parameters::fieldNames(':name', $fieldNames);
|
||||||
Custom::nonQuery(Query\RemoveFields::byId($tableName, $nameParams),
|
Custom::nonQuery(Query\RemoveFields::byId($tableName, $nameParams, $docId),
|
||||||
array_merge(Parameters::id($docId), $nameParams));
|
array_merge(Parameters::id($docId), $nameParams));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -28,15 +28,45 @@ class RemoveFields
|
|||||||
* @param string $tableName The table in which documents should have fields removed
|
* @param string $tableName The table in which documents should have fields removed
|
||||||
* @param array|Field[] $fields The field comparison to match
|
* @param array|Field[] $fields The field comparison to match
|
||||||
* @param array|string[] $fieldNames The names of the fields to be removed
|
* @param array|string[] $fieldNames The names of the fields to be removed
|
||||||
* @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
|
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
|
||||||
* @throws DocumentException If any is encountered
|
* @throws DocumentException If any is encountered
|
||||||
*/
|
*/
|
||||||
public static function byFields(string $tableName, array $fields, array $fieldNames,
|
public static function byFields(string $tableName, array $fields, array $fieldNames,
|
||||||
string $conjunction = 'AND'): void
|
?FieldMatch $match = null): void
|
||||||
{
|
{
|
||||||
$nameParams = Parameters::fieldNames(':name', $fieldNames);
|
$nameParams = Parameters::fieldNames(':name', $fieldNames);
|
||||||
$namedFields = Parameters::nameFields($fields);
|
$namedFields = Parameters::nameFields($fields);
|
||||||
Custom::nonQuery(Query\RemoveFields::byFields($tableName, $namedFields, $nameParams, $conjunction),
|
Custom::nonQuery(Query\RemoveFields::byFields($tableName, $namedFields, $nameParams, $match),
|
||||||
Parameters::addFields($namedFields, $nameParams));
|
Parameters::addFields($namedFields, $nameParams));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove fields from documents via a JSON containment query (`@>`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The table in which documents should have fields removed
|
||||||
|
* @param array|object $criteria The JSON containment query values
|
||||||
|
* @param array|string[] $fieldNames The names of the fields to be removed
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function byContains(string $tableName, array|object $criteria, array $fieldNames): void
|
||||||
|
{
|
||||||
|
$nameParams = Parameters::fieldNames(':name', $fieldNames);
|
||||||
|
Custom::nonQuery(Query\RemoveFields::byContains($tableName, $nameParams),
|
||||||
|
array_merge(Parameters::json(':criteria', $criteria), $nameParams));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove fields from documents via a JSON Path match query (`@?`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The table in which documents should have fields removed
|
||||||
|
* @param string $path The JSON Path match string
|
||||||
|
* @param array|string[] $fieldNames The names of the fields to be removed
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function byJsonPath(string $tableName, string $path, array $fieldNames): void
|
||||||
|
{
|
||||||
|
$nameParams = Parameters::fieldNames(':name', $fieldNames);
|
||||||
|
Custom::nonQuery(Query\RemoveFields::byJsonPath($tableName, $nameParams),
|
||||||
|
array_merge([':path' => $path], $nameParams));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
11
tests/integration/NumDocument.php
Normal file
11
tests/integration/NumDocument.php
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A test document with a numeric ID
|
||||||
|
*/
|
||||||
|
class NumDocument
|
||||||
|
{
|
||||||
|
public function __construct(public int $id = 0, public string $value = '') { }
|
||||||
|
}
|
||||||
73
tests/integration/postgresql/CountTest.php
Normal file
73
tests/integration/postgresql/CountTest.php
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\PostgreSQL;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Count, Field};
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PostgreSQL integration tests for the Count class
|
||||||
|
*/
|
||||||
|
#[TestDox('Count (PostgreSQL integration)')]
|
||||||
|
class CountTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->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');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsSucceedsWhenDocumentsMatch(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(2, Count::byContains(ThrowawayDb::TABLE, ['value' => 'purple']),
|
||||||
|
'There should have been 2 matching documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsSucceedsWhenNoDocumentsMatch(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(0, Count::byContains(ThrowawayDb::TABLE, ['value' => 'magenta']),
|
||||||
|
'There should have been no matching documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds when documents match')]
|
||||||
|
public function testByJsonPathSucceedsWhenDocumentsMatch(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(2, Count::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ < 5)'),
|
||||||
|
'There should have been 2 matching documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds when no documents match')]
|
||||||
|
public function testByJsonPathSucceedsWhenNoDocumentsMatch(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(0, Count::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 100)'),
|
||||||
|
'There should have been no matching documents');
|
||||||
|
}
|
||||||
|
}
|
||||||
121
tests/integration/postgresql/CustomTest.php
Normal file
121
tests/integration/postgresql/CustomTest.php
Normal file
@@ -0,0 +1,121 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\PostgreSQL;
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PostgreSQL integration tests for the Custom class
|
||||||
|
*/
|
||||||
|
#[TestDox('Custom (PostgreSQL integration)')]
|
||||||
|
class CustomTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
public function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->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')::numeric > :value",
|
||||||
|
[':value' => 100], new DocumentMapper(TestDocument::class));
|
||||||
|
$this->assertNotNull($list, 'The document list should not be null');
|
||||||
|
$this->assertFalse($list->hasItems(), '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->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertEquals('one', $doc->get()->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->assertTrue($doc->isEmpty(), 'There should not have been a document returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testNonQuerySucceedsWhenOperatingOnData()
|
||||||
|
{
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
$remaining = Count::all(ThrowawayDb::TABLE);
|
||||||
|
$this->assertEquals(0, $remaining, 'There should be no documents remaining in the table');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testNonQuerySucceedsWhenNoDataMatchesWhereClause()
|
||||||
|
{
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE . " WHERE (data->>'num_value')::numeric > :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');
|
||||||
|
}
|
||||||
|
}
|
||||||
78
tests/integration/postgresql/DefinitionTest.php
Normal file
78
tests/integration/postgresql/DefinitionTest.php
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\PostgreSQL;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Custom, Definition, DocumentException, DocumentIndex};
|
||||||
|
use BitBadger\PDODocument\Mapper\ExistsMapper;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PostgreSQL integration tests for the Definition class
|
||||||
|
*/
|
||||||
|
#[TestDox('Definition (PostgreSQL integration)')]
|
||||||
|
class DefinitionTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->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 pg_class WHERE relname = :name)',
|
||||||
|
[':name' => $name], new ExistsMapper());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testEnsureTableSucceeds(): void
|
||||||
|
{
|
||||||
|
$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(): void
|
||||||
|
{
|
||||||
|
$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');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testEnsureDocumentIndexSucceedsForFull(): void
|
||||||
|
{
|
||||||
|
$docIdx = 'idx_' . ThrowawayDb::TABLE . '_document';
|
||||||
|
Definition::ensureTable(ThrowawayDb::TABLE);
|
||||||
|
$this->assertFalse($this->itExists($docIdx), 'The document index should not exist');
|
||||||
|
Definition::ensureDocumentIndex(ThrowawayDb::TABLE, DocumentIndex::Full);
|
||||||
|
$this->assertTrue($this->itExists($docIdx), 'The document index should now exist');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testEnsureDocumentIndexSucceedsForOptimized(): void
|
||||||
|
{
|
||||||
|
$docIdx = 'idx_' . ThrowawayDb::TABLE . '_document';
|
||||||
|
Definition::ensureTable(ThrowawayDb::TABLE);
|
||||||
|
$this->assertFalse($this->itExists($docIdx), 'The document index should not exist');
|
||||||
|
Definition::ensureDocumentIndex(ThrowawayDb::TABLE, DocumentIndex::Optimized);
|
||||||
|
$this->assertTrue($this->itExists($docIdx), 'The document index should now exist');
|
||||||
|
}
|
||||||
|
}
|
||||||
89
tests/integration/postgresql/DeleteTest.php
Normal file
89
tests/integration/postgresql/DeleteTest.php
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\PostgreSQL;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Count, Delete, Field};
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PostgreSQL integration tests for the Delete class
|
||||||
|
*/
|
||||||
|
#[TestDox('Delete (PostgreSQL integration)')]
|
||||||
|
class DeleteTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->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');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsSucceedsWhenDocumentsAreDeleted(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
||||||
|
Delete::byContains(ThrowawayDb::TABLE, ['value' => 'purple']);
|
||||||
|
$this->assertEquals(3, Count::all(ThrowawayDb::TABLE), 'There should have been 3 documents remaining');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsSucceedsWhenDocumentsAreNotDeleted(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
||||||
|
Delete::byContains(ThrowawayDb::TABLE, ['target' => 'acquired']);
|
||||||
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents remaining');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds when documents are deleted')]
|
||||||
|
public function testByJsonPathSucceedsWhenDocumentsAreDeleted(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
||||||
|
Delete::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ <> 0)');
|
||||||
|
$this->assertEquals(1, Count::all(ThrowawayDb::TABLE), 'There should have been 1 document remaining');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds when documents are not deleted')]
|
||||||
|
public function testByJsonPathSucceedsWhenDocumentsAreNotDeleted(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
||||||
|
Delete::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ < 0)');
|
||||||
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents remaining');
|
||||||
|
}
|
||||||
|
}
|
||||||
74
tests/integration/postgresql/DocumentListTest.php
Normal file
74
tests/integration/postgresql/DocumentListTest.php
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\PostgreSQL;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{DocumentList, Query};
|
||||||
|
use BitBadger\PDODocument\Mapper\DocumentMapper;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
use Test\Integration\TestDocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PostgreSQL integration tests for the DocumentList class
|
||||||
|
*/
|
||||||
|
#[TestDox('DocumentList (PostgreSQL integration)')]
|
||||||
|
class DocumentListTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->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')::numeric < 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');
|
||||||
|
}
|
||||||
|
}
|
||||||
308
tests/integration/postgresql/DocumentTest.php
Normal file
308
tests/integration/postgresql/DocumentTest.php
Normal file
@@ -0,0 +1,308 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\PostgreSQL;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{AutoId, Configuration, Custom, Document, DocumentException, Field, Find, Query};
|
||||||
|
use BitBadger\PDODocument\Mapper\ArrayMapper;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
use Test\Integration\{NumDocument, SubDocument, TestDocument};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PostgreSQL integration tests for the Document class
|
||||||
|
*/
|
||||||
|
#[TestDox('Document (PostgreSQL integration)')]
|
||||||
|
class DocumentTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->dbName = ThrowawayDb::create();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
ThrowawayDb::destroy($this->dbName);
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for array no auto ID')]
|
||||||
|
public function testInsertSucceedsForArrayNoAutoId(): void
|
||||||
|
{
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => 'turkey', 'sub' => ['foo' => 'gobble', 'bar' => 'gobble']]);
|
||||||
|
$tryDoc = Find::byId(ThrowawayDb::TABLE, 'turkey', TestDocument::class);
|
||||||
|
$this->assertTrue($tryDoc->isDefined(), 'There should have been a document inserted');
|
||||||
|
$doc = $tryDoc->get();
|
||||||
|
$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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for array with auto number ID not provided')]
|
||||||
|
public function testInsertSucceedsForArrayWithAutoNumberIdNotProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::Number;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => 0, 'value' => 'new', 'num_value' => 8]);
|
||||||
|
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE, [], new ArrayMapper());
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$obj = json_decode($doc->get()['data']);
|
||||||
|
$this->assertEquals(1, $obj->id, 'The ID 1 should have been auto-generated');
|
||||||
|
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => 0, 'value' => 'again', 'num_value' => 7]);
|
||||||
|
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE " . Query::whereById(docId: 2),
|
||||||
|
[':id' => 2], new ArrayMapper());
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$obj = json_decode($doc->get()['data']);
|
||||||
|
$this->assertEquals(2, $obj->id, 'The ID 2 should have been auto-generated');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for array with auto number ID with ID provided')]
|
||||||
|
public function testInsertSucceedsForArrayWithAutoNumberIdWithIdProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::Number;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => 7, 'value' => 'new', 'num_value' => 8]);
|
||||||
|
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE, [], new ArrayMapper());
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$obj = json_decode($doc->get()['data']);
|
||||||
|
$this->assertEquals(7, $obj->id, 'The ID 7 should have been stored');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for array with auto UUID ID not provided')]
|
||||||
|
public function testInsertSucceedsForArrayWithAutoUuidIdNotProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::UUID;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => '', 'num_value' => 5]);
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 5)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertNotEmpty($doc->get()->id, 'The ID should have been auto-generated');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for array with auto UUID ID with ID provided')]
|
||||||
|
public function testInsertSucceedsForArrayWithAutoUuidIdWithIdProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::UUID;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
$uuid = AutoId::generateUUID();
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => $uuid, 'value' => 'uuid', 'num_value' => 12]);
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 12)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertEquals($uuid, $doc->get()->id, 'The ID should not have been changed');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for array with auto string ID not provided')]
|
||||||
|
public function testInsertSucceedsForArrayWithAutoStringIdNotProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::RandomString;
|
||||||
|
Configuration::$idStringLength = 6;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => '', 'value' => 'new', 'num_value' => 8]);
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 8)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertEquals(6, strlen($doc->get()->id),
|
||||||
|
'The ID should have been auto-generated and had 6 characters');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
Configuration::$idStringLength = 16;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for array with auto string ID with ID provided')]
|
||||||
|
public function testInsertSucceedsForArrayWithAutoStringIdWithIdProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::RandomString;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => 'my-key', 'value' => 'old', 'num_value' => 3]);
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 3)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertEquals('my-key', $doc->get()->id, 'The ID should not have been changed');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for object no auto ID')]
|
||||||
|
public function testInsertSucceedsForObjectNoAutoId(): void
|
||||||
|
{
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new TestDocument('turkey', sub: new SubDocument('gobble', 'gobble')));
|
||||||
|
$tryDoc = Find::byId(ThrowawayDb::TABLE, 'turkey', TestDocument::class);
|
||||||
|
$this->assertTrue($tryDoc->isDefined(), 'There should have been a document inserted');
|
||||||
|
$doc = $tryDoc->get();
|
||||||
|
$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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for object with auto number ID not provided')]
|
||||||
|
public function testInsertSucceedsForObjectWithAutoNumberIdNotProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::Number;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new NumDocument(value: 'taco'));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'taco')], NumDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertEquals(1, $doc->get()->id, 'The ID 1 should have been auto-generated');
|
||||||
|
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new NumDocument(value: 'burrito'));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'burrito')], NumDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertEquals(2, $doc->get()->id, 'The ID 2 should have been auto-generated');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for object with auto number ID with ID provided')]
|
||||||
|
public function testInsertSucceedsForObjectWithAutoNumberIdWithIdProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::Number;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new NumDocument(64, 'large'));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'large')], NumDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertEquals(64, $doc->get()->id, 'The ID 64 should have been stored');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for object with auto UUID ID not provided')]
|
||||||
|
public function testInsertSucceedsForObjectWithAutoUuidIdNotProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::UUID;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new TestDocument(value: 'something', num_value: 9));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EX('value')], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertNotEmpty($doc->get()->id, 'The ID should have been auto-generated');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for object with auto UUID ID with ID provided')]
|
||||||
|
public function testInsertSucceedsForObjectWithAutoUuidIdWithIdProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::UUID;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
$uuid = AutoId::generateUUID();
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new TestDocument($uuid, num_value: 14));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 14)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertEquals($uuid, $doc->get()->id, 'The ID should not have been changed');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for object with auto string ID not provided')]
|
||||||
|
public function testInsertSucceedsForObjectWithAutoStringIdNotProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::RandomString;
|
||||||
|
Configuration::$idStringLength = 40;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new TestDocument(num_value: 55));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 55)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertEquals(40, strlen($doc->get()->id),
|
||||||
|
'The ID should have been auto-generated and had 40 characters');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
Configuration::$idStringLength = 16;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for object with auto string ID with ID provided')]
|
||||||
|
public function testInsertSucceedsForObjectWithAutoStringIdWithIdProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::RandomString;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new TestDocument('my-key', num_value: 3));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 3)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertEquals('my-key', $doc->get()->id, 'The ID should not have been changed');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testSaveSucceedsWhenADocumentIsUpdated(): void
|
||||||
|
{
|
||||||
|
Document::save(ThrowawayDb::TABLE, new TestDocument('two', num_value: 44));
|
||||||
|
$tryDoc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class);
|
||||||
|
$this->assertTrue($tryDoc->isDefined(), 'There should have been a document returned');
|
||||||
|
$doc = $tryDoc->get();
|
||||||
|
$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')));
|
||||||
|
$tryDoc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class);
|
||||||
|
$this->assertNotFalse($tryDoc->isDefined(), 'There should have been a document returned');
|
||||||
|
$doc = $tryDoc->get();
|
||||||
|
$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->assertTrue($doc->isEmpty(), 'There should not have been a document returned');
|
||||||
|
}
|
||||||
|
}
|
||||||
80
tests/integration/postgresql/ExistsTest.php
Normal file
80
tests/integration/postgresql/ExistsTest.php
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\PostgreSQL;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Exists, Field};
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PostgreSQL integration tests for the Exists class
|
||||||
|
*/
|
||||||
|
#[TestDox('Exists (PostgreSQL integration)')]
|
||||||
|
class ExistsTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->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');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsSucceedsWhenDocumentsExist(): void
|
||||||
|
{
|
||||||
|
$this->assertTrue(Exists::byContains(ThrowawayDb::TABLE, ['value' => 'purple']),
|
||||||
|
'There should have been existing documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsSucceedsWhenNoMatchingDocumentsExist(): void
|
||||||
|
{
|
||||||
|
$this->assertFalse(Exists::byContains(ThrowawayDb::TABLE, ['value' => 'violet']),
|
||||||
|
'There should not have been existing documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds when documents exist')]
|
||||||
|
public function testByJsonPathSucceedsWhenDocumentsExist(): void
|
||||||
|
{
|
||||||
|
$this->assertTrue(Exists::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ == 10)'),
|
||||||
|
'There should have been existing documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds when no matching documents exist')]
|
||||||
|
public function testByJsonPathSucceedsWhenNoMatchingDocumentsExist(): void
|
||||||
|
{
|
||||||
|
$this->assertFalse(Exists::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ == 10.1)'),
|
||||||
|
'There should have been existing documents');
|
||||||
|
}
|
||||||
|
}
|
||||||
185
tests/integration/postgresql/FindTest.php
Normal file
185
tests/integration/postgresql/FindTest.php
Normal file
@@ -0,0 +1,185 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\PostgreSQL;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Custom, Delete, Document, Field, Find};
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
use Test\Integration\{NumDocument, TestDocument};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PostgreSQL integration tests for the Find class
|
||||||
|
*/
|
||||||
|
#[TestDox('Find (PostgreSQL integration)')]
|
||||||
|
class FindTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->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->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertEquals('two', $doc->get()->id, 'An incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds when a document is found with numeric ID')]
|
||||||
|
public function testByIdSucceedsWhenADocumentIsFoundWithNumericId(): void
|
||||||
|
{
|
||||||
|
Delete::byFields(ThrowawayDb::TABLE, [Field::NEX('absent')]);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => 18, 'value' => 'howdy']);
|
||||||
|
$doc = Find::byId(ThrowawayDb::TABLE, 18, NumDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertEquals(18, $doc->get()->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->assertTrue($doc->isEmpty(), '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');
|
||||||
|
$this->assertFalse($docs->hasItems(), 'There should have been no documents in the list');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsSucceedsWhenDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$docs = Find::byContains(ThrowawayDb::TABLE, ['value' => 'purple'], 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 testByContainsSucceedsWhenNoDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$docs = Find::byContains(ThrowawayDb::TABLE, ['value' => 'indigo'], TestDocument::class);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertFalse($docs->hasItems(), 'The document list should be empty');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds when documents are found')]
|
||||||
|
public function testByJsonPathSucceedsWhenDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$docs = Find::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 10)', 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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds when no documents are found')]
|
||||||
|
public function testByJsonPathSucceedsWhenNoDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$docs = Find::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 100)', TestDocument::class);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertFalse($docs->hasItems(), 'The document list should be empty');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testFirstByFieldsSucceedsWhenADocumentIsFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'another')], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertEquals('two', $doc->get()->id, 'The incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testFirstByFieldsSucceedsWhenMultipleDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('sub.foo', 'green')], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertContains($doc->get()->id, ['two', 'four'], 'An incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testFirstByFieldsSucceedsWhenADocumentIsNotFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'absent')], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isEmpty(), 'There should not have been a document returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testFirstByContainsSucceedsWhenADocumentIsFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByContains(ThrowawayDb::TABLE, ['value' => 'FIRST!'], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertEquals('one', $doc->get()->id, 'The incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testFirstByContainsSucceedsWhenMultipleDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByContains(ThrowawayDb::TABLE, ['value' => 'purple'], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertContains($doc->get()->id, ['four', 'five'], 'An incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testFirstByContainsSucceedsWhenADocumentIsNotFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByContains(ThrowawayDb::TABLE, ['value' => 'indigo'], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isEmpty(), 'There should not have been a document returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('First by JSON Path succeeds when a document is found')]
|
||||||
|
public function testFirstByJsonPathSucceedsWhenADocumentIsFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ == 10)', TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertEquals('two', $doc->get()->id, 'The incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('First by JSON Path succeeds when multiple documents are found')]
|
||||||
|
public function testFirstByJsonPathSucceedsWhenMultipleDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 10)', TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertContains($doc->get()->id, ['four', 'five'], 'An incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('First by JSON Path succeeds when a document is not found')]
|
||||||
|
public function testFirstByJsonPathSucceedsWhenADocumentIsNotFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 100)', TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isEmpty(), 'There should not have been a document returned');
|
||||||
|
}
|
||||||
|
}
|
||||||
105
tests/integration/postgresql/PatchTest.php
Normal file
105
tests/integration/postgresql/PatchTest.php
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\PostgreSQL;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Count, Exists, Field, Find, Patch};
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
use Test\Integration\TestDocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PostgreSQL integration tests for the Patch class
|
||||||
|
*/
|
||||||
|
#[TestDox('Patch (PostgreSQL integration)')]
|
||||||
|
class PatchTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->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->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertEquals(44, $doc->get()->num_value, 'The updated document is not correct');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds when no document is updated')]
|
||||||
|
public function testByIdSucceedsWhenNoDocumentIsUpdated(): void
|
||||||
|
{
|
||||||
|
$id = 'forty-seven';
|
||||||
|
$this->assertFalse(Exists::byId(ThrowawayDb::TABLE, $id), 'The document should not exist');
|
||||||
|
Patch::byId(ThrowawayDb::TABLE, $id, ['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
|
||||||
|
{
|
||||||
|
$fields = [Field::EQ('value', 'burgundy')];
|
||||||
|
$this->assertEquals(0, Count::byFields(ThrowawayDb::TABLE, $fields), 'There should be no matching documents');
|
||||||
|
Patch::byFields(ThrowawayDb::TABLE, $fields, ['foo' => 'green']);
|
||||||
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsSucceedsWhenDocumentsAreUpdated(): void
|
||||||
|
{
|
||||||
|
Patch::byContains(ThrowawayDb::TABLE, ['value' => 'another'], ['num_value' => 12]);
|
||||||
|
$tryDoc = Find::firstByContains(ThrowawayDb::TABLE, ['value' => 'another'], TestDocument::class);
|
||||||
|
$this->assertNotFalse($tryDoc->isDefined(), 'There should have been a document returned');
|
||||||
|
$doc = $tryDoc->get();
|
||||||
|
$this->assertEquals('two', $doc->id, 'An incorrect document was returned');
|
||||||
|
$this->assertEquals(12, $doc->num_value, 'The document was not patched');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsSucceedsWhenNoDocumentsAreUpdated(): void
|
||||||
|
{
|
||||||
|
$criteria = ['value' => 'updated'];
|
||||||
|
$this->assertEquals(0, Count::byContains(ThrowawayDb::TABLE, $criteria),
|
||||||
|
'There should be no matching documents');
|
||||||
|
Patch::byContains(ThrowawayDb::TABLE, $criteria, ['sub.foo' => 'green']);
|
||||||
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds when documents are updated')]
|
||||||
|
public function testByJsonPathSucceedsWhenDocumentsAreUpdated(): void
|
||||||
|
{
|
||||||
|
Patch::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 10)', ['value' => 'blue']);
|
||||||
|
$docs = Find::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 10)', TestDocument::class);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertTrue($docs->hasItems(), 'The document list should not be empty');
|
||||||
|
foreach ($docs->items() as $item) {
|
||||||
|
$this->assertContains($item->id, ['four', 'five'], 'An incorrect document was returned');
|
||||||
|
$this->assertEquals('blue', $item->value, 'The document was not patched');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds when documents are not updated')]
|
||||||
|
public function testByJsonPathSucceedsWhenDocumentsAreNotUpdated(): void
|
||||||
|
{
|
||||||
|
$path = '$.num_value ? (@ > 100)';
|
||||||
|
$this->assertEquals(0, Count::byJsonPath(ThrowawayDb::TABLE, $path),
|
||||||
|
'There should be no documents matching this path');
|
||||||
|
Patch::byJsonPath(ThrowawayDb::TABLE, $path, ['value' => 'blue']);
|
||||||
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
|
}
|
||||||
|
}
|
||||||
128
tests/integration/postgresql/RemoveFieldsTest.php
Normal file
128
tests/integration/postgresql/RemoveFieldsTest.php
Normal file
@@ -0,0 +1,128 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\PostgreSQL;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Field, Find, RemoveFields};
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
use Test\Integration\TestDocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PostgreSQL integration tests for the RemoveFields class
|
||||||
|
*/
|
||||||
|
#[TestDox('Remove Fields (PostgreSQL integration)')]
|
||||||
|
class RemoveFieldsTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->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']);
|
||||||
|
$tryDoc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class);
|
||||||
|
$this->assertNotFalse($tryDoc->isDefined(), 'There should have been a document returned');
|
||||||
|
$doc = $tryDoc->get();
|
||||||
|
$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->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertNull($doc->get()->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');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsSucceedsWhenAFieldIsRemoved(): void
|
||||||
|
{
|
||||||
|
$criteria = ['sub' => ['foo' => 'green']];
|
||||||
|
RemoveFields::byContains(ThrowawayDb::TABLE, $criteria, ['value']);
|
||||||
|
$docs = Find::byContains(ThrowawayDb::TABLE, $criteria, TestDocument::class);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertTrue($docs->hasItems(), 'The document list should not have been empty');
|
||||||
|
foreach ($docs->items() as $item) {
|
||||||
|
$this->assertContains($item->id, ['two', 'four'], 'An incorrect document was returned');
|
||||||
|
$this->assertEquals('', $item->value, 'The value field was not removed');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsSucceedsWhenAFieldIsNotRemoved(): void
|
||||||
|
{
|
||||||
|
RemoveFields::byContains(ThrowawayDb::TABLE, ['sub' => ['foo' => 'green']], ['invalid_field']);
|
||||||
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsSucceedsWhenNoDocumentIsMatched(): void
|
||||||
|
{
|
||||||
|
RemoveFields::byContains(ThrowawayDb::TABLE, ['value' => 'substantial'], ['num_value']);
|
||||||
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds when a field is removed')]
|
||||||
|
public function testByJsonPathSucceedsWhenAFieldIsRemoved(): void
|
||||||
|
{
|
||||||
|
$path = '$.value ? (@ == "purple")';
|
||||||
|
RemoveFields::byJsonPath(ThrowawayDb::TABLE, $path, ['sub']);
|
||||||
|
$docs = Find::byJsonPath(ThrowawayDb::TABLE, $path, TestDocument::class);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertTrue($docs->hasItems(), 'The document list should not have been empty');
|
||||||
|
foreach ($docs->items() as $item) {
|
||||||
|
$this->assertContains($item->id, ['four', 'five'], 'An incorrect document was returned');
|
||||||
|
$this->assertNull($item->sub, 'The sub field was not removed');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds when a field is not removed')]
|
||||||
|
public function testByJsonPathSucceedsWhenAFieldIsNotRemoved(): void
|
||||||
|
{
|
||||||
|
RemoveFields::byJsonPath(ThrowawayDb::TABLE, '$.value ? (@ == "purple")', ['submarine']);
|
||||||
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds when no document is matched')]
|
||||||
|
public function testByJsonPathSucceedsWhenNoDocumentIsMatched(): void
|
||||||
|
{
|
||||||
|
RemoveFields::byJsonPath(ThrowawayDb::TABLE, '$.value ? (@ == "mauve")', ['value']);
|
||||||
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
|
}
|
||||||
|
}
|
||||||
75
tests/integration/postgresql/ThrowawayDb.php
Normal file
75
tests/integration/postgresql/ThrowawayDb.php
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\PostgreSQL;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{AutoId, Configuration, Custom, Definition, Document, DocumentException, Mode};
|
||||||
|
use Random\RandomException;
|
||||||
|
use Test\Integration\{SubDocument, TestDocument};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Utilities to create and destroy a throwaway PostgreSQL database to use for testing
|
||||||
|
*/
|
||||||
|
class ThrowawayDb
|
||||||
|
{
|
||||||
|
/** @var string The table used for document manipulation */
|
||||||
|
public const TABLE = "test_table";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configure the document library for the given database (or the main PostgreSQL connection, if the database name
|
||||||
|
* is not provided; this is used for creating and dropping databases)
|
||||||
|
*
|
||||||
|
* @param string|null $dbName The name of the database to configure (optional, defaults to env or "postgres")
|
||||||
|
*/
|
||||||
|
private static function configure(?string $dbName = null): void
|
||||||
|
{
|
||||||
|
Configuration::$pdoDSN = sprintf("pgsql:host=%s;dbname=%s", $_ENV['PDO_DOC_PGSQL_HOST'] ?? 'localhost',
|
||||||
|
$dbName ?? $_ENV['PDO_DOC_PGSQL_DB'] ?? 'postgres');
|
||||||
|
Configuration::$username = $_ENV['PDO_DOC_PGSQL_USER'] ?? 'postgres';
|
||||||
|
Configuration::$password = $_ENV['PDO_DOC_PGSQL_PASS'] ?? 'postgres';
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
Configuration::resetPDO();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a throwaway PostgreSQL database
|
||||||
|
*
|
||||||
|
* @param bool $withData Whether to initialize this database with data (optional; defaults to `true`)
|
||||||
|
* @return string The name of the database (use to pass to `destroy` function at end of test)
|
||||||
|
* @throws DocumentException|RandomException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function create(bool $withData = true): string
|
||||||
|
{
|
||||||
|
$dbName = 'throwaway_' . AutoId::generateRandom(10);
|
||||||
|
self::configure();
|
||||||
|
Custom::nonQuery("CREATE DATABASE $dbName WITH OWNER " . Configuration::$username, []);
|
||||||
|
self::configure($dbName);
|
||||||
|
|
||||||
|
if ($withData) {
|
||||||
|
Definition::ensureTable(self::TABLE);
|
||||||
|
Document::insert(self::TABLE, new TestDocument('one', 'FIRST!', 0));
|
||||||
|
Document::insert(self::TABLE, new TestDocument('two', 'another', 10, new SubDocument('green', 'blue')));
|
||||||
|
Document::insert(self::TABLE, new TestDocument('three', '', 4));
|
||||||
|
Document::insert(self::TABLE, new TestDocument('four', 'purple', 17, new SubDocument('green', 'red')));
|
||||||
|
Document::insert(self::TABLE, new TestDocument('five', 'purple', 18));
|
||||||
|
}
|
||||||
|
|
||||||
|
return $dbName;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Destroy a throwaway PostgreSQL database
|
||||||
|
*
|
||||||
|
* @param string $dbName The name of the PostgreSQL database to be dropped
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function destroy(string $dbName): void
|
||||||
|
{
|
||||||
|
self::configure();
|
||||||
|
Custom::nonQuery("DROP DATABASE IF EXISTS $dbName WITH (FORCE)", []);
|
||||||
|
Configuration::$pdoDSN = '';
|
||||||
|
Configuration::$username = null;
|
||||||
|
Configuration::$password = null;
|
||||||
|
Configuration::$mode = null;
|
||||||
|
Configuration::resetPDO();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
namespace Test\Integration\SQLite;
|
namespace Test\Integration\SQLite;
|
||||||
|
|
||||||
use BitBadger\PDODocument\{Count, Field};
|
use BitBadger\PDODocument\{Count, DocumentException, Field};
|
||||||
use PHPUnit\Framework\Attributes\TestDox;
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
@@ -44,4 +44,17 @@ class CountTest extends TestCase
|
|||||||
$count = Count::byFields(ThrowawayDb::TABLE, [Field::BT('value', 'aardvark', 'apple')]);
|
$count = Count::byFields(ThrowawayDb::TABLE, [Field::BT('value', 'aardvark', 'apple')]);
|
||||||
$this->assertEquals(1, $count, 'There should have been 1 matching document');
|
$this->assertEquals(1, $count, 'There should have been 1 matching document');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function testByContainsFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Count::byContains('', []);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path fails')]
|
||||||
|
public function testByJsonPathFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Count::byJsonPath('', '');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -86,15 +86,15 @@ class CustomTest extends TestCase
|
|||||||
{
|
{
|
||||||
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id", [':id' => 'one'],
|
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id", [':id' => 'one'],
|
||||||
new DocumentMapper(TestDocument::class));
|
new DocumentMapper(TestDocument::class));
|
||||||
$this->assertNotNull($doc, 'There should have been a document returned');
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
$this->assertEquals('one', $doc->id, 'The incorrect document was returned');
|
$this->assertEquals('one', $doc->get()->id, 'The incorrect document was returned');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testSingleSucceedsWhenARowIsNotFound(): void
|
public function testSingleSucceedsWhenARowIsNotFound(): void
|
||||||
{
|
{
|
||||||
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id",
|
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id",
|
||||||
[':id' => 'eighty'], new DocumentMapper(TestDocument::class));
|
[':id' => 'eighty'], new DocumentMapper(TestDocument::class));
|
||||||
$this->assertFalse($doc, 'There should not have been a document returned');
|
$this->assertTrue($doc->isEmpty(), 'There should not have been a document returned');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testNonQuerySucceedsWhenOperatingOnData()
|
public function testNonQuerySucceedsWhenOperatingOnData()
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
namespace Test\Integration\SQLite;
|
namespace Test\Integration\SQLite;
|
||||||
|
|
||||||
use BitBadger\PDODocument\{Custom, Definition, DocumentException};
|
use BitBadger\PDODocument\{Custom, Definition, DocumentException, DocumentIndex};
|
||||||
use BitBadger\PDODocument\Mapper\ExistsMapper;
|
use BitBadger\PDODocument\Mapper\ExistsMapper;
|
||||||
use PHPUnit\Framework\Attributes\TestDox;
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
@@ -41,7 +41,7 @@ class DefinitionTest extends TestCase
|
|||||||
[':name' => $name], new ExistsMapper());
|
[':name' => $name], new ExistsMapper());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testEnsureTableSucceeds()
|
public function testEnsureTableSucceeds(): void
|
||||||
{
|
{
|
||||||
$this->assertFalse($this->itExists('ensured'), 'The table should not exist already');
|
$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');
|
$this->assertFalse($this->itExists('idx_ensured_key'), 'The key index should not exist already');
|
||||||
@@ -50,11 +50,17 @@ class DefinitionTest extends TestCase
|
|||||||
$this->assertTrue($this->itExists('idx_ensured_key'), 'The key index should now exist');
|
$this->assertTrue($this->itExists('idx_ensured_key'), 'The key index should now exist');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testEnsureFieldIndexSucceeds()
|
public function testEnsureFieldIndexSucceeds(): void
|
||||||
{
|
{
|
||||||
$this->assertFalse($this->itExists('idx_ensured_test'), 'The index should not exist already');
|
$this->assertFalse($this->itExists('idx_ensured_test'), 'The index should not exist already');
|
||||||
Definition::ensureTable('ensured');
|
Definition::ensureTable('ensured');
|
||||||
Definition::ensureFieldIndex('ensured', 'test', ['name', 'age']);
|
Definition::ensureFieldIndex('ensured', 'test', ['name', 'age']);
|
||||||
$this->assertTrue($this->itExists('idx_ensured_test'), 'The index should now exist');
|
$this->assertTrue($this->itExists('idx_ensured_test'), 'The index should now exist');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function testEnsureDocumentIndexFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Definition::ensureDocumentIndex('nope', DocumentIndex::Full);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
namespace Test\Integration\SQLite;
|
namespace Test\Integration\SQLite;
|
||||||
|
|
||||||
use BitBadger\PDODocument\{Count, Delete, Field};
|
use BitBadger\PDODocument\{Count, Delete, DocumentException, Field};
|
||||||
use PHPUnit\Framework\Attributes\TestDox;
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
@@ -56,4 +56,17 @@ class DeleteTest extends TestCase
|
|||||||
Delete::byFields(ThrowawayDb::TABLE, [Field::EQ('value', 'crimson')]);
|
Delete::byFields(ThrowawayDb::TABLE, [Field::EQ('value', 'crimson')]);
|
||||||
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents remaining');
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents remaining');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function testByContainsFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Delete::byContains('', []);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path fails')]
|
||||||
|
public function testByJsonPathFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Delete::byJsonPath('', '');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,10 +2,11 @@
|
|||||||
|
|
||||||
namespace Test\Integration\SQLite;
|
namespace Test\Integration\SQLite;
|
||||||
|
|
||||||
use BitBadger\PDODocument\{Document, DocumentException, Find};
|
use BitBadger\PDODocument\{AutoId, Configuration, Custom, Document, DocumentException, Field, Find};
|
||||||
|
use BitBadger\PDODocument\Mapper\ArrayMapper;
|
||||||
use PHPUnit\Framework\Attributes\TestDox;
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
use Test\Integration\{SubDocument, TestDocument};
|
use Test\Integration\{NumDocument, SubDocument, TestDocument};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* SQLite integration tests for the Document class
|
* SQLite integration tests for the Document class
|
||||||
@@ -28,11 +29,13 @@ class DocumentTest extends TestCase
|
|||||||
parent::tearDown();
|
parent::tearDown();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testInsertSucceeds(): void
|
#[TestDox('Insert succeeds for array no auto ID')]
|
||||||
|
public function testInsertSucceedsForArrayNoAutoId(): void
|
||||||
{
|
{
|
||||||
Document::insert(ThrowawayDb::TABLE, new TestDocument('turkey', sub: new SubDocument('gobble', 'gobble')));
|
Document::insert(ThrowawayDb::TABLE, ['id' => 'turkey', 'sub' => ['foo' => 'gobble', 'bar' => 'gobble']]);
|
||||||
$doc = Find::byId(ThrowawayDb::TABLE, 'turkey', TestDocument::class);
|
$tryDoc = Find::byId(ThrowawayDb::TABLE, 'turkey', TestDocument::class);
|
||||||
$this->assertNotFalse($doc, 'There should have been a document inserted');
|
$this->assertTrue($tryDoc->isDefined(), 'There should have been a document inserted');
|
||||||
|
$doc = $tryDoc->get();
|
||||||
$this->assertEquals('turkey', $doc->id, 'The ID was incorrect');
|
$this->assertEquals('turkey', $doc->id, 'The ID was incorrect');
|
||||||
$this->assertEquals('', $doc->value, 'The value was incorrect');
|
$this->assertEquals('', $doc->value, 'The value was incorrect');
|
||||||
$this->assertEquals(0, $doc->num_value, 'The numeric value was incorrect');
|
$this->assertEquals(0, $doc->num_value, 'The numeric value was incorrect');
|
||||||
@@ -41,6 +44,225 @@ class DocumentTest extends TestCase
|
|||||||
$this->assertEquals('gobble', $doc->sub->bar, 'The sub-document bar property was incorrect');
|
$this->assertEquals('gobble', $doc->sub->bar, 'The sub-document bar property was incorrect');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for array with auto number ID not provided')]
|
||||||
|
public function testInsertSucceedsForArrayWithAutoNumberIdNotProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::Number;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => 0, 'value' => 'new', 'num_value' => 8]);
|
||||||
|
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE, [], new ArrayMapper());
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$obj = json_decode($doc->get()['data']);
|
||||||
|
$this->assertEquals(1, $obj->id, 'The ID 1 should have been auto-generated');
|
||||||
|
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => 0, 'value' => 'again', 'num_value' => 7]);
|
||||||
|
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = 2", [],
|
||||||
|
new ArrayMapper());
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$obj = json_decode($doc->get()['data']);
|
||||||
|
$this->assertEquals(2, $obj->id, 'The ID 2 should have been auto-generated');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for array with auto number ID with ID provided')]
|
||||||
|
public function testInsertSucceedsForArrayWithAutoNumberIdWithIdProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::Number;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => 7, 'value' => 'new', 'num_value' => 8]);
|
||||||
|
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE, [], new ArrayMapper());
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$obj = json_decode($doc->get()['data']);
|
||||||
|
$this->assertEquals(7, $obj->id, 'The ID 7 should have been stored');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for array with auto UUID ID not provided')]
|
||||||
|
public function testInsertSucceedsForArrayWithAutoUuidIdNotProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::UUID;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => '', 'num_value' => 5]);
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 5)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertNotEmpty($doc->get()->id, 'The ID should have been auto-generated');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for array with auto UUID ID with ID provided')]
|
||||||
|
public function testInsertSucceedsForArrayWithAutoUuidIdWithIdProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::UUID;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
$uuid = AutoId::generateUUID();
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => $uuid, 'value' => 'uuid', 'num_value' => 12]);
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 12)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertEquals($uuid, $doc->get()->id, 'The ID should not have been changed');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for array with auto string ID not provided')]
|
||||||
|
public function testInsertSucceedsForArrayWithAutoStringIdNotProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::RandomString;
|
||||||
|
Configuration::$idStringLength = 6;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => '', 'value' => 'new', 'num_value' => 8]);
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 8)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertEquals(6, strlen($doc->get()->id),
|
||||||
|
'The ID should have been auto-generated and had 6 characters');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
Configuration::$idStringLength = 16;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for array with auto string ID with ID provided')]
|
||||||
|
public function testInsertSucceedsForArrayWithAutoStringIdWithIdProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::RandomString;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => 'my-key', 'value' => 'old', 'num_value' => 3]);
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 3)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertEquals('my-key', $doc->get()->id, 'The ID should not have been changed');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for object no auto ID')]
|
||||||
|
public function testInsertSucceedsForObjectNoAutoId(): void
|
||||||
|
{
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new TestDocument('turkey', sub: new SubDocument('gobble', 'gobble')));
|
||||||
|
$tryDoc = Find::byId(ThrowawayDb::TABLE, 'turkey', TestDocument::class);
|
||||||
|
$this->assertNotFalse($tryDoc->isDefined(), 'There should have been a document inserted');
|
||||||
|
$doc = $tryDoc->get();
|
||||||
|
$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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for object with auto number ID not provided')]
|
||||||
|
public function testInsertSucceedsForObjectWithAutoNumberIdNotProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::Number;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new NumDocument(value: 'taco'));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'taco')], NumDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertEquals(1, $doc->get()->id, 'The ID 1 should have been auto-generated');
|
||||||
|
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new NumDocument(value: 'burrito'));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'burrito')], NumDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertEquals(2, $doc->get()->id, 'The ID 2 should have been auto-generated');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for object with auto number ID with ID provided')]
|
||||||
|
public function testInsertSucceedsForObjectWithAutoNumberIdWithIdProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::Number;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new NumDocument(64, 'large'));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'large')], NumDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertEquals(64, $doc->get()->id, 'The ID 64 should have been stored');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for object with auto UUID ID not provided')]
|
||||||
|
public function testInsertSucceedsForObjectWithAutoUuidIdNotProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::UUID;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new TestDocument(value: 'something', num_value: 9));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EX('value')], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertNotEmpty($doc->get()->id, 'The ID should have been auto-generated');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for object with auto UUID ID with ID provided')]
|
||||||
|
public function testInsertSucceedsForObjectWithAutoUuidIdWithIdProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::UUID;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
$uuid = AutoId::generateUUID();
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new TestDocument($uuid, num_value: 14));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 14)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertEquals($uuid, $doc->get()->id, 'The ID should not have been changed');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for object with auto string ID not provided')]
|
||||||
|
public function testInsertSucceedsForObjectWithAutoStringIdNotProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::RandomString;
|
||||||
|
Configuration::$idStringLength = 40;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new TestDocument(num_value: 55));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 55)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertEquals(40, strlen($doc->get()->id),
|
||||||
|
'The ID should have been auto-generated and had 40 characters');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
Configuration::$idStringLength = 16;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for object with auto string ID with ID provided')]
|
||||||
|
public function testInsertSucceedsForObjectWithAutoStringIdWithIdProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::RandomString;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new TestDocument('my-key', num_value: 3));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 3)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
|
$this->assertEquals('my-key', $doc->get()->id, 'The ID should not have been changed');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public function testInsertFailsForDuplicateKey(): void
|
public function testInsertFailsForDuplicateKey(): void
|
||||||
{
|
{
|
||||||
$this->expectException(DocumentException::class);
|
$this->expectException(DocumentException::class);
|
||||||
@@ -51,14 +273,15 @@ class DocumentTest extends TestCase
|
|||||||
{
|
{
|
||||||
Document::save(ThrowawayDb::TABLE, new TestDocument('test', sub: new SubDocument('a', 'b')));
|
Document::save(ThrowawayDb::TABLE, new TestDocument('test', sub: new SubDocument('a', 'b')));
|
||||||
$doc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class);
|
$doc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class);
|
||||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testSaveSucceedsWhenADocumentIsUpdated(): void
|
public function testSaveSucceedsWhenADocumentIsUpdated(): void
|
||||||
{
|
{
|
||||||
Document::save(ThrowawayDb::TABLE, new TestDocument('two', num_value: 44));
|
Document::save(ThrowawayDb::TABLE, new TestDocument('two', num_value: 44));
|
||||||
$doc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class);
|
$tryDoc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class);
|
||||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
$this->assertTrue($tryDoc->isDefined(), 'There should have been a document returned');
|
||||||
|
$doc = $tryDoc->get();
|
||||||
$this->assertEquals(44, $doc->num_value, 'The numeric value was not updated');
|
$this->assertEquals(44, $doc->num_value, 'The numeric value was not updated');
|
||||||
$this->assertNull($doc->sub, 'The sub-document should have been null');
|
$this->assertNull($doc->sub, 'The sub-document should have been null');
|
||||||
}
|
}
|
||||||
@@ -66,8 +289,9 @@ class DocumentTest extends TestCase
|
|||||||
public function testUpdateSucceedsWhenReplacingADocument(): void
|
public function testUpdateSucceedsWhenReplacingADocument(): void
|
||||||
{
|
{
|
||||||
Document::update(ThrowawayDb::TABLE, 'one', new TestDocument('one', 'howdy', 8, new SubDocument('y', 'z')));
|
Document::update(ThrowawayDb::TABLE, 'one', new TestDocument('one', 'howdy', 8, new SubDocument('y', 'z')));
|
||||||
$doc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class);
|
$tryDoc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class);
|
||||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
$this->assertTrue($tryDoc->isDefined(), 'There should have been a document returned');
|
||||||
|
$doc = $tryDoc->get();
|
||||||
$this->assertEquals('howdy', $doc->value, 'The value was incorrect');
|
$this->assertEquals('howdy', $doc->value, 'The value was incorrect');
|
||||||
$this->assertEquals(8, $doc->num_value, 'The numeric 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->assertNotNull($doc->sub, 'The sub-document should not have been null');
|
||||||
@@ -79,6 +303,6 @@ class DocumentTest extends TestCase
|
|||||||
{
|
{
|
||||||
Document::update(ThrowawayDb::TABLE, 'two-hundred', new TestDocument('200'));
|
Document::update(ThrowawayDb::TABLE, 'two-hundred', new TestDocument('200'));
|
||||||
$doc = Find::byId(ThrowawayDb::TABLE, 'two-hundred', TestDocument::class);
|
$doc = Find::byId(ThrowawayDb::TABLE, 'two-hundred', TestDocument::class);
|
||||||
$this->assertFalse($doc, 'There should not have been a document returned');
|
$this->assertTrue($doc->isEmpty(), 'There should not have been a document returned');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
namespace Test\Integration\SQLite;
|
namespace Test\Integration\SQLite;
|
||||||
|
|
||||||
use BitBadger\PDODocument\{Exists, Field};
|
use BitBadger\PDODocument\{DocumentException, Exists, Field};
|
||||||
use PHPUnit\Framework\Attributes\TestDox;
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
@@ -51,4 +51,18 @@ class ExistsTest extends TestCase
|
|||||||
$this->assertFalse(Exists::byFields(ThrowawayDb::TABLE, [Field::LT('nothing', 'none')]),
|
$this->assertFalse(Exists::byFields(ThrowawayDb::TABLE, [Field::LT('nothing', 'none')]),
|
||||||
'There should not have been any existing documents');
|
'There should not have been any existing documents');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function testByContainsFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Exists::byContains('', []);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path fails')]
|
||||||
|
public function testByJsonPathFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Exists::byJsonPath('', '');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
namespace Test\Integration\SQLite;
|
namespace Test\Integration\SQLite;
|
||||||
|
|
||||||
use BitBadger\PDODocument\{Custom, Document, Field, Find};
|
use BitBadger\PDODocument\{Custom, Document, DocumentException, Field, Find};
|
||||||
use PHPUnit\Framework\Attributes\TestDox;
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
use Test\Integration\TestDocument;
|
use Test\Integration\TestDocument;
|
||||||
@@ -49,8 +49,8 @@ class FindTest extends TestCase
|
|||||||
public function testByIdSucceedsWhenADocumentIsFound(): void
|
public function testByIdSucceedsWhenADocumentIsFound(): void
|
||||||
{
|
{
|
||||||
$doc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class);
|
$doc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class);
|
||||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
$this->assertEquals('two', $doc->id, 'An incorrect document was returned');
|
$this->assertEquals('two', $doc->get()->id, 'An incorrect document was returned');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By ID succeeds when a document is found with numeric ID')]
|
#[TestDox('By ID succeeds when a document is found with numeric ID')]
|
||||||
@@ -58,15 +58,15 @@ class FindTest extends TestCase
|
|||||||
{
|
{
|
||||||
Document::insert(ThrowawayDb::TABLE, ['id' => 18, 'value' => 'howdy']);
|
Document::insert(ThrowawayDb::TABLE, ['id' => 18, 'value' => 'howdy']);
|
||||||
$doc = Find::byId(ThrowawayDb::TABLE, 18, TestDocument::class);
|
$doc = Find::byId(ThrowawayDb::TABLE, 18, TestDocument::class);
|
||||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
$this->assertEquals('18', $doc->id, 'An incorrect document was returned');
|
$this->assertEquals('18', $doc->get()->id, 'An incorrect document was returned');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By ID succeeds when a document is not found')]
|
#[TestDox('By ID succeeds when a document is not found')]
|
||||||
public function testByIdSucceedsWhenADocumentIsNotFound(): void
|
public function testByIdSucceedsWhenADocumentIsNotFound(): void
|
||||||
{
|
{
|
||||||
$doc = Find::byId(ThrowawayDb::TABLE, 'seventy-five', TestDocument::class);
|
$doc = Find::byId(ThrowawayDb::TABLE, 'seventy-five', TestDocument::class);
|
||||||
$this->assertFalse($doc, 'There should not have been a document returned');
|
$this->assertTrue($doc->isEmpty(), 'There should not have been a document returned');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testByFieldsSucceedsWhenDocumentsAreFound(): void
|
public function testByFieldsSucceedsWhenDocumentsAreFound(): void
|
||||||
@@ -82,28 +82,52 @@ class FindTest extends TestCase
|
|||||||
{
|
{
|
||||||
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::GT('num_value', 100)], TestDocument::class);
|
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::GT('num_value', 100)], TestDocument::class);
|
||||||
$this->assertNotNull($docs, 'There should have been a document list returned');
|
$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');
|
$this->assertFalse($docs->hasItems(), 'There should have been no documents in the list');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function testByContainsFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Find::byContains('', [], TestDocument::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path fails')]
|
||||||
|
public function testByJsonPathFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Find::byJsonPath('', '', TestDocument::class);
|
||||||
|
}
|
||||||
|
|
||||||
public function testFirstByFieldsSucceedsWhenADocumentIsFound(): void
|
public function testFirstByFieldsSucceedsWhenADocumentIsFound(): void
|
||||||
{
|
{
|
||||||
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'another')], TestDocument::class);
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'another')], TestDocument::class);
|
||||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
$this->assertEquals('two', $doc->id, 'The incorrect document was returned');
|
$this->assertEquals('two', $doc->get()->id, 'The incorrect document was returned');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testFirstByFieldsSucceedsWhenMultipleDocumentsAreFound(): void
|
public function testFirstByFieldsSucceedsWhenMultipleDocumentsAreFound(): void
|
||||||
{
|
{
|
||||||
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('sub.foo', 'green')], TestDocument::class);
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('sub.foo', 'green')], TestDocument::class);
|
||||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
$this->assertContains($doc->id, ['two', 'four'], 'An incorrect document was returned');
|
$this->assertContains($doc->get()->id, ['two', 'four'], 'An incorrect document was returned');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testFirstByFieldsSucceedsWhenADocumentIsNotFound(): void
|
public function testFirstByFieldsSucceedsWhenADocumentIsNotFound(): void
|
||||||
{
|
{
|
||||||
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'absent')], TestDocument::class);
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'absent')], TestDocument::class);
|
||||||
$this->assertFalse($doc, 'There should not have been a document returned');
|
$this->assertTrue($doc->isEmpty(), 'There should not have been a document returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testFirstByContainsFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Find::firstByContains('', [], TestDocument::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('First by JSON Path fails')]
|
||||||
|
public function testFirstByJsonPathFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Find::firstByJsonPath('', '', TestDocument::class);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
namespace Test\Integration\SQLite;
|
namespace Test\Integration\SQLite;
|
||||||
|
|
||||||
use BitBadger\PDODocument\{Count, Field, Find, Patch};
|
use BitBadger\PDODocument\{Count, DocumentException, Field, Find, Patch};
|
||||||
use PHPUnit\Framework\Attributes\TestDox;
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
use Test\Integration\TestDocument;
|
use Test\Integration\TestDocument;
|
||||||
@@ -33,8 +33,8 @@ class PatchTest extends TestCase
|
|||||||
{
|
{
|
||||||
Patch::byId(ThrowawayDb::TABLE, 'one', ['num_value' => 44]);
|
Patch::byId(ThrowawayDb::TABLE, 'one', ['num_value' => 44]);
|
||||||
$doc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class);
|
$doc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class);
|
||||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
$this->assertEquals(44, $doc->num_value, 'The updated document is not correct');
|
$this->assertEquals(44, $doc->get()->num_value, 'The updated document is not correct');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By ID succeeds when no document is updated')]
|
#[TestDox('By ID succeeds when no document is updated')]
|
||||||
@@ -44,7 +44,6 @@ class PatchTest extends TestCase
|
|||||||
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public function testByFieldsSucceedsWhenADocumentIsUpdated(): void
|
public function testByFieldsSucceedsWhenADocumentIsUpdated(): void
|
||||||
{
|
{
|
||||||
Patch::byFields(ThrowawayDb::TABLE, [Field::EQ('value', 'purple')], ['num_value' => 77]);
|
Patch::byFields(ThrowawayDb::TABLE, [Field::EQ('value', 'purple')], ['num_value' => 77]);
|
||||||
@@ -57,4 +56,17 @@ class PatchTest extends TestCase
|
|||||||
Patch::byFields(ThrowawayDb::TABLE, [Field::EQ('value', 'burgundy')], ['foo' => 'green']);
|
Patch::byFields(ThrowawayDb::TABLE, [Field::EQ('value', 'burgundy')], ['foo' => 'green']);
|
||||||
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function testByContainsFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Patch::byContains('', [], []);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path fails')]
|
||||||
|
public function testByJsonPathFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Patch::byJsonPath('', '', []);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
namespace Test\Integration\SQLite;
|
namespace Test\Integration\SQLite;
|
||||||
|
|
||||||
use BitBadger\PDODocument\{Field, Find, RemoveFields};
|
use BitBadger\PDODocument\{DocumentException, Field, Find, RemoveFields};
|
||||||
use PHPUnit\Framework\Attributes\TestDox;
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
use Test\Integration\TestDocument;
|
use Test\Integration\TestDocument;
|
||||||
@@ -32,8 +32,9 @@ class RemoveFieldsTest extends TestCase
|
|||||||
public function testByIdSucceedsWhenFieldsAreRemoved(): void
|
public function testByIdSucceedsWhenFieldsAreRemoved(): void
|
||||||
{
|
{
|
||||||
RemoveFields::byId(ThrowawayDb::TABLE, 'two', ['sub', 'value']);
|
RemoveFields::byId(ThrowawayDb::TABLE, 'two', ['sub', 'value']);
|
||||||
$doc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class);
|
$tryDoc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class);
|
||||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
$this->assertTrue($tryDoc->isDefined(), 'There should have been a document returned');
|
||||||
|
$doc = $tryDoc->get();
|
||||||
$this->assertEquals('', $doc->value, 'Value should have been blank (its default value)');
|
$this->assertEquals('', $doc->value, 'Value should have been blank (its default value)');
|
||||||
$this->assertNull($doc->sub, 'Sub-document should have been null');
|
$this->assertNull($doc->sub, 'Sub-document should have been null');
|
||||||
}
|
}
|
||||||
@@ -56,8 +57,8 @@ class RemoveFieldsTest extends TestCase
|
|||||||
{
|
{
|
||||||
RemoveFields::byFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 17)], ['sub']);
|
RemoveFields::byFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 17)], ['sub']);
|
||||||
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 17)], TestDocument::class);
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 17)], TestDocument::class);
|
||||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
$this->assertTrue($doc->isDefined(), 'There should have been a document returned');
|
||||||
$this->assertNull($doc->sub, 'Sub-document should have been null');
|
$this->assertNull($doc->get()->sub, 'Sub-document should have been null');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testByFieldsSucceedsWhenAFieldIsNotRemoved(): void
|
public function testByFieldsSucceedsWhenAFieldIsNotRemoved(): void
|
||||||
@@ -71,4 +72,17 @@ class RemoveFieldsTest extends TestCase
|
|||||||
RemoveFields::byFields(ThrowawayDb::TABLE, [Field::NE('missing', 'nope')], ['value']);
|
RemoveFields::byFields(ThrowawayDb::TABLE, [Field::NE('missing', 'nope')], ['value']);
|
||||||
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function testByContainsFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
RemoveFields::byContains('', [], []);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path fails')]
|
||||||
|
public function testByJsonPathFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
RemoveFields::byJsonPath('', '', []);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,13 +2,9 @@
|
|||||||
|
|
||||||
namespace Test\Integration\SQLite;
|
namespace Test\Integration\SQLite;
|
||||||
|
|
||||||
use BitBadger\PDODocument\Configuration;
|
use BitBadger\PDODocument\{AutoId, Configuration, Definition, Document, DocumentException, Mode};
|
||||||
use BitBadger\PDODocument\Definition;
|
use Random\RandomException;
|
||||||
use BitBadger\PDODocument\Document;
|
use Test\Integration\{SubDocument, TestDocument};
|
||||||
use BitBadger\PDODocument\DocumentException;
|
|
||||||
use BitBadger\PDODocument\Mode;
|
|
||||||
use Test\Integration\SubDocument;
|
|
||||||
use Test\Integration\TestDocument;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Utilities to create and destroy a throwaway SQLite database to use for testing
|
* Utilities to create and destroy a throwaway SQLite database to use for testing
|
||||||
@@ -16,18 +12,18 @@ use Test\Integration\TestDocument;
|
|||||||
class ThrowawayDb
|
class ThrowawayDb
|
||||||
{
|
{
|
||||||
/** @var string The table used for document manipulation */
|
/** @var string The table used for document manipulation */
|
||||||
public const string TABLE = "test_table";
|
public const TABLE = "test_table";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a throwaway SQLite database
|
* Create a throwaway SQLite database
|
||||||
*
|
*
|
||||||
* @param bool $withData Whether to initialize this database with data (optional; defaults to `true`)
|
* @param bool $withData Whether to initialize this database with data (optional; defaults to `true`)
|
||||||
* @return string The name of the database (use to pass to `destroy` function at end of test)
|
* @return string The name of the database (use to pass to `destroy` function at end of test)
|
||||||
* @throws DocumentException If any is encountered
|
* @throws DocumentException|RandomException If any is encountered
|
||||||
*/
|
*/
|
||||||
public static function create(bool $withData = true): string
|
public static function create(bool $withData = true): string
|
||||||
{
|
{
|
||||||
$fileName = sprintf('throwaway-%s-%d.db', date('His'), rand(10, 99));
|
$fileName = sprintf('throwaway-%s.db', AutoId::generateRandom(10));
|
||||||
Configuration::$pdoDSN = "sqlite:./$fileName";
|
Configuration::$pdoDSN = "sqlite:./$fileName";
|
||||||
Configuration::$mode = Mode::SQLite;
|
Configuration::$mode = Mode::SQLite;
|
||||||
Configuration::resetPDO();
|
Configuration::resetPDO();
|
||||||
@@ -52,20 +48,6 @@ class ThrowawayDb
|
|||||||
public static function destroy(string $fileName): void
|
public static function destroy(string $fileName): void
|
||||||
{
|
{
|
||||||
Configuration::resetPDO();
|
Configuration::resetPDO();
|
||||||
unlink("./$fileName");
|
if (file_exists("./$fileName")) unlink("./$fileName");
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Destroy the given throwaway database and create another
|
|
||||||
*
|
|
||||||
* @param string $fileName The name of the database to be destroyed
|
|
||||||
* @param bool $withData Whether to initialize the database with data (optional; defaults to `true`)
|
|
||||||
* @return string The name of the new database
|
|
||||||
* @throws DocumentException If any is encountered
|
|
||||||
*/
|
|
||||||
public static function exchange(string $fileName, bool $withData = true): string
|
|
||||||
{
|
|
||||||
self::destroy($fileName);
|
|
||||||
return self::create($withData);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,13 +2,14 @@
|
|||||||
|
|
||||||
namespace Test\Unit;
|
namespace Test\Unit;
|
||||||
|
|
||||||
use BitBadger\PDODocument\{Configuration, DocumentException};
|
use BitBadger\PDODocument\{AutoId, Configuration, DocumentException};
|
||||||
use PHPUnit\Framework\Attributes\TestDox;
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unit tests for the Configuration class
|
* Unit tests for the Configuration class
|
||||||
*/
|
*/
|
||||||
|
#[TestDox('Configuration (Unit tests)')]
|
||||||
class ConfigurationTest extends TestCase
|
class ConfigurationTest extends TestCase
|
||||||
{
|
{
|
||||||
#[TestDox('ID field default succeeds')]
|
#[TestDox('ID field default succeeds')]
|
||||||
@@ -29,6 +30,18 @@ class ConfigurationTest extends TestCase
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('Auto ID default succeeds')]
|
||||||
|
public function testAutoIdDefaultSucceeds(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(AutoId::None, Configuration::$autoId, 'Auto ID should default to None');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('ID string length default succeeds')]
|
||||||
|
public function testIdStringLengthDefaultSucceeds(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(16, Configuration::$idStringLength, 'ID string length should default to 16');
|
||||||
|
}
|
||||||
|
|
||||||
#[TestDox("Db conn fails when no DSN specified")]
|
#[TestDox("Db conn fails when no DSN specified")]
|
||||||
public function testDbConnFailsWhenNoDSNSpecified(): void
|
public function testDbConnFailsWhenNoDSNSpecified(): void
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -4,11 +4,13 @@ namespace Test\Unit;
|
|||||||
|
|
||||||
use BitBadger\PDODocument\DocumentException;
|
use BitBadger\PDODocument\DocumentException;
|
||||||
use Exception;
|
use Exception;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unit tests for the DocumentException class
|
* Unit tests for the DocumentException class
|
||||||
*/
|
*/
|
||||||
|
#[TestDox('Document Exception (Unit tests)')]
|
||||||
class DocumentExceptionTest extends TestCase
|
class DocumentExceptionTest extends TestCase
|
||||||
{
|
{
|
||||||
public function testConstructorSucceedsWithCodeAndPriorException()
|
public function testConstructorSucceedsWithCodeAndPriorException()
|
||||||
|
|||||||
24
tests/unit/FieldMatchTest.php
Normal file
24
tests/unit/FieldMatchTest.php
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Unit;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\FieldMatch;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unit tests for the FieldMatch enum
|
||||||
|
*/
|
||||||
|
#[TestDox('Field Match (Unit tests)')]
|
||||||
|
class FieldMatchTest extends TestCase
|
||||||
|
{
|
||||||
|
public function testToStringSucceedsForAll(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals('AND', FieldMatch::All->toString(), 'All should have returned AND');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testToStringSucceedsForAny(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals('OR', FieldMatch::Any->toString(), 'Any should have returned OR');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,6 +9,7 @@ use PHPUnit\Framework\TestCase;
|
|||||||
/**
|
/**
|
||||||
* Unit tests for the Field class
|
* Unit tests for the Field class
|
||||||
*/
|
*/
|
||||||
|
#[TestDox('Field (Unit tests)')]
|
||||||
class FieldTest extends TestCase
|
class FieldTest extends TestCase
|
||||||
{
|
{
|
||||||
#[TestDox('Append parameter succeeds for EX')]
|
#[TestDox('Append parameter succeeds for EX')]
|
||||||
@@ -221,7 +222,7 @@ class FieldTest extends TestCase
|
|||||||
try {
|
try {
|
||||||
$field = Field::LE('le_field', 18, '@it');
|
$field = Field::LE('le_field', 18, '@it');
|
||||||
$field->qualifier = 'q';
|
$field->qualifier = 'q';
|
||||||
$this->assertEquals("q.data->>'le_field' <= @it", $field->toWhere(),
|
$this->assertEquals("(q.data->>'le_field')::numeric <= @it", $field->toWhere(),
|
||||||
'WHERE fragment not generated correctly');
|
'WHERE fragment not generated correctly');
|
||||||
} finally {
|
} finally {
|
||||||
Configuration::$mode = null;
|
Configuration::$mode = null;
|
||||||
@@ -248,7 +249,7 @@ class FieldTest extends TestCase
|
|||||||
Configuration::$mode = Mode::PgSQL;
|
Configuration::$mode = Mode::PgSQL;
|
||||||
try {
|
try {
|
||||||
$field = Field::EQ('sub.foo.bar', 22, '@it');
|
$field = Field::EQ('sub.foo.bar', 22, '@it');
|
||||||
$this->assertEquals("data->>'sub.foo.bar' = @it", $field->toWhere(),
|
$this->assertEquals("(data#>>'{sub,foo,bar}')::numeric = @it", $field->toWhere(),
|
||||||
'WHERE fragment not generated correctly');
|
'WHERE fragment not generated correctly');
|
||||||
} finally {
|
} finally {
|
||||||
Configuration::$mode = null;
|
Configuration::$mode = null;
|
||||||
|
|||||||
@@ -3,11 +3,13 @@
|
|||||||
namespace Test\Unit\Mapper;
|
namespace Test\Unit\Mapper;
|
||||||
|
|
||||||
use BitBadger\PDODocument\Mapper\ArrayMapper;
|
use BitBadger\PDODocument\Mapper\ArrayMapper;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unit tests for the ArrayMapper class
|
* Unit tests for the ArrayMapper class
|
||||||
*/
|
*/
|
||||||
|
#[TestDox('Array Mapper (Unit tests)')]
|
||||||
class ArrayMapperTest extends TestCase
|
class ArrayMapperTest extends TestCase
|
||||||
{
|
{
|
||||||
public function testMapSucceeds(): void
|
public function testMapSucceeds(): void
|
||||||
|
|||||||
@@ -3,11 +3,13 @@
|
|||||||
namespace Test\Unit\Mapper;
|
namespace Test\Unit\Mapper;
|
||||||
|
|
||||||
use BitBadger\PDODocument\Mapper\CountMapper;
|
use BitBadger\PDODocument\Mapper\CountMapper;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unit tests for the CountMapper class
|
* Unit tests for the CountMapper class
|
||||||
*/
|
*/
|
||||||
|
#[TestDox('Count Mapper (Unit tests)')]
|
||||||
class CountMapperTest extends TestCase
|
class CountMapperTest extends TestCase
|
||||||
{
|
{
|
||||||
public function testMapSucceeds(): void
|
public function testMapSucceeds(): void
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ class TestDocument
|
|||||||
/**
|
/**
|
||||||
* Unit tests for the DocumentMapper class
|
* Unit tests for the DocumentMapper class
|
||||||
*/
|
*/
|
||||||
|
#[TestDox('Document Mapper (Unit tests)')]
|
||||||
class DocumentMapperTest extends TestCase
|
class DocumentMapperTest extends TestCase
|
||||||
{
|
{
|
||||||
public function testConstructorSucceedsWithDefaultField(): void
|
public function testConstructorSucceedsWithDefaultField(): void
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ use PHPUnit\Framework\TestCase;
|
|||||||
/**
|
/**
|
||||||
* Unit tests for the ExistsMapper class
|
* Unit tests for the ExistsMapper class
|
||||||
*/
|
*/
|
||||||
|
#[TestDox('Exists Mapper (Unit tests)')]
|
||||||
class ExistsMapperTest extends TestCase
|
class ExistsMapperTest extends TestCase
|
||||||
{
|
{
|
||||||
#[TestDox('Map succeeds for PostgreSQL')]
|
#[TestDox('Map succeeds for PostgreSQL')]
|
||||||
|
|||||||
@@ -3,8 +3,13 @@
|
|||||||
namespace Test\Unit\Mapper;
|
namespace Test\Unit\Mapper;
|
||||||
|
|
||||||
use BitBadger\PDODocument\Mapper\StringMapper;
|
use BitBadger\PDODocument\Mapper\StringMapper;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unit tests for the StringMapper class
|
||||||
|
*/
|
||||||
|
#[TestDox('String Mapper (Unit tests)')]
|
||||||
class StringMapperTest extends TestCase
|
class StringMapperTest extends TestCase
|
||||||
{
|
{
|
||||||
public function testMapSucceedsWhenFieldIsPresentAndString()
|
public function testMapSucceedsWhenFieldIsPresentAndString()
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ use PHPUnit\Framework\TestCase;
|
|||||||
/**
|
/**
|
||||||
* Unit tests for the Op enumeration
|
* Unit tests for the Op enumeration
|
||||||
*/
|
*/
|
||||||
|
#[TestDox('Op (Unit tests)')]
|
||||||
class OpTest extends TestCase
|
class OpTest extends TestCase
|
||||||
{
|
{
|
||||||
#[TestDox('To string succeeds for EQ')]
|
#[TestDox('To string succeeds for EQ')]
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ use PHPUnit\Framework\TestCase;
|
|||||||
/**
|
/**
|
||||||
* Unit tests for the Parameters class
|
* Unit tests for the Parameters class
|
||||||
*/
|
*/
|
||||||
|
#[TestDox('Parameters (Unit tests)')]
|
||||||
class ParametersTest extends TestCase
|
class ParametersTest extends TestCase
|
||||||
{
|
{
|
||||||
#[TestDox('ID succeeds with string')]
|
#[TestDox('ID succeeds with string')]
|
||||||
@@ -51,7 +52,7 @@ class ParametersTest extends TestCase
|
|||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
Configuration::$mode = Mode::PgSQL;
|
Configuration::$mode = Mode::PgSQL;
|
||||||
$this->assertEquals([':names' => "ARRAY['one','two','seven']"],
|
$this->assertEquals([':names' => "{one,two,seven}"],
|
||||||
Parameters::fieldNames(':names', ['one', 'two', 'seven']), 'Field name parameters not correct');
|
Parameters::fieldNames(':names', ['one', 'two', 'seven']), 'Field name parameters not correct');
|
||||||
} finally {
|
} finally {
|
||||||
Configuration::$mode = null;
|
Configuration::$mode = null;
|
||||||
|
|||||||
@@ -2,30 +2,64 @@
|
|||||||
|
|
||||||
namespace Test\Unit\Query;
|
namespace Test\Unit\Query;
|
||||||
|
|
||||||
use BitBadger\PDODocument\{Configuration, Field, Mode};
|
use BitBadger\PDODocument\{Configuration, DocumentException, Field, Mode};
|
||||||
use BitBadger\PDODocument\Query\Count;
|
use BitBadger\PDODocument\Query\Count;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unit tests for the Count class
|
* Unit tests for the Count class
|
||||||
*/
|
*/
|
||||||
|
#[TestDox('Count Queries (Unit tests)')]
|
||||||
class CountTest extends TestCase
|
class CountTest extends TestCase
|
||||||
{
|
{
|
||||||
|
public function tearDown(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = null;
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
|
|
||||||
public function testAllSucceeds()
|
public function testAllSucceeds(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals('SELECT COUNT(*) FROM a_table', Count::all('a_table'),
|
$this->assertEquals('SELECT COUNT(*) FROM a_table', Count::all('a_table'),
|
||||||
'SELECT statement not generated correctly');
|
'SELECT statement not generated correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testByFieldsSucceeds()
|
public function testByFieldsSucceeds(): void
|
||||||
{
|
{
|
||||||
Configuration::$mode = Mode::SQLite;
|
Configuration::$mode = Mode::SQLite;
|
||||||
try {
|
|
||||||
$this->assertEquals("SELECT COUNT(*) FROM somewhere WHERE data->>'errors' > :errors",
|
$this->assertEquals("SELECT COUNT(*) FROM somewhere WHERE data->>'errors' > :errors",
|
||||||
Count::byFields('somewhere', [Field::GT('errors', 10, ':errors')]));
|
Count::byFields('somewhere', [Field::GT('errors', 10, ':errors')]),
|
||||||
} finally {
|
'SELECT statement not generated correctly');
|
||||||
Configuration::$mode = null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('By contains succeeds for PostgreSQL')]
|
||||||
|
public function testByContainsSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals('SELECT COUNT(*) FROM the_table WHERE data @> :criteria', Count::byContains('the_table'),
|
||||||
|
'SELECT statement not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By contains fails for non PostgreSQL')]
|
||||||
|
public function testByContainsFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Count::byContains('');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds for PostgreSQL')]
|
||||||
|
public function testByJsonPathSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals('SELECT COUNT(*) FROM a_table WHERE jsonb_path_exists(data, :path::jsonpath)',
|
||||||
|
Count::byJsonPath('a_table'), 'SELECT statement not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path fails for non PostgreSQL')]
|
||||||
|
public function testByJsonPathFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Count::byJsonPath('');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
namespace Test\Unit\Query;
|
namespace Test\Unit\Query;
|
||||||
|
|
||||||
use BitBadger\PDODocument\{Configuration, DocumentException, Mode};
|
use BitBadger\PDODocument\{Configuration, DocumentException, DocumentIndex, Mode};
|
||||||
use BitBadger\PDODocument\Query\Definition;
|
use BitBadger\PDODocument\Query\Definition;
|
||||||
use PHPUnit\Framework\Attributes\TestDox;
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
@@ -10,36 +10,34 @@ use PHPUnit\Framework\TestCase;
|
|||||||
/**
|
/**
|
||||||
* Unit tests for the Definition class
|
* Unit tests for the Definition class
|
||||||
*/
|
*/
|
||||||
|
#[TestDox('Definition Queries (Unit tests)')]
|
||||||
class DefinitionTest extends TestCase
|
class DefinitionTest extends TestCase
|
||||||
{
|
{
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = null;
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
|
|
||||||
#[TestDox('Ensure table succeeds for PosgtreSQL')]
|
#[TestDox('Ensure table succeeds for PosgtreSQL')]
|
||||||
public function testEnsureTableSucceedsForPostgreSQL(): void
|
public function testEnsureTableSucceedsForPostgreSQL(): void
|
||||||
{
|
{
|
||||||
try {
|
|
||||||
Configuration::$mode = Mode::PgSQL;
|
Configuration::$mode = Mode::PgSQL;
|
||||||
$this->assertEquals('CREATE TABLE IF NOT EXISTS documents (data JSONB NOT NULL)',
|
$this->assertEquals('CREATE TABLE IF NOT EXISTS documents (data JSONB NOT NULL)',
|
||||||
Definition::ensureTable('documents'), 'CREATE TABLE statement not generated correctly');
|
Definition::ensureTable('documents'), 'CREATE TABLE statement not generated correctly');
|
||||||
} finally {
|
|
||||||
Configuration::$mode = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('Ensure table succeeds for SQLite')]
|
#[TestDox('Ensure table succeeds for SQLite')]
|
||||||
public function testEnsureTableSucceedsForSQLite(): void
|
public function testEnsureTableSucceedsForSQLite(): void
|
||||||
{
|
{
|
||||||
try {
|
|
||||||
Configuration::$mode = Mode::SQLite;
|
Configuration::$mode = Mode::SQLite;
|
||||||
$this->assertEquals('CREATE TABLE IF NOT EXISTS dox (data TEXT NOT NULL)', Definition::ensureTable('dox'),
|
$this->assertEquals('CREATE TABLE IF NOT EXISTS dox (data TEXT NOT NULL)', Definition::ensureTable('dox'),
|
||||||
'CREATE TABLE statement not generated correctly');
|
'CREATE TABLE statement not generated correctly');
|
||||||
} finally {
|
|
||||||
Configuration::$mode = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testEnsureTableFailsWhenModeNotSet(): void
|
public function testEnsureTableFailsWhenModeNotSet(): void
|
||||||
{
|
{
|
||||||
$this->expectException(DocumentException::class);
|
$this->expectException(DocumentException::class);
|
||||||
Configuration::$mode = null;
|
|
||||||
Definition::ensureTable('boom');
|
Definition::ensureTable('boom');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,9 +55,30 @@ class DefinitionTest extends TestCase
|
|||||||
'CREATE INDEX statement not generated correctly');
|
'CREATE INDEX statement not generated correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testEnsureKey(): void
|
public function testEnsureKeySucceeds(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals("CREATE UNIQUE INDEX IF NOT EXISTS idx_tbl_key ON tbl ((data->>'id'))",
|
$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');
|
Definition::ensureKey('tbl'), 'CREATE INDEX statement for document key not generated correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function testEnsureDocumentIndexOnSucceedsForSchemaAndFull(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals("CREATE INDEX IF NOT EXISTS idx_tbl_document ON my.tbl USING GIN (data)",
|
||||||
|
Definition::ensureDocumentIndexOn('my.tbl', DocumentIndex::Full));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testEnsureDocumentIndexOnSucceedsForNoSchemaAndOptimized(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals("CREATE INDEX IF NOT EXISTS idx_it_document ON it USING GIN (data jsonb_path_ops)",
|
||||||
|
Definition::ensureDocumentIndexOn('it', DocumentIndex::Optimized));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Ensure document index on fails for non PostgreSQL')]
|
||||||
|
public function testEnsureDocumentIndexOnFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Definition::ensureDocumentIndexOn('', DocumentIndex::Full);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
namespace Test\Unit\Query;
|
namespace Test\Unit\Query;
|
||||||
|
|
||||||
use BitBadger\PDODocument\{Configuration, Field, Mode};
|
use BitBadger\PDODocument\{Configuration, DocumentException, Field, Mode};
|
||||||
use BitBadger\PDODocument\Query\Delete;
|
use BitBadger\PDODocument\Query\Delete;
|
||||||
use PHPUnit\Framework\Attributes\TestDox;
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
@@ -10,13 +10,9 @@ use PHPUnit\Framework\TestCase;
|
|||||||
/**
|
/**
|
||||||
* Unit tests for the Delete class
|
* Unit tests for the Delete class
|
||||||
*/
|
*/
|
||||||
|
#[TestDox('Delete Queries (Unit tests)')]
|
||||||
class DeleteTest extends TestCase
|
class DeleteTest extends TestCase
|
||||||
{
|
{
|
||||||
protected function setUp(): void
|
|
||||||
{
|
|
||||||
Configuration::$mode = Mode::SQLite;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function tearDown(): void
|
protected function tearDown(): void
|
||||||
{
|
{
|
||||||
Configuration::$mode = null;
|
Configuration::$mode = null;
|
||||||
@@ -25,14 +21,46 @@ class DeleteTest extends TestCase
|
|||||||
#[TestDox('By ID succeeds')]
|
#[TestDox('By ID succeeds')]
|
||||||
public function testByIdSucceeds(): void
|
public function testByIdSucceeds(): void
|
||||||
{
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
$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');
|
'DELETE statement not constructed correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testByFieldsSucceeds(): void
|
public function testByFieldsSucceeds(): void
|
||||||
{
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
$this->assertEquals("DELETE FROM my_table WHERE data->>'value' < :max AND data->>'value' >= :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::byFields('my_table', [Field::LT('value', 99, ':max'), Field::GE('value', 18, ':min')]),
|
||||||
'DELETE statement not constructed correctly');
|
'DELETE statement not constructed correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('By contains succeeds for PostgreSQL')]
|
||||||
|
public function testByContainsSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals('DELETE FROM somewhere WHERE data @> :criteria', Delete::byContains('somewhere'),
|
||||||
|
'DELETE statement not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By contains fails for non PostgreSQL')]
|
||||||
|
public function testByContainsFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Delete::byContains('');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds for PostgreSQL')]
|
||||||
|
public function testByJsonPathSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals('DELETE FROM here WHERE jsonb_path_exists(data, :path::jsonpath)',
|
||||||
|
Delete::byJsonPath('here'), 'DELETE statement not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path fails for non PostgreSQL')]
|
||||||
|
public function testByJsonPathFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Delete::byJsonPath('');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
namespace Test\Unit\Query;
|
namespace Test\Unit\Query;
|
||||||
|
|
||||||
use BitBadger\PDODocument\{Configuration, Field, Mode};
|
use BitBadger\PDODocument\{Configuration, DocumentException, Field, Mode};
|
||||||
use BitBadger\PDODocument\Query\Exists;
|
use BitBadger\PDODocument\Query\Exists;
|
||||||
use PHPUnit\Framework\Attributes\TestDox;
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
@@ -10,13 +10,9 @@ use PHPUnit\Framework\TestCase;
|
|||||||
/**
|
/**
|
||||||
* Unit tests for the Exists class
|
* Unit tests for the Exists class
|
||||||
*/
|
*/
|
||||||
|
#[TestDox('Exists Queries (Unit tests)')]
|
||||||
class ExistsTest extends TestCase
|
class ExistsTest extends TestCase
|
||||||
{
|
{
|
||||||
protected function setUp(): void
|
|
||||||
{
|
|
||||||
Configuration::$mode = Mode::SQLite;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function tearDown(): void
|
protected function tearDown(): void
|
||||||
{
|
{
|
||||||
Configuration::$mode = null;
|
Configuration::$mode = null;
|
||||||
@@ -24,6 +20,7 @@ class ExistsTest extends TestCase
|
|||||||
|
|
||||||
public function testQuerySucceeds(): void
|
public function testQuerySucceeds(): void
|
||||||
{
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
$this->assertEquals('SELECT EXISTS (SELECT 1 FROM abc WHERE def)', Exists::query('abc', 'def'),
|
$this->assertEquals('SELECT EXISTS (SELECT 1 FROM abc WHERE def)', Exists::query('abc', 'def'),
|
||||||
'Existence query not generated correctly');
|
'Existence query not generated correctly');
|
||||||
}
|
}
|
||||||
@@ -31,14 +28,46 @@ class ExistsTest extends TestCase
|
|||||||
#[TestDox('By ID succeeds')]
|
#[TestDox('By ID succeeds')]
|
||||||
public function testByIdSucceeds(): void
|
public function testByIdSucceeds(): void
|
||||||
{
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
$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');
|
'Existence query not generated correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testByFieldsSucceeds(): void
|
public function testByFieldsSucceeds(): void
|
||||||
{
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
$this->assertEquals("SELECT EXISTS (SELECT 1 FROM box WHERE data->>'status' <> :status)",
|
$this->assertEquals("SELECT EXISTS (SELECT 1 FROM box WHERE data->>'status' <> :status)",
|
||||||
Exists::byFields('box', [Field::NE('status', 'occupied', ':status')]),
|
Exists::byFields('box', [Field::NE('status', 'occupied', ':status')]),
|
||||||
'Existence query not generated correctly');
|
'Existence query not generated correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('By contains succeeds for PostgreSQL')]
|
||||||
|
public function testByContainsSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals('SELECT EXISTS (SELECT 1 FROM pocket WHERE data @> :criteria)',
|
||||||
|
Exists::byContains('pocket'), 'Existence query not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By contains fails for non PostgreSQL')]
|
||||||
|
public function testByContainsFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Exists::byContains('');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds for PostgreSQL')]
|
||||||
|
public function testByJsonPathSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals('SELECT EXISTS (SELECT 1 FROM lint WHERE jsonb_path_exists(data, :path::jsonpath))',
|
||||||
|
Exists::byJsonPath('lint'), 'Existence query not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path fails for non PostgreSQL')]
|
||||||
|
public function testByJsonPathFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Exists::byJsonPath('');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
namespace Test\Unit\Query;
|
namespace Test\Unit\Query;
|
||||||
|
|
||||||
use BitBadger\PDODocument\{Configuration, Field, Mode};
|
use BitBadger\PDODocument\{Configuration, DocumentException, Field, FieldMatch, Mode};
|
||||||
use BitBadger\PDODocument\Query\Find;
|
use BitBadger\PDODocument\Query\Find;
|
||||||
use PHPUnit\Framework\Attributes\TestDox;
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
@@ -10,13 +10,9 @@ use PHPUnit\Framework\TestCase;
|
|||||||
/**
|
/**
|
||||||
* Unit tests for the Find class
|
* Unit tests for the Find class
|
||||||
*/
|
*/
|
||||||
|
#[TestDox('Find Queries (Unit tests)')]
|
||||||
class FindTest extends TestCase
|
class FindTest extends TestCase
|
||||||
{
|
{
|
||||||
protected function setUp(): void
|
|
||||||
{
|
|
||||||
Configuration::$mode = Mode::SQLite;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function tearDown(): void
|
protected function tearDown(): void
|
||||||
{
|
{
|
||||||
Configuration::$mode = null;
|
Configuration::$mode = null;
|
||||||
@@ -25,14 +21,47 @@ class FindTest extends TestCase
|
|||||||
#[TestDox('By ID succeeds')]
|
#[TestDox('By ID succeeds')]
|
||||||
public function testByIdSucceeds(): void
|
public function testByIdSucceeds(): void
|
||||||
{
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
$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');
|
'SELECT query not generated correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testByFieldsSucceeds(): void
|
public function testByFieldsSucceeds(): void
|
||||||
{
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
$this->assertEquals("SELECT data FROM there WHERE data->>'active' = :act OR data->>'locked' = :lock",
|
$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'),
|
Find::byFields('there', [Field::EQ('active', true, ':act'), Field::EQ('locked', true, ':lock')],
|
||||||
|
FieldMatch::Any),
|
||||||
'SELECT query not generated correctly');
|
'SELECT query not generated correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('By contains succeeds for PostgreSQL')]
|
||||||
|
public function testByContainsSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals('SELECT data FROM disc WHERE data @> :criteria', Find::byContains('disc'),
|
||||||
|
'SELECT query not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By contains fails for non PostgreSQL')]
|
||||||
|
public function testByContainsFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Find::byContains('');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds for PostgreSQL')]
|
||||||
|
public function testByJsonPathSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals('SELECT data FROM light WHERE jsonb_path_exists(data, :path::jsonpath)',
|
||||||
|
Find::byJsonPath('light'), 'SELECT query not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path fails for non PostgreSQL')]
|
||||||
|
public function testByJsonPathFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Find::byJsonPath('');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,71 +10,87 @@ use PHPUnit\Framework\TestCase;
|
|||||||
/**
|
/**
|
||||||
* Unit tests for the Patch class
|
* Unit tests for the Patch class
|
||||||
*/
|
*/
|
||||||
|
#[TestDox('Patch Queries (Unit tests)')]
|
||||||
class PatchTest extends TestCase
|
class PatchTest extends TestCase
|
||||||
{
|
{
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = null;
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
#[TestDox('By ID succeeds for PostgreSQL')]
|
#[TestDox('By ID succeeds for PostgreSQL')]
|
||||||
public function testByIdSucceedsForPostgreSQL(): void
|
public function testByIdSucceedsForPostgreSQL(): void
|
||||||
{
|
{
|
||||||
try {
|
|
||||||
Configuration::$mode = Mode::PgSQL;
|
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');
|
Patch::byId('doc_table'), 'Patch UPDATE statement is not correct');
|
||||||
} finally {
|
|
||||||
Configuration::$mode = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By ID succeeds for SQLite')]
|
#[TestDox('By ID succeeds for SQLite')]
|
||||||
public function testByIdSucceedsForSQLite(): void
|
public function testByIdSucceedsForSQLite(): void
|
||||||
{
|
{
|
||||||
try {
|
|
||||||
Configuration::$mode = Mode::SQLite;
|
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');
|
Patch::byId('my_table'), 'Patch UPDATE statement is not correct');
|
||||||
} finally {
|
|
||||||
Configuration::$mode = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By ID fails when mode not set')]
|
#[TestDox('By ID fails when mode not set')]
|
||||||
public function testByIdFailsWhenModeNotSet(): void
|
public function testByIdFailsWhenModeNotSet(): void
|
||||||
{
|
{
|
||||||
$this->expectException(DocumentException::class);
|
$this->expectException(DocumentException::class);
|
||||||
Configuration::$mode = null;
|
|
||||||
Patch::byId('oof');
|
Patch::byId('oof');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By fields succeeds for PostgreSQL')]
|
#[TestDox('By fields succeeds for PostgreSQL')]
|
||||||
public function testByFieldsSucceedsForPostgreSQL(): void
|
public function testByFieldsSucceedsForPostgreSQL(): void
|
||||||
{
|
{
|
||||||
try {
|
|
||||||
Configuration::$mode = Mode::PgSQL;
|
Configuration::$mode = Mode::PgSQL;
|
||||||
$this->assertEquals("UPDATE that SET data = data || :data WHERE data->>'something' < :some",
|
$this->assertEquals("UPDATE that SET data = data || :data WHERE (data->>'something')::numeric < :some",
|
||||||
Patch::byFields('that', [Field::LT('something', 17, ':some')]),
|
Patch::byFields('that', [Field::LT('something', 17, ':some')]), 'Patch UPDATE statement is not correct');
|
||||||
'Patch UPDATE statement is not correct');
|
|
||||||
} finally {
|
|
||||||
Configuration::$mode = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By fields succeeds for SQLite')]
|
#[TestDox('By fields succeeds for SQLite')]
|
||||||
public function testByFieldsSucceedsForSQLite(): void
|
public function testByFieldsSucceedsForSQLite(): void
|
||||||
{
|
{
|
||||||
try {
|
|
||||||
Configuration::$mode = Mode::SQLite;
|
Configuration::$mode = Mode::SQLite;
|
||||||
$this->assertEquals(
|
$this->assertEquals(
|
||||||
"UPDATE a_table SET data = json_patch(data, json(:data)) WHERE data->>'something' > :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::byFields('a_table', [Field::GT('something', 17, ':it')]), 'Patch UPDATE statement is not correct');
|
||||||
'Patch UPDATE statement is not correct');
|
|
||||||
} finally {
|
|
||||||
Configuration::$mode = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testByFieldsFailsWhenModeNotSet(): void
|
public function testByFieldsFailsWhenModeNotSet(): void
|
||||||
{
|
{
|
||||||
$this->expectException(DocumentException::class);
|
$this->expectException(DocumentException::class);
|
||||||
Configuration::$mode = null;
|
|
||||||
Patch::byFields('oops', []);
|
Patch::byFields('oops', []);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('By contains succeeds for PostgreSQL')]
|
||||||
|
public function testByContainsSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals('UPDATE this SET data = data || :data WHERE data @> :criteria', Patch::byContains('this'),
|
||||||
|
'Patch UPDATE statement is not correct');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By contains fails for non PostgreSQL')]
|
||||||
|
public function testByContainsFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Patch::byContains('');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds for PostgreSQL')]
|
||||||
|
public function testByJsonPathSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals('UPDATE that SET data = data || :data WHERE jsonb_path_exists(data, :path::jsonpath)',
|
||||||
|
Patch::byJsonPath('that'), 'Patch UPDATE statement is not correct');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path fails for non PostgreSQL')]
|
||||||
|
public function testByJsonPathFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Patch::byJsonPath('');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,108 +10,118 @@ use PHPUnit\Framework\TestCase;
|
|||||||
/**
|
/**
|
||||||
* Unit tests for the RemoveFields class
|
* Unit tests for the RemoveFields class
|
||||||
*/
|
*/
|
||||||
|
#[TestDox('Remove Fields Queries (Unit tests)')]
|
||||||
class RemoveFieldsTest extends TestCase
|
class RemoveFieldsTest extends TestCase
|
||||||
{
|
{
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
|
||||||
#[TestDox('Update succeeds for PostgreSQL')]
|
#[TestDox('Update succeeds for PostgreSQL')]
|
||||||
public function testUpdateSucceedsForPostgreSQL(): void
|
public function testUpdateSucceedsForPostgreSQL(): void
|
||||||
{
|
{
|
||||||
try {
|
|
||||||
Configuration::$mode = Mode::PgSQL;
|
Configuration::$mode = Mode::PgSQL;
|
||||||
$this->assertEquals('UPDATE taco SET data = data - :names WHERE it = true',
|
$this->assertEquals('UPDATE taco SET data = data - :names::text[] WHERE it = true',
|
||||||
RemoveFields::update('taco', [':names' => "ARRAY['one','two']"], 'it = true'),
|
RemoveFields::update('taco', [':names' => "{one,two}"], 'it = true'), 'UPDATE statement not correct');
|
||||||
'UPDATE statement not correct');
|
|
||||||
} finally {
|
|
||||||
Configuration::$mode = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('Update succeeds for SQLite')]
|
#[TestDox('Update succeeds for SQLite')]
|
||||||
public function testUpdateSucceedsForSQLite(): void
|
public function testUpdateSucceedsForSQLite(): void
|
||||||
{
|
{
|
||||||
try {
|
|
||||||
Configuration::$mode = Mode::SQLite;
|
Configuration::$mode = Mode::SQLite;
|
||||||
$this->assertEquals('UPDATE burrito SET data = json_remove(data, :name0, :name1, :name2) WHERE a = b',
|
$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'),
|
RemoveFields::update('burrito', Parameters::fieldNames(':name', ['one', 'two', 'ten']), 'a = b'),
|
||||||
'UPDATE statement not correct');
|
'UPDATE statement not correct');
|
||||||
} finally {
|
|
||||||
Configuration::$mode = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testUpdateFailsWhenModeNotSet(): void
|
public function testUpdateFailsWhenModeNotSet(): void
|
||||||
{
|
{
|
||||||
$this->expectException(DocumentException::class);
|
$this->expectException(DocumentException::class);
|
||||||
Configuration::$mode = null;
|
|
||||||
RemoveFields::update('wow', [], '');
|
RemoveFields::update('wow', [], '');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By ID succeeds for PostgreSQL')]
|
#[TestDox('By ID succeeds for PostgreSQL')]
|
||||||
public function testByIdSucceedsForPostgreSQL()
|
public function testByIdSucceedsForPostgreSQL()
|
||||||
{
|
{
|
||||||
try {
|
|
||||||
Configuration::$mode = Mode::PgSQL;
|
Configuration::$mode = Mode::PgSQL;
|
||||||
$this->assertEquals("UPDATE churro SET data = data - :bite WHERE data->>'id' = :id",
|
$this->assertEquals("UPDATE churro SET data = data - :bite::text[] WHERE data->>'id' = :id",
|
||||||
RemoveFields::byId('churro', Parameters::fieldNames(':bite', ['byte'])),
|
RemoveFields::byId('churro', Parameters::fieldNames(':bite', ['byte'])), 'UPDATE statement not correct');
|
||||||
'UPDATE statement not correct');
|
|
||||||
} finally {
|
|
||||||
Configuration::$mode = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By ID succeeds for SQLite')]
|
#[TestDox('By ID succeeds for SQLite')]
|
||||||
public function testByIdSucceedsForSQLite()
|
public function testByIdSucceedsForSQLite()
|
||||||
{
|
{
|
||||||
try {
|
|
||||||
Configuration::$mode = Mode::SQLite;
|
Configuration::$mode = Mode::SQLite;
|
||||||
$this->assertEquals("UPDATE quesadilla SET data = json_remove(data, :bite0) WHERE data->>'id' = :id",
|
$this->assertEquals("UPDATE quesadilla SET data = json_remove(data, :bite0) WHERE data->>'id' = :id",
|
||||||
RemoveFields::byId('quesadilla', Parameters::fieldNames(':bite', ['byte'])),
|
RemoveFields::byId('quesadilla', Parameters::fieldNames(':bite', ['byte'])),
|
||||||
'UPDATE statement not correct');
|
'UPDATE statement not correct');
|
||||||
} finally {
|
|
||||||
Configuration::$mode = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By ID fails when mode not set')]
|
#[TestDox('By ID fails when mode not set')]
|
||||||
public function testByIdFailsWhenModeNotSet(): void
|
public function testByIdFailsWhenModeNotSet(): void
|
||||||
{
|
{
|
||||||
$this->expectException(DocumentException::class);
|
$this->expectException(DocumentException::class);
|
||||||
Configuration::$mode = null;
|
|
||||||
RemoveFields::byId('oof', []);
|
RemoveFields::byId('oof', []);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By fields succeeds for PostgreSQL')]
|
#[TestDox('By fields succeeds for PostgreSQL')]
|
||||||
public function testByFieldsSucceedsForPostgreSQL()
|
public function testByFieldsSucceedsForPostgreSQL()
|
||||||
{
|
{
|
||||||
try {
|
|
||||||
Configuration::$mode = Mode::PgSQL;
|
Configuration::$mode = Mode::PgSQL;
|
||||||
$this->assertEquals("UPDATE enchilada SET data = data - :sauce WHERE data->>'cheese' = :queso",
|
$this->assertEquals("UPDATE enchilada SET data = data - :sauce::text[] WHERE data->>'cheese' = :queso",
|
||||||
RemoveFields::byFields('enchilada', [Field::EQ('cheese', 'jack', ':queso')],
|
RemoveFields::byFields('enchilada', [Field::EQ('cheese', 'jack', ':queso')],
|
||||||
Parameters::fieldNames(':sauce', ['white'])),
|
Parameters::fieldNames(':sauce', ['white'])),
|
||||||
'UPDATE statement not correct');
|
'UPDATE statement not correct');
|
||||||
} finally {
|
|
||||||
Configuration::$mode = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By fields succeeds for SQLite')]
|
#[TestDox('By fields succeeds for SQLite')]
|
||||||
public function testByFieldsSucceedsForSQLite()
|
public function testByFieldsSucceedsForSQLite()
|
||||||
{
|
{
|
||||||
try {
|
|
||||||
Configuration::$mode = Mode::SQLite;
|
Configuration::$mode = Mode::SQLite;
|
||||||
$this->assertEquals(
|
$this->assertEquals(
|
||||||
"UPDATE chimichanga SET data = json_remove(data, :filling0) WHERE data->>'side' = :rice",
|
"UPDATE chimichanga SET data = json_remove(data, :filling0) WHERE data->>'side' = :rice",
|
||||||
RemoveFields::byFields('chimichanga', [Field::EQ('side', 'beans', ':rice')],
|
RemoveFields::byFields('chimichanga', [Field::EQ('side', 'beans', ':rice')],
|
||||||
Parameters::fieldNames(':filling', ['beef'])),
|
Parameters::fieldNames(':filling', ['beef'])),
|
||||||
'UPDATE statement not correct');
|
'UPDATE statement not correct');
|
||||||
} finally {
|
|
||||||
Configuration::$mode = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testByFieldsFailsWhenModeNotSet(): void
|
public function testByFieldsFailsWhenModeNotSet(): void
|
||||||
{
|
{
|
||||||
$this->expectException(DocumentException::class);
|
$this->expectException(DocumentException::class);
|
||||||
Configuration::$mode = null;
|
|
||||||
RemoveFields::byFields('boing', [], []);
|
RemoveFields::byFields('boing', [], []);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('By contains succeeds for PostgreSQL')]
|
||||||
|
public function testByContainsSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals('UPDATE food SET data = data - :drink::text[] WHERE data @> :criteria',
|
||||||
|
RemoveFields::byContains('food', Parameters::fieldNames(':drink', ['a', 'b'])),
|
||||||
|
'UPDATE statement not correct');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By contains fails for non PostgreSQL')]
|
||||||
|
public function testByContainsFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
RemoveFields::byContains('', []);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds for PostgreSQL')]
|
||||||
|
public function testByJsonPathSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals(
|
||||||
|
'UPDATE dessert SET data = data - :cake::text[] WHERE jsonb_path_exists(data, :path::jsonpath)',
|
||||||
|
RemoveFields::byJsonPath('dessert', Parameters::fieldNames(':cake', ['b', 'c'])),
|
||||||
|
'UPDATE statement not correct');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path fails for non PostgreSQL')]
|
||||||
|
public function testByJsonPathFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
RemoveFields::byJsonPath('', []);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,13 +2,14 @@
|
|||||||
|
|
||||||
namespace Test\Unit;
|
namespace Test\Unit;
|
||||||
|
|
||||||
use BitBadger\PDODocument\{Configuration, Field, Mode, Query};
|
use BitBadger\PDODocument\{AutoId, Configuration, DocumentException, Field, FieldMatch, Mode, Query};
|
||||||
use PHPUnit\Framework\Attributes\TestDox;
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unit tests for the Query class
|
* Unit tests for the Query class
|
||||||
*/
|
*/
|
||||||
|
#[TestDox('Query (Unit tests)')]
|
||||||
class QueryTest extends TestCase
|
class QueryTest extends TestCase
|
||||||
{
|
{
|
||||||
protected function setUp(): void
|
protected function setUp(): void
|
||||||
@@ -33,17 +34,18 @@ class QueryTest extends TestCase
|
|||||||
Query::whereByFields([Field::LE('test_field', '', ':it')]), 'WHERE fragment not constructed correctly');
|
Query::whereByFields([Field::LE('test_field', '', ':it')]), 'WHERE fragment not constructed correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testWhereByFieldsSucceedsForMultipleFields(): void
|
public function testWhereByFieldsSucceedsForMultipleFieldsAll(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals("data->>'test_field' <= :it AND data->>'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')]),
|
Query::whereByFields([Field::LE('test_field', '', ':it'), Field::EQ('other_field', '', ':other')]),
|
||||||
'WHERE fragment not constructed correctly');
|
'WHERE fragment not constructed correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testWhereByFieldsSucceedsForMultipleFieldsWithOr(): void
|
public function testWhereByFieldsSucceedsForMultipleFieldsAny(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals("data->>'test_field' <= :it OR data->>'other_field' = :other",
|
$this->assertEquals("data->>'test_field' <= :it OR data->>'other_field' = :other",
|
||||||
Query::whereByFields([Field::LE('test_field', '', ':it'), Field::EQ('other_field', '', ':other')], 'OR'),
|
Query::whereByFields([Field::LE('test_field', '', ':it'), Field::EQ('other_field', '', ':other')],
|
||||||
|
FieldMatch::Any),
|
||||||
'WHERE fragment not constructed correctly');
|
'WHERE fragment not constructed correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,10 +61,187 @@ class QueryTest extends TestCase
|
|||||||
$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
|
public function testWhereDataContainsSucceedsWithDefaultParameter(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals('INSERT INTO my_table VALUES (:data)', Query::insert('my_table'),
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
try {
|
||||||
|
$this->assertEquals('data @> :criteria', Query::whereDataContains(),
|
||||||
|
'WHERE fragment not constructed correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testWhereDataContainsSucceedsWithSpecifiedParameter(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
try {
|
||||||
|
$this->assertEquals('data @> :it', Query::whereDataContains(':it'),
|
||||||
|
'WHERE fragment not constructed correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Where data contains fails if not PostgreSQL')]
|
||||||
|
public function testWhereDataContainsFailsIfNotPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = null;
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Query::whereDataContains();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Where JSON Path matches succeeds with default parameter')]
|
||||||
|
public function testWhereJsonPathMatchesSucceedsWithDefaultParameter(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
try {
|
||||||
|
$this->assertEquals('jsonb_path_exists(data, :path::jsonpath)', Query::whereJsonPathMatches(),
|
||||||
|
'WHERE fragment not constructed correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Where JSON Path matches succeeds with specified parameter')]
|
||||||
|
public function testWhereJsonPathMatchesSucceedsWithSpecifiedParameter(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
try {
|
||||||
|
$this->assertEquals('jsonb_path_exists(data, :road::jsonpath)', Query::whereJsonPathMatches(':road'),
|
||||||
|
'WHERE fragment not constructed correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Where JSON Path matches fails if not PostgreSQL')]
|
||||||
|
public function testWhereJsonPathMatchesFailsIfNotPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = null;
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Query::whereJsonPathMatches();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds with no auto-ID for PostgreSQL')]
|
||||||
|
public function testInsertSucceedsWithNoAutoIdForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
try {
|
||||||
|
$this->assertEquals('INSERT INTO test_tbl VALUES (:data)', Query::insert('test_tbl'),
|
||||||
'INSERT statement not constructed correctly');
|
'INSERT statement not constructed correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds with no auto-ID for SQLite')]
|
||||||
|
public function testInsertSucceedsWithNoAutoIdForSQLite(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
try {
|
||||||
|
$this->assertEquals('INSERT INTO test_tbl VALUES (:data)', Query::insert('test_tbl'),
|
||||||
|
'INSERT statement not constructed correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds with auto numeric ID for PostgreSQL')]
|
||||||
|
public function testInsertSucceedsWithAutoNumericIdForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
try {
|
||||||
|
$this->assertEquals(
|
||||||
|
"INSERT INTO test_tbl VALUES (:data::jsonb || ('{\"id\":' "
|
||||||
|
. "|| (SELECT COALESCE(MAX((data->>'id')::numeric), 0) + 1 FROM test_tbl) || '}')::jsonb)",
|
||||||
|
Query::insert('test_tbl', AutoId::Number), 'INSERT statement not constructed correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds with auto numeric ID for SQLite')]
|
||||||
|
public function testInsertSucceedsWithAutoNumericIdForSQLite(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
try {
|
||||||
|
$this->assertEquals(
|
||||||
|
"INSERT INTO test_tbl VALUES (json_set(:data, '$.id', "
|
||||||
|
. "(SELECT coalesce(max(data->>'id'), 0) + 1 FROM test_tbl)))",
|
||||||
|
Query::insert('test_tbl', AutoId::Number), 'INSERT statement not constructed correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds with auto UUID for PostgreSQL')]
|
||||||
|
public function testInsertSucceedsWithAutoUuidForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
try {
|
||||||
|
$query = Query::insert('test_tbl', AutoId::UUID);
|
||||||
|
$this->assertStringStartsWith("INSERT INTO test_tbl VALUES (:data::jsonb || '{\"id\":\"", $query,
|
||||||
|
'INSERT statement not constructed correctly');
|
||||||
|
$this->assertStringEndsWith("\"}')", $query, 'INSERT statement not constructed correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds with auto UUID for SQLite')]
|
||||||
|
public function testInsertSucceedsWithAutoUuidForSQLite(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
try {
|
||||||
|
$query = Query::insert('test_tbl', AutoId::UUID);
|
||||||
|
$this->assertStringStartsWith("INSERT INTO test_tbl VALUES (json_set(:data, '$.id', '", $query,
|
||||||
|
'INSERT statement not constructed correctly');
|
||||||
|
$this->assertStringEndsWith("'))", $query, 'INSERT statement not constructed correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds with auto random string for PostgreSQL')]
|
||||||
|
public function testInsertSucceedsWithAutoRandomStringForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
Configuration::$idStringLength = 8;
|
||||||
|
try {
|
||||||
|
$query = Query::insert('test_tbl', AutoId::RandomString);
|
||||||
|
$this->assertStringStartsWith("INSERT INTO test_tbl VALUES (:data::jsonb || '{\"id\":\"", $query,
|
||||||
|
'INSERT statement not constructed correctly');
|
||||||
|
$this->assertStringEndsWith("\"}')", $query, 'INSERT statement not constructed correctly');
|
||||||
|
$id = str_replace(["INSERT INTO test_tbl VALUES (:data::jsonb || '{\"id\":\"", "\"}')"], '', $query);
|
||||||
|
$this->assertEquals(8, strlen($id), "Generated ID [$id] should have been 8 characters long");
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
Configuration::$idStringLength = 16;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds with auto random string for SQLite')]
|
||||||
|
public function testInsertSucceedsWithAutoRandomStringForSQLite(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
try {
|
||||||
|
$query = Query::insert('test_tbl', AutoId::RandomString);
|
||||||
|
$this->assertStringStartsWith("INSERT INTO test_tbl VALUES (json_set(:data, '$.id', '", $query,
|
||||||
|
'INSERT statement not constructed correctly');
|
||||||
|
$this->assertStringEndsWith("'))", $query, 'INSERT statement not constructed correctly');
|
||||||
|
$id = str_replace(["INSERT INTO test_tbl VALUES (json_set(:data, '$.id', '", "'))"], '', $query);
|
||||||
|
$this->assertEquals(16, strlen($id), "Generated ID [$id] should have been 16 characters long");
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testInsertFailsWhenModeNotSet(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Configuration::$mode = null;
|
||||||
|
Query::insert('kaboom');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testSaveSucceeds(): void
|
public function testSaveSucceeds(): void
|
||||||
|
|||||||
Reference in New Issue
Block a user