Compare commits
23 Commits
v1.0.0-alp
...
main
Author | SHA1 | Date | |
---|---|---|---|
486028bd40 | |||
df436c9ef4 | |||
d067f8983f | |||
9e0e663811 | |||
039283224a | |||
407441e857 | |||
3d2bc2a904 | |||
4d764cbb3f | |||
57d8f9ddc1 | |||
37fa200fa7 | |||
adbe4e6614 | |||
0659de3f99 | |||
d8330d828a | |||
1a37b009ea | |||
5201e564ca | |||
478684621c | |||
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
|
||||||
|
|
31
README.md
31
README.md
|
@ -1,11 +1,36 @@
|
||||||
# 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`
|
[![Static Badge](https://img.shields.io/badge/v1.0.0--rc1-orange?label=php%208.2)
|
||||||
|
](https://packagist.org/packages/bit-badger/pdo-document#v1.0.0-rc1) [![Packagist Version](https://img.shields.io/packagist/v/bit-badger/pdo-document?include_prereleases&label=php%208.4)
|
||||||
|
](https://packagist.org/packages/bit-badger/pdo-document)
|
||||||
|
|
||||||
|
`composer require bit-badger/pdo-document`
|
||||||
|
|
||||||
|
For the v1 series, the `DocumentList` type's members `hasItems` and `items` are functions; in the v2 series, they are properties. Additionally, the `Option` and `Result` types included in the project have a similar difference; see the [v1 README](https://git.bitbadger.solutions/bit-badger/inspired-by-fsharp/src/branch/v1/README.md) for PHP 8.2 or 8.3 and the [v2 README](https://git.bitbadger.solutions/bit-badger/inspired-by-fsharp/src/branch/main/README.md) for PHP 8.4. Both versions are supported; the v1 / v2 distinction helps composer make the right choice based on the target PHP version of your project.
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
### Connection Details
|
||||||
|
|
||||||
|
The [PDO data source name](https://www.php.net/manual/en/pdo.construct.php#refsect1-pdo.construct-parameters) must be provided via `Configuration::useDSN()`. `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.
|
Full documentation [is available on the project site](https://bitbadger.solutions/open-source/pdo-document/).
|
||||||
|
|
|
@ -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": [
|
||||||
{
|
{
|
||||||
|
@ -14,15 +14,20 @@
|
||||||
"support": {
|
"support": {
|
||||||
"email": "daniel@bitbadger.solutions",
|
"email": "daniel@bitbadger.solutions",
|
||||||
"source": "https://git.bitbadger.solutions/bit-badger/pdo-document",
|
"source": "https://git.bitbadger.solutions/bit-badger/pdo-document",
|
||||||
"rss": "https://git.bitbadger.solutions/bit-badger/pdo-document.rss"
|
"rss": "https://git.bitbadger.solutions/bit-badger/pdo-document.rss",
|
||||||
|
"docs": "https://bitbadger.solutions/open-source/pdo-document/"
|
||||||
},
|
},
|
||||||
|
"minimum-stability": "RC",
|
||||||
"require": {
|
"require": {
|
||||||
"php": ">=8.3",
|
"php": ">=8.4",
|
||||||
|
"bit-badger/inspired-by-fsharp": "^2",
|
||||||
"netresearch/jsonmapper": "^4",
|
"netresearch/jsonmapper": "^4",
|
||||||
"ext-pdo": "*"
|
"ext-pdo": "*"
|
||||||
},
|
},
|
||||||
"require-dev": {
|
"require-dev": {
|
||||||
"phpunit/phpunit": "^11"
|
"phpunit/phpunit": "^11",
|
||||||
|
"square/pjson": "^0.5.0",
|
||||||
|
"phpstan/phpstan": "^1.12"
|
||||||
},
|
},
|
||||||
"autoload": {
|
"autoload": {
|
||||||
"psr-4": {
|
"psr-4": {
|
||||||
|
@ -33,9 +38,14 @@
|
||||||
},
|
},
|
||||||
"autoload-dev": {
|
"autoload-dev": {
|
||||||
"psr-4": {
|
"psr-4": {
|
||||||
|
"Test\\": "./tests",
|
||||||
"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" ]
|
||||||
}
|
}
|
||||||
}
|
}
|
526
composer.lock
generated
526
composer.lock
generated
File diff suppressed because it is too large
Load Diff
58
src/AutoId.php
Normal file
58
src/AutoId.php
Normal file
|
@ -0,0 +1,58 @@
|
||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,7 +1,15 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace BitBadger\PDODocument;
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
use BitBadger\InspiredByFSharp\Option;
|
||||||
|
use Exception;
|
||||||
use PDO;
|
use PDO;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -12,8 +20,13 @@ 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 string The data source name (DSN) of the connection string */
|
/** @var AutoId The automatic ID generation process to use */
|
||||||
public static string $pdoDSN = '';
|
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|null The username to use to establish a data connection (use env PDO_DOC_USERNAME if possible) */
|
/** @var string|null The username to use to establish a data connection (use env PDO_DOC_USERNAME if possible) */
|
||||||
public static ?string $username = null;
|
public static ?string $username = null;
|
||||||
|
@ -21,47 +34,79 @@ class Configuration
|
||||||
/** @var string|null The password to use to establish a data connection (use env PDO_DOC_PASSWORD if possible) */
|
/** @var string|null The password to use to establish a data connection (use env PDO_DOC_PASSWORD if possible) */
|
||||||
public static ?string $password = null;
|
public static ?string $password = null;
|
||||||
|
|
||||||
/** @var array|null Options to use for connections (driver-specific) */
|
/** @var mixed[]|null Options to use for connections (driver-specific) */
|
||||||
public static ?array $options = null;
|
public static ?array $options = null;
|
||||||
|
|
||||||
/** @var Mode|null The mode in which the library is operating (filled after first connection if not configured) */
|
/** @var Option<Mode> The mode in which the library is operating */
|
||||||
public static ?Mode $mode = null;
|
public static Option $mode;
|
||||||
|
|
||||||
|
/** @var Option<string> The data source name (DSN) of the connection string */
|
||||||
|
private static Option $pdoDSN;
|
||||||
|
|
||||||
/** @var PDO|null The PDO instance to use for database commands */
|
/** @var PDO|null The PDO instance to use for database commands */
|
||||||
private static ?PDO $_pdo = null;
|
private static ?PDO $pdo = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Use a Data Source Name (DSN)
|
||||||
|
*
|
||||||
|
* @param string $dsn The data source name to use (driver:[parameters])
|
||||||
|
* @throws DocumentException If a DSN does not start with `pgsql:` or `sqlite:`
|
||||||
|
*/
|
||||||
|
public static function useDSN(string $dsn): void
|
||||||
|
{
|
||||||
|
if (empty($dsn)) {
|
||||||
|
self::$mode = self::$pdoDSN = Option::None();
|
||||||
|
} else {
|
||||||
|
self::$mode = Option::Some(Mode::deriveFromDSN($dsn));
|
||||||
|
self::$pdoDSN = Option::Some($dsn);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieve a new connection to the database
|
* Retrieve a new connection to the database
|
||||||
*
|
*
|
||||||
* @return PDO A new connection to the SQLite database with foreign key support enabled
|
* @return PDO A new connection to the SQLite database with foreign key support enabled
|
||||||
* @throws DocumentException If this is called before a connection string is set
|
* @throws Exception If this is called before a connection string is set
|
||||||
*/
|
*/
|
||||||
public static function dbConn(): PDO
|
public static function dbConn(): PDO
|
||||||
{
|
{
|
||||||
if (is_null(self::$_pdo)) {
|
if (is_null(self::$pdo)) {
|
||||||
if (empty(self::$pdoDSN)) {
|
$dsn = self::$pdoDSN->getOrThrow(fn()
|
||||||
throw new DocumentException('Please provide a data source name (DSN) before attempting data access');
|
=> new DocumentException('Please provide a data source name (DSN) before attempting data access'));
|
||||||
}
|
self::$pdo = new PDO($dsn, $_ENV['PDO_DOC_USERNAME'] ?? self::$username,
|
||||||
self::$_pdo = new PDO(self::$pdoDSN, $_ENV['PDO_DOC_USERNAME'] ?? self::$username,
|
|
||||||
$_ENV['PDO_DOC_PASSWORD'] ?? self::$password, self::$options);
|
$_ENV['PDO_DOC_PASSWORD'] ?? self::$password, self::$options);
|
||||||
|
|
||||||
if (is_null(self::$mode)) {
|
|
||||||
$driver = self::$_pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
|
|
||||||
self::$mode = match ($driver) {
|
|
||||||
'pgsql' => Mode::PgSQL,
|
|
||||||
'sqlite' => Mode::SQLite,
|
|
||||||
default => throw new DocumentException(
|
|
||||||
"Unsupported driver $driver: this library currently supports PostgreSQL and SQLite")
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return self::$_pdo;
|
return self::$pdo;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve the mode for the current database connection
|
||||||
|
*
|
||||||
|
* @return Mode The mode for the current database connection
|
||||||
|
* @throws Exception If the database mode has not been set
|
||||||
|
*/
|
||||||
|
public static function mode(?string $process = null): Mode
|
||||||
|
{
|
||||||
|
return self::$mode->getOrThrow(fn()
|
||||||
|
=> new DocumentException('Database mode not set' . (is_null($process) ? '' : "; cannot $process")));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* You probably don't mean to be calling this; it is here for testing only
|
||||||
|
*
|
||||||
|
* @param Mode|null $mode The mode to set
|
||||||
|
*/
|
||||||
|
public static function overrideMode(?Mode $mode): void
|
||||||
|
{
|
||||||
|
self::$mode = Option::of($mode);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clear the current PDO instance
|
||||||
|
*/
|
||||||
public static function resetPDO(): void
|
public static function resetPDO(): void
|
||||||
{
|
{
|
||||||
self::$_pdo = null;
|
self::$pdo = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,10 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace BitBadger\PDODocument;
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
@ -25,15 +31,42 @@ class Count
|
||||||
* Count matching documents using a comparison on JSON fields
|
* Count matching documents using a comparison on JSON fields
|
||||||
*
|
*
|
||||||
* @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 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);
|
Parameters::nameFields($fields);
|
||||||
return Custom::scalar(Query\Count::byFields($tableName, $namedFields, $conjunction),
|
return Custom::scalar(Query\Count::byFields($tableName, $fields, $match), Parameters::addFields($fields, []),
|
||||||
Parameters::addFields($namedFields, []), new CountMapper());
|
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 mixed[]|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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,7 +1,14 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace BitBadger\PDODocument;
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
use BitBadger\InspiredByFSharp\Option;
|
||||||
use BitBadger\PDODocument\Mapper\Mapper;
|
use BitBadger\PDODocument\Mapper\Mapper;
|
||||||
use PDO;
|
use PDO;
|
||||||
use PDOException;
|
use PDOException;
|
||||||
|
@ -16,7 +23,7 @@ class Custom
|
||||||
* Prepare a query for execution and run it
|
* Prepare a query for execution and run it
|
||||||
*
|
*
|
||||||
* @param string $query The query to be run
|
* @param string $query The query to be run
|
||||||
* @param array $parameters The parameters for the query
|
* @param array<string, mixed> $parameters The parameters for the query
|
||||||
* @return PDOStatement The result of executing the query
|
* @return PDOStatement The result of executing the query
|
||||||
* @throws DocumentException If the query execution is unsuccessful
|
* @throws DocumentException If the query execution is unsuccessful
|
||||||
*/
|
*/
|
||||||
|
@ -38,7 +45,7 @@ class Custom
|
||||||
is_bool($value) => PDO::PARAM_BOOL,
|
is_bool($value) => PDO::PARAM_BOOL,
|
||||||
is_int($value) => PDO::PARAM_INT,
|
is_int($value) => PDO::PARAM_INT,
|
||||||
is_null($value) => PDO::PARAM_NULL,
|
is_null($value) => PDO::PARAM_NULL,
|
||||||
default => PDO::PARAM_STR
|
default => PDO::PARAM_STR,
|
||||||
};
|
};
|
||||||
$stmt->bindValue($key, $value, $dataType);
|
$stmt->bindValue($key, $value, $dataType);
|
||||||
}
|
}
|
||||||
|
@ -60,7 +67,7 @@ class Custom
|
||||||
*
|
*
|
||||||
* @template TDoc The domain type of the document to retrieve
|
* @template TDoc The domain type of the document to retrieve
|
||||||
* @param string $query The query to be executed
|
* @param string $query The query to be executed
|
||||||
* @param array $parameters Parameters to use in executing the query
|
* @param array<string, mixed> $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 DocumentList<TDoc> The items matching the query
|
* @return DocumentList<TDoc> The items matching the query
|
||||||
* @throws DocumentException If any is encountered
|
* @throws DocumentException If any is encountered
|
||||||
|
@ -75,14 +82,14 @@ class Custom
|
||||||
*
|
*
|
||||||
* @template TDoc The domain type of the document to retrieve
|
* @template TDoc The domain type of the document to retrieve
|
||||||
* @param string $query The query to be executed
|
* @param string $query The query to be executed
|
||||||
* @param array $parameters Parameters to use in executing the query
|
* @param array<string, mixed> $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 TDoc[] The items matching the query
|
* @return TDoc[] The items matching the query
|
||||||
* @throws DocumentException If any is encountered
|
* @throws DocumentException If any is encountered
|
||||||
*/
|
*/
|
||||||
public static function array(string $query, array $parameters, Mapper $mapper): array
|
public static function array(string $query, array $parameters, Mapper $mapper): array
|
||||||
{
|
{
|
||||||
return iterator_to_array(self::list($query, $parameters, $mapper)->items());
|
return iterator_to_array(self::list($query, $parameters, $mapper)->items);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -90,16 +97,16 @@ class Custom
|
||||||
*
|
*
|
||||||
* @template TDoc The domain type of the document to retrieve
|
* @template TDoc The domain type of the document to retrieve
|
||||||
* @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<string, mixed> $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)) ? Option::Some($mapper->map($first)) : Option::None();
|
||||||
} finally {
|
} finally {
|
||||||
$stmt = null;
|
$stmt = null;
|
||||||
}
|
}
|
||||||
|
@ -109,7 +116,7 @@ class Custom
|
||||||
* Execute a query that does not return a value
|
* Execute a query that does not return a value
|
||||||
*
|
*
|
||||||
* @param string $query The query to execute
|
* @param string $query The query to execute
|
||||||
* @param array $parameters Parameters to use in executing the query
|
* @param array<string, mixed> $parameters Parameters to use in executing the query
|
||||||
* @throws DocumentException If any is encountered
|
* @throws DocumentException If any is encountered
|
||||||
*/
|
*/
|
||||||
public static function nonQuery(string $query, array $parameters): void
|
public static function nonQuery(string $query, array $parameters): void
|
||||||
|
@ -126,7 +133,7 @@ class Custom
|
||||||
*
|
*
|
||||||
* @template T The scalar type to return
|
* @template T The scalar type to return
|
||||||
* @param string $query The query to retrieve the value
|
* @param string $query The query to retrieve the value
|
||||||
* @param array $parameters Parameters to use in executing the query
|
* @param array<string, mixed> $parameters Parameters to use in executing the query
|
||||||
* @param Mapper<T> $mapper The mapper to obtain the result
|
* @param Mapper<T> $mapper The mapper to obtain the result
|
||||||
* @return mixed|false|T The scalar value if found, false if not
|
* @return mixed|false|T The scalar value if found, false if not
|
||||||
* @throws DocumentException If any is encountered
|
* @throws DocumentException If any is encountered
|
||||||
|
|
|
@ -1,4 +1,10 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace BitBadger\PDODocument;
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
@ -24,11 +30,23 @@ class Definition
|
||||||
*
|
*
|
||||||
* @param string $tableName The name of the table which should be indexed
|
* @param string $tableName The name of the table which should be indexed
|
||||||
* @param string $indexName The name of the index
|
* @param string $indexName The name of the index
|
||||||
* @param array $fields Fields which should be a part of this index
|
* @param string[] $fields Fields which should be a part of this index
|
||||||
* @throws DocumentException If any is encountered
|
* @throws DocumentException If any is encountered
|
||||||
*/
|
*/
|
||||||
public static function ensureFieldIndex(string $tableName, string $indexName, array $fields): void
|
public static function ensureFieldIndex(string $tableName, string $indexName, array $fields): void
|
||||||
{
|
{
|
||||||
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), []);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,10 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace BitBadger\PDODocument;
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
@ -16,21 +22,44 @@ 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));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Delete documents by matching a comparison on JSON fields
|
* Delete documents by matching a comparison on JSON fields
|
||||||
*
|
*
|
||||||
* @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 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);
|
Parameters::nameFields($fields);
|
||||||
Custom::nonQuery(Query\Delete::byFields($tableName, $namedFields, $conjunction),
|
Custom::nonQuery(Query\Delete::byFields($tableName, $fields, $match), Parameters::addFields($fields, []));
|
||||||
Parameters::addFields($namedFields, []));
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete documents matching a JSON containment query (`@>`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The table from which documents should be deleted
|
||||||
|
* @param mixed[]|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]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,10 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace BitBadger\PDODocument;
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
@ -11,19 +17,37 @@ class Document
|
||||||
* Insert a new document
|
* Insert a new document
|
||||||
*
|
*
|
||||||
* @param string $tableName The name of the table into which the document should be inserted
|
* @param string $tableName The name of the table into which the document should be inserted
|
||||||
* @param array|object $document The document to be inserted
|
* @param mixed[]|object $document The document to be inserted
|
||||||
* @throws DocumentException If any is encountered
|
* @throws DocumentException If any is encountered
|
||||||
*/
|
*/
|
||||||
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));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Save a document, inserting it if it does not exist and updating it if it does (AKA "upsert")
|
* Save a document, inserting it if it does not exist and updating it if it does (AKA "upsert")
|
||||||
*
|
*
|
||||||
* @param string $tableName The name of the table to which the document should be saved
|
* @param string $tableName The name of the table to which the document should be saved
|
||||||
* @param array|object $document The document to be saved
|
* @param mixed[]|object $document The document to be saved
|
||||||
* @throws DocumentException If any is encountered
|
* @throws DocumentException If any is encountered
|
||||||
*/
|
*/
|
||||||
public static function save(string $tableName, array|object $document): void
|
public static function save(string $tableName, array|object $document): void
|
||||||
|
@ -36,7 +60,7 @@ class Document
|
||||||
*
|
*
|
||||||
* @param string $tableName The table in which the document should be updated
|
* @param string $tableName The table in which the document should be updated
|
||||||
* @param mixed $docId The ID of the document to be updated
|
* @param mixed $docId The ID of the document to be updated
|
||||||
* @param array|object $document The document to be updated
|
* @param mixed[]|object $document The document to be updated
|
||||||
* @throws DocumentException If any is encountered
|
* @throws DocumentException If any is encountered
|
||||||
*/
|
*/
|
||||||
public static function update(string $tableName, mixed $docId, array|object $document): void
|
public static function update(string $tableName, mixed $docId, array|object $document): void
|
||||||
|
|
|
@ -1,4 +1,10 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace BitBadger\PDODocument;
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
|
21
src/DocumentIndex.php
Normal file
21
src/DocumentIndex.php
Normal file
|
@ -0,0 +1,21 @@
|
||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
|
@ -1,4 +1,10 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace BitBadger\PDODocument;
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
@ -15,8 +21,11 @@ use PDOStatement;
|
||||||
*/
|
*/
|
||||||
class DocumentList
|
class DocumentList
|
||||||
{
|
{
|
||||||
/** @var TDoc|null $_first The first item from the results */
|
/** @var TDoc|null $first The first item from the results */
|
||||||
private mixed $_first = null;
|
private mixed $first = null;
|
||||||
|
|
||||||
|
/** @var bool $isConsumed This is set to true once the generator has been exhausted */
|
||||||
|
private bool $isConsumed = false;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructor
|
* Constructor
|
||||||
|
@ -26,51 +35,91 @@ class DocumentList
|
||||||
*/
|
*/
|
||||||
private function __construct(private ?PDOStatement &$result, private readonly Mapper $mapper)
|
private function __construct(private ?PDOStatement &$result, private readonly Mapper $mapper)
|
||||||
{
|
{
|
||||||
|
if (!is_null($this->result)) {
|
||||||
if ($row = $this->result->fetch(PDO::FETCH_ASSOC)) {
|
if ($row = $this->result->fetch(PDO::FETCH_ASSOC)) {
|
||||||
$this->_first = $this->mapper->map($row);
|
$this->first = $this->mapper->map($row);
|
||||||
} else {
|
} else {
|
||||||
$this->result = null;
|
$this->result = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/** @var bool True if there are items still to be retrieved from the list, false if not */
|
||||||
* Construct a new document list
|
public bool $hasItems {
|
||||||
*
|
get => !is_null($this->result);
|
||||||
* @param string $query The query to run to retrieve results
|
|
||||||
* @param array $parameters An associative array of parameters for the query
|
|
||||||
* @param Mapper<TDoc> $mapper A mapper to deserialize JSON documents
|
|
||||||
* @return static The document list instance
|
|
||||||
* @throws DocumentException If any is encountered
|
|
||||||
*/
|
|
||||||
public static function create(string $query, array $parameters, Mapper $mapper): static
|
|
||||||
{
|
|
||||||
$stmt = &Custom::runQuery($query, $parameters);
|
|
||||||
return new static($stmt, $mapper);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The items from the query result
|
* @var Generator<TDoc> The items from the document list
|
||||||
*
|
* @throws DocumentException If this is called once the generator has been consumed
|
||||||
* @return Generator<TDoc> The items from the document list
|
|
||||||
*/
|
*/
|
||||||
public function items(): Generator
|
public Generator $items {
|
||||||
{
|
get {
|
||||||
if (!$this->result) return;
|
if (!$this->result) {
|
||||||
yield $this->_first;
|
if ($this->isConsumed) {
|
||||||
|
throw new DocumentException('Cannot call items() multiple times');
|
||||||
|
}
|
||||||
|
$this->isConsumed = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!$this->first) {
|
||||||
|
$this->isConsumed = true;
|
||||||
|
$this->result = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
yield $this->first;
|
||||||
while ($row = $this->result->fetch(PDO::FETCH_ASSOC)) {
|
while ($row = $this->result->fetch(PDO::FETCH_ASSOC)) {
|
||||||
yield $this->mapper->map($row);
|
yield $this->mapper->map($row);
|
||||||
}
|
}
|
||||||
|
$this->isConsumed = true;
|
||||||
$this->result = null;
|
$this->result = null;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Does this list have items remaining?
|
* Map items by consuming the generator
|
||||||
*
|
*
|
||||||
* @return bool True if there are items still to be retrieved from the list, false if not
|
* @template U The type to which each item should be mapped
|
||||||
|
* @param callable(TDoc): U $map The mapping function
|
||||||
|
* @return Generator<U> The result of the mapping function
|
||||||
|
* @throws DocumentException If this is called once the generator has been consumed
|
||||||
*/
|
*/
|
||||||
public function hasItems(): bool
|
public function map(callable $map): Generator
|
||||||
{
|
{
|
||||||
return !is_null($this->result);
|
foreach ($this->items as $item) {
|
||||||
|
yield $map($item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Iterate the generator, running the given function for each item
|
||||||
|
*
|
||||||
|
* @param callable(TDoc): void $f The function to run for each item
|
||||||
|
* @throws DocumentException If this is called once the generator has been consumed
|
||||||
|
*/
|
||||||
|
public function iter(callable $f): void
|
||||||
|
{
|
||||||
|
foreach ($this->items as $item) {
|
||||||
|
$f($item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Iterate the generator, extracting key/value pairs returned as an associative array
|
||||||
|
*
|
||||||
|
* @template TValue The type for the mapped value
|
||||||
|
* @param callable(TDoc): (int|string) $keyFunc The function to extract a key from the document
|
||||||
|
* @param callable(TDoc): TValue $valueFunc The function to extract a value from the document
|
||||||
|
* @return TValue[] An associative array of values, keyed by the extracted keys
|
||||||
|
* @throws DocumentException If this is called once the generator has been consumed
|
||||||
|
*/
|
||||||
|
public function mapToArray(callable $keyFunc, callable $valueFunc): array
|
||||||
|
{
|
||||||
|
$results = [];
|
||||||
|
foreach ($this->items as $item) {
|
||||||
|
$results[$keyFunc($item)] = $valueFunc($item);
|
||||||
|
}
|
||||||
|
return $results;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -80,4 +129,19 @@ class DocumentList
|
||||||
{
|
{
|
||||||
if (!is_null($this->result)) $this->result = null;
|
if (!is_null($this->result)) $this->result = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Construct a new document list
|
||||||
|
*
|
||||||
|
* @param string $query The query to run to retrieve results
|
||||||
|
* @param array<string, mixed> $parameters An associative array of parameters for the query
|
||||||
|
* @param Mapper<TDoc> $mapper A mapper to deserialize JSON documents
|
||||||
|
* @return self<TDoc> The document list instance
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function create(string $query, array $parameters, Mapper $mapper): self
|
||||||
|
{
|
||||||
|
$stmt = &Custom::runQuery($query, $parameters);
|
||||||
|
return new self($stmt, $mapper);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,10 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace BitBadger\PDODocument;
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
@ -19,7 +25,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 +33,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);
|
Parameters::nameFields($fields);
|
||||||
return Custom::scalar(Query\Exists::byFields($tableName, $namedFields, $conjunction),
|
return Custom::scalar(Query\Exists::byFields($tableName, $fields, $match), Parameters::addFields($fields, []),
|
||||||
Parameters::addFields($namedFields, []), new ExistsMapper());
|
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 mixed[]|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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
318
src/Field.php
318
src/Field.php
|
@ -1,7 +1,15 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace BitBadger\PDODocument;
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
use Exception;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Criteria for a field WHERE clause
|
* Criteria for a field WHERE clause
|
||||||
*/
|
*/
|
||||||
|
@ -19,57 +27,110 @@ class Field
|
||||||
* @param string $paramName The name of the parameter to which this should be bound
|
* @param string $paramName The name of the parameter to which this should be bound
|
||||||
* @param string $qualifier A table qualifier for the `data` column
|
* @param string $qualifier A table qualifier for the `data` column
|
||||||
*/
|
*/
|
||||||
public function __construct(public string $fieldName = '', public Op $op = Op::EQ, public mixed $value = '',
|
public function __construct(public string $fieldName = '', public Op $op = Op::Equal, public mixed $value = '',
|
||||||
public string $paramName = '', public string $qualifier = '') { }
|
public string $paramName = '', public string $qualifier = '') { }
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Append the parameter name and value to the given associative array
|
* Append the parameter name and value to the given associative array
|
||||||
*
|
*
|
||||||
* @param array $existing The existing parameters
|
* @param array<string, mixed> $existing The existing parameters
|
||||||
* @return array The given parameter array with this field's name and value appended
|
* @return array<string, mixed> The given parameter array with this field's name and value(s) appended
|
||||||
*/
|
*/
|
||||||
public function appendParameter(array $existing): array
|
public function appendParameter(array $existing): array
|
||||||
{
|
{
|
||||||
switch ($this->op) {
|
switch ($this->op) {
|
||||||
case Op::EX:
|
case Op::Exists:
|
||||||
case Op::NEX:
|
case Op::NotExists:
|
||||||
break;
|
break;
|
||||||
case Op::BT:
|
case Op::Between:
|
||||||
$existing["{$this->paramName}min"] = $this->value[0];
|
$existing["{$this->paramName}min"] = $this->value[0];
|
||||||
$existing["{$this->paramName}max"] = $this->value[1];
|
$existing["{$this->paramName}max"] = $this->value[1];
|
||||||
break;
|
break;
|
||||||
|
case Op::In:
|
||||||
|
for ($idx = 0; $idx < count($this->value); $idx++) {
|
||||||
|
$existing["{$this->paramName}_$idx"] = $this->value[$idx];
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case Op::InArray:
|
||||||
|
$mkString = Configuration::mode("Append parameters for InArray condition") === Mode::PgSQL;
|
||||||
|
$values = $this->value['values'];
|
||||||
|
for ($idx = 0; $idx < count($values); $idx++) {
|
||||||
|
$existing["{$this->paramName}_$idx"] = $mkString ? "$values[$idx]" : $values[$idx];
|
||||||
|
}
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
$existing[$this->paramName] = $this->value;
|
$existing[$this->paramName] = $this->value;
|
||||||
}
|
}
|
||||||
return $existing;
|
return $existing;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Derive the path for this field
|
||||||
|
*
|
||||||
|
* @param bool $asJSON Whether the field should be treated as JSON in the query (optional, default false)
|
||||||
|
* @return string The path for this field
|
||||||
|
* @throws Exception If the database mode has not been set
|
||||||
|
*/
|
||||||
|
public function path(bool $asJSON = false): string
|
||||||
|
{
|
||||||
|
$extra = $asJSON ? '' : '>';
|
||||||
|
if (str_contains($this->fieldName, '.')) {
|
||||||
|
$mode = Configuration::mode('determine field path');
|
||||||
|
if ($mode === Mode::PgSQL) {
|
||||||
|
return "data#>$extra'{" . implode(',', explode('.', $this->fieldName)) . "}'";
|
||||||
|
}
|
||||||
|
if ($mode === Mode::SQLite) {
|
||||||
|
$parts = explode('.', $this->fieldName);
|
||||||
|
$last = array_pop($parts);
|
||||||
|
return "data->'" . implode("'->'", $parts) . "'->$extra'$last'";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "data->$extra'$this->fieldName'";
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the WHERE clause fragment for this parameter
|
* Get the WHERE clause fragment for this parameter
|
||||||
*
|
*
|
||||||
* @return string The WHERE clause fragment for this parameter
|
* @return string The WHERE clause fragment for this parameter
|
||||||
* @throws DocumentException If the database mode has not been set
|
* @throws Exception|DocumentException If the database mode has not been set
|
||||||
*/
|
*/
|
||||||
public function toWhere(): string
|
public function toWhere(): string
|
||||||
{
|
{
|
||||||
|
$mode = Configuration::mode('make field WHERE clause');
|
||||||
|
$fieldName = (empty($this->qualifier) ? '' : "$this->qualifier.") . $this->path($this->op === Op::InArray);
|
||||||
|
$fieldPath = match ($mode) {
|
||||||
|
Mode::PgSQL => match (true) {
|
||||||
|
$this->op === Op::Between,
|
||||||
|
$this->op === Op::In => 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::Exists,
|
||||||
Op::BT => " {$this->paramName}min AND {$this->paramName}max",
|
Op::NotExists => '',
|
||||||
default => " $this->paramName"
|
Op::Between => " {$this->paramName}min AND {$this->paramName}max",
|
||||||
|
Op::In => ' (' . $this->inParameterNames() . ')',
|
||||||
|
Op::InArray => $mode === Mode::PgSQL ? ' ARRAY[' . $this->inParameterNames() . ']' : '',
|
||||||
|
default => " $this->paramName",
|
||||||
};
|
};
|
||||||
$prefix = $this->qualifier == '' ? '' : "$this->qualifier.";
|
return $mode === Mode::SQLite && $this->op === Op::InArray
|
||||||
$fieldPath = match (Configuration::$mode) {
|
? "EXISTS (SELECT 1 FROM json_each({$this->value['table']}.data, '\$.$this->fieldName') WHERE value IN ("
|
||||||
Mode::SQLite => "{$prefix}data->>'"
|
. $this->inParameterNames() . '))'
|
||||||
. (str_contains($this->fieldName, '.')
|
: $fieldPath . ' ' . $this->op->toSQL() . $criteria;
|
||||||
? implode("'->>'", explode('.', $this->fieldName))
|
}
|
||||||
: $this->fieldName)
|
|
||||||
. "'",
|
/**
|
||||||
Mode::PgSQL => $this->op == Op::BT && is_numeric($this->value[0])
|
* Create parameter names for an IN clause
|
||||||
? "({$prefix}data->>'$this->fieldName')::numeric"
|
*
|
||||||
: "{$prefix}data->>'$this->fieldName'",
|
* @return string A comma-delimited string of parameter names
|
||||||
default => throw new DocumentException('Database mode not set; cannot make field WHERE clause')
|
*/
|
||||||
};
|
private function inParameterNames(): string
|
||||||
return $fieldPath . ' ' . $this->op->toString() . $criteria;
|
{
|
||||||
|
$values = $this->op === Op::In ? $this->value : $this->value['values'];
|
||||||
|
return implode(', ',
|
||||||
|
array_map(fn($value, $key) => "{$this->paramName}_$key", $values, range(0, count($values) - 1)));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -78,11 +139,24 @@ class Field
|
||||||
* @param string $fieldName The name of the field against which the value will be compared
|
* @param string $fieldName The name of the field against which the value will be compared
|
||||||
* @param mixed $value The value for which equality will be checked
|
* @param mixed $value The value for which equality will be checked
|
||||||
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||||
* @return static The field with the requested criterion
|
* @return self The field with the requested criterion
|
||||||
*/
|
*/
|
||||||
public static function EQ(string $fieldName, mixed $value, string $paramName = ''): static
|
public static function equal(string $fieldName, mixed $value, string $paramName = ''): self
|
||||||
{
|
{
|
||||||
return new static($fieldName, Op::EQ, $value, $paramName);
|
return new self($fieldName, Op::Equal, $value, $paramName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create an equals (=) field criterion _(alias for `Field.equal`)_
|
||||||
|
*
|
||||||
|
* @param string $fieldName The name of the field against which the value will be compared
|
||||||
|
* @param mixed $value The value for which equality will be checked
|
||||||
|
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||||
|
* @return self The field with the requested criterion
|
||||||
|
*/
|
||||||
|
public static function EQ(string $fieldName, mixed $value, string $paramName = ''): self
|
||||||
|
{
|
||||||
|
return self::equal($fieldName, $value, $paramName);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -91,11 +165,24 @@ class Field
|
||||||
* @param string $fieldName The name of the field against which the value will be compared
|
* @param string $fieldName The name of the field against which the value will be compared
|
||||||
* @param mixed $value The value for the greater than comparison
|
* @param mixed $value The value for the greater than comparison
|
||||||
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||||
* @return static The field with the requested criterion
|
* @return self The field with the requested criterion
|
||||||
*/
|
*/
|
||||||
public static function GT(string $fieldName, mixed $value, string $paramName = ''): static
|
public static function greater(string $fieldName, mixed $value, string $paramName = ''): self
|
||||||
{
|
{
|
||||||
return new static($fieldName, Op::GT, $value, $paramName);
|
return new self($fieldName, Op::Greater, $value, $paramName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a greater than (>) field criterion _(alias for `Field.greater`)_
|
||||||
|
*
|
||||||
|
* @param string $fieldName The name of the field against which the value will be compared
|
||||||
|
* @param mixed $value The value for the greater than comparison
|
||||||
|
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||||
|
* @return self The field with the requested criterion
|
||||||
|
*/
|
||||||
|
public static function GT(string $fieldName, mixed $value, string $paramName = ''): self
|
||||||
|
{
|
||||||
|
return self::greater($fieldName, $value, $paramName);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -104,11 +191,24 @@ class Field
|
||||||
* @param string $fieldName The name of the field against which the value will be compared
|
* @param string $fieldName The name of the field against which the value will be compared
|
||||||
* @param mixed $value The value for the greater than or equal to comparison
|
* @param mixed $value The value for the greater than or equal to comparison
|
||||||
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||||
* @return static The field with the requested criterion
|
* @return self The field with the requested criterion
|
||||||
*/
|
*/
|
||||||
public static function GE(string $fieldName, mixed $value, string $paramName = ''): static
|
public static function greaterOrEqual(string $fieldName, mixed $value, string $paramName = ''): self
|
||||||
{
|
{
|
||||||
return new static($fieldName, Op::GE, $value, $paramName);
|
return new self($fieldName, Op::GreaterOrEqual, $value, $paramName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a greater than or equal to (>=) field criterion _(alias for `Field.greaterOrEqual`)_
|
||||||
|
*
|
||||||
|
* @param string $fieldName The name of the field against which the value will be compared
|
||||||
|
* @param mixed $value The value for the greater than or equal to comparison
|
||||||
|
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||||
|
* @return self The field with the requested criterion
|
||||||
|
*/
|
||||||
|
public static function GE(string $fieldName, mixed $value, string $paramName = ''): self
|
||||||
|
{
|
||||||
|
return self::greaterOrEqual($fieldName, $value, $paramName);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -117,11 +217,24 @@ class Field
|
||||||
* @param string $fieldName The name of the field against which the value will be compared
|
* @param string $fieldName The name of the field against which the value will be compared
|
||||||
* @param mixed $value The value for the less than comparison
|
* @param mixed $value The value for the less than comparison
|
||||||
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||||
* @return static The field with the requested criterion
|
* @return self The field with the requested criterion
|
||||||
*/
|
*/
|
||||||
public static function LT(string $fieldName, mixed $value, string $paramName = ''): static
|
public static function less(string $fieldName, mixed $value, string $paramName = ''): self
|
||||||
{
|
{
|
||||||
return new static($fieldName, Op::LT, $value, $paramName);
|
return new self($fieldName, Op::Less, $value, $paramName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a less than (<) field criterion _(alias for `Field.less`)_
|
||||||
|
*
|
||||||
|
* @param string $fieldName The name of the field against which the value will be compared
|
||||||
|
* @param mixed $value The value for the less than comparison
|
||||||
|
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||||
|
* @return self The field with the requested criterion
|
||||||
|
*/
|
||||||
|
public static function LT(string $fieldName, mixed $value, string $paramName = ''): self
|
||||||
|
{
|
||||||
|
return self::less($fieldName, $value, $paramName);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -130,11 +243,24 @@ class Field
|
||||||
* @param string $fieldName The name of the field against which the value will be compared
|
* @param string $fieldName The name of the field against which the value will be compared
|
||||||
* @param mixed $value The value for the less than or equal to comparison
|
* @param mixed $value The value for the less than or equal to comparison
|
||||||
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||||
* @return static The field with the requested criterion
|
* @return self The field with the requested criterion
|
||||||
*/
|
*/
|
||||||
public static function LE(string $fieldName, mixed $value, string $paramName = ''): static
|
public static function lessOrEqual(string $fieldName, mixed $value, string $paramName = ''): self
|
||||||
{
|
{
|
||||||
return new static($fieldName, Op::LE, $value, $paramName);
|
return new self($fieldName, Op::LessOrEqual, $value, $paramName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a less than or equal to (<=) field criterion _(alias for `Field.lessOrEqual`)_
|
||||||
|
*
|
||||||
|
* @param string $fieldName The name of the field against which the value will be compared
|
||||||
|
* @param mixed $value The value for the less than or equal to comparison
|
||||||
|
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||||
|
* @return self The field with the requested criterion
|
||||||
|
*/
|
||||||
|
public static function LE(string $fieldName, mixed $value, string $paramName = ''): self
|
||||||
|
{
|
||||||
|
return self::lessOrEqual($fieldName, $value, $paramName);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -143,11 +269,24 @@ class Field
|
||||||
* @param string $fieldName The name of the field against which the value will be compared
|
* @param string $fieldName The name of the field against which the value will be compared
|
||||||
* @param mixed $value The value for the not equals comparison
|
* @param mixed $value The value for the not equals comparison
|
||||||
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||||
* @return static The field with the requested criterion
|
* @return self The field with the requested criterion
|
||||||
*/
|
*/
|
||||||
public static function NE(string $fieldName, mixed $value, string $paramName = ''): static
|
public static function notEqual(string $fieldName, mixed $value, string $paramName = ''): self
|
||||||
{
|
{
|
||||||
return new static($fieldName, Op::NE, $value, $paramName);
|
return new self($fieldName, Op::NotEqual, $value, $paramName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a not equals (<>) field criterion _(alias for `Field.notEqual`)_
|
||||||
|
*
|
||||||
|
* @param string $fieldName The name of the field against which the value will be compared
|
||||||
|
* @param mixed $value The value for the not equals comparison
|
||||||
|
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||||
|
* @return self The field with the requested criterion
|
||||||
|
*/
|
||||||
|
public static function NE(string $fieldName, mixed $value, string $paramName = ''): self
|
||||||
|
{
|
||||||
|
return self::notEqual($fieldName, $value, $paramName);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -157,32 +296,109 @@ class Field
|
||||||
* @param mixed $minValue The lower value for range
|
* @param mixed $minValue The lower value for range
|
||||||
* @param mixed $maxValue The upper value for the range
|
* @param mixed $maxValue The upper value for the range
|
||||||
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||||
* @return static The field with the requested criterion
|
* @return self The field with the requested criterion
|
||||||
*/
|
*/
|
||||||
public static function BT(string $fieldName, mixed $minValue, mixed $maxValue, string $paramName = ''): static
|
public static function between(string $fieldName, mixed $minValue, mixed $maxValue, string $paramName = ''): self
|
||||||
{
|
{
|
||||||
return new static($fieldName, Op::BT, [$minValue, $maxValue], $paramName);
|
return new self($fieldName, Op::Between, [$minValue, $maxValue], $paramName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a BETWEEN field criterion _(alias for `Field.between`)_
|
||||||
|
*
|
||||||
|
* @param string $fieldName The name of the field against which the value will be compared
|
||||||
|
* @param mixed $minValue The lower value for range
|
||||||
|
* @param mixed $maxValue The upper value for the range
|
||||||
|
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||||
|
* @return self The field with the requested criterion
|
||||||
|
*/
|
||||||
|
public static function BT(string $fieldName, mixed $minValue, mixed $maxValue, string $paramName = ''): self
|
||||||
|
{
|
||||||
|
return self::between($fieldName, $minValue, $maxValue, $paramName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create an IN field criterion
|
||||||
|
*
|
||||||
|
* @param string $fieldName The name of the field against which the values will be compared
|
||||||
|
* @param mixed[] $values The potential matching values for the field
|
||||||
|
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||||
|
* @return self The field with the requested criterion
|
||||||
|
*/
|
||||||
|
public static function in(string $fieldName, array $values, string $paramName = ''): self
|
||||||
|
{
|
||||||
|
return new self($fieldName, Op::In, $values, $paramName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create an IN ARRAY field criterion
|
||||||
|
*
|
||||||
|
* @param string $fieldName The name of the field against which the values will be compared
|
||||||
|
* @param string $tableName The table name where this field is located
|
||||||
|
* @param mixed[] $values The potential matching values for the field
|
||||||
|
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||||
|
* @return self The field with the requested criterion
|
||||||
|
*/
|
||||||
|
public static function inArray(string $fieldName, string $tableName, array $values, string $paramName = ''): self
|
||||||
|
{
|
||||||
|
return new self($fieldName, Op::InArray, ['table' => $tableName, 'values' => $values], $paramName);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create an exists (IS NOT NULL) field criterion
|
* Create an exists (IS NOT NULL) field criterion
|
||||||
*
|
*
|
||||||
* @param string $fieldName The name of the field for which existence will be checked
|
* @param string $fieldName The name of the field for which existence will be checked
|
||||||
* @return static The field with the requested criterion
|
* @return self The field with the requested criterion
|
||||||
*/
|
*/
|
||||||
public static function EX(string $fieldName): static
|
public static function exists(string $fieldName): self
|
||||||
{
|
{
|
||||||
return new static($fieldName, Op::EX, '', '');
|
return new self($fieldName, Op::Exists, '', '');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create an exists (IS NOT NULL) field criterion _(alias for `Field.exists`)_
|
||||||
|
*
|
||||||
|
* @param string $fieldName The name of the field for which existence will be checked
|
||||||
|
* @return self The field with the requested criterion
|
||||||
|
*/
|
||||||
|
public static function EX(string $fieldName): self
|
||||||
|
{
|
||||||
|
return self::exists($fieldName);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a not exists (IS NULL) field criterion
|
* Create a not exists (IS NULL) field criterion
|
||||||
*
|
*
|
||||||
* @param string $fieldName The name of the field for which non-existence will be checked
|
* @param string $fieldName The name of the field for which non-existence will be checked
|
||||||
* @return static The field with the requested criterion
|
* @return self The field with the requested criterion
|
||||||
*/
|
*/
|
||||||
public static function NEX(string $fieldName): static
|
public static function notExists(string $fieldName): self
|
||||||
{
|
{
|
||||||
return new static($fieldName, Op::NEX, '', '');
|
return new self($fieldName, Op::NotExists, '', '');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a not exists (IS NULL) field criterion _(alias for `Field.notExists`)_
|
||||||
|
*
|
||||||
|
* @param string $fieldName The name of the field for which non-existence will be checked
|
||||||
|
* @return self The field with the requested criterion
|
||||||
|
*/
|
||||||
|
public static function NEX(string $fieldName): self
|
||||||
|
{
|
||||||
|
return self::notExists($fieldName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a named fields (used for creating fields for ORDER BY clauses)
|
||||||
|
*
|
||||||
|
* Prepend the field name with 'n:' to treat the field as a number; prepend the field name with 'i:' to perform
|
||||||
|
* a case-insensitive ordering.
|
||||||
|
*
|
||||||
|
* @param string $name The name of the field, plus any direction for the ordering
|
||||||
|
* @return self
|
||||||
|
*/
|
||||||
|
public static function named(string $name): self
|
||||||
|
{
|
||||||
|
return new self($name, Op::Equal, '', '');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
34
src/FieldMatch.php
Normal file
34
src/FieldMatch.php
Normal file
|
@ -0,0 +1,34 @@
|
||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
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 toSQL(): string
|
||||||
|
{
|
||||||
|
return match ($this) {
|
||||||
|
FieldMatch::All => 'AND',
|
||||||
|
FieldMatch::Any => 'OR',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
122
src/Find.php
122
src/Find.php
|
@ -1,7 +1,14 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace BitBadger\PDODocument;
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
use BitBadger\InspiredByFSharp\Option;
|
||||||
use BitBadger\PDODocument\Mapper\DocumentMapper;
|
use BitBadger\PDODocument\Mapper\DocumentMapper;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -15,12 +22,14 @@ class Find
|
||||||
* @template TDoc The type of document to be retrieved
|
* @template TDoc The type of document to be retrieved
|
||||||
* @param string $tableName The table from which documents should be retrieved
|
* @param string $tableName The table from which documents should be retrieved
|
||||||
* @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 Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
|
||||||
* @return DocumentList<TDoc> A list of all documents from the table
|
* @return DocumentList<TDoc> A list of all documents from the table
|
||||||
* @throws DocumentException If any is encountered
|
* @throws DocumentException If any is encountered
|
||||||
*/
|
*/
|
||||||
public static function all(string $tableName, string $className): DocumentList
|
public static function all(string $tableName, string $className, array $orderBy = []): DocumentList
|
||||||
{
|
{
|
||||||
return Custom::list(Query::selectFromTable($tableName), [], new DocumentMapper($className));
|
return Custom::list(Query::selectFromTable($tableName) . Query::orderBy($orderBy), [],
|
||||||
|
new DocumentMapper($className));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -30,12 +39,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));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -43,18 +53,55 @@ class Find
|
||||||
*
|
*
|
||||||
* @template TDoc The type of document to be retrieved
|
* @template TDoc The type of document to be retrieved
|
||||||
* @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 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)
|
||||||
|
* @param Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
|
||||||
* @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, array $orderBy = []): DocumentList
|
||||||
{
|
{
|
||||||
$namedFields = Parameters::nameFields($fields);
|
Parameters::nameFields($fields);
|
||||||
return Custom::list(Query\Find::byFields($tableName, $namedFields, $conjunction),
|
return Custom::list(Query\Find::byFields($tableName, $fields, $match) . Query::orderBy($orderBy),
|
||||||
Parameters::addFields($namedFields, []), new DocumentMapper($className));
|
Parameters::addFields($fields, []), 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 mixed[]|object $criteria The criteria for the JSON containment query
|
||||||
|
* @param class-string<TDoc> $className The name of the class to be retrieved
|
||||||
|
* @param Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
|
||||||
|
* @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,
|
||||||
|
array $orderBy = []): DocumentList
|
||||||
|
{
|
||||||
|
return Custom::list(Query\Find::byContains($tableName) . Query::orderBy($orderBy),
|
||||||
|
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
|
||||||
|
* @param Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
|
||||||
|
* @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,
|
||||||
|
array $orderBy = []): DocumentList
|
||||||
|
{
|
||||||
|
return Custom::list(Query\Find::byJsonPath($tableName) . Query::orderBy($orderBy), [':path' => $path],
|
||||||
|
new DocumentMapper($className));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -62,17 +109,54 @@ class Find
|
||||||
*
|
*
|
||||||
* @template TDoc The type of document to be retrieved
|
* @template TDoc The type of document to be retrieved
|
||||||
* @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 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
|
* @param Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
|
||||||
|
* @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, array $orderBy = []): Option
|
||||||
{
|
{
|
||||||
$namedFields = Parameters::nameFields($fields);
|
Parameters::nameFields($fields);
|
||||||
return Custom::single(Query\Find::byFields($tableName, $namedFields, $conjunction),
|
return Custom::single(Query\Find::byFields($tableName, $fields, $match) . Query::orderBy($orderBy),
|
||||||
Parameters::addFields($namedFields, []), new DocumentMapper($className));
|
Parameters::addFields($fields, []), 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 mixed[]|object $criteria The criteria for the JSON containment query
|
||||||
|
* @param class-string<TDoc> $className The name of the class to be retrieved
|
||||||
|
* @param Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
|
||||||
|
* @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,
|
||||||
|
array $orderBy = []): Option
|
||||||
|
{
|
||||||
|
return Custom::single(Query\Find::byContains($tableName) . Query::orderBy($orderBy),
|
||||||
|
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
|
||||||
|
* @param Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
|
||||||
|
* @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,
|
||||||
|
array $orderBy = []): Option
|
||||||
|
{
|
||||||
|
return Custom::single(Query\Find::byJsonPath($tableName) . Query::orderBy($orderBy), [':path' => $path],
|
||||||
|
new DocumentMapper($className));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,14 +1,23 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace BitBadger\PDODocument\Mapper;
|
namespace BitBadger\PDODocument\Mapper;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A mapper that returns the associative array from the database
|
* A mapper that returns the associative array from the database
|
||||||
|
*
|
||||||
|
* @implements Mapper<array<string|int, mixed>>
|
||||||
*/
|
*/
|
||||||
class ArrayMapper implements Mapper
|
class ArrayMapper implements Mapper
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* @inheritDoc
|
* @inheritDoc
|
||||||
|
* @return array<string|int, mixed> The array given as the parameter
|
||||||
*/
|
*/
|
||||||
public function map(array $result): array
|
public function map(array $result): array
|
||||||
{
|
{
|
||||||
|
|
|
@ -1,15 +1,21 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace BitBadger\PDODocument\Mapper;
|
namespace BitBadger\PDODocument\Mapper;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A mapper that returns the integer value of the first item in the results
|
* A mapper that returns the integer value of the first item in the results
|
||||||
|
*
|
||||||
|
* @implements Mapper<int>
|
||||||
*/
|
*/
|
||||||
class CountMapper implements Mapper
|
class CountMapper implements Mapper
|
||||||
{
|
{
|
||||||
/**
|
/** @inheritDoc */
|
||||||
* @inheritDoc
|
|
||||||
*/
|
|
||||||
public function map(array $result): int
|
public function map(array $result): int
|
||||||
{
|
{
|
||||||
return (int) $result[0];
|
return (int) $result[0];
|
||||||
|
|
|
@ -1,10 +1,16 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace BitBadger\PDODocument\Mapper;
|
namespace BitBadger\PDODocument\Mapper;
|
||||||
|
|
||||||
use BitBadger\PDODocument\DocumentException;
|
use BitBadger\PDODocument\DocumentException;
|
||||||
|
use Exception;
|
||||||
use JsonMapper;
|
use JsonMapper;
|
||||||
use JsonMapper_Exception;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Map domain class instances from JSON documents
|
* Map domain class instances from JSON documents
|
||||||
|
@ -25,19 +31,22 @@ class DocumentMapper implements Mapper
|
||||||
/**
|
/**
|
||||||
* Map a result to a domain class instance
|
* Map a result to a domain class instance
|
||||||
*
|
*
|
||||||
* @param array $result An associative array representing a single database result
|
* @param array<string|int, mixed> $result An associative array representing a single database result
|
||||||
* @return TDoc The document, deserialized from its JSON representation
|
* @return TDoc The document, deserialized from its JSON representation
|
||||||
* @throws DocumentException If the JSON cannot be deserialized
|
* @throws DocumentException If the JSON cannot be deserialized
|
||||||
*/
|
*/
|
||||||
public function map(array $result): mixed
|
public function map(array $result): mixed
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
|
if (method_exists($this->className, 'fromJsonString')) {
|
||||||
|
return $this->className::fromJsonString($result[$this->fieldName]);
|
||||||
|
}
|
||||||
$json = json_decode($result[$this->fieldName]);
|
$json = json_decode($result[$this->fieldName]);
|
||||||
if (is_null($json)) {
|
if (is_null($json)) {
|
||||||
throw new DocumentException("Could not map document for $this->className: " . json_last_error_msg());
|
throw new DocumentException("Could not map document for $this->className: " . json_last_error_msg());
|
||||||
}
|
}
|
||||||
return (new JsonMapper())->map($json, $this->className);
|
return (new JsonMapper())->map($json, $this->className);
|
||||||
} catch (JsonMapper_Exception $ex) {
|
} catch (Exception $ex) {
|
||||||
throw new DocumentException("Could not map document for $this->className", previous: $ex);
|
throw new DocumentException("Could not map document for $this->className", previous: $ex);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,24 +1,32 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace BitBadger\PDODocument\Mapper;
|
namespace BitBadger\PDODocument\Mapper;
|
||||||
|
|
||||||
use BitBadger\PDODocument\{Configuration, DocumentException, Mode};
|
use BitBadger\PDODocument\{Configuration, Mode};
|
||||||
|
use Exception;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Map an EXISTS result to a boolean value
|
* Map an EXISTS result to a boolean value
|
||||||
|
*
|
||||||
|
* @implements Mapper<bool>
|
||||||
*/
|
*/
|
||||||
class ExistsMapper implements Mapper
|
class ExistsMapper implements Mapper
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* @inheritDoc
|
* @inheritDoc
|
||||||
* @throws DocumentException If the database mode has not been set
|
* @throws Exception If the database mode has not been set
|
||||||
*/
|
*/
|
||||||
public function map(array $result): bool
|
public function map(array $result): bool
|
||||||
{
|
{
|
||||||
return match (Configuration::$mode) {
|
return match (Configuration::mode('map existence result')) {
|
||||||
Mode::PgSQL => (bool)$result[0],
|
Mode::PgSQL => (bool)$result[0],
|
||||||
Mode::SQLite => (int)$result[0] > 0,
|
Mode::SQLite => (int)$result[0] > 0,
|
||||||
default => throw new DocumentException('Database mode not set; cannot map existence result'),
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,10 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace BitBadger\PDODocument\Mapper;
|
namespace BitBadger\PDODocument\Mapper;
|
||||||
|
|
||||||
|
@ -12,7 +18,7 @@ interface Mapper
|
||||||
/**
|
/**
|
||||||
* Map a result to the specified type
|
* Map a result to the specified type
|
||||||
*
|
*
|
||||||
* @param array $result An associative array representing a single database result
|
* @param array<string|int, mixed> $result An associative array representing a single database result
|
||||||
* @return T The item mapped from the given result
|
* @return T The item mapped from the given result
|
||||||
*/
|
*/
|
||||||
public function map(array $result): mixed;
|
public function map(array $result): mixed;
|
||||||
|
|
|
@ -1,9 +1,15 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace BitBadger\PDODocument\Mapper;
|
namespace BitBadger\PDODocument\Mapper;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Map a string result from the
|
* Map a string result from the named field
|
||||||
*
|
*
|
||||||
* @implements Mapper<string>
|
* @implements Mapper<string>
|
||||||
*/
|
*/
|
||||||
|
@ -24,7 +30,7 @@ class StringMapper implements Mapper
|
||||||
return match (false) {
|
return match (false) {
|
||||||
key_exists($this->fieldName, $result) => null,
|
key_exists($this->fieldName, $result) => null,
|
||||||
is_string($result[$this->fieldName]) => "{$result[$this->fieldName]}",
|
is_string($result[$this->fieldName]) => "{$result[$this->fieldName]}",
|
||||||
default => $result[$this->fieldName]
|
default => $result[$this->fieldName],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
23
src/Mode.php
23
src/Mode.php
|
@ -1,4 +1,10 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace BitBadger\PDODocument;
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
@ -12,4 +18,19 @@ enum Mode
|
||||||
|
|
||||||
/** Storing documents in a SQLite database */
|
/** Storing documents in a SQLite database */
|
||||||
case SQLite;
|
case SQLite;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Derive the mode from the Data Source Name (DSN)
|
||||||
|
*
|
||||||
|
* @return Mode The database mode based on the DSN
|
||||||
|
* @throws DocumentException If the DSN does not start with `pgsql:` or `sqlite:`
|
||||||
|
*/
|
||||||
|
public static function deriveFromDSN(string $dsn): Mode
|
||||||
|
{
|
||||||
|
return match (true) {
|
||||||
|
str_starts_with($dsn, 'pgsql:') => Mode::PgSQL,
|
||||||
|
str_starts_with($dsn, 'sqlite:') => Mode::SQLite,
|
||||||
|
default => throw new DocumentException('This library currently supports PostgreSQL and SQLite'),
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
56
src/Op.php
56
src/Op.php
|
@ -1,48 +1,60 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace BitBadger\PDODocument;
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The types of logical operations allowed for JSON fields
|
* The types of comparison operators allowed for JSON fields
|
||||||
*/
|
*/
|
||||||
enum Op
|
enum Op
|
||||||
{
|
{
|
||||||
/** Equals (=) */
|
/** Equals (=) */
|
||||||
case EQ;
|
case Equal;
|
||||||
/** Greater Than (>) */
|
/** Greater Than (>) */
|
||||||
case GT;
|
case Greater;
|
||||||
/** Greater Than or Equal To (>=) */
|
/** Greater Than or Equal To (>=) */
|
||||||
case GE;
|
case GreaterOrEqual;
|
||||||
/** Less Than (<) */
|
/** Less Than (<) */
|
||||||
case LT;
|
case Less;
|
||||||
/** Less Than or Equal To (<=) */
|
/** Less Than or Equal To (<=) */
|
||||||
case LE;
|
case LessOrEqual;
|
||||||
/** Not Equal to (<>) */
|
/** Not Equal to (<>) */
|
||||||
case NE;
|
case NotEqual;
|
||||||
/** Between (BETWEEN) */
|
/** Between (BETWEEN) */
|
||||||
case BT;
|
case Between;
|
||||||
|
/** In (IN) */
|
||||||
|
case In;
|
||||||
|
/** In Array (PostgreSQL - ?|, SQLite - EXISTS / json_each / IN) */
|
||||||
|
case InArray;
|
||||||
/** Exists (IS NOT NULL) */
|
/** Exists (IS NOT NULL) */
|
||||||
case EX;
|
case Exists;
|
||||||
/** Does Not Exist (IS NULL) */
|
/** Does Not Exist (IS NULL) */
|
||||||
case NEX;
|
case NotExists;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the string representation of this operator
|
* Get the SQL representation of this operator
|
||||||
*
|
*
|
||||||
* @return string The operator to use in SQL statements
|
* @return string The operator to use in SQL statements
|
||||||
*/
|
*/
|
||||||
public function toString(): string
|
public function toSQL(): string
|
||||||
{
|
{
|
||||||
return match ($this) {
|
return match ($this) {
|
||||||
Op::EQ => "=",
|
Op::Equal => "=",
|
||||||
Op::GT => ">",
|
Op::Greater => ">",
|
||||||
Op::GE => ">=",
|
Op::GreaterOrEqual => ">=",
|
||||||
Op::LT => "<",
|
Op::Less => "<",
|
||||||
Op::LE => "<=",
|
Op::LessOrEqual => "<=",
|
||||||
Op::NE => "<>",
|
Op::NotEqual => "<>",
|
||||||
Op::BT => "BETWEEN",
|
Op::Between => "BETWEEN",
|
||||||
Op::EX => "IS NOT NULL",
|
Op::In => "IN",
|
||||||
Op::NEX => "IS NULL"
|
Op::InArray => "??|", // The actual operator is ?|, but needs to be escaped by doubling
|
||||||
|
Op::Exists => "IS NOT NULL",
|
||||||
|
Op::NotExists => "IS NULL",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,7 +1,15 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace BitBadger\PDODocument;
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
use Exception;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functions to create parameters for queries
|
* Functions to create parameters for queries
|
||||||
*/
|
*/
|
||||||
|
@ -11,45 +19,61 @@ class Parameters
|
||||||
* Create an ID parameter (name ":id", key will be treated as a string)
|
* Create an ID parameter (name ":id", key will be treated as a string)
|
||||||
*
|
*
|
||||||
* @param mixed $key The key representing the ID of the document
|
* @param mixed $key The key representing the ID of the document
|
||||||
* @return array|string[] An associative array with an "@id" parameter/value pair
|
* @return array<string, mixed> An associative array with an "@id" parameter/value pair
|
||||||
*/
|
*/
|
||||||
public static function id(mixed $key): array
|
public static function id(mixed $key): array
|
||||||
{
|
{
|
||||||
return [':id' => is_int($key) || is_string($key) ? $key : "$key"];
|
return [':id' => ((is_int($key) || is_string($key)) ? $key : "$key")];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a parameter with a JSON value
|
* Create a parameter with a JSON value
|
||||||
*
|
*
|
||||||
* @param string $name The name of the JSON parameter
|
* @param string $name The name of the JSON parameter
|
||||||
* @param object|array $document The value that should be passed as a JSON string
|
* @param mixed[]|object $document The value that should be passed as a JSON string
|
||||||
* @return array An associative array with the named parameter/value pair
|
* @return array<string, string> An associative array with the named parameter/value pair
|
||||||
*/
|
*/
|
||||||
public static function json(string $name, object|array $document): array
|
public static function json(string $name, object|array $document): array
|
||||||
{
|
{
|
||||||
return [$name => json_encode($document, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)];
|
$flags = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES;
|
||||||
|
|
||||||
|
if (is_object($document)) {
|
||||||
|
return [
|
||||||
|
$name => method_exists($document, 'toJson') ? $document->toJson($flags) : json_encode($document, $flags)
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
$key = array_key_first($document);
|
||||||
|
if (is_array($document[$key])) {
|
||||||
|
if (empty($document[$key])) return [$name => json_encode($document, $flags)];
|
||||||
|
if (method_exists($document[$key][array_key_first($document[$key])], 'toJson')) {
|
||||||
|
return [
|
||||||
|
$name => sprintf('{%s:[%s]}', json_encode($key, $flags),
|
||||||
|
implode(',', array_map(fn($it) => $it->toJson($flags), $document[$key])))
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [$name => json_encode($document, $flags)];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fill in parameter names for any fields missing one
|
* Fill in parameter names for any fields missing one
|
||||||
*
|
*
|
||||||
* @param array|Field[] $fields The fields for the query
|
* @param Field[] $fields The fields for the query (entries with no names will be modified)
|
||||||
* @return array|Field[] The fields, all with non-blank parameter names
|
|
||||||
*/
|
*/
|
||||||
public static function nameFields(array $fields): array
|
public static function nameFields(array &$fields): void
|
||||||
{
|
{
|
||||||
for ($idx = 0; $idx < sizeof($fields); $idx++) {
|
array_walk($fields, function (Field $field, int $idx) {
|
||||||
if ($fields[$idx]->paramName == '') $fields[$idx]->paramName = ":field$idx";
|
if (empty($field->paramName)) $field->paramName =":field$idx";
|
||||||
}
|
});
|
||||||
return $fields;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Add field parameters to the given set of parameters
|
* Add field parameters to the given set of parameters
|
||||||
*
|
*
|
||||||
* @param array|Field[] $fields The fields being compared in the query
|
* @param Field[] $fields The fields being compared in the query
|
||||||
* @param array $parameters An associative array of parameters to which the fields should be added
|
* @param array<string, mixed> $parameters An associative array of parameters to which the fields should be added
|
||||||
* @return array An associative array of parameter names and values with the fields added
|
* @return array<string, mixed> An associative array of parameter names and values with the fields added
|
||||||
*/
|
*/
|
||||||
public static function addFields(array $fields, array $parameters): array
|
public static function addFields(array $fields, array $parameters): array
|
||||||
{
|
{
|
||||||
|
@ -60,22 +84,18 @@ class Parameters
|
||||||
* Create JSON field name parameters for the given field names to the given parameter
|
* Create JSON field name parameters for the given field names to the given parameter
|
||||||
*
|
*
|
||||||
* @param string $paramName The name of the parameter for the field names
|
* @param string $paramName The name of the parameter for the field names
|
||||||
* @param array|string[] $fieldNames The names of the fields for the parameter
|
* @param string[] $fieldNames The names of the fields for the parameter
|
||||||
* @return array An associative array of parameter/value pairs for the field names
|
* @return array<string, string> An associative array of parameter/value pairs for the field names
|
||||||
* @throws DocumentException If the database mode has not been set
|
* @throws Exception If the database mode has not been set
|
||||||
*/
|
*/
|
||||||
public static function fieldNames(string $paramName, array $fieldNames): array
|
public static function fieldNames(string $paramName, array $fieldNames): array
|
||||||
{
|
{
|
||||||
switch (Configuration::$mode) {
|
$mode = Configuration::mode('generate field name parameters');
|
||||||
case Mode::PgSQL:
|
return match ($mode) {
|
||||||
return [$paramName => "ARRAY['" . implode("','", $fieldNames) . "']"];
|
Mode::PgSQL => [$paramName => "{" . implode(",", $fieldNames) . "}"],
|
||||||
case Mode::SQLite:
|
Mode::SQLite => array_combine(array_map(fn($idx) => $paramName . $idx,
|
||||||
$it = [];
|
empty($fieldNames) ? [] : range(0, sizeof($fieldNames) - 1)),
|
||||||
$idx = 0;
|
array_map(fn($field) => "$.$field", $fieldNames))
|
||||||
foreach ($fieldNames as $field) $it[$paramName . $idx++] = "$.$field";
|
};
|
||||||
return $it;
|
|
||||||
default:
|
|
||||||
throw new DocumentException('Database mode not set; cannot generate field name parameters');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,10 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace BitBadger\PDODocument;
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
@ -12,12 +18,12 @@ class Patch
|
||||||
*
|
*
|
||||||
* @param string $tableName The table in which the document should be patched
|
* @param string $tableName The table in which the document should be patched
|
||||||
* @param mixed $docId The ID of the document to be patched
|
* @param mixed $docId The ID of the document to be patched
|
||||||
* @param array|object $patch The object with which the document should be patched (will be JSON-encoded)
|
* @param mixed[]|object $patch The object with which the document should be patched (will be JSON-encoded)
|
||||||
* @throws DocumentException If any is encountered (database mode must be set)
|
* @throws DocumentException If any is encountered (database mode must be set)
|
||||||
*/
|
*/
|
||||||
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)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -25,16 +31,44 @@ class Patch
|
||||||
* Patch documents using a comparison on JSON fields
|
* Patch documents using a comparison on JSON fields
|
||||||
*
|
*
|
||||||
* @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 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 mixed[]|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);
|
Parameters::nameFields($fields);
|
||||||
Custom::nonQuery(Query\Patch::byFields($tableName, $namedFields, $conjunction),
|
Custom::nonQuery(Query\Patch::byFields($tableName, $fields, $match),
|
||||||
Parameters::addFields($namedFields, Parameters::json(':data', $patch)));
|
Parameters::addFields($fields, 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 mixed[]|object $criteria The JSON containment query values to match
|
||||||
|
* @param mixed[]|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 mixed[]|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)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
144
src/Query.php
144
src/Query.php
|
@ -1,7 +1,16 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace BitBadger\PDODocument;
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
use Exception;
|
||||||
|
use Random\RandomException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Query construction functions
|
* Query construction functions
|
||||||
*/
|
*/
|
||||||
|
@ -22,34 +31,92 @@ 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)->toSQL() . ' ', 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::equal(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 Exception|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 Exception|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 Exception|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('generate auto-ID INSERT statement')) {
|
||||||
|
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() . "\"}'",
|
||||||
|
}
|
||||||
|
};
|
||||||
|
return "INSERT INTO $tableName VALUES ($values)";
|
||||||
|
} catch (RandomException $ex) {
|
||||||
|
throw new DocumentException('Unable to generate ID: ' . $ex->getMessage(), previous: $ex);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -60,8 +127,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,9 +136,60 @@ 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
|
||||||
{
|
{
|
||||||
return "UPDATE $tableName SET data = :data WHERE " . self::whereById();
|
return "UPDATE $tableName SET data = :data WHERE " . self::whereById();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Transform a field to an ORDER BY clause segment
|
||||||
|
*
|
||||||
|
* @param Field $field The field by which ordering should be implemented
|
||||||
|
* @return string The ORDER BY fragment for the given field
|
||||||
|
* @throws Exception If the database mode has not been set
|
||||||
|
*/
|
||||||
|
private static function mapToOrderBy(Field $field): string
|
||||||
|
{
|
||||||
|
$mode = Configuration::mode('render ORDER BY clause');
|
||||||
|
|
||||||
|
if (str_contains($field->fieldName, ' ')) {
|
||||||
|
$parts = explode(' ', $field->fieldName);
|
||||||
|
$field->fieldName = array_shift($parts);
|
||||||
|
$direction = ' ' . implode(' ', $parts);
|
||||||
|
} else {
|
||||||
|
$direction = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (str_starts_with($field->fieldName, 'n:')) {
|
||||||
|
$field->fieldName = substr($field->fieldName, 2);
|
||||||
|
$value = match ($mode) {
|
||||||
|
Mode::PgSQL => '(' . $field->path() . ')::numeric',
|
||||||
|
Mode::SQLite => $field->path()
|
||||||
|
};
|
||||||
|
} elseif (str_starts_with($field->fieldName, 'i:')) {
|
||||||
|
$field->fieldName = substr($field->fieldName, 2);
|
||||||
|
$value = match ($mode) {
|
||||||
|
Mode::PgSQL => 'LOWER(' . $field->path() . ')',
|
||||||
|
Mode::SQLite => $field->path() . ' COLLATE NOCASE'
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
$value = $field->path();
|
||||||
|
}
|
||||||
|
|
||||||
|
return (empty($field->qualifier) ? '' : "$field->qualifier.") . $value . $direction;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create an `ORDER BY` clause ('n:' treats field as number, 'i:' does case-insensitive ordering)
|
||||||
|
*
|
||||||
|
* @param Field[] $fields The fields, named for the field plus directions (ex. 'field DESC NULLS FIRST')
|
||||||
|
* @return string The ORDER BY clause with the given fields
|
||||||
|
* @throws Exception If the database mode has not been set
|
||||||
|
*/
|
||||||
|
public static function orderBy(array $fields): string
|
||||||
|
{
|
||||||
|
return empty($fields) ? "" : ' ORDER BY ' . implode(', ', array_map(self::mapToOrderBy(...), $fields));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,8 +1,14 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
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 +31,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();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,8 +1,15 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace BitBadger\PDODocument\Query;
|
namespace BitBadger\PDODocument\Query;
|
||||||
|
|
||||||
use BitBadger\PDODocument\{Configuration, DocumentException, Mode};
|
use BitBadger\PDODocument\{Configuration, DocumentException, DocumentIndex, Mode};
|
||||||
|
use Exception;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Queries to define tables and indexes
|
* Queries to define tables and indexes
|
||||||
|
@ -14,14 +21,13 @@ class Definition
|
||||||
*
|
*
|
||||||
* @param string $name The name of the table (including schema, if applicable)
|
* @param string $name The name of the table (including schema, if applicable)
|
||||||
* @return string The CREATE TABLE statement for the document table
|
* @return string The CREATE TABLE statement for the document table
|
||||||
* @throws DocumentException If the database mode has not been set
|
* @throws Exception If the database mode has not been set
|
||||||
*/
|
*/
|
||||||
public static function ensureTable(string $name): string
|
public static function ensureTable(string $name): string
|
||||||
{
|
{
|
||||||
$dataType = match (Configuration::$mode) {
|
$dataType = match (Configuration::mode('make create table statement')) {
|
||||||
Mode::PgSQL => 'JSONB',
|
Mode::PgSQL => 'JSONB',
|
||||||
Mode::SQLite => 'TEXT',
|
Mode::SQLite => 'TEXT',
|
||||||
default => throw new DocumentException('Database mode not set; cannot make create table statement')
|
|
||||||
};
|
};
|
||||||
return "CREATE TABLE IF NOT EXISTS $name (data $dataType NOT NULL)";
|
return "CREATE TABLE IF NOT EXISTS $name (data $dataType NOT NULL)";
|
||||||
}
|
}
|
||||||
|
@ -35,7 +41,7 @@ class Definition
|
||||||
private static function splitSchemaAndTable(string $tableName): array
|
private static function splitSchemaAndTable(string $tableName): array
|
||||||
{
|
{
|
||||||
$parts = explode('.', $tableName);
|
$parts = explode('.', $tableName);
|
||||||
return sizeof($parts) == 1 ? ["", $tableName] : [$parts[0], $parts[1]];
|
return sizeof($parts) === 1 ? ["", $tableName] : [$parts[0], $parts[1]];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -43,7 +49,7 @@ class Definition
|
||||||
*
|
*
|
||||||
* @param string $tableName The name of the table which should be indexed
|
* @param string $tableName The name of the table which should be indexed
|
||||||
* @param string $indexName The name of the index to create
|
* @param string $indexName The name of the index to create
|
||||||
* @param array $fields An array of fields to be indexed; may contain direction (ex. 'salary DESC')
|
* @param string[] $fields An array of fields to be indexed; may contain direction (ex. 'salary DESC')
|
||||||
* @return string The CREATE INDEX statement to ensure the index exists
|
* @return string The CREATE INDEX statement to ensure the index exists
|
||||||
*/
|
*/
|
||||||
public static function ensureIndexOn(string $tableName, string $indexName, array $fields): string
|
public static function ensureIndexOn(string $tableName, string $indexName, array $fields): string
|
||||||
|
@ -51,7 +57,7 @@ class Definition
|
||||||
[, $tbl] = self::splitSchemaAndTable($tableName);
|
[, $tbl] = self::splitSchemaAndTable($tableName);
|
||||||
$jsonFields = implode(', ', array_map(function (string $field) {
|
$jsonFields = implode(', ', array_map(function (string $field) {
|
||||||
$parts = explode(' ', $field);
|
$parts = explode(' ', $field);
|
||||||
$fieldName = sizeof($parts) == 1 ? $field : $parts[0];
|
$fieldName = sizeof($parts) === 1 ? $field : $parts[0];
|
||||||
$direction = sizeof($parts) < 2 ? "" : " $parts[1]";
|
$direction = sizeof($parts) < 2 ? "" : " $parts[1]";
|
||||||
return "(data->>'$fieldName')$direction";
|
return "(data->>'$fieldName')$direction";
|
||||||
}, $fields));
|
}, $fields));
|
||||||
|
@ -68,4 +74,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 Exception|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)";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,8 +1,14 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
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 +19,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 +33,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();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,8 +1,14 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
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 +31,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 +45,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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,8 +1,14 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
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 +19,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 +33,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();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,8 +1,15 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
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};
|
||||||
|
use Exception;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Queries to perform partial updates on documents
|
* Queries to perform partial updates on documents
|
||||||
|
@ -15,14 +22,13 @@ 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 string $whereClause The body of the WHERE clause to use in the UPDATE statement
|
* @param string $whereClause The body of the WHERE clause to use in the UPDATE statement
|
||||||
* @return string The UPDATE statement to perform the patch
|
* @return string The UPDATE statement to perform the patch
|
||||||
* @throws DocumentException If the database mode has not been set
|
* @throws Exception If the database mode has not been set
|
||||||
*/
|
*/
|
||||||
public static function update(string $tableName, string $whereClause): string
|
public static function update(string $tableName, string $whereClause): string
|
||||||
{
|
{
|
||||||
$setValue = match (Configuration::$mode) {
|
$setValue = match (Configuration::mode('make patch statement')) {
|
||||||
Mode::PgSQL => 'data || :data',
|
Mode::PgSQL => 'data || :data',
|
||||||
Mode::SQLite => 'json_patch(data, json(:data))',
|
Mode::SQLite => 'json_patch(data, json(:data))',
|
||||||
default => throw new DocumentException('Database mode not set; cannot make patch statement')
|
|
||||||
};
|
};
|
||||||
return "UPDATE $tableName SET data = $setValue WHERE $whereClause";
|
return "UPDATE $tableName SET data = $setValue WHERE $whereClause";
|
||||||
}
|
}
|
||||||
|
@ -31,12 +37,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 +51,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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,8 +1,15 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
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};
|
||||||
|
use Exception;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Queries to remove fields from documents
|
* Queries to remove fields from documents
|
||||||
|
@ -17,50 +24,74 @@ class RemoveFields
|
||||||
* Create an UPDATE statement to remove fields from a JSON document
|
* Create an UPDATE statement to remove fields from a JSON document
|
||||||
*
|
*
|
||||||
* @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 $parameters The parameter list for the query
|
* @param array<string, mixed> $parameters The parameter list for the query
|
||||||
* @param string $whereClause The body of the WHERE clause for the update
|
* @param string $whereClause The body of the WHERE clause for the update
|
||||||
* @return string The UPDATE statement to remove fields from a JSON document
|
* @return string The UPDATE statement to remove fields from a JSON document
|
||||||
* @throws DocumentException If the database mode has not been set
|
* @throws Exception If the database mode has not been set
|
||||||
*/
|
*/
|
||||||
public static function update(string $tableName, array $parameters, string $whereClause): string
|
public static function update(string $tableName, array $parameters, string $whereClause): string
|
||||||
{
|
{
|
||||||
switch (Configuration::$mode) {
|
return match (Configuration::mode('generate field removal query')) {
|
||||||
case Mode::PgSQL:
|
Mode::PgSQL => "UPDATE $tableName SET data = data - " . array_keys($parameters)[0]
|
||||||
return "UPDATE $tableName SET data = data - " . array_keys($parameters)[0] . " WHERE $whereClause";
|
. "::text[] WHERE $whereClause",
|
||||||
case Mode::SQLite:
|
Mode::SQLite => "UPDATE $tableName SET data = json_remove(data, " . implode(', ', array_keys($parameters))
|
||||||
$paramNames = implode(', ', array_keys($parameters));
|
. ") WHERE $whereClause",
|
||||||
return "UPDATE $tableName SET data = json_remove(data, $paramNames) WHERE $whereClause";
|
};
|
||||||
default:
|
|
||||||
throw new DocumentException('Database mode not set; cannot generate field removal query');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Query to remove fields from a document by the document's ID
|
* Query to remove fields from a document by the document's ID
|
||||||
*
|
*
|
||||||
* @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<string, mixed> $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));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Query to remove fields from documents via a comparison on JSON fields within the document
|
* Query to remove fields from documents via a comparison on JSON fields within the document
|
||||||
*
|
*
|
||||||
* @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 Field[] $fields The field comparison to match
|
||||||
* @param array $parameters The parameter list for the query
|
* @param array<string, mixed> $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<string, mixed> $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<string, mixed> $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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,10 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace BitBadger\PDODocument;
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
@ -12,13 +18,13 @@ class RemoveFields
|
||||||
*
|
*
|
||||||
* @param string $tableName The table in which the document should have fields removed
|
* @param string $tableName The table in which the document should have fields removed
|
||||||
* @param mixed $docId The ID of the document from which fields should be removed
|
* @param mixed $docId The ID of the document from which fields should be removed
|
||||||
* @param array|string[] $fieldNames The names of the fields to be removed
|
* @param string[] $fieldNames The names of the fields to be removed
|
||||||
* @throws DocumentException If any is encountered
|
* @throws DocumentException If any is encountered
|
||||||
*/
|
*/
|
||||||
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));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -26,17 +32,47 @@ class RemoveFields
|
||||||
* Remove fields from documents via a comparison on a JSON field in the document
|
* Remove fields from documents via a comparison on a JSON field in the document
|
||||||
*
|
*
|
||||||
* @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 Field[] $fields The field comparison to match
|
||||||
* @param array|string[] $fieldNames The names of the fields to be removed
|
* @param 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);
|
Parameters::nameFields($fields);
|
||||||
Custom::nonQuery(Query\RemoveFields::byFields($tableName, $namedFields, $nameParams, $conjunction),
|
Custom::nonQuery(Query\RemoveFields::byFields($tableName, $fields, $nameParams, $match),
|
||||||
Parameters::addFields($namedFields, $nameParams));
|
Parameters::addFields($fields, $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 mixed[]|object $criteria The JSON containment query values
|
||||||
|
* @param 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 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));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
22
tests/PjsonDocument.php
Normal file
22
tests/PjsonDocument.php
Normal file
|
@ -0,0 +1,22 @@
|
||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test;
|
||||||
|
|
||||||
|
use Square\Pjson\{Json, JsonSerialize};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A test document annotated with pjson attributes using the `JsonSerialize` trait
|
||||||
|
*/
|
||||||
|
class PjsonDocument
|
||||||
|
{
|
||||||
|
use JsonSerialize;
|
||||||
|
|
||||||
|
public function __construct(#[Json] public PjsonId $id = new PjsonId(''), #[Json] public string $name = '',
|
||||||
|
#[Json('num_value')] public int $numValue = 0, public string $skipped = 'yep') { }
|
||||||
|
}
|
34
tests/PjsonId.php
Normal file
34
tests/PjsonId.php
Normal file
|
@ -0,0 +1,34 @@
|
||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test;
|
||||||
|
|
||||||
|
use Square\Pjson\JsonDataSerializable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A serializable ID wrapper class
|
||||||
|
*/
|
||||||
|
final class PjsonId implements JsonDataSerializable
|
||||||
|
{
|
||||||
|
public function __construct(protected string $value) { }
|
||||||
|
|
||||||
|
public function toJsonData(): string
|
||||||
|
{
|
||||||
|
return $this->value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param mixed $jd JSON data
|
||||||
|
* @param mixed[]|string $path path segments
|
||||||
|
* @return static
|
||||||
|
*/
|
||||||
|
public static function fromJsonData($jd, array|string $path = []): static
|
||||||
|
{
|
||||||
|
return new static($jd);
|
||||||
|
}
|
||||||
|
}
|
35
tests/integration/ArrayDocument.php
Normal file
35
tests/integration/ArrayDocument.php
Normal file
|
@ -0,0 +1,35 @@
|
||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A document with an array of values
|
||||||
|
*/
|
||||||
|
class ArrayDocument
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param string $id The ID of the document
|
||||||
|
* @param string[] $values The values for the document
|
||||||
|
*/
|
||||||
|
public function __construct(public string $id = '', public array $values = []) { }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A set of documents used for integration tests
|
||||||
|
*
|
||||||
|
* @return ArrayDocument[] Test documents for InArray tests
|
||||||
|
*/
|
||||||
|
public static function testDocuments(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
new ArrayDocument('first', ['a', 'b', 'c']),
|
||||||
|
new ArrayDocument('second', ['c', 'd', 'e']),
|
||||||
|
new ArrayDocument('third', ['x', 'y', 'z'])
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
17
tests/integration/NumDocument.php
Normal file
17
tests/integration/NumDocument.php
Normal file
|
@ -0,0 +1,17 @@
|
||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
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 = '') { }
|
||||||
|
}
|
|
@ -1,4 +1,10 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Test\Integration;
|
namespace Test\Integration;
|
||||||
|
|
||||||
|
|
|
@ -1,4 +1,10 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Test\Integration;
|
namespace Test\Integration;
|
||||||
|
|
||||||
|
|
84
tests/integration/postgresql/CountTest.php
Normal file
84
tests/integration/postgresql/CountTest.php
Normal file
|
@ -0,0 +1,84 @@
|
||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('all() succeeds')]
|
||||||
|
public function testAllSucceeds(): void
|
||||||
|
{
|
||||||
|
$count = Count::all(ThrowawayDb::TABLE);
|
||||||
|
$this->assertEquals(5, $count, 'There should have been 5 matching documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds for a numeric range')]
|
||||||
|
public function testByFieldsSucceedsForANumericRange(): void
|
||||||
|
{
|
||||||
|
$count = Count::byFields(ThrowawayDb::TABLE, [Field::between('num_value', 10, 20)]);
|
||||||
|
$this->assertEquals(3, $count, 'There should have been 3 matching documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds for a non-numeric range')]
|
||||||
|
public function testByFieldsSucceedsForANonNumericRange(): void
|
||||||
|
{
|
||||||
|
$count = Count::byFields(ThrowawayDb::TABLE, [Field::between('value', 'aardvark', 'apple')]);
|
||||||
|
$this->assertEquals(1, $count, 'There should have been 1 matching document');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byContains() succeeds when documents match')]
|
||||||
|
public function testByContainsSucceedsWhenDocumentsMatch(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(2, Count::byContains(ThrowawayDb::TABLE, ['value' => 'purple']),
|
||||||
|
'There should have been 2 matching documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byContains() succeeds when no documents match')]
|
||||||
|
public function testByContainsSucceedsWhenNoDocumentsMatch(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(0, Count::byContains(ThrowawayDb::TABLE, ['value' => 'magenta']),
|
||||||
|
'There should have been no matching documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byJsonPath() 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('byJsonPath() 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');
|
||||||
|
}
|
||||||
|
}
|
138
tests/integration/postgresql/CustomTest.php
Normal file
138
tests/integration/postgresql/CustomTest.php
Normal file
|
@ -0,0 +1,138 @@
|
||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('runQuery() succeeds with a valid query')]
|
||||||
|
public function testRunQuerySucceedsWithAValidQuery(): void
|
||||||
|
{
|
||||||
|
$stmt = &Custom::runQuery('SELECT data FROM ' . ThrowawayDb::TABLE . ' LIMIT 1', []);
|
||||||
|
try {
|
||||||
|
$this->assertNotNull($stmt, 'The statement should not have been null');
|
||||||
|
} finally {
|
||||||
|
$stmt = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('runQuery() fails with an invalid query')]
|
||||||
|
public function testRunQueryFailsWithAnInvalidQuery(): void
|
||||||
|
{
|
||||||
|
$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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('list() succeeds when data is found')]
|
||||||
|
public function testListSucceedsWhenDataIsFound(): void
|
||||||
|
{
|
||||||
|
$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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('list() succeeds when no data is found')]
|
||||||
|
public function testListSucceedsWhenNoDataIsFound(): void
|
||||||
|
{
|
||||||
|
$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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('array() succeeds when data is found')]
|
||||||
|
public function testArraySucceedsWhenDataIsFound(): void
|
||||||
|
{
|
||||||
|
$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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('array() succeeds when no data is found')]
|
||||||
|
public function testArraySucceedsWhenNoDataIsFound(): void
|
||||||
|
{
|
||||||
|
$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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('single() succeeds when a row is found')]
|
||||||
|
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->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('one', $doc->value->id, 'The incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('single() succeeds when a row is not found')]
|
||||||
|
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->isNone, 'There should not have been a document returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('nonQuery() succeeds when operating on data')]
|
||||||
|
public function testNonQuerySucceedsWhenOperatingOnData(): void
|
||||||
|
{
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
$remaining = Count::all(ThrowawayDb::TABLE);
|
||||||
|
$this->assertEquals(0, $remaining, 'There should be no documents remaining in the table');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('nonQuery() succeeds when no data matches WHERE clause')]
|
||||||
|
public function testNonQuerySucceedsWhenNoDataMatchesWhereClause(): void
|
||||||
|
{
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('scalar() succeeds')]
|
||||||
|
public function testScalarSucceeds(): void
|
||||||
|
{
|
||||||
|
$value = Custom::scalar("SELECT 5 AS it", [], new CountMapper());
|
||||||
|
$this->assertEquals(5, $value, 'The scalar value was not returned correctly');
|
||||||
|
}
|
||||||
|
}
|
88
tests/integration/postgresql/DefinitionTest.php
Normal file
88
tests/integration/postgresql/DefinitionTest.php
Normal file
|
@ -0,0 +1,88 @@
|
||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('ensureTable() succeeds')]
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('ensureFieldIndex() succeeds')]
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('ensureDocumentIndex() succeeds for Full')]
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('ensureDocumentIndex() succeeds for Optimized')]
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
}
|
99
tests/integration/postgresql/DeleteTest.php
Normal file
99
tests/integration/postgresql/DeleteTest.php
Normal file
|
@ -0,0 +1,99 @@
|
||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
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('byId() 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('byId() 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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds when documents are deleted')]
|
||||||
|
public function testByFieldsSucceedsWhenDocumentsAreDeleted(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
||||||
|
Delete::byFields(ThrowawayDb::TABLE, [Field::notEqual('value', 'purple')]);
|
||||||
|
$this->assertEquals(2, Count::all(ThrowawayDb::TABLE), 'There should have been 2 documents remaining');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds when documents are not deleted')]
|
||||||
|
public function testByFieldsSucceedsWhenDocumentsAreNotDeleted(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
||||||
|
Delete::byFields(ThrowawayDb::TABLE, [Field::equal('value', 'crimson')]);
|
||||||
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents remaining');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byContains() succeeds when documents are deleted')]
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byContains() succeeds when documents are not deleted')]
|
||||||
|
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('byJsonPath() 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('byJsonPath() 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');
|
||||||
|
}
|
||||||
|
}
|
135
tests/integration/postgresql/DocumentListTest.php
Normal file
135
tests/integration/postgresql/DocumentListTest.php
Normal file
|
@ -0,0 +1,135 @@
|
||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\PostgreSQL;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{DocumentException, 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();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('create() succeeds')]
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('items succeeds')]
|
||||||
|
public function testItemsSucceeds(): 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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('items fails when already consumed')]
|
||||||
|
public function testItemsFailsWhenAlreadyConsumed(): 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');
|
||||||
|
$ignored = iterator_to_array($list->items);
|
||||||
|
$this->assertFalse($list->hasItems, 'The list should no longer have items');
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
iterator_to_array($list->items);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('hasItems succeeds with empty results')]
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('hasItems succeeds with non-empty results')]
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('map() succeeds')]
|
||||||
|
public function testMapSucceeds(): 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->map(fn($doc) => strrev($doc->id)) as $mapped) {
|
||||||
|
$this->assertContains($mapped, ['eno', 'owt', 'eerht', 'ruof', 'evif'],
|
||||||
|
'An unexpected mapped value was returned');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('iter() succeeds')]
|
||||||
|
public function testIterSucceeds(): 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');
|
||||||
|
$splats = [];
|
||||||
|
$list->iter(function ($doc) use (&$splats) { $splats[] = str_repeat('*', strlen($doc->id)); });
|
||||||
|
$this->assertEquals('*** *** ***** **** ****', implode(' ', $splats),
|
||||||
|
'Iteration did not have the expected result');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('mapToArray() succeeds')]
|
||||||
|
public function testMapToArraySucceeds(): 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');
|
||||||
|
$lookup = $list->mapToArray(fn($it) => $it->id, fn($it) => $it->value);
|
||||||
|
$expected = ['one' => 'FIRST!', 'two' => 'another', 'three' => '', 'four' => 'purple', 'five' => 'purple'];
|
||||||
|
$this->assertEquals($expected, $lookup, 'The array was not mapped correctly');
|
||||||
|
}
|
||||||
|
}
|
319
tests/integration/postgresql/DocumentTest.php
Normal file
319
tests/integration/postgresql/DocumentTest.php
Normal file
|
@ -0,0 +1,319 @@
|
||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
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->isSome, 'There should have been a document inserted');
|
||||||
|
$doc = $tryDoc->value;
|
||||||
|
$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->isSome, 'There should have been a document returned');
|
||||||
|
$obj = json_decode($doc->value['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->isSome, 'There should have been a document returned');
|
||||||
|
$obj = json_decode($doc->value['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->isSome, 'There should have been a document returned');
|
||||||
|
$obj = json_decode($doc->value['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::equal('num_value', 5)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertNotEmpty($doc->value->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::equal('num_value', 12)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals($uuid, $doc->value->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::equal('num_value', 8)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals(6, strlen($doc->value->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::equal('num_value', 3)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('my-key', $doc->value->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->isSome, 'There should have been a document inserted');
|
||||||
|
$doc = $tryDoc->value;
|
||||||
|
$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::equal('value', 'taco')], NumDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals(1, $doc->value->id, 'The ID 1 should have been auto-generated');
|
||||||
|
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new NumDocument(value: 'burrito'));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'burrito')], NumDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals(2, $doc->value->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::equal('value', 'large')], NumDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals(64, $doc->value->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::exists('value')], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertNotEmpty($doc->value->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::equal('num_value', 14)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals($uuid, $doc->value->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::equal('num_value', 55)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals(40, strlen($doc->value->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::equal('num_value', 3)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('my-key', $doc->value->id, 'The ID should not have been changed');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('insert() fails for duplicate key')]
|
||||||
|
public function testInsertFailsForDuplicateKey(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new TestDocument('one'));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('save() succeeds when a document is inserted')]
|
||||||
|
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->isSome, 'There should have been a document returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('save() succeeds when a document is updated')]
|
||||||
|
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->isSome, 'There should have been a document returned');
|
||||||
|
$doc = $tryDoc->value;
|
||||||
|
$this->assertEquals(44, $doc->num_value, 'The numeric value was not updated');
|
||||||
|
$this->assertNull($doc->sub, 'The sub-document should have been null');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('update() succeeds when replacing a document')]
|
||||||
|
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->isSome, 'There should have been a document returned');
|
||||||
|
$doc = $tryDoc->value;
|
||||||
|
$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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('update() succeeds when no document is replaced')]
|
||||||
|
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->isNone, 'There should not have been a document returned');
|
||||||
|
}
|
||||||
|
}
|
90
tests/integration/postgresql/ExistsTest.php
Normal file
90
tests/integration/postgresql/ExistsTest.php
Normal file
|
@ -0,0 +1,90 @@
|
||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
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('byId() succeeds when a document exists')]
|
||||||
|
public function testByIdSucceedsWhenADocumentExists(): void
|
||||||
|
{
|
||||||
|
$this->assertTrue(Exists::byId(ThrowawayDb::TABLE, 'three'), 'There should have been an existing document');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byId() 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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds when documents exist')]
|
||||||
|
public function testByFieldsSucceedsWhenDocumentsExist(): void
|
||||||
|
{
|
||||||
|
$this->assertTrue(Exists::byFields(ThrowawayDb::TABLE, [Field::equal('num_value', 10)]),
|
||||||
|
'There should have been existing documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds when no matching documents exist')]
|
||||||
|
public function testByFieldsSucceedsWhenNoMatchingDocumentsExist(): void
|
||||||
|
{
|
||||||
|
$this->assertFalse(Exists::byFields(ThrowawayDb::TABLE, [Field::less('nothing', 'none')]),
|
||||||
|
'There should not have been any existing documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byContains() succeeds when documents exist')]
|
||||||
|
public function testByContainsSucceedsWhenDocumentsExist(): void
|
||||||
|
{
|
||||||
|
$this->assertTrue(Exists::byContains(ThrowawayDb::TABLE, ['value' => 'purple']),
|
||||||
|
'There should have been existing documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byContains() succeeds when no matching documents exist')]
|
||||||
|
public function testByContainsSucceedsWhenNoMatchingDocumentsExist(): void
|
||||||
|
{
|
||||||
|
$this->assertFalse(Exists::byContains(ThrowawayDb::TABLE, ['value' => 'violet']),
|
||||||
|
'There should not have been existing documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byJsonPath() succeeds when documents exist')]
|
||||||
|
public function testByJsonPathSucceedsWhenDocumentsExist(): void
|
||||||
|
{
|
||||||
|
$this->assertTrue(Exists::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ == 10)'),
|
||||||
|
'There should have been existing documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byJsonPath() 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');
|
||||||
|
}
|
||||||
|
}
|
335
tests/integration/postgresql/FindTest.php
Normal file
335
tests/integration/postgresql/FindTest.php
Normal file
|
@ -0,0 +1,335 @@
|
||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\PostgreSQL;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Custom, Delete, Document, Field, FieldMatch, Find};
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
use Test\Integration\{ArrayDocument, 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();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('all() succeeds when there is data')]
|
||||||
|
public function testAllSucceedsWhenThereIsData(): void
|
||||||
|
{
|
||||||
|
$docs = Find::all(ThrowawayDb::TABLE, TestDocument::class);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
|
||||||
|
$count = 0;
|
||||||
|
foreach ($docs->items as $ignored) $count++;
|
||||||
|
$this->assertEquals(5, $count, 'There should have been 5 documents in the list');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('all() succeeds when ordering data ascending')]
|
||||||
|
public function testAllSucceedsWhenOrderingDataAscending(): void
|
||||||
|
{
|
||||||
|
$docs = Find::all(ThrowawayDb::TABLE, TestDocument::class, [Field::named('id')]);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
|
||||||
|
$ids = iterator_to_array($docs->map(fn ($it) => $it->id), false);
|
||||||
|
$this->assertEquals(['five', 'four', 'one', 'three', 'two'], $ids, 'The documents were not ordered correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('all() succeeds when ordering data descending')]
|
||||||
|
public function testAllSucceedsWhenOrderingDataDescending(): void
|
||||||
|
{
|
||||||
|
$docs = Find::all(ThrowawayDb::TABLE, TestDocument::class, [Field::named('id DESC')]);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
|
||||||
|
$ids = iterator_to_array($docs->map(fn ($it) => $it->id), false);
|
||||||
|
$this->assertEquals(['two', 'three', 'one', 'four', 'five'], $ids, 'The documents were not ordered correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('all() succeeds when ordering data numerically')]
|
||||||
|
public function testAllSucceedsWhenOrderingDataNumerically(): void
|
||||||
|
{
|
||||||
|
$docs = Find::all(ThrowawayDb::TABLE, TestDocument::class,
|
||||||
|
[Field::named('sub.foo NULLS LAST'), Field::named('n:num_value')]);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
|
||||||
|
$ids = iterator_to_array($docs->map(fn ($it) => $it->id), false);
|
||||||
|
$this->assertEquals(['two', 'four', 'one', 'three', 'five'], $ids, 'The documents were not ordered correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('all() succeeds when there is no data')]
|
||||||
|
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('byId() succeeds when a document is found')]
|
||||||
|
public function testByIdSucceedsWhenADocumentIsFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('two', $doc->value->id, 'An incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byId() succeeds when a document is found with numeric ID')]
|
||||||
|
public function testByIdSucceedsWhenADocumentIsFoundWithNumericId(): void
|
||||||
|
{
|
||||||
|
Delete::byFields(ThrowawayDb::TABLE, [Field::notExists('absent')]);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => 18, 'value' => 'howdy']);
|
||||||
|
$doc = Find::byId(ThrowawayDb::TABLE, 18, NumDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals(18, $doc->value->id, 'An incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byId() succeeds when a document is not found')]
|
||||||
|
public function testByIdSucceedsWhenADocumentIsNotFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::byId(ThrowawayDb::TABLE, 'seventy-five', TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isNone, 'There should not have been a document returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds when documents are found')]
|
||||||
|
public function testByFieldsSucceedsWhenDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::in('value', ['blue', 'purple']), Field::exists('sub')],
|
||||||
|
TestDocument::class, FieldMatch::All);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
|
||||||
|
$count = 0;
|
||||||
|
foreach ($docs->items as $ignored) $count++;
|
||||||
|
$this->assertEquals(1, $count, 'There should have been 1 document in the list');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds when documents are found and ordered')]
|
||||||
|
public function testByFieldsSucceedsWhenDocumentsAreFoundAndOrdered(): void
|
||||||
|
{
|
||||||
|
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::equal('value', 'purple')], TestDocument::class,
|
||||||
|
FieldMatch::All, [Field::named('id')]);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
|
||||||
|
$ids = iterator_to_array($docs->map(fn ($it) => $it->id), false);
|
||||||
|
$this->assertEquals(['five', 'four'], $ids, 'The documents were not ordered correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds when documents are found using IN with numeric field')]
|
||||||
|
public function testByFieldsSucceedsWhenDocumentsAreFoundUsingInWithNumericField(): void
|
||||||
|
{
|
||||||
|
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::in('num_value', [2, 4, 6, 8])], TestDocument::class);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
|
||||||
|
$count = 0;
|
||||||
|
foreach ($docs->items as $ignored) $count++;
|
||||||
|
$this->assertEquals(1, $count, 'There should have been 1 document in the list');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds when no documents are found')]
|
||||||
|
public function testByFieldsSucceedsWhenNoDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::greater('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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds for inArray when matching documents exist')]
|
||||||
|
public function testByFieldsSucceedsForInArrayWhenMatchingDocumentsExist(): void
|
||||||
|
{
|
||||||
|
Delete::byFields(ThrowawayDb::TABLE, [Field::notExists('absentField')]);
|
||||||
|
foreach (ArrayDocument::testDocuments() as $doc) Document::insert(ThrowawayDb::TABLE, $doc);
|
||||||
|
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::inArray('values', ThrowawayDb::TABLE, ['c'])],
|
||||||
|
ArrayDocument::class);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
|
||||||
|
$count = 0;
|
||||||
|
foreach ($docs->items as $ignored) $count++;
|
||||||
|
$this->assertEquals(2, $count, 'There should have been 2 documents in the list');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds for inArray when no matching documents exist')]
|
||||||
|
public function testByFieldsSucceedsForInArrayWhenNoMatchingDocumentsExist(): void
|
||||||
|
{
|
||||||
|
Delete::byFields(ThrowawayDb::TABLE, [Field::notExists('absentField')]);
|
||||||
|
foreach (ArrayDocument::testDocuments() as $doc) Document::insert(ThrowawayDb::TABLE, $doc);
|
||||||
|
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::inArray('values', ThrowawayDb::TABLE, ['j'])],
|
||||||
|
ArrayDocument::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('byContains() succeeds when documents are found')]
|
||||||
|
public function testByContainsSucceedsWhenDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$docs = Find::byContains(ThrowawayDb::TABLE, ['value' => 'purple'], TestDocument::class);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
|
||||||
|
$count = 0;
|
||||||
|
foreach ($docs->items as $ignored) $count++;
|
||||||
|
$this->assertEquals(2, $count, 'There should have been 2 documents in the list');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byContains() succeeds when documents are found and ordered')]
|
||||||
|
public function testByContainsSucceedsWhenDocumentsAreFoundAndOrdered(): void
|
||||||
|
{
|
||||||
|
$docs = Find::byContains(ThrowawayDb::TABLE, ['sub' => ['foo' => 'green']], TestDocument::class,
|
||||||
|
[Field::named('value')]);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
|
||||||
|
$ids = iterator_to_array($docs->map(fn ($it) => $it->id), false);
|
||||||
|
$this->assertEquals(['two', 'four'], $ids, 'The documents were not ordered correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byContains() succeeds when no documents are found')]
|
||||||
|
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('byJsonPath() 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');
|
||||||
|
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
|
||||||
|
$count = 0;
|
||||||
|
foreach ($docs->items as $ignored) $count++;
|
||||||
|
$this->assertEquals(2, $count, 'There should have been 2 documents in the list');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byJsonPath() succeeds when documents are found and ordered')]
|
||||||
|
public function testByJsonPathSucceedsWhenDocumentsAreFoundAndOrdered(): void
|
||||||
|
{
|
||||||
|
$docs = Find::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 10)', TestDocument::class,
|
||||||
|
[Field::named('id')]);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
|
||||||
|
$ids = iterator_to_array($docs->map(fn ($it) => $it->id), false);
|
||||||
|
$this->assertEquals(['five', 'four'], $ids, 'The documents were not ordered correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byJsonPath() 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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('firstByFields() succeeds when a document is found')]
|
||||||
|
public function testFirstByFieldsSucceedsWhenADocumentIsFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'another')], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('two', $doc->value->id, 'The incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('firstByFields() succeeds when multiple documents are found')]
|
||||||
|
public function testFirstByFieldsSucceedsWhenMultipleDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('sub.foo', 'green')], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertContains($doc->value->id, ['two', 'four'], 'An incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('firstByFields() succeeds when multiple ordered documents are found')]
|
||||||
|
public function testFirstByFieldsSucceedsWhenMultipleOrderedDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('sub.foo', 'green')], TestDocument::class,
|
||||||
|
orderBy: [Field::named('n:num_value DESC')]);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('four', $doc->value->id, 'The incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('firstByFields() succeeds when a document is not found')]
|
||||||
|
public function testFirstByFieldsSucceedsWhenADocumentIsNotFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'absent')], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isNone, 'There should not have been a document returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('firstByContains() succeeds when a document is found')]
|
||||||
|
public function testFirstByContainsSucceedsWhenADocumentIsFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByContains(ThrowawayDb::TABLE, ['value' => 'FIRST!'], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('one', $doc->value->id, 'The incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('firstByContains() succeeds when multiple documents are found')]
|
||||||
|
public function testFirstByContainsSucceedsWhenMultipleDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByContains(ThrowawayDb::TABLE, ['value' => 'purple'], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertContains($doc->value->id, ['four', 'five'], 'An incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('firstByContains() succeeds when multiple ordered documents are found')]
|
||||||
|
public function testFirstByContainsSucceedsWhenMultipleOrderedDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByContains(ThrowawayDb::TABLE, ['value' => 'purple'], TestDocument::class,
|
||||||
|
[Field::named('sub.bar NULLS FIRST')]);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('five', $doc->value->id, 'The incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('firstByContains() succeeds when a document is not found')]
|
||||||
|
public function testFirstByContainsSucceedsWhenADocumentIsNotFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByContains(ThrowawayDb::TABLE, ['value' => 'indigo'], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isNone, 'There should not have been a document returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('firstByJsonPath() succeeds when a document is found')]
|
||||||
|
public function testFirstByJsonPathSucceedsWhenADocumentIsFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ == 10)', TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('two', $doc->value->id, 'The incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('firstByJsonPath() succeeds when multiple documents are found')]
|
||||||
|
public function testFirstByJsonPathSucceedsWhenMultipleDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 10)', TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertContains($doc->value->id, ['four', 'five'], 'An incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('firstByJsonPath() succeeds when multiple ordered documents are found')]
|
||||||
|
public function testFirstByJsonPathSucceedsWhenMultipleOrderedDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 10)', TestDocument::class,
|
||||||
|
[Field::named('id DESC')]);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('four', $doc->value->id, 'The incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('firstByJsonPath() succeeds when a document is not found')]
|
||||||
|
public function testFirstByJsonPathSucceedsWhenADocumentIsNotFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 100)', TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isNone, 'There should not have been a document returned');
|
||||||
|
}
|
||||||
|
}
|
115
tests/integration/postgresql/PatchTest.php
Normal file
115
tests/integration/postgresql/PatchTest.php
Normal file
|
@ -0,0 +1,115 @@
|
||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
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('byId() 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->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals(44, $doc->value->num_value, 'The updated document is not correct');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byId() 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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds when a document is updated')]
|
||||||
|
public function testByFieldsSucceedsWhenADocumentIsUpdated(): void
|
||||||
|
{
|
||||||
|
Patch::byFields(ThrowawayDb::TABLE, [Field::equal('value', 'purple')], ['num_value' => 77]);
|
||||||
|
$after = Count::byFields(ThrowawayDb::TABLE, [Field::equal('num_value', 77)]);
|
||||||
|
$this->assertEquals(2, $after, 'There should have been 2 documents updated');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds when no document is updated')]
|
||||||
|
public function testByFieldsSucceedsWhenNoDocumentIsUpdated(): void
|
||||||
|
{
|
||||||
|
$fields = [Field::equal('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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byContains() succeeds when documents are updated')]
|
||||||
|
public function testByContainsSucceedsWhenDocumentsAreUpdated(): void
|
||||||
|
{
|
||||||
|
Patch::byContains(ThrowawayDb::TABLE, ['value' => 'another'], ['num_value' => 12]);
|
||||||
|
$tryDoc = Find::firstByContains(ThrowawayDb::TABLE, ['value' => 'another'], TestDocument::class);
|
||||||
|
$this->assertTrue($tryDoc->isSome, 'There should have been a document returned');
|
||||||
|
$doc = $tryDoc->value;
|
||||||
|
$this->assertEquals('two', $doc->id, 'An incorrect document was returned');
|
||||||
|
$this->assertEquals(12, $doc->num_value, 'The document was not patched');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byContains() succeeds when no documents are updated')]
|
||||||
|
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('byJsonPath() 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('byJsonPath() 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');
|
||||||
|
}
|
||||||
|
}
|
140
tests/integration/postgresql/RemoveFieldsTest.php
Normal file
140
tests/integration/postgresql/RemoveFieldsTest.php
Normal file
|
@ -0,0 +1,140 @@
|
||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
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('byId() 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->assertTrue($tryDoc->isSome, 'There should have been a document returned');
|
||||||
|
$doc = $tryDoc->value;
|
||||||
|
$this->assertEquals('', $doc->value, 'Value should have been blank (its default value)');
|
||||||
|
$this->assertNull($doc->sub, 'Sub-document should have been null');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byId() 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('byId() 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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds when a field is removed')]
|
||||||
|
public function testByFieldsSucceedsWhenAFieldIsRemoved(): void
|
||||||
|
{
|
||||||
|
RemoveFields::byFields(ThrowawayDb::TABLE, [Field::equal('num_value', 17)], ['sub']);
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 17)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertNull($doc->value->sub, 'Sub-document should have been null');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds when a field is not removed')]
|
||||||
|
public function testByFieldsSucceedsWhenAFieldIsNotRemoved(): void
|
||||||
|
{
|
||||||
|
RemoveFields::byFields(ThrowawayDb::TABLE, [Field::equal('num_value', 17)], ['nada']);
|
||||||
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds when no document is matched')]
|
||||||
|
public function testByFieldsSucceedsWhenNoDocumentIsMatched(): void
|
||||||
|
{
|
||||||
|
RemoveFields::byFields(ThrowawayDb::TABLE, [Field::notEqual('missing', 'nope')], ['value']);
|
||||||
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byContains() succeeds when a field is removed')]
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byContains() succeeds when a field is 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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byContains() succeeds when no document is matched')]
|
||||||
|
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('byJsonPath() 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('byJsonPath() 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('byJsonPath() 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');
|
||||||
|
}
|
||||||
|
}
|
81
tests/integration/postgresql/ThrowawayDb.php
Normal file
81
tests/integration/postgresql/ThrowawayDb.php
Normal file
|
@ -0,0 +1,81 @@
|
||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
* @see https://github.com/Zaid-Ajaj/ThrowawayDb The origin concept
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\PostgreSQL;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{AutoId, Configuration, Custom, Definition, Document, DocumentException};
|
||||||
|
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")
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
private static function configure(?string $dbName = null): void
|
||||||
|
{
|
||||||
|
Configuration::useDSN(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::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::useDSN('');
|
||||||
|
Configuration::$username = null;
|
||||||
|
Configuration::$password = null;
|
||||||
|
Configuration::resetPDO();
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,8 +1,14 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
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;
|
||||||
|
|
||||||
|
@ -27,21 +33,38 @@ class CountTest extends TestCase
|
||||||
parent::tearDown();
|
parent::tearDown();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('all() succeeds')]
|
||||||
public function testAllSucceeds(): void
|
public function testAllSucceeds(): void
|
||||||
{
|
{
|
||||||
$count = Count::all(ThrowawayDb::TABLE);
|
$count = Count::all(ThrowawayDb::TABLE);
|
||||||
$this->assertEquals(5, $count, 'There should have been 5 matching documents');
|
$this->assertEquals(5, $count, 'There should have been 5 matching documents');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds for a numeric range')]
|
||||||
public function testByFieldsSucceedsForANumericRange(): void
|
public function testByFieldsSucceedsForANumericRange(): void
|
||||||
{
|
{
|
||||||
$count = Count::byFields(ThrowawayDb::TABLE, [Field::BT('num_value', 10, 20)]);
|
$count = Count::byFields(ThrowawayDb::TABLE, [Field::between('num_value', 10, 20)]);
|
||||||
$this->assertEquals(3, $count, 'There should have been 3 matching documents');
|
$this->assertEquals(3, $count, 'There should have been 3 matching documents');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds for a non-numeric range')]
|
||||||
public function testByFieldsSucceedsForANonNumericRange(): void
|
public function testByFieldsSucceedsForANonNumericRange(): void
|
||||||
{
|
{
|
||||||
$count = Count::byFields(ThrowawayDb::TABLE, [Field::BT('value', 'aardvark', 'apple')]);
|
$count = Count::byFields(ThrowawayDb::TABLE, [Field::between('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');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('byContains() fails')]
|
||||||
|
public function testByContainsFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Count::byContains('', []);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byJsonPath() fails')]
|
||||||
|
public function testByJsonPathFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Count::byJsonPath('', '');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,10 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Test\Integration\SQLite;
|
namespace Test\Integration\SQLite;
|
||||||
|
|
||||||
|
@ -28,7 +34,8 @@ class CustomTest extends TestCase
|
||||||
ThrowawayDb::destroy($this->dbName);
|
ThrowawayDb::destroy($this->dbName);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRunQuerySucceedsWithAValidQuery()
|
#[TestDox('runQuery() succeeds with a valid query')]
|
||||||
|
public function testRunQuerySucceedsWithAValidQuery(): void
|
||||||
{
|
{
|
||||||
$stmt = &Custom::runQuery('SELECT data FROM ' . ThrowawayDb::TABLE . ' LIMIT 1', []);
|
$stmt = &Custom::runQuery('SELECT data FROM ' . ThrowawayDb::TABLE . ' LIMIT 1', []);
|
||||||
try {
|
try {
|
||||||
|
@ -38,7 +45,8 @@ class CustomTest extends TestCase
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRunQueryFailsWithAnInvalidQuery()
|
#[TestDox('runQuery() fails with an invalid query')]
|
||||||
|
public function testRunQueryFailsWithAnInvalidQuery(): void
|
||||||
{
|
{
|
||||||
$this->expectException(DocumentException::class);
|
$this->expectException(DocumentException::class);
|
||||||
$stmt = &Custom::runQuery('GRAB stuff FROM over_there UNTIL done', []);
|
$stmt = &Custom::runQuery('GRAB stuff FROM over_there UNTIL done', []);
|
||||||
|
@ -49,24 +57,28 @@ class CustomTest extends TestCase
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testListSucceedsWhenDataIsFound()
|
#[TestDox('list() succeeds when data is found')]
|
||||||
|
public function testListSucceedsWhenDataIsFound(): void
|
||||||
{
|
{
|
||||||
$list = Custom::list(Query::selectFromTable(ThrowawayDb::TABLE), [], new DocumentMapper(TestDocument::class));
|
$list = Custom::list(Query::selectFromTable(ThrowawayDb::TABLE), [], new DocumentMapper(TestDocument::class));
|
||||||
$this->assertNotNull($list, 'The document list should not be null');
|
$this->assertNotNull($list, 'The document list should not be null');
|
||||||
|
$this->assertTrue($list->hasItems, 'There should have been documents in the list');
|
||||||
$count = 0;
|
$count = 0;
|
||||||
foreach ($list->items() as $ignored) $count++;
|
foreach ($list->items as $ignored) $count++;
|
||||||
$this->assertEquals(5, $count, 'There should have been 5 documents in the list');
|
$this->assertEquals(5, $count, 'There should have been 5 documents in the list');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testListSucceedsWhenNoDataIsFound()
|
#[TestDox('list() succeeds when no data is found')]
|
||||||
|
public function testListSucceedsWhenNoDataIsFound(): void
|
||||||
{
|
{
|
||||||
$list = Custom::list(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'num_value' > :value",
|
$list = Custom::list(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'num_value' > :value",
|
||||||
[':value' => 100], new DocumentMapper(TestDocument::class));
|
[':value' => 100], new DocumentMapper(TestDocument::class));
|
||||||
$this->assertNotNull($list, 'The document list should not be null');
|
$this->assertNotNull($list, 'The document list should not be null');
|
||||||
$this->assertFalse($list->hasItems(), 'There should have been no documents in the list');
|
$this->assertFalse($list->hasItems, 'There should have been no documents in the list');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testArraySucceedsWhenDataIsFound()
|
#[TestDox('array() succeeds when data is found')]
|
||||||
|
public function testArraySucceedsWhenDataIsFound(): void
|
||||||
{
|
{
|
||||||
$array = Custom::array(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'sub' IS NOT NULL", [],
|
$array = Custom::array(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'sub' IS NOT NULL", [],
|
||||||
new DocumentMapper(TestDocument::class));
|
new DocumentMapper(TestDocument::class));
|
||||||
|
@ -74,7 +86,8 @@ class CustomTest extends TestCase
|
||||||
$this->assertCount(2, $array, 'There should have been 2 documents in the array');
|
$this->assertCount(2, $array, 'There should have been 2 documents in the array');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testArraySucceedsWhenNoDataIsFound()
|
#[TestDox('array() succeeds when no data is found')]
|
||||||
|
public function testArraySucceedsWhenNoDataIsFound(): void
|
||||||
{
|
{
|
||||||
$array = Custom::array(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'value' = :value",
|
$array = Custom::array(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'value' = :value",
|
||||||
[':value' => 'not there'], new DocumentMapper(TestDocument::class));
|
[':value' => 'not there'], new DocumentMapper(TestDocument::class));
|
||||||
|
@ -82,36 +95,41 @@ class CustomTest extends TestCase
|
||||||
$this->assertCount(0, $array, 'There should have been no documents in the array');
|
$this->assertCount(0, $array, 'There should have been no documents in the array');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('single() succeeds when a row is found')]
|
||||||
public function testSingleSucceedsWhenARowIsFound(): void
|
public function testSingleSucceedsWhenARowIsFound(): void
|
||||||
{
|
{
|
||||||
$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->isSome, 'There should have been a document returned');
|
||||||
$this->assertEquals('one', $doc->id, 'The incorrect document was returned');
|
$this->assertEquals('one', $doc->value->id, 'The incorrect document was returned');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('single() succeeds when a row is not found')]
|
||||||
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->isNone, 'There should not have been a document returned');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testNonQuerySucceedsWhenOperatingOnData()
|
#[TestDox('nonQuery() succeeds when operating on data')]
|
||||||
|
public function testNonQuerySucceedsWhenOperatingOnData(): void
|
||||||
{
|
{
|
||||||
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
$remaining = Count::all(ThrowawayDb::TABLE);
|
$remaining = Count::all(ThrowawayDb::TABLE);
|
||||||
$this->assertEquals(0, $remaining, 'There should be no documents remaining in the table');
|
$this->assertEquals(0, $remaining, 'There should be no documents remaining in the table');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testNonQuerySucceedsWhenNoDataMatchesWhereClause()
|
#[TestDox('nonQuery() succeeds when no data matches WHERE clause')]
|
||||||
|
public function testNonQuerySucceedsWhenNoDataMatchesWhereClause(): void
|
||||||
{
|
{
|
||||||
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE . " WHERE data->>'num_value' > :value", [':value' => 100]);
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE . " WHERE data->>'num_value' > :value", [':value' => 100]);
|
||||||
$remaining = Count::all(ThrowawayDb::TABLE);
|
$remaining = Count::all(ThrowawayDb::TABLE);
|
||||||
$this->assertEquals(5, $remaining, 'There should be 5 documents remaining in the table');
|
$this->assertEquals(5, $remaining, 'There should be 5 documents remaining in the table');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testScalarSucceeds()
|
#[TestDox('scalar() succeeds')]
|
||||||
|
public function testScalarSucceeds(): void
|
||||||
{
|
{
|
||||||
$value = Custom::scalar("SELECT 5 AS it", [], new CountMapper());
|
$value = Custom::scalar("SELECT 5 AS it", [], new CountMapper());
|
||||||
$this->assertEquals(5, $value, 'The scalar value was not returned correctly');
|
$this->assertEquals(5, $value, 'The scalar value was not returned correctly');
|
||||||
|
|
|
@ -1,8 +1,14 @@
|
||||||
<?php
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
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 +47,8 @@ class DefinitionTest extends TestCase
|
||||||
[':name' => $name], new ExistsMapper());
|
[':name' => $name], new ExistsMapper());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testEnsureTableSucceeds()
|
#[TestDox('ensureTable() succeeds')]
|
||||||
|
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 +57,19 @@ 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()
|
#[TestDox('ensureFieldIndex() succeeds')]
|
||||||
|
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');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('ensureDocumentIndex() fails')]
|
||||||
|
public function testEnsureDocumentIndexFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Definition::ensureDocumentIndex('nope', DocumentIndex::Full);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,8 +1,14 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
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;
|
||||||
|
|
||||||
|
@ -27,7 +33,7 @@ class DeleteTest extends TestCase
|
||||||
parent::tearDown();
|
parent::tearDown();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By ID succeeds when a document is deleted')]
|
#[TestDox('byId() succeeds when a document is deleted')]
|
||||||
public function testByIdSucceedsWhenADocumentIsDeleted(): void
|
public function testByIdSucceedsWhenADocumentIsDeleted(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
||||||
|
@ -35,7 +41,7 @@ class DeleteTest extends TestCase
|
||||||
$this->assertEquals(4, Count::all(ThrowawayDb::TABLE), 'There should have been 4 documents remaining');
|
$this->assertEquals(4, Count::all(ThrowawayDb::TABLE), 'There should have been 4 documents remaining');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By ID succeeds when a document is not deleted')]
|
#[TestDox('byId() succeeds when a document is not deleted')]
|
||||||
public function testByIdSucceedsWhenADocumentIsNotDeleted(): void
|
public function testByIdSucceedsWhenADocumentIsNotDeleted(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
||||||
|
@ -43,17 +49,33 @@ class DeleteTest extends TestCase
|
||||||
$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');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds when documents are deleted')]
|
||||||
public function testByFieldsSucceedsWhenDocumentsAreDeleted(): void
|
public function testByFieldsSucceedsWhenDocumentsAreDeleted(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
||||||
Delete::byFields(ThrowawayDb::TABLE, [Field::NE('value', 'purple')]);
|
Delete::byFields(ThrowawayDb::TABLE, [Field::notEqual('value', 'purple')]);
|
||||||
$this->assertEquals(2, Count::all(ThrowawayDb::TABLE), 'There should have been 2 documents remaining');
|
$this->assertEquals(2, Count::all(ThrowawayDb::TABLE), 'There should have been 2 documents remaining');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds when documents are not deleted')]
|
||||||
public function testByFieldsSucceedsWhenDocumentsAreNotDeleted(): void
|
public function testByFieldsSucceedsWhenDocumentsAreNotDeleted(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
||||||
Delete::byFields(ThrowawayDb::TABLE, [Field::EQ('value', 'crimson')]);
|
Delete::byFields(ThrowawayDb::TABLE, [Field::equal('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');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('byContains() fails')]
|
||||||
|
public function testByContainsFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Delete::byContains('', []);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byJsonPath() fails')]
|
||||||
|
public function testByJsonPathFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Delete::byJsonPath('', '');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,8 +1,14 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Test\Integration\SQLite;
|
namespace Test\Integration\SQLite;
|
||||||
|
|
||||||
use BitBadger\PDODocument\{DocumentList, Query};
|
use BitBadger\PDODocument\{DocumentException, DocumentList, Query};
|
||||||
use BitBadger\PDODocument\Mapper\DocumentMapper;
|
use BitBadger\PDODocument\Mapper\DocumentMapper;
|
||||||
use PHPUnit\Framework\Attributes\TestDox;
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
|
@ -29,6 +35,7 @@ class DocumentListTest extends TestCase
|
||||||
parent::tearDown();
|
parent::tearDown();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('create() succeeds')]
|
||||||
public function testCreateSucceeds(): void
|
public function testCreateSucceeds(): void
|
||||||
{
|
{
|
||||||
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
|
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
|
||||||
|
@ -37,13 +44,14 @@ class DocumentListTest extends TestCase
|
||||||
$list = null;
|
$list = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testItems(): void
|
#[TestDox('items succeeds')]
|
||||||
|
public function testItemsSucceeds(): void
|
||||||
{
|
{
|
||||||
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
|
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
|
||||||
new DocumentMapper(TestDocument::class));
|
new DocumentMapper(TestDocument::class));
|
||||||
$this->assertNotNull($list, 'There should have been a document list created');
|
$this->assertNotNull($list, 'There should have been a document list created');
|
||||||
$count = 0;
|
$count = 0;
|
||||||
foreach ($list->items() as $item) {
|
foreach ($list->items as $item) {
|
||||||
$this->assertContains($item->id, ['one', 'two', 'three', 'four', 'five'],
|
$this->assertContains($item->id, ['one', 'two', 'three', 'four', 'five'],
|
||||||
'An unexpected document ID was returned');
|
'An unexpected document ID was returned');
|
||||||
$count++;
|
$count++;
|
||||||
|
@ -51,23 +59,76 @@ class DocumentListTest extends TestCase
|
||||||
$this->assertEquals(5, $count, 'There should have been 5 documents returned');
|
$this->assertEquals(5, $count, 'There should have been 5 documents returned');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('items fails when already consumed')]
|
||||||
|
public function testItemsFailsWhenAlreadyConsumed(): 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');
|
||||||
|
$ignored = iterator_to_array($list->items);
|
||||||
|
$this->assertFalse($list->hasItems, 'The list should no longer have items');
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
iterator_to_array($list->items);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('hasItems succeeds with empty results')]
|
||||||
public function testHasItemsSucceedsWithEmptyResults(): void
|
public function testHasItemsSucceedsWithEmptyResults(): void
|
||||||
{
|
{
|
||||||
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'num_value' < 0", [],
|
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'num_value' < 0", [],
|
||||||
new DocumentMapper(TestDocument::class));
|
new DocumentMapper(TestDocument::class));
|
||||||
$this->assertNotNull($list, 'There should have been a document list created');
|
$this->assertNotNull($list, 'There should have been a document list created');
|
||||||
$this->assertFalse($list->hasItems(), 'There should be no items in the list');
|
$this->assertFalse($list->hasItems, 'There should be no items in the list');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('hasItems succeeds with non-empty results')]
|
||||||
public function testHasItemsSucceedsWithNonEmptyResults(): void
|
public function testHasItemsSucceedsWithNonEmptyResults(): void
|
||||||
{
|
{
|
||||||
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
|
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
|
||||||
new DocumentMapper(TestDocument::class));
|
new DocumentMapper(TestDocument::class));
|
||||||
$this->assertNotNull($list, 'There should have been a document list created');
|
$this->assertNotNull($list, 'There should have been a document list created');
|
||||||
$this->assertTrue($list->hasItems(), 'There should be items in the list');
|
$this->assertTrue($list->hasItems, 'There should be items in the list');
|
||||||
foreach ($list->items() as $ignored) {
|
foreach ($list->items as $ignored) {
|
||||||
$this->assertTrue($list->hasItems(), 'There should be items remaining in the list');
|
$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');
|
$this->assertFalse($list->hasItems, 'There should be no remaining items in the list');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('map() succeeds')]
|
||||||
|
public function testMapSucceeds(): 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->map(fn($doc) => strrev($doc->id)) as $mapped) {
|
||||||
|
$this->assertContains($mapped, ['eno', 'owt', 'eerht', 'ruof', 'evif'],
|
||||||
|
'An unexpected mapped value was returned');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('iter() succeeds')]
|
||||||
|
public function testIterSucceeds(): 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');
|
||||||
|
$splats = [];
|
||||||
|
$list->iter(function ($doc) use (&$splats) { $splats[] = str_repeat('*', strlen($doc->id)); });
|
||||||
|
$this->assertEquals('*** *** ***** **** ****', implode(' ', $splats),
|
||||||
|
'Iteration did not have the expected result');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('mapToArray() succeeds')]
|
||||||
|
public function testMapToArraySucceeds(): 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');
|
||||||
|
$lookup = $list->mapToArray(fn($it) => $it->id, fn($it) => $it->value);
|
||||||
|
$expected = ['one' => 'FIRST!', 'two' => 'another', 'three' => '', 'four' => 'purple', 'five' => 'purple'];
|
||||||
|
$this->assertEquals($expected, $lookup, 'The array was not mapped correctly');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,11 +1,18 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
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 +35,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->isSome, 'There should have been a document inserted');
|
||||||
|
$doc = $tryDoc->value;
|
||||||
$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,33 +50,258 @@ 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->isSome, 'There should have been a document returned');
|
||||||
|
$obj = json_decode($doc->value['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->isSome, 'There should have been a document returned');
|
||||||
|
$obj = json_decode($doc->value['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->isSome, 'There should have been a document returned');
|
||||||
|
$obj = json_decode($doc->value['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::equal('num_value', 5)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertNotEmpty($doc->value->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::equal('num_value', 12)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals($uuid, $doc->value->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::equal('num_value', 8)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals(6, strlen($doc->value->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::equal('num_value', 3)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('my-key', $doc->value->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->isSome, 'There should have been a document inserted');
|
||||||
|
$doc = $tryDoc->value;
|
||||||
|
$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::equal('value', 'taco')], NumDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals(1, $doc->value->id, 'The ID 1 should have been auto-generated');
|
||||||
|
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new NumDocument(value: 'burrito'));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'burrito')], NumDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals(2, $doc->value->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::equal('value', 'large')], NumDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals(64, $doc->value->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::exists('value')], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertNotEmpty($doc->value->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::equal('num_value', 14)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals($uuid, $doc->value->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::equal('num_value', 55)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals(40, strlen($doc->value->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::equal('num_value', 3)], TestDocument::class);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('my-key', $doc->value->id, 'The ID should not have been changed');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('insert() fails for duplicate key')]
|
||||||
public function testInsertFailsForDuplicateKey(): void
|
public function testInsertFailsForDuplicateKey(): void
|
||||||
{
|
{
|
||||||
$this->expectException(DocumentException::class);
|
$this->expectException(DocumentException::class);
|
||||||
Document::insert(ThrowawayDb::TABLE, new TestDocument('one'));
|
Document::insert(ThrowawayDb::TABLE, new TestDocument('one'));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('save() succeeds when a document is inserted')]
|
||||||
public function testSaveSucceedsWhenADocumentIsInserted(): void
|
public function testSaveSucceedsWhenADocumentIsInserted(): void
|
||||||
{
|
{
|
||||||
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->isSome, 'There should have been a document returned');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('save() succeeds when a document is updated')]
|
||||||
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->isSome, 'There should have been a document returned');
|
||||||
|
$doc = $tryDoc->value;
|
||||||
$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');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('update() succeeds when replacing a document')]
|
||||||
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->isSome, 'There should have been a document returned');
|
||||||
|
$doc = $tryDoc->value;
|
||||||
$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');
|
||||||
|
@ -75,10 +309,11 @@ class DocumentTest extends TestCase
|
||||||
$this->assertEquals('z', $doc->sub->bar, 'The sub-document bar property was incorrect');
|
$this->assertEquals('z', $doc->sub->bar, 'The sub-document bar property was incorrect');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('update() succeeds when no document is replaced')]
|
||||||
public function testUpdateSucceedsWhenNoDocumentIsReplaced(): void
|
public function testUpdateSucceedsWhenNoDocumentIsReplaced(): void
|
||||||
{
|
{
|
||||||
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->isNone, 'There should not have been a document returned');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,8 +1,14 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
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;
|
||||||
|
|
||||||
|
@ -27,28 +33,45 @@ class ExistsTest extends TestCase
|
||||||
parent::tearDown();
|
parent::tearDown();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By ID succeeds when a document exists')]
|
#[TestDox('byId() succeeds when a document exists')]
|
||||||
public function testByIdSucceedsWhenADocumentExists(): void
|
public function testByIdSucceedsWhenADocumentExists(): void
|
||||||
{
|
{
|
||||||
$this->assertTrue(Exists::byId(ThrowawayDb::TABLE, 'three'), 'There should have been an existing document');
|
$this->assertTrue(Exists::byId(ThrowawayDb::TABLE, 'three'), 'There should have been an existing document');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By ID succeeds when a document does not exist')]
|
#[TestDox('byId() succeeds when a document does not exist')]
|
||||||
public function testByIdSucceedsWhenADocumentDoesNotExist(): void
|
public function testByIdSucceedsWhenADocumentDoesNotExist(): void
|
||||||
{
|
{
|
||||||
$this->assertFalse(Exists::byId(ThrowawayDb::TABLE, 'seven'),
|
$this->assertFalse(Exists::byId(ThrowawayDb::TABLE, 'seven'),
|
||||||
'There should not have been an existing document');
|
'There should not have been an existing document');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds when documents exist')]
|
||||||
public function testByFieldsSucceedsWhenDocumentsExist(): void
|
public function testByFieldsSucceedsWhenDocumentsExist(): void
|
||||||
{
|
{
|
||||||
$this->assertTrue(Exists::byFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 10)]),
|
$this->assertTrue(Exists::byFields(ThrowawayDb::TABLE, [Field::equal('num_value', 10)]),
|
||||||
'There should have been existing documents');
|
'There should have been existing documents');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds when no matching documents exist')]
|
||||||
public function testByFieldsSucceedsWhenNoMatchingDocumentsExist(): void
|
public function testByFieldsSucceedsWhenNoMatchingDocumentsExist(): void
|
||||||
{
|
{
|
||||||
$this->assertFalse(Exists::byFields(ThrowawayDb::TABLE, [Field::LT('nothing', 'none')]),
|
$this->assertFalse(Exists::byFields(ThrowawayDb::TABLE, [Field::less('nothing', 'none')]),
|
||||||
'There should not have been any existing documents');
|
'There should not have been any existing documents');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('byContains() fails')]
|
||||||
|
public function testByContainsFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Exists::byContains('', []);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('byJsonPath() fails')]
|
||||||
|
public function testByJsonPathFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Exists::byJsonPath('', '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
|
@ -1,10 +1,17 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Test\Integration\SQLite;
|
namespace Test\Integration\SQLite;
|
||||||
|
|
||||||
use BitBadger\PDODocument\{Custom, Document, Field, Find};
|
use BitBadger\PDODocument\{Custom, Delete, Document, DocumentException, Field, FieldMatch, Find};
|
||||||
use PHPUnit\Framework\Attributes\TestDox;
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
|
use Test\Integration\ArrayDocument;
|
||||||
use Test\Integration\TestDocument;
|
use Test\Integration\TestDocument;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -28,82 +35,205 @@ class FindTest extends TestCase
|
||||||
parent::tearDown();
|
parent::tearDown();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('all() succeeds when there is data')]
|
||||||
public function testAllSucceedsWhenThereIsData(): void
|
public function testAllSucceedsWhenThereIsData(): void
|
||||||
{
|
{
|
||||||
$docs = Find::all(ThrowawayDb::TABLE, TestDocument::class);
|
$docs = Find::all(ThrowawayDb::TABLE, TestDocument::class);
|
||||||
$this->assertNotNull($docs, 'There should have been a document list returned');
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
|
||||||
$count = 0;
|
$count = 0;
|
||||||
foreach ($docs->items() as $ignored) $count++;
|
foreach ($docs->items as $ignored) $count++;
|
||||||
$this->assertEquals(5, $count, 'There should have been 5 documents in the list');
|
$this->assertEquals(5, $count, 'There should have been 5 documents in the list');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('all() succeeds when ordering data ascending')]
|
||||||
|
public function testAllSucceedsWhenOrderingDataAscending(): void
|
||||||
|
{
|
||||||
|
$docs = Find::all(ThrowawayDb::TABLE, TestDocument::class, [Field::named('id')]);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
|
||||||
|
$ids = iterator_to_array($docs->map(fn ($it) => $it->id), false);
|
||||||
|
$this->assertEquals(['five', 'four', 'one', 'three', 'two'], $ids, 'The documents were not ordered correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('all() succeeds when ordering data descending')]
|
||||||
|
public function testAllSucceedsWhenOrderingDataDescending(): void
|
||||||
|
{
|
||||||
|
$docs = Find::all(ThrowawayDb::TABLE, TestDocument::class, [Field::named('id DESC')]);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
|
||||||
|
$ids = iterator_to_array($docs->map(fn ($it) => $it->id), false);
|
||||||
|
$this->assertEquals(['two', 'three', 'one', 'four', 'five'], $ids, 'The documents were not ordered correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('all() succeeds when ordering data numerically')]
|
||||||
|
public function testAllSucceedsWhenOrderingDataNumerically(): void
|
||||||
|
{
|
||||||
|
$docs = Find::all(ThrowawayDb::TABLE, TestDocument::class,
|
||||||
|
[Field::named('sub.foo NULLS LAST'), Field::named('n:num_value')]);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
|
||||||
|
$ids = iterator_to_array($docs->map(fn ($it) => $it->id), false);
|
||||||
|
$this->assertEquals(['two', 'four', 'one', 'three', 'five'], $ids, 'The documents were not ordered correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('all() succeeds when there is no data')]
|
||||||
public function testAllSucceedsWhenThereIsNoData(): void
|
public function testAllSucceedsWhenThereIsNoData(): void
|
||||||
{
|
{
|
||||||
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
$docs = Find::all(ThrowawayDb::TABLE, TestDocument::class);
|
$docs = Find::all(ThrowawayDb::TABLE, TestDocument::class);
|
||||||
$this->assertNotNull($docs, 'There should have been a document list returned');
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
$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');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By ID succeeds when a document is found')]
|
#[TestDox('byId() succeeds when a document is found')]
|
||||||
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->isSome, 'There should have been a document returned');
|
||||||
$this->assertEquals('two', $doc->id, 'An incorrect document was returned');
|
$this->assertEquals('two', $doc->value->id, 'An incorrect document was returned');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By ID succeeds when a document is found with numeric ID')]
|
#[TestDox('byId() succeeds when a document is found with numeric ID')]
|
||||||
public function testByIdSucceedsWhenADocumentIsFoundWithNumericId(): void
|
public function testByIdSucceedsWhenADocumentIsFoundWithNumericId(): void
|
||||||
{
|
{
|
||||||
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->isSome, 'There should have been a document returned');
|
||||||
$this->assertEquals('18', $doc->id, 'An incorrect document was returned');
|
$this->assertEquals('18', $doc->value->id, 'An incorrect document was returned');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By ID succeeds when a document is not found')]
|
#[TestDox('byId() 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->isNone, 'There should not have been a document returned');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds when documents are found')]
|
||||||
public function testByFieldsSucceedsWhenDocumentsAreFound(): void
|
public function testByFieldsSucceedsWhenDocumentsAreFound(): void
|
||||||
{
|
{
|
||||||
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::GT('num_value', 15)], TestDocument::class);
|
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::in('value', ['blue', 'purple']), Field::exists('sub')],
|
||||||
|
TestDocument::class, FieldMatch::All);
|
||||||
$this->assertNotNull($docs, 'There should have been a document list returned');
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
|
||||||
$count = 0;
|
$count = 0;
|
||||||
foreach ($docs->items() as $ignored) $count++;
|
foreach ($docs->items as $ignored) $count++;
|
||||||
|
$this->assertEquals(1, $count, 'There should have been 1 document in the list');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds when documents are found and ordered')]
|
||||||
|
public function testByFieldsSucceedsWhenDocumentsAreFoundAndOrdered(): void
|
||||||
|
{
|
||||||
|
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::equal('value', 'purple')], TestDocument::class,
|
||||||
|
FieldMatch::All, [Field::named('id')]);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
|
||||||
|
$ids = iterator_to_array($docs->map(fn ($it) => $it->id), false);
|
||||||
|
$this->assertEquals(['five', 'four'], $ids, 'The documents were not ordered correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds when documents are found using IN with numeric field')]
|
||||||
|
public function testByFieldsSucceedsWhenDocumentsAreFoundUsingInWithNumericField(): void
|
||||||
|
{
|
||||||
|
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::in('num_value', [2, 4, 6, 8])], TestDocument::class);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
|
||||||
|
$count = 0;
|
||||||
|
foreach ($docs->items as $ignored) $count++;
|
||||||
|
$this->assertEquals(1, $count, 'There should have been 1 document in the list');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds when no documents are found')]
|
||||||
|
public function testByFieldsSucceedsWhenNoDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::greater('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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds for inArray when matching documents exist')]
|
||||||
|
public function testByFieldsSucceedsForInArrayWhenMatchingDocumentsExist(): void
|
||||||
|
{
|
||||||
|
Delete::byFields(ThrowawayDb::TABLE, [Field::notExists('absentField')]);
|
||||||
|
foreach (ArrayDocument::testDocuments() as $doc) Document::insert(ThrowawayDb::TABLE, $doc);
|
||||||
|
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::inArray('values', ThrowawayDb::TABLE, ['c'])],
|
||||||
|
ArrayDocument::class);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
|
||||||
|
$count = 0;
|
||||||
|
foreach ($docs->items as $ignored) $count++;
|
||||||
$this->assertEquals(2, $count, 'There should have been 2 documents in the list');
|
$this->assertEquals(2, $count, 'There should have been 2 documents in the list');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testByFieldsSucceedsWhenNoDocumentsAreFound(): void
|
#[TestDox('byFields() succeeds for inArray when no matching documents exist')]
|
||||||
|
public function testByFieldsSucceedsForInArrayWhenNoMatchingDocumentsExist(): void
|
||||||
{
|
{
|
||||||
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::GT('num_value', 100)], TestDocument::class);
|
Delete::byFields(ThrowawayDb::TABLE, [Field::notExists('absentField')]);
|
||||||
|
foreach (ArrayDocument::testDocuments() as $doc) Document::insert(ThrowawayDb::TABLE, $doc);
|
||||||
|
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::inArray('values', ThrowawayDb::TABLE, ['j'])],
|
||||||
|
ArrayDocument::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;
|
$this->assertFalse($docs->hasItems, 'There should have been no documents in the list');
|
||||||
foreach ($docs->items() as $ignored) $count++;
|
|
||||||
$this->assertFalse($docs->hasItems(), 'There should have been no documents in the list');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('byContains() fails')]
|
||||||
|
public function testByContainsFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Find::byContains('', [], TestDocument::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byJsonPath() fails')]
|
||||||
|
public function testByJsonPathFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Find::byJsonPath('', '', TestDocument::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('firstByFields() succeeds when a document is found')]
|
||||||
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::equal('value', 'another')], TestDocument::class);
|
||||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
$this->assertEquals('two', $doc->id, 'The incorrect document was returned');
|
$this->assertEquals('two', $doc->value->id, 'The incorrect document was returned');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('firstByFields() succeeds when multiple documents are found')]
|
||||||
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::equal('sub.foo', 'green')], TestDocument::class);
|
||||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
$this->assertContains($doc->id, ['two', 'four'], 'An incorrect document was returned');
|
$this->assertContains($doc->value->id, ['two', 'four'], 'An incorrect document was returned');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('firstByFields() succeeds when multiple ordered documents are found')]
|
||||||
|
public function testFirstByFieldsSucceedsWhenMultipleOrderedDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('sub.foo', 'green')], TestDocument::class,
|
||||||
|
orderBy: [Field::named('n:num_value DESC')]);
|
||||||
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('four', $doc->value->id, 'The incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('firstByFields() succeeds when a document is not found')]
|
||||||
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::equal('value', 'absent')], TestDocument::class);
|
||||||
$this->assertFalse($doc, 'There should not have been a document returned');
|
$this->assertTrue($doc->isNone, 'There should not have been a document returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('firstByContains() fails')]
|
||||||
|
public function testFirstByContainsFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Find::firstByContains('', [], TestDocument::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('firstByJsonPath() fails')]
|
||||||
|
public function testFirstByJsonPathFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Find::firstByJsonPath('', '', TestDocument::class);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,8 +1,14 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
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;
|
||||||
|
@ -28,33 +34,48 @@ class PatchTest extends TestCase
|
||||||
parent::tearDown();
|
parent::tearDown();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By ID succeeds when a document is updated')]
|
#[TestDox('byId() succeeds when a document is updated')]
|
||||||
public function testByIdSucceedsWhenADocumentIsUpdated(): void
|
public function testByIdSucceedsWhenADocumentIsUpdated(): void
|
||||||
{
|
{
|
||||||
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->isSome, 'There should have been a document returned');
|
||||||
$this->assertEquals(44, $doc->num_value, 'The updated document is not correct');
|
$this->assertEquals(44, $doc->value->num_value, 'The updated document is not correct');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By ID succeeds when no document is updated')]
|
#[TestDox('byId() succeeds when no document is updated')]
|
||||||
public function testByIdSucceedsWhenNoDocumentIsUpdated(): void
|
public function testByIdSucceedsWhenNoDocumentIsUpdated(): void
|
||||||
{
|
{
|
||||||
Patch::byId(ThrowawayDb::TABLE, 'forty-seven', ['foo' => 'green']);
|
Patch::byId(ThrowawayDb::TABLE, 'forty-seven', ['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');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds when a document is updated')]
|
||||||
public function testByFieldsSucceedsWhenADocumentIsUpdated(): void
|
public function testByFieldsSucceedsWhenADocumentIsUpdated(): void
|
||||||
{
|
{
|
||||||
Patch::byFields(ThrowawayDb::TABLE, [Field::EQ('value', 'purple')], ['num_value' => 77]);
|
Patch::byFields(ThrowawayDb::TABLE, [Field::equal('value', 'purple')], ['num_value' => 77]);
|
||||||
$after = Count::byFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 77)]);
|
$after = Count::byFields(ThrowawayDb::TABLE, [Field::equal('num_value', 77)]);
|
||||||
$this->assertEquals(2, $after, 'There should have been 2 documents updated');
|
$this->assertEquals(2, $after, 'There should have been 2 documents updated');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds when no document is updated')]
|
||||||
public function testByFieldsSucceedsWhenNoDocumentIsUpdated(): void
|
public function testByFieldsSucceedsWhenNoDocumentIsUpdated(): void
|
||||||
{
|
{
|
||||||
Patch::byFields(ThrowawayDb::TABLE, [Field::EQ('value', 'burgundy')], ['foo' => 'green']);
|
Patch::byFields(ThrowawayDb::TABLE, [Field::equal('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');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('byContains() fails')]
|
||||||
|
public function testByContainsFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Patch::byContains('', [], []);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byJsonPath() fails')]
|
||||||
|
public function testByJsonPathFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Patch::byJsonPath('', '', []);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,8 +1,14 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
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;
|
||||||
|
@ -28,47 +34,65 @@ class RemoveFieldsTest extends TestCase
|
||||||
parent::tearDown();
|
parent::tearDown();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By ID succeeds when fields are removed')]
|
#[TestDox('byId() succeeds when fields are removed')]
|
||||||
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->isSome, 'There should have been a document returned');
|
||||||
|
$doc = $tryDoc->value;
|
||||||
$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');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By ID succeeds when a field is not removed')]
|
#[TestDox('byId() succeeds when a field is not removed')]
|
||||||
public function testByIdSucceedsWhenAFieldIsNotRemoved(): void
|
public function testByIdSucceedsWhenAFieldIsNotRemoved(): void
|
||||||
{
|
{
|
||||||
RemoveFields::byId(ThrowawayDb::TABLE, 'one', ['a_field_that_does_not_exist']);
|
RemoveFields::byId(ThrowawayDb::TABLE, 'one', ['a_field_that_does_not_exist']);
|
||||||
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By ID succeeds when no document is matched')]
|
#[TestDox('byId() succeeds when no document is matched')]
|
||||||
public function testByIdSucceedsWhenNoDocumentIsMatched(): void
|
public function testByIdSucceedsWhenNoDocumentIsMatched(): void
|
||||||
{
|
{
|
||||||
RemoveFields::byId(ThrowawayDb::TABLE, 'fifty', ['sub']);
|
RemoveFields::byId(ThrowawayDb::TABLE, 'fifty', ['sub']);
|
||||||
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds when a field is removed')]
|
||||||
public function testByFieldsSucceedsWhenAFieldIsRemoved(): void
|
public function testByFieldsSucceedsWhenAFieldIsRemoved(): void
|
||||||
{
|
{
|
||||||
RemoveFields::byFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 17)], ['sub']);
|
RemoveFields::byFields(ThrowawayDb::TABLE, [Field::equal('num_value', 17)], ['sub']);
|
||||||
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 17)], TestDocument::class);
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 17)], TestDocument::class);
|
||||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
$this->assertTrue($doc->isSome, 'There should have been a document returned');
|
||||||
$this->assertNull($doc->sub, 'Sub-document should have been null');
|
$this->assertNull($doc->value->sub, 'Sub-document should have been null');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds when a field is not removed')]
|
||||||
public function testByFieldsSucceedsWhenAFieldIsNotRemoved(): void
|
public function testByFieldsSucceedsWhenAFieldIsNotRemoved(): void
|
||||||
{
|
{
|
||||||
RemoveFields::byFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 17)], ['nada']);
|
RemoveFields::byFields(ThrowawayDb::TABLE, [Field::equal('num_value', 17)], ['nada']);
|
||||||
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds when no document is matched')]
|
||||||
public function testByFieldsSucceedsWhenNoDocumentIsMatched(): void
|
public function testByFieldsSucceedsWhenNoDocumentIsMatched(): void
|
||||||
{
|
{
|
||||||
RemoveFields::byFields(ThrowawayDb::TABLE, [Field::NE('missing', 'nope')], ['value']);
|
RemoveFields::byFields(ThrowawayDb::TABLE, [Field::notEqual('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');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('byContains() fails')]
|
||||||
|
public function testByContainsFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
RemoveFields::byContains('', [], []);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byJsonPath() fails')]
|
||||||
|
public function testByJsonPathFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
RemoveFields::byJsonPath('', '', []);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,14 +1,17 @@
|
||||||
<?php
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
* @see https://github.com/Zaid-Ajaj/ThrowawayDb The origin concept
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Test\Integration\SQLite;
|
namespace Test\Integration\SQLite;
|
||||||
|
|
||||||
use BitBadger\PDODocument\Configuration;
|
use BitBadger\PDODocument\{AutoId, Configuration, Definition, Document, DocumentException};
|
||||||
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,20 +19,19 @@ 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::useDSN("sqlite:./$fileName");
|
||||||
Configuration::$mode = Mode::SQLite;
|
|
||||||
Configuration::resetPDO();
|
Configuration::resetPDO();
|
||||||
|
|
||||||
if ($withData) {
|
if ($withData) {
|
||||||
|
@ -52,20 +54,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);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,24 +1,31 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
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 default succeeds')]
|
||||||
public function testIdFieldDefaultSucceeds(): void
|
public function testIdFieldDefaultSucceeds(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals('id', Configuration::$idField, 'Default ID field should be "id"');
|
$this->assertEquals('id', Configuration::$idField, 'Default ID field should be "id"');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('ID field change succeeds')]
|
#[TestDox('id change succeeds')]
|
||||||
public function testIdFieldChangeSucceeds()
|
public function testIdFieldChangeSucceeds(): void
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
Configuration::$idField = 'EyeDee';
|
Configuration::$idField = 'EyeDee';
|
||||||
|
@ -29,11 +36,23 @@ class ConfigurationTest extends TestCase
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox("Db conn fails when no DSN specified")]
|
#[TestDox('autoId default succeeds')]
|
||||||
|
public function testAutoIdDefaultSucceeds(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(AutoId::None, Configuration::$autoId, 'Auto ID should default to None');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('idStringLength default succeeds')]
|
||||||
|
public function testIdStringLengthDefaultSucceeds(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(16, Configuration::$idStringLength, 'ID string length should default to 16');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox("dbConn() fails when no DSN specified")]
|
||||||
public function testDbConnFailsWhenNoDSNSpecified(): void
|
public function testDbConnFailsWhenNoDSNSpecified(): void
|
||||||
{
|
{
|
||||||
$this->expectException(DocumentException::class);
|
$this->expectException(DocumentException::class);
|
||||||
Configuration::$pdoDSN = '';
|
Configuration::useDSN('');
|
||||||
Configuration::dbConn();
|
Configuration::dbConn();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,17 +1,25 @@
|
||||||
<?php
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Test\Unit;
|
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(): void
|
||||||
{
|
{
|
||||||
$priorEx = new Exception('Uh oh');
|
$priorEx = new Exception('Uh oh');
|
||||||
$ex = new DocumentException('Test Exception', 17, $priorEx);
|
$ex = new DocumentException('Test Exception', 17, $priorEx);
|
||||||
|
@ -21,7 +29,7 @@ class DocumentExceptionTest extends TestCase
|
||||||
$this->assertSame($priorEx, $ex->getPrevious(), 'Prior exception not filled properly');
|
$this->assertSame($priorEx, $ex->getPrevious(), 'Prior exception not filled properly');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testConstructorSucceedsWithoutCodeAndPriorException()
|
public function testConstructorSucceedsWithoutCodeAndPriorException(): void
|
||||||
{
|
{
|
||||||
$ex = new DocumentException('Oops');
|
$ex = new DocumentException('Oops');
|
||||||
$this->assertNotNull($ex, 'The exception should not have been null');
|
$this->assertNotNull($ex, 'The exception should not have been null');
|
||||||
|
@ -30,14 +38,16 @@ class DocumentExceptionTest extends TestCase
|
||||||
$this->assertNull($ex->getPrevious(), 'Prior exception should have been null');
|
$this->assertNull($ex->getPrevious(), 'Prior exception should have been null');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testToStringSucceedsWithoutCode()
|
#[TestDox('toString() succeeds without code')]
|
||||||
|
public function testToStringSucceedsWithoutCode(): void
|
||||||
{
|
{
|
||||||
$ex = new DocumentException('Test failure');
|
$ex = new DocumentException('Test failure');
|
||||||
$this->assertEquals("BitBadger\PDODocument\DocumentException: Test failure\n", "$ex",
|
$this->assertEquals("BitBadger\PDODocument\DocumentException: Test failure\n", "$ex",
|
||||||
'toString not generated correctly');
|
'toString not generated correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testToStringSucceedsWithCode()
|
#[TestDox('toString() succeeds with code')]
|
||||||
|
public function testToStringSucceedsWithCode(): void
|
||||||
{
|
{
|
||||||
$ex = new DocumentException('Oof', -6);
|
$ex = new DocumentException('Oof', -6);
|
||||||
$this->assertEquals("BitBadger\PDODocument\DocumentException: [-6] Oof\n", "$ex",
|
$this->assertEquals("BitBadger\PDODocument\DocumentException: [-6] Oof\n", "$ex",
|
||||||
|
|
32
tests/unit/FieldMatchTest.php
Normal file
32
tests/unit/FieldMatchTest.php
Normal file
|
@ -0,0 +1,32 @@
|
||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
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
|
||||||
|
{
|
||||||
|
#[TestDox('toSQL() succeeds for All')]
|
||||||
|
public function testToSQLSucceedsForAll(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals('AND', FieldMatch::All->toSQL(), 'All should have returned AND');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('toSQL() succeeds for Any')]
|
||||||
|
public function testToSQLSucceedsForAny(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals('OR', FieldMatch::Any->toSQL(), 'Any should have returned OR');
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,4 +1,10 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Test\Unit;
|
namespace Test\Unit;
|
||||||
|
|
||||||
|
@ -9,437 +15,668 @@ 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('appendParameter() succeeds for exists')]
|
||||||
public function testAppendParameterSucceedsForEX(): void
|
public function testAppendParameterSucceedsForExists(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals([], Field::EX('exists')->appendParameter([]), 'EX should not have appended a parameter');
|
$this->assertEquals([], Field::exists('exists')->appendParameter([]),
|
||||||
|
'exists should not have appended a parameter');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('Append parameter succeeds for NEX')]
|
#[TestDox('appendParameter() succeeds for notExists')]
|
||||||
public function testAppendParameterSucceedsForNEX(): void
|
public function testAppendParameterSucceedsForNotExists(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals([], Field::NEX('absent')->appendParameter([]), 'NEX should not have appended a parameter');
|
$this->assertEquals([], Field::notExists('absent')->appendParameter([]),
|
||||||
|
'notExists should not have appended a parameter');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('Append parameter succeeds for BT')]
|
#[TestDox('appendParameter() succeeds for between')]
|
||||||
public function testAppendParameterSucceedsForBT(): void
|
public function testAppendParameterSucceedsForBetween(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals(['@nummin' => 5, '@nummax' => 9], Field::BT('exists', 5, 9, '@num')->appendParameter([]),
|
$this->assertEquals(['@nummin' => 5, '@nummax' => 9],
|
||||||
'BT should have appended min and max parameters');
|
Field::between('exists', 5, 9, '@num')->appendParameter([]),
|
||||||
|
'Between should have appended min and max parameters');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('appendParameter() succeeds for in')]
|
||||||
|
public function testAppendParameterSucceedsForIn(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals([':val_0' => 'test', ':val_1' => 'unit', ':val_2' => 'great'],
|
||||||
|
Field::in('it', ['test', 'unit', 'great'], ':val')->appendParameter([]),
|
||||||
|
'In should have appended 3 parameters for the input values');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('appendParameter() succeeds for inArray for PostgreSQL')]
|
||||||
|
public function testAppendParameterSucceedsForInArrayForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
try {
|
||||||
|
$this->assertEquals([':bit_0' => '2', ':bit_1' => '8', ':bit_2' => '64'],
|
||||||
|
Field::inArray('it', 'table', [2, 8, 64], ':bit')->appendParameter([]),
|
||||||
|
'InArray should have appended 3 string parameters for the input values');
|
||||||
|
} finally {
|
||||||
|
Configuration::overrideMode(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('appendParameter() succeeds for inArray for SQLite')]
|
||||||
|
public function testAppendParameterSucceedsForInArrayForSQLite(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::SQLite);
|
||||||
|
try {
|
||||||
|
$this->assertEquals([':bit_0' => 2, ':bit_1' => 8, ':bit_2' => 64],
|
||||||
|
Field::inArray('it', 'table', [2, 8, 64], ':bit')->appendParameter([]),
|
||||||
|
'InArray should have appended 3 parameters for the input values');
|
||||||
|
} finally {
|
||||||
|
Configuration::overrideMode(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('appendParameter() succeeds for others')]
|
||||||
public function testAppendParameterSucceedsForOthers(): void
|
public function testAppendParameterSucceedsForOthers(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals(['@test' => 33], Field::EQ('the_field', 33, '@test')->appendParameter([]),
|
$this->assertEquals(['@test' => 33], Field::equal('the_field', 33, '@test')->appendParameter([]),
|
||||||
'Field parameter not returned correctly');
|
'Field parameter not returned correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('To where succeeds for EX without qualifier for PostgreSQL')]
|
#[TestDox('path() succeeds for simple SQL path for PostgreSQL')]
|
||||||
public function testToWhereSucceedsForEXWithoutQualifierForPostgreSQL(): void
|
public function testPathSucceedsForSimpleSqlPathForPostgreSQL(): void
|
||||||
{
|
{
|
||||||
Configuration::$mode = Mode::PgSQL;
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
try {
|
try {
|
||||||
$this->assertEquals("data->>'that_field' IS NOT NULL", Field::EX('that_field')->toWhere(),
|
$this->assertEquals("data->>'it'", Field::equal('it', 'that')->path(),
|
||||||
'WHERE fragment not generated correctly');
|
'SQL value path not generated correctly');
|
||||||
} finally {
|
} finally {
|
||||||
Configuration::$mode = null;
|
Configuration::overrideMode(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('To where succeeds for EX without qualifier for SQLite')]
|
#[TestDox('path() succeeds for simple SQL path for SQLite')]
|
||||||
public function testToWhereSucceedsForEXWithoutQualifierForSQLite(): void
|
public function testPathSucceedsForSimpleSqlPathForSQLite(): void
|
||||||
{
|
{
|
||||||
Configuration::$mode = Mode::SQLite;
|
Configuration::overrideMode(Mode::SQLite);
|
||||||
try {
|
try {
|
||||||
$this->assertEquals("data->>'that_field' IS NOT NULL", Field::EX('that_field')->toWhere(),
|
$this->assertEquals("data->>'top'", Field::equal('top', 'that')->path(),
|
||||||
'WHERE fragment not generated correctly');
|
'SQL value path not generated correctly');
|
||||||
} finally {
|
} finally {
|
||||||
Configuration::$mode = null;
|
Configuration::overrideMode(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('To where succeeds for NEX without qualifier for PostgreSQL')]
|
#[TestDox('path() succeeds for nested SQL path for PostgreSQL')]
|
||||||
public function testToWhereSucceedsForNEXWithoutQualifierForPostgreSQL(): void
|
public function testPathSucceedsForNestedSqlPathForPostgreSQL(): void
|
||||||
{
|
{
|
||||||
Configuration::$mode = Mode::PgSQL;
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
try {
|
try {
|
||||||
$this->assertEquals("data->>'a_field' IS NULL", Field::NEX('a_field')->toWhere(),
|
$this->assertEquals("data#>>'{parts,to,the,path}'", Field::equal('parts.to.the.path', '')->path(),
|
||||||
'WHERE fragment not generated correctly');
|
'SQL value path not generated correctly');
|
||||||
} finally {
|
} finally {
|
||||||
Configuration::$mode = null;
|
Configuration::overrideMode(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('To where succeeds for NEX without qualifier for SQLite')]
|
#[TestDox('path() succeeds for nested SQL path for SQLite')]
|
||||||
public function testToWhereSucceedsForNEXWithoutQualifierForSQLite(): void
|
public function testPathSucceedsForNestedSqlPathForSQLite(): void
|
||||||
{
|
{
|
||||||
Configuration::$mode = Mode::SQLite;
|
Configuration::overrideMode(Mode::SQLite);
|
||||||
try {
|
try {
|
||||||
$this->assertEquals("data->>'a_field' IS NULL", Field::NEX('a_field')->toWhere(),
|
$this->assertEquals("data->'one'->'two'->>'three'", Field::equal('one.two.three', '')->path(),
|
||||||
'WHERE fragment not generated correctly');
|
'SQL value path not generated correctly');
|
||||||
} finally {
|
} finally {
|
||||||
Configuration::$mode = null;
|
Configuration::overrideMode(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('To where succeeds for BT without qualifier for SQLite')]
|
#[TestDox('path() succeeds for simple JSON path for PostgreSQL')]
|
||||||
public function testToWhereSucceedsForBTWithoutQualifierForSQLite(): void
|
public function testPathSucceedsForSimpleJsonPathForPostgreSQL(): void
|
||||||
{
|
{
|
||||||
Configuration::$mode = Mode::SQLite;
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
try {
|
try {
|
||||||
$this->assertEquals("data->>'age' BETWEEN @agemin AND @agemax", Field::BT('age', 13, 17, '@age')->toWhere(),
|
$this->assertEquals("data->'it'", Field::equal('it', 'that')->path(true),
|
||||||
'WHERE fragment not generated correctly');
|
'JSON value path not generated correctly');
|
||||||
} finally {
|
} finally {
|
||||||
Configuration::$mode = null;
|
Configuration::overrideMode(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('To where succeeds for BT without qualifier for PostgreSQL with numeric range')]
|
#[TestDox('path() succeeds for simple JSON path for SQLite')]
|
||||||
public function testToWhereSucceedsForBTWithoutQualifierForPostgreSQLWithNumericRange(): void
|
public function testPathSucceedsForSimpleJsonPathForSQLite(): void
|
||||||
{
|
{
|
||||||
Configuration::$mode = Mode::PgSQL;
|
Configuration::overrideMode(Mode::SQLite);
|
||||||
|
try {
|
||||||
|
$this->assertEquals("data->'top'", Field::equal('top', 'that')->path(true),
|
||||||
|
'JSON value path not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::overrideMode(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('path() succeeds for nested JSON path for PostgreSQL')]
|
||||||
|
public function testPathSucceedsForNestedJsonPathForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
try {
|
||||||
|
$this->assertEquals("data#>'{parts,to,the,path}'", Field::equal('parts.to.the.path', '')->path(true),
|
||||||
|
'JSON value path not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::overrideMode(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('path() succeeds for nested JSON path for SQLite')]
|
||||||
|
public function testPathSucceedsForNestedJsonPathForSQLite(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::SQLite);
|
||||||
|
try {
|
||||||
|
$this->assertEquals("data->'one'->'two'->'three'", Field::equal('one.two.three', '')->path(true),
|
||||||
|
'SQL value path not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::overrideMode(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('toWhere() succeeds for exists without qualifier for PostgreSQL')]
|
||||||
|
public function testToWhereSucceedsForExistsWithoutQualifierForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
try {
|
||||||
|
$this->assertEquals("data->>'that_field' IS NOT NULL", Field::exists('that_field')->toWhere(),
|
||||||
|
'WHERE fragment not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::overrideMode(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('toWhere() succeeds for exists without qualifier for SQLite')]
|
||||||
|
public function testToWhereSucceedsForExistsWithoutQualifierForSQLite(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::SQLite);
|
||||||
|
try {
|
||||||
|
$this->assertEquals("data->>'that_field' IS NOT NULL", Field::exists('that_field')->toWhere(),
|
||||||
|
'WHERE fragment not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::overrideMode(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('toWhere() succeeds for notExists without qualifier for PostgreSQL')]
|
||||||
|
public function testToWhereSucceedsForNotExistsWithoutQualifierForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
try {
|
||||||
|
$this->assertEquals("data->>'a_field' IS NULL", Field::notExists('a_field')->toWhere(),
|
||||||
|
'WHERE fragment not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::overrideMode(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('toWhere() succeeds for notExists without qualifier for SQLite')]
|
||||||
|
public function testToWhereSucceedsForNotExistsWithoutQualifierForSQLite(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::SQLite);
|
||||||
|
try {
|
||||||
|
$this->assertEquals("data->>'a_field' IS NULL", Field::notExists('a_field')->toWhere(),
|
||||||
|
'WHERE fragment not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::overrideMode(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('toWhere() succeeds for between without qualifier for SQLite')]
|
||||||
|
public function testToWhereSucceedsForBetweenWithoutQualifierForSQLite(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::SQLite);
|
||||||
|
try {
|
||||||
|
$this->assertEquals("data->>'age' BETWEEN @agemin AND @agemax",
|
||||||
|
Field::between('age', 13, 17, '@age')->toWhere(), 'WHERE fragment not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::overrideMode(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('toWhere() succeeds for between without qualifier for PostgreSQL with numeric range')]
|
||||||
|
public function testToWhereSucceedsForBetweenWithoutQualifierForPostgreSQLWithNumericRange(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
try {
|
try {
|
||||||
$this->assertEquals("(data->>'age')::numeric BETWEEN @agemin AND @agemax",
|
$this->assertEquals("(data->>'age')::numeric BETWEEN @agemin AND @agemax",
|
||||||
Field::BT('age', 13, 17, '@age')->toWhere(), 'WHERE fragment not generated correctly');
|
Field::between('age', 13, 17, '@age')->toWhere(), 'WHERE fragment not generated correctly');
|
||||||
} finally {
|
} finally {
|
||||||
Configuration::$mode = null;
|
Configuration::overrideMode(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('To where succeeds for BT without qualifier for PostgreSQL with non-numeric range')]
|
#[TestDox('toWhere() succeeds for between without qualifier for PostgreSQL with non-numeric range')]
|
||||||
public function testToWhereSucceedsForBTWithoutQualifierForPostgreSQLWithNonNumericRange(): void
|
public function testToWhereSucceedsForBetweenWithoutQualifierForPostgreSQLWithNonNumericRange(): void
|
||||||
{
|
{
|
||||||
Configuration::$mode = Mode::PgSQL;
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
try {
|
try {
|
||||||
$this->assertEquals("data->>'city' BETWEEN :citymin AND :citymax",
|
$this->assertEquals("data->>'city' BETWEEN :citymin AND :citymax",
|
||||||
Field::BT('city', 'Atlanta', 'Chicago', ':city')->toWhere(), 'WHERE fragment not generated correctly');
|
Field::between('city', 'Atlanta', 'Chicago', ':city')->toWhere(),
|
||||||
|
'WHERE fragment not generated correctly');
|
||||||
} finally {
|
} finally {
|
||||||
Configuration::$mode = null;
|
Configuration::overrideMode(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('To where succeeds for BT with qualifier for SQLite')]
|
#[TestDox('toWhere() succeeds for between with qualifier for SQLite')]
|
||||||
public function testToWhereSucceedsForBTWithQualifierForSQLite(): void
|
public function testToWhereSucceedsForBetweenWithQualifierForSQLite(): void
|
||||||
{
|
{
|
||||||
Configuration::$mode = Mode::SQLite;
|
Configuration::overrideMode(Mode::SQLite);
|
||||||
try {
|
try {
|
||||||
$field = Field::BT('age', 13, 17, '@age');
|
$field = Field::between('age', 13, 17, '@age');
|
||||||
$field->qualifier = 'me';
|
$field->qualifier = 'me';
|
||||||
$this->assertEquals("me.data->>'age' BETWEEN @agemin AND @agemax", $field->toWhere(),
|
$this->assertEquals("me.data->>'age' BETWEEN @agemin AND @agemax", $field->toWhere(),
|
||||||
'WHERE fragment not generated correctly');
|
'WHERE fragment not generated correctly');
|
||||||
} finally {
|
} finally {
|
||||||
Configuration::$mode = null;
|
Configuration::overrideMode(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('To where succeeds for BT with qualifier for PostgreSQL with numeric range')]
|
#[TestDox('toWhere() succeeds for between with qualifier for PostgreSQL with numeric range')]
|
||||||
public function testToWhereSucceedsForBTWithQualifierForPostgreSQLWithNumericRange(): void
|
public function testToWhereSucceedsForBetweenWithQualifierForPostgreSQLWithNumericRange(): void
|
||||||
{
|
{
|
||||||
Configuration::$mode = Mode::PgSQL;
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
try {
|
try {
|
||||||
$field = Field::BT('age', 13, 17, '@age');
|
$field = Field::between('age', 13, 17, '@age');
|
||||||
$field->qualifier = 'me';
|
$field->qualifier = 'me';
|
||||||
$this->assertEquals("(me.data->>'age')::numeric BETWEEN @agemin AND @agemax", $field->toWhere(),
|
$this->assertEquals("(me.data->>'age')::numeric BETWEEN @agemin AND @agemax", $field->toWhere(),
|
||||||
'WHERE fragment not generated correctly');
|
'WHERE fragment not generated correctly');
|
||||||
} finally {
|
} finally {
|
||||||
Configuration::$mode = null;
|
Configuration::overrideMode(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('To where succeeds for BT with qualifier for PostgreSQL with non-numeric range')]
|
#[TestDox('toWhere() succeeds for between with qualifier for PostgreSQL with non-numeric range')]
|
||||||
public function testToWhereSucceedsForBTWithQualifierForPostgreSQLWithNonNumericRange(): void
|
public function testToWhereSucceedsForBetweenWithQualifierForPostgreSQLWithNonNumericRange(): void
|
||||||
{
|
{
|
||||||
Configuration::$mode = Mode::PgSQL;
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
try {
|
try {
|
||||||
$field = Field::BT('city', 'Atlanta', 'Chicago', ':city');
|
$field = Field::between('city', 'Atlanta', 'Chicago', ':city');
|
||||||
$field->qualifier = 'me';
|
$field->qualifier = 'me';
|
||||||
$this->assertEquals("me.data->>'city' BETWEEN :citymin AND :citymax", $field->toWhere(),
|
$this->assertEquals("me.data->>'city' BETWEEN :citymin AND :citymax", $field->toWhere(),
|
||||||
'WHERE fragment not generated correctly');
|
'WHERE fragment not generated correctly');
|
||||||
} finally {
|
} finally {
|
||||||
Configuration::$mode = null;
|
Configuration::overrideMode(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('To where succeeds for others without qualifier for PostgreSQL')]
|
#[TestDox('toWhere() succeeds for in for PostgreSQL with non-numeric values')]
|
||||||
|
public function testToWhereSucceedsForInForPostgreSQLWithNonNumericValues(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
try {
|
||||||
|
$field = Field::in('test', ['Atlanta', 'Chicago'], ':city');
|
||||||
|
$this->assertEquals("data->>'test' IN (:city_0, :city_1)", $field->toWhere(),
|
||||||
|
'WHERE fragment not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::overrideMode(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('toWhere() succeeds for in for PostgreSQL with numeric values')]
|
||||||
|
public function testToWhereSucceedsForInForPostgreSQLWithNumericValues(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
try {
|
||||||
|
$field = Field::in('even', [2, 4, 6], ':nbr');
|
||||||
|
$this->assertEquals("(data->>'even')::numeric IN (:nbr_0, :nbr_1, :nbr_2)", $field->toWhere(),
|
||||||
|
'WHERE fragment not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::overrideMode(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('toWhere() succeeds for in for SQLite')]
|
||||||
|
public function testToWhereSucceedsForInForSQLite(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::SQLite);
|
||||||
|
try {
|
||||||
|
$field = Field::in('test', ['Atlanta', 'Chicago'], ':city');
|
||||||
|
$this->assertEquals("data->>'test' IN (:city_0, :city_1)", $field->toWhere(),
|
||||||
|
'WHERE fragment not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::overrideMode(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('toWhere() succeeds for inArray for PostgreSQL')]
|
||||||
|
public function testToWhereSucceedsForInArrayForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
try {
|
||||||
|
$field = Field::inArray('even', 'tbl', [2, 4, 6, 8], ':it');
|
||||||
|
$this->assertEquals("data->'even' ??| ARRAY[:it_0, :it_1, :it_2, :it_3]", $field->toWhere(),
|
||||||
|
'WHERE fragment not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::overrideMode(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('toWhere() succeeds for inArray for SQLite')]
|
||||||
|
public function testToWhereSucceedsForInArrayForSQLite(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::SQLite);
|
||||||
|
try {
|
||||||
|
$field = Field::inArray('test', 'tbl', ['Atlanta', 'Chicago'], ':city');
|
||||||
|
$this->assertEquals(
|
||||||
|
"EXISTS (SELECT 1 FROM json_each(tbl.data, '\$.test') WHERE value IN (:city_0, :city_1))",
|
||||||
|
$field->toWhere(), 'WHERE fragment not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::overrideMode(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('toWhere() succeeds for others without qualifier for PostgreSQL')]
|
||||||
public function testToWhereSucceedsForOthersWithoutQualifierForPostgreSQL(): void
|
public function testToWhereSucceedsForOthersWithoutQualifierForPostgreSQL(): void
|
||||||
{
|
{
|
||||||
Configuration::$mode = Mode::PgSQL;
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
try {
|
try {
|
||||||
$this->assertEquals("data->>'some_field' = @value", Field::EQ('some_field', '', '@value')->toWhere(),
|
$this->assertEquals("data->>'some_field' = @value", Field::equal('some_field', '', '@value')->toWhere(),
|
||||||
'WHERE fragment not generated correctly');
|
'WHERE fragment not generated correctly');
|
||||||
} finally {
|
} finally {
|
||||||
Configuration::$mode = null;
|
Configuration::overrideMode(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('To where succeeds for others without qualifier for SQLite')]
|
#[TestDox('toWhere() succeeds for others without qualifier for SQLite')]
|
||||||
public function testToWhereSucceedsForOthersWithoutQualifierForSQLite(): void
|
public function testToWhereSucceedsForOthersWithoutQualifierForSQLite(): void
|
||||||
{
|
{
|
||||||
Configuration::$mode = Mode::SQLite;
|
Configuration::overrideMode(Mode::SQLite);
|
||||||
try {
|
try {
|
||||||
$this->assertEquals("data->>'some_field' = @value", Field::EQ('some_field', '', '@value')->toWhere(),
|
$this->assertEquals("data->>'some_field' = @value", Field::equal('some_field', '', '@value')->toWhere(),
|
||||||
'WHERE fragment not generated correctly');
|
'WHERE fragment not generated correctly');
|
||||||
} finally {
|
} finally {
|
||||||
Configuration::$mode = null;
|
Configuration::overrideMode(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('To where succeeds with qualifier no parameter for PostgreSQL')]
|
#[TestDox('toWhere() succeeds with qualifier no parameter for PostgreSQL')]
|
||||||
public function testToWhereSucceedsWithQualifierNoParameterForPostgreSQL(): void
|
public function testToWhereSucceedsWithQualifierNoParameterForPostgreSQL(): void
|
||||||
{
|
{
|
||||||
Configuration::$mode = Mode::PgSQL;
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
try {
|
try {
|
||||||
$field = Field::EX('no_field');
|
$field = Field::exists('no_field');
|
||||||
$field->qualifier = 'test';
|
$field->qualifier = 'test';
|
||||||
$this->assertEquals("test.data->>'no_field' IS NOT NULL", $field->toWhere(),
|
$this->assertEquals("test.data->>'no_field' IS NOT NULL", $field->toWhere(),
|
||||||
'WHERE fragment not generated correctly');
|
'WHERE fragment not generated correctly');
|
||||||
} finally {
|
} finally {
|
||||||
Configuration::$mode = null;
|
Configuration::overrideMode(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('To where succeeds with qualifier no parameter for SQLite')]
|
#[TestDox('toWhere() succeeds with qualifier no parameter for SQLite')]
|
||||||
public function testToWhereSucceedsWithQualifierNoParameterForSQLite(): void
|
public function testToWhereSucceedsWithQualifierNoParameterForSQLite(): void
|
||||||
{
|
{
|
||||||
Configuration::$mode = Mode::SQLite;
|
Configuration::overrideMode(Mode::SQLite);
|
||||||
try {
|
try {
|
||||||
$field = Field::EX('no_field');
|
$field = Field::exists('no_field');
|
||||||
$field->qualifier = 'test';
|
$field->qualifier = 'test';
|
||||||
$this->assertEquals("test.data->>'no_field' IS NOT NULL", $field->toWhere(),
|
$this->assertEquals("test.data->>'no_field' IS NOT NULL", $field->toWhere(),
|
||||||
'WHERE fragment not generated correctly');
|
'WHERE fragment not generated correctly');
|
||||||
} finally {
|
} finally {
|
||||||
Configuration::$mode = null;
|
Configuration::overrideMode(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('To where succeeds with qualifier and parameter for PostgreSQL')]
|
#[TestDox('toWhere() succeeds with qualifier and parameter for PostgreSQL')]
|
||||||
public function testToWhereSucceedsWithQualifierAndParameterForPostgreSQL(): void
|
public function testToWhereSucceedsWithQualifierAndParameterForPostgreSQL(): void
|
||||||
{
|
{
|
||||||
Configuration::$mode = Mode::PgSQL;
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
try {
|
try {
|
||||||
$field = Field::LE('le_field', 18, '@it');
|
$field = Field::lessOrEqual('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::overrideMode(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('To where succeeds with qualifier and parameter for SQLite')]
|
#[TestDox('toWhere() succeeds with qualifier and parameter for SQLite')]
|
||||||
public function testToWhereSucceedsWithQualifierAndParameterForSQLite(): void
|
public function testToWhereSucceedsWithQualifierAndParameterForSQLite(): void
|
||||||
{
|
{
|
||||||
Configuration::$mode = Mode::SQLite;
|
Configuration::overrideMode(Mode::SQLite);
|
||||||
try {
|
try {
|
||||||
$field = Field::LE('le_field', 18, '@it');
|
$field = Field::lessOrEqual('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' <= @it", $field->toWhere(),
|
||||||
'WHERE fragment not generated correctly');
|
'WHERE fragment not generated correctly');
|
||||||
} finally {
|
} finally {
|
||||||
Configuration::$mode = null;
|
Configuration::overrideMode(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('To where succeeds with sub-document for PostgreSQL')]
|
#[TestDox('equal() succeeds without parameter')]
|
||||||
public function testToWhereSucceedsWithSubDocumentForPostgreSQL(): void
|
public function testEqualSucceedsWithoutParameter(): void
|
||||||
{
|
{
|
||||||
Configuration::$mode = Mode::PgSQL;
|
$field = Field::equal('my_test', 9);
|
||||||
try {
|
|
||||||
$field = Field::EQ('sub.foo.bar', 22, '@it');
|
|
||||||
$this->assertEquals("data->>'sub.foo.bar' = @it", $field->toWhere(),
|
|
||||||
'WHERE fragment not generated correctly');
|
|
||||||
} finally {
|
|
||||||
Configuration::$mode = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[TestDox('To where succeeds with sub-document for SQLite')]
|
|
||||||
public function testToWhereSucceedsWithSubDocumentForSQLite(): void
|
|
||||||
{
|
|
||||||
Configuration::$mode = Mode::SQLite;
|
|
||||||
try {
|
|
||||||
$field = Field::EQ('sub.foo.bar', 22, '@it');
|
|
||||||
$this->assertEquals("data->>'sub'->>'foo'->>'bar' = @it", $field->toWhere(),
|
|
||||||
'WHERE fragment not generated correctly');
|
|
||||||
} finally {
|
|
||||||
Configuration::$mode = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[TestDox('EQ succeeds without parameter')]
|
|
||||||
public function testEQSucceedsWithoutParameter(): void
|
|
||||||
{
|
|
||||||
$field = Field::EQ('my_test', 9);
|
|
||||||
$this->assertNotNull($field, 'The field should not have been null');
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
$this->assertEquals('my_test', $field->fieldName, 'Field name not filled correctly');
|
$this->assertEquals('my_test', $field->fieldName, 'Field name not filled correctly');
|
||||||
$this->assertEquals(Op::EQ, $field->op, 'Operation not filled correctly');
|
$this->assertEquals(Op::Equal, $field->op, 'Operation not filled correctly');
|
||||||
$this->assertEquals(9, $field->value, 'Value not filled correctly');
|
$this->assertEquals(9, $field->value, 'Value not filled correctly');
|
||||||
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('EQ succeeds with parameter')]
|
#[TestDox('equal() succeeds with parameter')]
|
||||||
public function testEQSucceedsWithParameter(): void
|
public function testEqualSucceedsWithParameter(): void
|
||||||
{
|
{
|
||||||
$field = Field::EQ('another_test', 'turkey', '@test');
|
$field = Field::equal('another_test', 'turkey', '@test');
|
||||||
$this->assertNotNull($field, 'The field should not have been null');
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
$this->assertEquals('another_test', $field->fieldName, 'Field name not filled correctly');
|
$this->assertEquals('another_test', $field->fieldName, 'Field name not filled correctly');
|
||||||
$this->assertEquals(Op::EQ, $field->op, 'Operation not filled correctly');
|
$this->assertEquals(Op::Equal, $field->op, 'Operation not filled correctly');
|
||||||
$this->assertEquals('turkey', $field->value, 'Value not filled correctly');
|
$this->assertEquals('turkey', $field->value, 'Value not filled correctly');
|
||||||
$this->assertEquals('@test', $field->paramName, 'Parameter name not filled correctly');
|
$this->assertEquals('@test', $field->paramName, 'Parameter name not filled correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('GT succeeds without parameter')]
|
#[TestDox('greater() succeeds without parameter')]
|
||||||
public function testGTSucceedsWithoutParameter(): void
|
public function testGreaterSucceedsWithoutParameter(): void
|
||||||
{
|
{
|
||||||
$field = Field::GT('your_test', 4);
|
$field = Field::greater('your_test', 4);
|
||||||
$this->assertNotNull($field, 'The field should not have been null');
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
$this->assertEquals('your_test', $field->fieldName, 'Field name not filled correctly');
|
$this->assertEquals('your_test', $field->fieldName, 'Field name not filled correctly');
|
||||||
$this->assertEquals(Op::GT, $field->op, 'Operation not filled correctly');
|
$this->assertEquals(Op::Greater, $field->op, 'Operation not filled correctly');
|
||||||
$this->assertEquals(4, $field->value, 'Value not filled correctly');
|
$this->assertEquals(4, $field->value, 'Value not filled correctly');
|
||||||
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('GT succeeds with parameter')]
|
#[TestDox('greater() succeeds with parameter')]
|
||||||
public function testGTSucceedsWithParameter(): void
|
public function testGreaterSucceedsWithParameter(): void
|
||||||
{
|
{
|
||||||
$field = Field::GT('more_test', 'chicken', '@value');
|
$field = Field::greater('more_test', 'chicken', '@value');
|
||||||
$this->assertNotNull($field, 'The field should not have been null');
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
$this->assertEquals('more_test', $field->fieldName, 'Field name not filled correctly');
|
$this->assertEquals('more_test', $field->fieldName, 'Field name not filled correctly');
|
||||||
$this->assertEquals(Op::GT, $field->op, 'Operation not filled correctly');
|
$this->assertEquals(Op::Greater, $field->op, 'Operation not filled correctly');
|
||||||
$this->assertEquals('chicken', $field->value, 'Value not filled correctly');
|
$this->assertEquals('chicken', $field->value, 'Value not filled correctly');
|
||||||
$this->assertEquals('@value', $field->paramName, 'Parameter name not filled correctly');
|
$this->assertEquals('@value', $field->paramName, 'Parameter name not filled correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('GE succeeds without parameter')]
|
#[TestDox('greaterOrEqual() succeeds without parameter')]
|
||||||
public function testGESucceedsWithoutParameter(): void
|
public function testGreaterOrEqualSucceedsWithoutParameter(): void
|
||||||
{
|
{
|
||||||
$field = Field::GE('their_test', 6);
|
$field = Field::greaterOrEqual('their_test', 6);
|
||||||
$this->assertNotNull($field, 'The field should not have been null');
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
$this->assertEquals('their_test', $field->fieldName, 'Field name not filled correctly');
|
$this->assertEquals('their_test', $field->fieldName, 'Field name not filled correctly');
|
||||||
$this->assertEquals(Op::GE, $field->op, 'Operation not filled correctly');
|
$this->assertEquals(Op::GreaterOrEqual, $field->op, 'Operation not filled correctly');
|
||||||
$this->assertEquals(6, $field->value, 'Value not filled correctly');
|
$this->assertEquals(6, $field->value, 'Value not filled correctly');
|
||||||
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('GE succeeds with parameter')]
|
#[TestDox('greaterOrEqual() succeeds with parameter')]
|
||||||
public function testGESucceedsWithParameter(): void
|
public function testGreaterOrEqualSucceedsWithParameter(): void
|
||||||
{
|
{
|
||||||
$field = Field::GE('greater_test', 'poultry', '@cluck');
|
$field = Field::greaterOrEqual('greater_test', 'poultry', '@cluck');
|
||||||
$this->assertNotNull($field, 'The field should not have been null');
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
$this->assertEquals('greater_test', $field->fieldName, 'Field name not filled correctly');
|
$this->assertEquals('greater_test', $field->fieldName, 'Field name not filled correctly');
|
||||||
$this->assertEquals(Op::GE, $field->op, 'Operation not filled correctly');
|
$this->assertEquals(Op::GreaterOrEqual, $field->op, 'Operation not filled correctly');
|
||||||
$this->assertEquals('poultry', $field->value, 'Value not filled correctly');
|
$this->assertEquals('poultry', $field->value, 'Value not filled correctly');
|
||||||
$this->assertEquals('@cluck', $field->paramName, 'Parameter name not filled correctly');
|
$this->assertEquals('@cluck', $field->paramName, 'Parameter name not filled correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('LT succeeds without parameter')]
|
#[TestDox('less() succeeds without parameter')]
|
||||||
public function testLTSucceedsWithoutParameter(): void
|
public function testLessSucceedsWithoutParameter(): void
|
||||||
{
|
{
|
||||||
$field = Field::LT('z', 32);
|
$field = Field::less('z', 32);
|
||||||
$this->assertNotNull($field, 'The field should not have been null');
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
$this->assertEquals('z', $field->fieldName, 'Field name not filled correctly');
|
$this->assertEquals('z', $field->fieldName, 'Field name not filled correctly');
|
||||||
$this->assertEquals(Op::LT, $field->op, 'Operation not filled correctly');
|
$this->assertEquals(Op::Less, $field->op, 'Operation not filled correctly');
|
||||||
$this->assertEquals(32, $field->value, 'Value not filled correctly');
|
$this->assertEquals(32, $field->value, 'Value not filled correctly');
|
||||||
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('LT succeeds with parameter')]
|
#[TestDox('less() succeeds with parameter')]
|
||||||
public function testLTSucceedsWithParameter(): void
|
public function testLessSucceedsWithParameter(): void
|
||||||
{
|
{
|
||||||
$field = Field::LT('additional_test', 'fowl', '@boo');
|
$field = Field::less('additional_test', 'fowl', '@boo');
|
||||||
$this->assertNotNull($field, 'The field should not have been null');
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
$this->assertEquals('additional_test', $field->fieldName, 'Field name not filled correctly');
|
$this->assertEquals('additional_test', $field->fieldName, 'Field name not filled correctly');
|
||||||
$this->assertEquals(Op::LT, $field->op, 'Operation not filled correctly');
|
$this->assertEquals(Op::Less, $field->op, 'Operation not filled correctly');
|
||||||
$this->assertEquals('fowl', $field->value, 'Value not filled correctly');
|
$this->assertEquals('fowl', $field->value, 'Value not filled correctly');
|
||||||
$this->assertEquals('@boo', $field->paramName, 'Parameter name not filled correctly');
|
$this->assertEquals('@boo', $field->paramName, 'Parameter name not filled correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('LE succeeds without parameter')]
|
#[TestDox('lessOrEqual() succeeds without parameter')]
|
||||||
public function testLESucceedsWithoutParameter(): void
|
public function testLessOrEqualSucceedsWithoutParameter(): void
|
||||||
{
|
{
|
||||||
$field = Field::LE('g', 87);
|
$field = Field::lessOrEqual('g', 87);
|
||||||
$this->assertNotNull($field, 'The field should not have been null');
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
$this->assertEquals('g', $field->fieldName, 'Field name not filled correctly');
|
$this->assertEquals('g', $field->fieldName, 'Field name not filled correctly');
|
||||||
$this->assertEquals(Op::LE, $field->op, 'Operation not filled correctly');
|
$this->assertEquals(Op::LessOrEqual, $field->op, 'Operation not filled correctly');
|
||||||
$this->assertEquals(87, $field->value, 'Value not filled correctly');
|
$this->assertEquals(87, $field->value, 'Value not filled correctly');
|
||||||
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('LE succeeds with parameter')]
|
#[TestDox('lessOrEqual() succeeds with parameter')]
|
||||||
public function testLESucceedsWithParameter(): void
|
public function testLessOrEqualSucceedsWithParameter(): void
|
||||||
{
|
{
|
||||||
$field = Field::LE('lesser_test', 'hen', '@woo');
|
$field = Field::lessOrEqual('lesser_test', 'hen', '@woo');
|
||||||
$this->assertNotNull($field, 'The field should not have been null');
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
$this->assertEquals('lesser_test', $field->fieldName, 'Field name not filled correctly');
|
$this->assertEquals('lesser_test', $field->fieldName, 'Field name not filled correctly');
|
||||||
$this->assertEquals(Op::LE, $field->op, 'Operation not filled correctly');
|
$this->assertEquals(Op::LessOrEqual, $field->op, 'Operation not filled correctly');
|
||||||
$this->assertEquals('hen', $field->value, 'Value not filled correctly');
|
$this->assertEquals('hen', $field->value, 'Value not filled correctly');
|
||||||
$this->assertEquals('@woo', $field->paramName, 'Parameter name not filled correctly');
|
$this->assertEquals('@woo', $field->paramName, 'Parameter name not filled correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('NE succeeds without parameter')]
|
#[TestDox('notEqual() succeeds without parameter')]
|
||||||
public function testNESucceedsWithoutParameter(): void
|
public function testNotEqualSucceedsWithoutParameter(): void
|
||||||
{
|
{
|
||||||
$field = Field::NE('j', 65);
|
$field = Field::notEqual('j', 65);
|
||||||
$this->assertNotNull($field, 'The field should not have been null');
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
$this->assertEquals('j', $field->fieldName, 'Field name not filled correctly');
|
$this->assertEquals('j', $field->fieldName, 'Field name not filled correctly');
|
||||||
$this->assertEquals(Op::NE, $field->op, 'Operation not filled correctly');
|
$this->assertEquals(Op::NotEqual, $field->op, 'Operation not filled correctly');
|
||||||
$this->assertEquals(65, $field->value, 'Value not filled correctly');
|
$this->assertEquals(65, $field->value, 'Value not filled correctly');
|
||||||
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('NE succeeds with parameter')]
|
#[TestDox('notEqual() succeeds with parameter')]
|
||||||
public function testNESucceedsWithParameter(): void
|
public function testNotEqualSucceedsWithParameter(): void
|
||||||
{
|
{
|
||||||
$field = Field::NE('unequal_test', 'egg', '@zoo');
|
$field = Field::notEqual('unequal_test', 'egg', '@zoo');
|
||||||
$this->assertNotNull($field, 'The field should not have been null');
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
$this->assertEquals('unequal_test', $field->fieldName, 'Field name not filled correctly');
|
$this->assertEquals('unequal_test', $field->fieldName, 'Field name not filled correctly');
|
||||||
$this->assertEquals(Op::NE, $field->op, 'Operation not filled correctly');
|
$this->assertEquals(Op::NotEqual, $field->op, 'Operation not filled correctly');
|
||||||
$this->assertEquals('egg', $field->value, 'Value not filled correctly');
|
$this->assertEquals('egg', $field->value, 'Value not filled correctly');
|
||||||
$this->assertEquals('@zoo', $field->paramName, 'Parameter name not filled correctly');
|
$this->assertEquals('@zoo', $field->paramName, 'Parameter name not filled correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('BT succeeds without parameter')]
|
#[TestDox('between() succeeds without parameter')]
|
||||||
public function testBTSucceedsWithoutParameter(): void
|
public function testBetweenSucceedsWithoutParameter(): void
|
||||||
{
|
{
|
||||||
$field = Field::BT('k', 'alpha', 'zed');
|
$field = Field::between('k', 'alpha', 'zed');
|
||||||
$this->assertNotNull($field, 'The field should not have been null');
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
$this->assertEquals('k', $field->fieldName, 'Field name not filled correctly');
|
$this->assertEquals('k', $field->fieldName, 'Field name not filled correctly');
|
||||||
$this->assertEquals(Op::BT, $field->op, 'Operation not filled correctly');
|
$this->assertEquals(Op::Between, $field->op, 'Operation not filled correctly');
|
||||||
$this->assertEquals(['alpha', 'zed'], $field->value, 'Value not filled correctly');
|
$this->assertEquals(['alpha', 'zed'], $field->value, 'Value not filled correctly');
|
||||||
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('BT succeeds with parameter')]
|
#[TestDox('between() succeeds with parameter')]
|
||||||
public function testBTSucceedsWithParameter(): void
|
public function testBetweenSucceedsWithParameter(): void
|
||||||
{
|
{
|
||||||
$field = Field::BT('between_test', 18, 49, '@count');
|
$field = Field::between('between_test', 18, 49, '@count');
|
||||||
$this->assertNotNull($field, 'The field should not have been null');
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
$this->assertEquals('between_test', $field->fieldName, 'Field name not filled correctly');
|
$this->assertEquals('between_test', $field->fieldName, 'Field name not filled correctly');
|
||||||
$this->assertEquals(Op::BT, $field->op, 'Operation not filled correctly');
|
$this->assertEquals(Op::Between, $field->op, 'Operation not filled correctly');
|
||||||
$this->assertEquals([18, 49], $field->value, 'Value not filled correctly');
|
$this->assertEquals([18, 49], $field->value, 'Value not filled correctly');
|
||||||
$this->assertEquals('@count', $field->paramName, 'Parameter name not filled correctly');
|
$this->assertEquals('@count', $field->paramName, 'Parameter name not filled correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('EX succeeds')]
|
#[TestDox('in() succeeds without parameter')]
|
||||||
public function testEXSucceeds(): void
|
public function testInSucceedsWithoutParameter(): void
|
||||||
{
|
{
|
||||||
$field = Field::EX('be_there');
|
$field = Field::in('test', [1, 2, 3]);
|
||||||
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
|
$this->assertEquals('test', $field->fieldName, 'Field name not filled correctly');
|
||||||
|
$this->assertEquals(Op::In, $field->op, 'Operation not filled correctly');
|
||||||
|
$this->assertEquals([1, 2, 3], $field->value, 'Value not filled correctly');
|
||||||
|
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('in() succeeds with parameter')]
|
||||||
|
public function testInSucceedsWithParameter(): void
|
||||||
|
{
|
||||||
|
$field = Field::in('unit', ['a', 'b'], '@inParam');
|
||||||
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
|
$this->assertEquals('unit', $field->fieldName, 'Field name not filled correctly');
|
||||||
|
$this->assertEquals(Op::In, $field->op, 'Operation not filled correctly');
|
||||||
|
$this->assertEquals(['a', 'b'], $field->value, 'Value not filled correctly');
|
||||||
|
$this->assertEquals('@inParam', $field->paramName, 'Parameter name not filled correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('inArray() succeeds without parameter')]
|
||||||
|
public function testInArraySucceedsWithoutParameter(): void
|
||||||
|
{
|
||||||
|
$field = Field::inArray('test', 'tbl', [1, 2, 3]);
|
||||||
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
|
$this->assertEquals('test', $field->fieldName, 'Field name not filled correctly');
|
||||||
|
$this->assertEquals(Op::InArray, $field->op, 'Operation not filled correctly');
|
||||||
|
$this->assertEquals(['table' => 'tbl', 'values' => [1, 2, 3]], $field->value, 'Value not filled correctly');
|
||||||
|
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('inArray() succeeds with parameter')]
|
||||||
|
public function testInArraySucceedsWithParameter(): void
|
||||||
|
{
|
||||||
|
$field = Field::inArray('unit', 'tab', ['a', 'b'], '@inAParam');
|
||||||
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
|
$this->assertEquals('unit', $field->fieldName, 'Field name not filled correctly');
|
||||||
|
$this->assertEquals(Op::InArray, $field->op, 'Operation not filled correctly');
|
||||||
|
$this->assertEquals(['table' => 'tab', 'values' => ['a', 'b']], $field->value, 'Value not filled correctly');
|
||||||
|
$this->assertEquals('@inAParam', $field->paramName, 'Parameter name not filled correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('exists() succeeds')]
|
||||||
|
public function testExistsSucceeds(): void
|
||||||
|
{
|
||||||
|
$field = Field::exists('be_there');
|
||||||
$this->assertNotNull($field, 'The field should not have been null');
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
$this->assertEquals('be_there', $field->fieldName, 'Field name not filled correctly');
|
$this->assertEquals('be_there', $field->fieldName, 'Field name not filled correctly');
|
||||||
$this->assertEquals(Op::EX, $field->op, 'Operation not filled correctly');
|
$this->assertEquals(Op::Exists, $field->op, 'Operation not filled correctly');
|
||||||
$this->assertEquals('', $field->value, 'Value should have been blank');
|
$this->assertEquals('', $field->value, 'Value should have been blank');
|
||||||
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('NEX succeeds')]
|
#[TestDox('notExists() succeeds')]
|
||||||
public function testNEXSucceeds(): void
|
public function testNotExistsSucceeds(): void
|
||||||
{
|
{
|
||||||
$field = Field::NEX('be_absent');
|
$field = Field::notExists('be_absent');
|
||||||
$this->assertNotNull($field, 'The field should not have been null');
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
$this->assertEquals('be_absent', $field->fieldName, 'Field name not filled correctly');
|
$this->assertEquals('be_absent', $field->fieldName, 'Field name not filled correctly');
|
||||||
$this->assertEquals(Op::NEX, $field->op, 'Operation not filled correctly');
|
$this->assertEquals(Op::NotExists, $field->op, 'Operation not filled correctly');
|
||||||
|
$this->assertEquals('', $field->value, 'Value should have been blank');
|
||||||
|
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('named() succeeds')]
|
||||||
|
public function testNamedSucceeds(): void
|
||||||
|
{
|
||||||
|
$field = Field::named('the_field');
|
||||||
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
|
$this->assertEquals('the_field', $field->fieldName, 'Field name not filled correctly');
|
||||||
|
$this->assertEquals(Op::Equal, $field->op, 'Operation not filled correctly');
|
||||||
$this->assertEquals('', $field->value, 'Value should have been blank');
|
$this->assertEquals('', $field->value, 'Value should have been blank');
|
||||||
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,19 +1,28 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
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
|
||||||
{
|
{
|
||||||
|
#[TestDox('map() succeeds')]
|
||||||
public function testMapSucceeds(): void
|
public function testMapSucceeds(): void
|
||||||
{
|
{
|
||||||
$result = ['one' => 2, 'three' => 4, 'eight' => 'five'];
|
$result = ['one' => 2, 'three' => 4, 'eight' => 'five'];
|
||||||
$mapped = (new ArrayMapper())->map($result);
|
$mapped = new ArrayMapper()->map($result);
|
||||||
$this->assertSame($result, $mapped, 'The array mapper should return the parameter given to it');
|
$this->assertSame($result, $mapped, 'The array mapper should return the parameter given to it');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,17 +1,26 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
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
|
||||||
{
|
{
|
||||||
|
#[TestDox('map() succeeds')]
|
||||||
public function testMapSucceeds(): void
|
public function testMapSucceeds(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals(5, (new CountMapper())->map([5, 8, 10]), 'Count not correct');
|
$this->assertEquals(5, new CountMapper()->map([5, 8, 10]), 'Count not correct');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,10 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Test\Unit\Mapper;
|
namespace Test\Unit\Mapper;
|
||||||
|
|
||||||
|
@ -6,6 +12,7 @@ use BitBadger\PDODocument\{DocumentException, Field};
|
||||||
use BitBadger\PDODocument\Mapper\DocumentMapper;
|
use BitBadger\PDODocument\Mapper\DocumentMapper;
|
||||||
use PHPUnit\Framework\Attributes\TestDox;
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
|
use Test\{PjsonDocument, PjsonId};
|
||||||
|
|
||||||
// ** Test class hierarchy for serialization **
|
// ** Test class hierarchy for serialization **
|
||||||
|
|
||||||
|
@ -22,6 +29,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
|
||||||
|
@ -36,10 +44,10 @@ class DocumentMapperTest extends TestCase
|
||||||
$this->assertEquals('json', $mapper->fieldName, 'Field name not recorded correctly');
|
$this->assertEquals('json', $mapper->fieldName, 'Field name not recorded correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('Map succeeds with valid JSON')]
|
#[TestDox('map() succeeds with valid JSON')]
|
||||||
public function testMapSucceedsWithValidJSON(): void
|
public function testMapSucceedsWithValidJSON(): void
|
||||||
{
|
{
|
||||||
$doc = (new DocumentMapper(TestDocument::class))->map(['data' => '{"id":7,"subDoc":{"id":22,"name":"tester"}}']);
|
$doc = new DocumentMapper(TestDocument::class)->map(['data' => '{"id":7,"subDoc":{"id":22,"name":"tester"}}']);
|
||||||
$this->assertNotNull($doc, 'The document should not have been null');
|
$this->assertNotNull($doc, 'The document should not have been null');
|
||||||
$this->assertEquals(7, $doc->id, 'ID not filled correctly');
|
$this->assertEquals(7, $doc->id, 'ID not filled correctly');
|
||||||
$this->assertNotNull($doc->subDoc, 'The sub-document should not have been null');
|
$this->assertNotNull($doc->subDoc, 'The sub-document should not have been null');
|
||||||
|
@ -47,10 +55,28 @@ class DocumentMapperTest extends TestCase
|
||||||
$this->assertEquals('tester', $doc->subDoc->name, 'Sub-document name not filled correctly');
|
$this->assertEquals('tester', $doc->subDoc->name, 'Sub-document name not filled correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('Map fails with invalid JSON')]
|
#[TestDox('map() succeeds with valid JSON for Pjson class')]
|
||||||
|
public function testMapSucceedsWithValidJSONForPjsonClass(): void
|
||||||
|
{
|
||||||
|
$doc = new DocumentMapper(PjsonDocument::class)->map(['data' => '{"id":"seven","name":"bob","num_value":8}']);
|
||||||
|
$this->assertNotNull($doc, 'The document should not have been null');
|
||||||
|
$this->assertEquals(new PjsonId('seven'), $doc->id, 'ID not filled correctly');
|
||||||
|
$this->assertEquals('bob', $doc->name, 'Name not filled correctly');
|
||||||
|
$this->assertEquals(8, $doc->numValue, 'Numeric value not filled correctly');
|
||||||
|
$this->assertFalse(isset($doc->skipped), 'Non-JSON field has not been set');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('map() fails with invalid JSON')]
|
||||||
public function testMapFailsWithInvalidJSON(): void
|
public function testMapFailsWithInvalidJSON(): void
|
||||||
{
|
{
|
||||||
$this->expectException(DocumentException::class);
|
$this->expectException(DocumentException::class);
|
||||||
(new DocumentMapper(TestDocument::class))->map(['data' => 'this is not valid']);
|
new DocumentMapper(TestDocument::class)->map(['data' => 'this is not valid']);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('map() fails with invalid JSON for Pjson class')]
|
||||||
|
public function testMapFailsWithInvalidJSONForPjsonClass(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
new DocumentMapper(PjsonDocument::class)->map(['data' => 'not even close']);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,10 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Test\Unit\Mapper;
|
namespace Test\Unit\Mapper;
|
||||||
|
|
||||||
|
@ -10,34 +16,36 @@ 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')]
|
||||||
public function testMapSucceedsForPostgreSQL(): void
|
public function testMapSucceedsForPostgreSQL(): void
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
Configuration::$mode = Mode::PgSQL;
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
$this->assertFalse((new ExistsMapper())->map([false, 'nope']), 'Result should have been false');
|
$this->assertFalse(new ExistsMapper()->map([false, 'nope']), 'Result should have been false');
|
||||||
} finally {
|
} finally {
|
||||||
Configuration::$mode = null;
|
Configuration::overrideMode(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('Map succeeds for SQLite')]
|
#[TestDox('map() succeeds for SQLite')]
|
||||||
public function testMapSucceedsForSQLite(): void
|
public function testMapSucceedsForSQLite(): void
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
Configuration::$mode = Mode::SQLite;
|
Configuration::overrideMode(Mode::SQLite);
|
||||||
$this->assertTrue((new ExistsMapper())->map([1, 'yep']), 'Result should have been true');
|
$this->assertTrue(new ExistsMapper()->map([1, 'yep']), 'Result should have been true');
|
||||||
} finally {
|
} finally {
|
||||||
Configuration::$mode = null;
|
Configuration::overrideMode(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('map() fails when mode not set')]
|
||||||
public function testMapFailsWhenModeNotSet(): void
|
public function testMapFailsWhenModeNotSet(): void
|
||||||
{
|
{
|
||||||
$this->expectException(DocumentException::class);
|
$this->expectException(DocumentException::class);
|
||||||
Configuration::$mode = null;
|
Configuration::overrideMode(null);
|
||||||
(new ExistsMapper())->map(['0']);
|
new ExistsMapper()->map(['0']);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,27 +1,41 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
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()
|
#[TestDox('map() succeeds when field is present and string')]
|
||||||
|
public function testMapSucceedsWhenFieldIsPresentAndString(): void
|
||||||
{
|
{
|
||||||
$result = ['test_field' => 'test_value'];
|
$result = ['test_field' => 'test_value'];
|
||||||
$mapper = new StringMapper('test_field');
|
$mapper = new StringMapper('test_field');
|
||||||
$this->assertEquals('test_value', $mapper->map($result), 'String value not returned correctly');
|
$this->assertEquals('test_value', $mapper->map($result), 'String value not returned correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testMapSucceedsWhenFieldIsPresentAndNotString()
|
#[TestDox('map() succeeds when field is present and not string')]
|
||||||
|
public function testMapSucceedsWhenFieldIsPresentAndNotString(): void
|
||||||
{
|
{
|
||||||
$result = ['a_number' => 6.7];
|
$result = ['a_number' => 6.7];
|
||||||
$mapper = new StringMapper('a_number');
|
$mapper = new StringMapper('a_number');
|
||||||
$this->assertEquals('6.7', $mapper->map($result), 'Number value not returned correctly');
|
$this->assertEquals('6.7', $mapper->map($result), 'Number value not returned correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testMapSucceedsWhenFieldIsNotPresent()
|
#[TestDox('map() succeeds when field is not present')]
|
||||||
|
public function testMapSucceedsWhenFieldIsNotPresent(): void
|
||||||
{
|
{
|
||||||
$mapper = new StringMapper('something_else');
|
$mapper = new StringMapper('something_else');
|
||||||
$this->assertNull($mapper->map([]), 'Missing value not returned correctly');
|
$this->assertNull($mapper->map([]), 'Missing value not returned correctly');
|
||||||
|
|
39
tests/unit/ModeTest.php
Normal file
39
tests/unit/ModeTest.php
Normal file
|
@ -0,0 +1,39 @@
|
||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Unit;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{DocumentException, Mode};
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unit tests for the Mode enumeration
|
||||||
|
*/
|
||||||
|
#[TestDox('Mode (Unit tests)')]
|
||||||
|
class ModeTest extends TestCase
|
||||||
|
{
|
||||||
|
#[TestDox('deriveFromDSN() succeeds for PostgreSQL')]
|
||||||
|
public function testDeriveFromDSNSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(Mode::PgSQL, Mode::deriveFromDSN('pgsql:Host=localhost'), 'PostgreSQL mode incorrect');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('deriveFromDSN() succeeds for SQLite')]
|
||||||
|
public function testDeriveFromDSNSucceedsForSQLite(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(Mode::SQLite, Mode::deriveFromDSN('sqlite:data.db'), 'SQLite mode incorrect');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('deriveFromDSN() fails for MySQL')]
|
||||||
|
public function testDeriveFromDSNFailsForMySQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Mode::deriveFromDSN('mysql:Host=localhost');
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,4 +1,10 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Test\Unit;
|
namespace Test\Unit;
|
||||||
|
|
||||||
|
@ -9,59 +15,72 @@ 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('toSQL() succeeds for Equal')]
|
||||||
public function testToStringSucceedsForEQ(): void
|
public function testToSQLSucceedsForEqual(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals('=', Op::EQ->toString(), 'EQ operator incorrect');
|
$this->assertEquals('=', Op::Equal->toSQL(), 'Equal SQL operator incorrect');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('To string succeeds for GT')]
|
#[TestDox('toSQL() succeeds for Greater')]
|
||||||
public function testToStringSucceedsForGT(): void
|
public function testToSQLSucceedsForGreater(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals('>', Op::GT->toString(), 'GT operator incorrect');
|
$this->assertEquals('>', Op::Greater->toSQL(), 'Greater SQL operator incorrect');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('To string succeeds for GE')]
|
#[TestDox('toSQL() succeeds for GreaterOrEqual')]
|
||||||
public function testToStringSucceedsForGE(): void
|
public function testToSQLSucceedsForGreaterOrEqual(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals('>=', Op::GE->toString(), 'GE operator incorrect');
|
$this->assertEquals('>=', Op::GreaterOrEqual->toSQL(), 'GreaterOrEqual SQL operator incorrect');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('To string succeeds for LT')]
|
#[TestDox('toSQL() succeeds for Less')]
|
||||||
public function testToStringSucceedsForLT(): void
|
public function testToSQLSucceedsForLess(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals('<', Op::LT->toString(), 'LT operator incorrect');
|
$this->assertEquals('<', Op::Less->toSQL(), 'Less SQL operator incorrect');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('To string succeeds for LE')]
|
#[TestDox('toSQL() succeeds for LessOrEqual')]
|
||||||
public function testToStringSucceedsForLE(): void
|
public function testToSQLSucceedsForLessOrEqual(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals('<=', Op::LE->toString(), 'LE operator incorrect');
|
$this->assertEquals('<=', Op::LessOrEqual->toSQL(), 'LessOrEqual SQL operator incorrect');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('To string succeeds for NE')]
|
#[TestDox('toSQL() succeeds for NotEqual')]
|
||||||
public function testToStringSucceedsForNE(): void
|
public function testToSQLSucceedsForNotEqual(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals('<>', Op::NE->toString(), 'NE operator incorrect');
|
$this->assertEquals('<>', Op::NotEqual->toSQL(), 'NotEqual SQL operator incorrect');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('To string succeeds for BT')]
|
#[TestDox('toSQL() succeeds for Between')]
|
||||||
public function testToStringSucceedsForBT(): void
|
public function testToSQLSucceedsForBetween(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals('BETWEEN', Op::BT->toString(), 'BT operator incorrect');
|
$this->assertEquals('BETWEEN', Op::Between->toSQL(), 'Between SQL operator incorrect');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('To string succeeds for EX')]
|
#[TestDox('toSQL() succeeds for In')]
|
||||||
public function testToStringSucceedsForEX(): void
|
public function testToSQLSucceedsForIn(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals('IS NOT NULL', Op::EX->toString(), 'EX operator incorrect');
|
$this->assertEquals('IN', Op::In->toSQL(), 'In SQL operator incorrect');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('To string succeeds for NEX')]
|
#[TestDox('toSQL() succeeds for InArray')]
|
||||||
public function testToStringSucceedsForNEX(): void
|
public function testToSQLSucceedsForInArray(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals('IS NULL', Op::NEX->toString(), 'NEX operator incorrect');
|
$this->assertEquals('??|', Op::InArray->toSQL(), 'InArray SQL operator incorrect');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('toSQL() succeeds for Exists')]
|
||||||
|
public function testToSQLSucceedsForExists(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals('IS NOT NULL', Op::Exists->toSQL(), 'Exists SQL operator incorrect');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('toSQL() succeeds for NotExists')]
|
||||||
|
public function testToSQLSucceedsForNEX(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals('IS NULL', Op::NotExists->toSQL(), 'NotExists SQL operator incorrect');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,79 +1,134 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Test\Unit;
|
namespace Test\Unit;
|
||||||
|
|
||||||
use BitBadger\PDODocument\{Configuration, DocumentException, Field, Mode, Parameters};
|
use BitBadger\PDODocument\{Configuration, DocumentException, Field, Mode, Parameters};
|
||||||
use PHPUnit\Framework\Attributes\TestDox;
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
|
use stdClass;
|
||||||
|
use Test\{PjsonDocument, PjsonId};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 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')]
|
||||||
public function testIdSucceedsWithString(): void
|
public function testIdSucceedsWithString(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals([':id' => 'key'], Parameters::id('key'), 'ID parameter not constructed correctly');
|
$this->assertEquals([':id' => 'key'], Parameters::id('key'), 'ID parameter not constructed correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('ID succeeds with non string')]
|
#[TestDox('id() succeeds with non string')]
|
||||||
public function testIdSucceedsWithNonString(): void
|
public function testIdSucceedsWithNonString(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals([':id' => '7'], Parameters::id(7), 'ID parameter not constructed correctly');
|
$this->assertEquals([':id' => '7'], Parameters::id(7), 'ID parameter not constructed correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testJsonSucceeds(): void
|
#[TestDox('json() succeeds for array')]
|
||||||
|
public function testJsonSucceedsForArray(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals([':it' => '{"id":18,"url":"https://www.unittest.com"}'],
|
$this->assertEquals([':it' => '{"id":18,"url":"https://www.unittest.com"}'],
|
||||||
Parameters::json(':it', ['id' => 18, 'url' => 'https://www.unittest.com']),
|
Parameters::json(':it', ['id' => 18, 'url' => 'https://www.unittest.com']),
|
||||||
'JSON parameter not constructed correctly');
|
'JSON parameter not constructed correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('json() succeeds for array with empty array parameter')]
|
||||||
|
public function testJsonSucceedsForArrayWithEmptyArrayParameter(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals([':it' => '{"id":18,"urls":[]}'], Parameters::json(':it', ['id' => 18, 'urls' => []]),
|
||||||
|
'JSON parameter not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('json() succeeds for 1D array with empty array parameter')]
|
||||||
|
public function testJsonSucceedsFor1DArrayWithEmptyArrayParameter(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals([':it' => '{"urls":[]}'], Parameters::json(':it', ['urls' => []]),
|
||||||
|
'JSON parameter not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('json() succeeds for stdClass')]
|
||||||
|
public function testJsonSucceedsForStdClass(): void
|
||||||
|
{
|
||||||
|
$obj = new stdClass();
|
||||||
|
$obj->id = 19;
|
||||||
|
$obj->url = 'https://testhere.info';
|
||||||
|
$this->assertEquals([':it' => '{"id":19,"url":"https://testhere.info"}'], Parameters::json(':it', $obj),
|
||||||
|
'JSON parameter not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('json() succeeds for Pjson class')]
|
||||||
|
public function testJsonSucceedsForPjsonClass(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals([':it' => '{"id":"999","name":"a test","num_value":98}'],
|
||||||
|
Parameters::json(':it', new PjsonDocument(new PjsonId('999'), 'a test', 98, 'nothing')),
|
||||||
|
'JSON parameter not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('json() succeeds for array of Pjson class')]
|
||||||
|
public function testJsonSucceedsForArrayOfPjsonClass(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals([':it' => '{"pjson":[{"id":"997","name":"another test","num_value":94}]}'],
|
||||||
|
Parameters::json(':it',
|
||||||
|
['pjson' => [new PjsonDocument(new PjsonId('997'), 'another test', 94, 'nothing')]]),
|
||||||
|
'JSON parameter not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('nameFields() succeeds')]
|
||||||
public function testNameFieldsSucceeds(): void
|
public function testNameFieldsSucceeds(): void
|
||||||
{
|
{
|
||||||
$named = Parameters::nameFields([Field::EQ('it', 17), Field::EQ('also', 22, ':also'), Field::EQ('other', 24)]);
|
$named = [Field::equal('it', 17), Field::equal('also', 22, ':also'), Field::equal('other', 24)];
|
||||||
|
Parameters::nameFields($named);
|
||||||
$this->assertCount(3, $named, 'There should be 3 parameters in the array');
|
$this->assertCount(3, $named, 'There should be 3 parameters in the array');
|
||||||
$this->assertEquals(':field0', $named[0]->paramName, 'Parameter 1 not named correctly');
|
$this->assertEquals(':field0', $named[0]->paramName, 'Parameter 1 not named correctly');
|
||||||
$this->assertEquals(':also', $named[1]->paramName, 'Parameter 2 not named correctly');
|
$this->assertEquals(':also', $named[1]->paramName, 'Parameter 2 not named correctly');
|
||||||
$this->assertEquals(':field2', $named[2]->paramName, 'Parameter 3 not named correctly');
|
$this->assertEquals(':field2', $named[2]->paramName, 'Parameter 3 not named correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('addFields() succeeds')]
|
||||||
public function testAddFieldsSucceeds(): void
|
public function testAddFieldsSucceeds(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals([':a' => 1, ':b' => 'two', ':z' => 18],
|
$this->assertEquals([':a' => 1, ':b' => 'two', ':z' => 18],
|
||||||
Parameters::addFields([Field::EQ('b', 'two', ':b'), Field::EQ('z', 18, ':z')], [':a' => 1]),
|
Parameters::addFields([Field::equal('b', 'two', ':b'), Field::equal('z', 18, ':z')], [':a' => 1]),
|
||||||
'Field parameters not added correctly');
|
'Field parameters not added correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('Field names succeeds for PostgreSQL')]
|
#[TestDox('fieldNames() succeeds for PostgreSQL')]
|
||||||
public function testFieldNamesSucceedsForPostgreSQL(): void
|
public function testFieldNamesSucceedsForPostgreSQL(): void
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
Configuration::$mode = Mode::PgSQL;
|
Configuration::overrideMode(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::overrideMode(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('Field names succeeds for SQLite')]
|
#[TestDox('fieldNames() succeeds for SQLite')]
|
||||||
public function testFieldNamesSucceedsForSQLite(): void
|
public function testFieldNamesSucceedsForSQLite(): void
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
Configuration::$mode = Mode::SQLite;
|
Configuration::overrideMode(Mode::SQLite);
|
||||||
$this->assertEquals([':it0' => '$.test', ':it1' => '$.unit', ':it2' => '$.wow'],
|
$this->assertEquals([':it0' => '$.test', ':it1' => '$.unit', ':it2' => '$.wow'],
|
||||||
Parameters::fieldNames(':it', ['test', 'unit', 'wow']), 'Field name parameters not correct');
|
Parameters::fieldNames(':it', ['test', 'unit', 'wow']), 'Field name parameters not correct');
|
||||||
} finally {
|
} finally {
|
||||||
Configuration::$mode = null;
|
Configuration::overrideMode(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('fieldNames() fails when mode not set')]
|
||||||
public function testFieldNamesFailsWhenModeNotSet(): void
|
public function testFieldNamesFailsWhenModeNotSet(): void
|
||||||
{
|
{
|
||||||
$this->expectException(DocumentException::class);
|
$this->expectException(DocumentException::class);
|
||||||
Configuration::$mode = null;
|
Configuration::overrideMode(null);
|
||||||
Parameters::fieldNames('', []);
|
Parameters::fieldNames('', []);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,31 +1,73 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
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::overrideMode(null);
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
|
|
||||||
public function testAllSucceeds()
|
#[TestDox('all() succeeds')]
|
||||||
|
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()
|
#[TestDox('byFields() succeeds')]
|
||||||
|
public function testByFieldsSucceeds(): void
|
||||||
{
|
{
|
||||||
Configuration::$mode = Mode::SQLite;
|
Configuration::overrideMode(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::greater('errors', 10, ':errors')]),
|
||||||
} finally {
|
'SELECT statement not generated correctly');
|
||||||
Configuration::$mode = null;
|
}
|
||||||
}
|
|
||||||
|
#[TestDox('byContains() succeeds for PostgreSQL')]
|
||||||
|
public function testByContainsSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
$this->assertEquals('SELECT COUNT(*) FROM the_table WHERE data @> :criteria', Count::byContains('the_table'),
|
||||||
|
'SELECT statement not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byContains() fails for non PostgreSQL')]
|
||||||
|
public function testByContainsFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Count::byContains('');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byJsonPath() succeeds for PostgreSQL')]
|
||||||
|
public function testByJsonPathSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(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('byJsonPath() fails for non PostgreSQL')]
|
||||||
|
public function testByJsonPathFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Count::byJsonPath('');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,8 +1,14 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
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,45 +16,46 @@ 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
|
||||||
{
|
{
|
||||||
#[TestDox('Ensure table succeeds for PosgtreSQL')]
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(null);
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('ensureTable() succeeds for PostgreSQL')]
|
||||||
public function testEnsureTableSucceedsForPostgreSQL(): void
|
public function testEnsureTableSucceedsForPostgreSQL(): void
|
||||||
{
|
{
|
||||||
try {
|
Configuration::overrideMode(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('ensureTable() succeeds for SQLite')]
|
||||||
public function testEnsureTableSucceedsForSQLite(): void
|
public function testEnsureTableSucceedsForSQLite(): void
|
||||||
{
|
{
|
||||||
try {
|
Configuration::overrideMode(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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('ensureTable() fails when mode not set')]
|
||||||
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');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('ensureIndexOn() succeeds without schema single ascending field')]
|
||||||
public function testEnsureIndexOnSucceedsWithoutSchemaSingleAscendingField(): void
|
public function testEnsureIndexOnSucceedsWithoutSchemaSingleAscendingField(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals("CREATE INDEX IF NOT EXISTS idx_test_fields ON test ((data->>'details'))",
|
$this->assertEquals("CREATE INDEX IF NOT EXISTS idx_test_fields ON test ((data->>'details'))",
|
||||||
Definition::ensureIndexOn('test', 'fields', ['details']), 'CREATE INDEX statement not generated correctly');
|
Definition::ensureIndexOn('test', 'fields', ['details']), 'CREATE INDEX statement not generated correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('ensureIndexOn() succeeds with schema multiple fields')]
|
||||||
public function testEnsureIndexOnSucceedsWithSchemaMultipleFields(): void
|
public function testEnsureIndexOnSucceedsWithSchemaMultipleFields(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals(
|
$this->assertEquals(
|
||||||
|
@ -57,9 +64,33 @@ class DefinitionTest extends TestCase
|
||||||
'CREATE INDEX statement not generated correctly');
|
'CREATE INDEX statement not generated correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testEnsureKey(): void
|
#[TestDox('ensureKey() succeeds')]
|
||||||
|
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');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('ensureDocumentIndexOn() succeeds for schema and Full')]
|
||||||
|
public function testEnsureDocumentIndexOnSucceedsForSchemaAndFull(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
$this->assertEquals("CREATE INDEX IF NOT EXISTS idx_tbl_document ON my.tbl USING GIN (data)",
|
||||||
|
Definition::ensureDocumentIndexOn('my.tbl', DocumentIndex::Full));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('ensureDocumentIndexOn() succeeds for no schema and Optimized')]
|
||||||
|
public function testEnsureDocumentIndexOnSucceedsForNoSchemaAndOptimized(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(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('ensureDocumentIndexOn() fails for non PostgreSQL')]
|
||||||
|
public function testEnsureDocumentIndexOnFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Definition::ensureDocumentIndexOn('', DocumentIndex::Full);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,8 +1,14 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
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,29 +16,59 @@ 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::overrideMode(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By ID succeeds')]
|
#[TestDox('byId() succeeds')]
|
||||||
public function testByIdSucceeds(): void
|
public function testByIdSucceeds(): void
|
||||||
{
|
{
|
||||||
|
Configuration::overrideMode(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');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds')]
|
||||||
public function testByFieldsSucceeds(): void
|
public function testByFieldsSucceeds(): void
|
||||||
{
|
{
|
||||||
|
Configuration::overrideMode(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::less('value', 99, ':max'), Field::greaterOrEqual('value', 18, ':min')]),
|
||||||
'DELETE statement not constructed correctly');
|
'DELETE statement not constructed correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('byContains() succeeds for PostgreSQL')]
|
||||||
|
public function testByContainsSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
$this->assertEquals('DELETE FROM somewhere WHERE data @> :criteria', Delete::byContains('somewhere'),
|
||||||
|
'DELETE statement not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byContains() fails for non PostgreSQL')]
|
||||||
|
public function testByContainsFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Delete::byContains('');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byJsonPath() succeeds for PostgreSQL')]
|
||||||
|
public function testByJsonPathSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
$this->assertEquals('DELETE FROM here WHERE jsonb_path_exists(data, :path::jsonpath)',
|
||||||
|
Delete::byJsonPath('here'), 'DELETE statement not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byJsonPath() fails for non PostgreSQL')]
|
||||||
|
public function testByJsonPathFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Delete::byJsonPath('');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,8 +1,14 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
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,35 +16,66 @@ 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::overrideMode(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('query() succeeds')]
|
||||||
public function testQuerySucceeds(): void
|
public function testQuerySucceeds(): void
|
||||||
{
|
{
|
||||||
|
Configuration::overrideMode(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');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By ID succeeds')]
|
#[TestDox('byId() succeeds')]
|
||||||
public function testByIdSucceeds(): void
|
public function testByIdSucceeds(): void
|
||||||
{
|
{
|
||||||
|
Configuration::overrideMode(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');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds')]
|
||||||
public function testByFieldsSucceeds(): void
|
public function testByFieldsSucceeds(): void
|
||||||
{
|
{
|
||||||
|
Configuration::overrideMode(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::notEqual('status', 'occupied', ':status')]),
|
||||||
'Existence query not generated correctly');
|
'Existence query not generated correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('byContains() succeeds for PostgreSQL')]
|
||||||
|
public function testByContainsSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
$this->assertEquals('SELECT EXISTS (SELECT 1 FROM pocket WHERE data @> :criteria)',
|
||||||
|
Exists::byContains('pocket'), 'Existence query not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byContains() fails for non PostgreSQL')]
|
||||||
|
public function testByContainsFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Exists::byContains('');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byJsonPath() succeeds for PostgreSQL')]
|
||||||
|
public function testByJsonPathSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(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('byJsonPath() fails for non PostgreSQL')]
|
||||||
|
public function testByJsonPathFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Exists::byJsonPath('');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,8 +1,14 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
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,29 +16,59 @@ 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::overrideMode(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By ID succeeds')]
|
#[TestDox('byId() succeeds')]
|
||||||
public function testByIdSucceeds(): void
|
public function testByIdSucceeds(): void
|
||||||
{
|
{
|
||||||
|
Configuration::overrideMode(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');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() succeeds')]
|
||||||
public function testByFieldsSucceeds(): void
|
public function testByFieldsSucceeds(): void
|
||||||
{
|
{
|
||||||
|
Configuration::overrideMode(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::equal('active', true, ':act'), Field::equal('locked', true, ':lock')],
|
||||||
|
FieldMatch::Any),
|
||||||
'SELECT query not generated correctly');
|
'SELECT query not generated correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('byContains() succeeds for PostgreSQL')]
|
||||||
|
public function testByContainsSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
$this->assertEquals('SELECT data FROM disc WHERE data @> :criteria', Find::byContains('disc'),
|
||||||
|
'SELECT query not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byContains() fails for non PostgreSQL')]
|
||||||
|
public function testByContainsFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Find::byContains('');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byJsonPath() succeeds for PostgreSQL')]
|
||||||
|
public function testByJsonPathSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
$this->assertEquals('SELECT data FROM light WHERE jsonb_path_exists(data, :path::jsonpath)',
|
||||||
|
Find::byJsonPath('light'), 'SELECT query not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byJsonPath() fails for non PostgreSQL')]
|
||||||
|
public function testByJsonPathFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Find::byJsonPath('');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,10 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Test\Unit\Query;
|
namespace Test\Unit\Query;
|
||||||
|
|
||||||
|
@ -10,71 +16,89 @@ 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
|
||||||
{
|
{
|
||||||
#[TestDox('By ID succeeds for PostgreSQL')]
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(null);
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
|
#[TestDox('byId() succeeds for PostgreSQL')]
|
||||||
public function testByIdSucceedsForPostgreSQL(): void
|
public function testByIdSucceedsForPostgreSQL(): void
|
||||||
{
|
{
|
||||||
try {
|
Configuration::overrideMode(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('byId() succeeds for SQLite')]
|
||||||
public function testByIdSucceedsForSQLite(): void
|
public function testByIdSucceedsForSQLite(): void
|
||||||
{
|
{
|
||||||
try {
|
Configuration::overrideMode(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('byId() 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('byFields() succeeds for PostgreSQL')]
|
||||||
public function testByFieldsSucceedsForPostgreSQL(): void
|
public function testByFieldsSucceedsForPostgreSQL(): void
|
||||||
{
|
{
|
||||||
try {
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
Configuration::$mode = Mode::PgSQL;
|
$this->assertEquals("UPDATE that SET data = data || :data WHERE (data->>'something')::numeric < :some",
|
||||||
$this->assertEquals("UPDATE that SET data = data || :data WHERE data->>'something' < :some",
|
Patch::byFields('that', [Field::less('something', 17, ':some')]), 'Patch UPDATE statement is not correct');
|
||||||
Patch::byFields('that', [Field::LT('something', 17, ':some')]),
|
|
||||||
'Patch UPDATE statement is not correct');
|
|
||||||
} finally {
|
|
||||||
Configuration::$mode = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By fields succeeds for SQLite')]
|
#[TestDox('byFields() succeeds for SQLite')]
|
||||||
public function testByFieldsSucceedsForSQLite(): void
|
public function testByFieldsSucceedsForSQLite(): void
|
||||||
{
|
{
|
||||||
try {
|
Configuration::overrideMode(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::greater('something', 17, ':it')]),
|
||||||
'Patch UPDATE statement is not correct');
|
'Patch UPDATE statement is not correct');
|
||||||
} finally {
|
|
||||||
Configuration::$mode = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() fails when mode not set')]
|
||||||
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('byContains() succeeds for PostgreSQL')]
|
||||||
|
public function testByContainsSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
$this->assertEquals('UPDATE this SET data = data || :data WHERE data @> :criteria', Patch::byContains('this'),
|
||||||
|
'Patch UPDATE statement is not correct');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byContains() fails for non PostgreSQL')]
|
||||||
|
public function testByContainsFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Patch::byContains('');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byJsonPath() succeeds for PostgreSQL')]
|
||||||
|
public function testByJsonPathSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(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('byJsonPath() fails for non PostgreSQL')]
|
||||||
|
public function testByJsonPathFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Patch::byJsonPath('');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,10 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Test\Unit\Query;
|
namespace Test\Unit\Query;
|
||||||
|
|
||||||
|
@ -10,108 +16,120 @@ 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
|
||||||
{
|
{
|
||||||
#[TestDox('Update succeeds for PostgreSQL')]
|
protected function tearDown(): void
|
||||||
public function testUpdateSucceedsForPostgreSQL(): void
|
|
||||||
{
|
{
|
||||||
try {
|
Configuration::overrideMode(null);
|
||||||
Configuration::$mode = Mode::PgSQL;
|
|
||||||
$this->assertEquals('UPDATE taco SET data = data - :names WHERE it = true',
|
|
||||||
RemoveFields::update('taco', [':names' => "ARRAY['one','two']"], 'it = true'),
|
|
||||||
'UPDATE statement not correct');
|
|
||||||
} finally {
|
|
||||||
Configuration::$mode = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('Update succeeds for SQLite')]
|
#[TestDox('update() succeeds for PostgreSQL')]
|
||||||
|
public function testUpdateSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
$this->assertEquals('UPDATE taco SET data = data - :names::text[] WHERE it = true',
|
||||||
|
RemoveFields::update('taco', [':names' => "{one,two}"], 'it = true'), 'UPDATE statement not correct');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('update() succeeds for SQLite')]
|
||||||
public function testUpdateSucceedsForSQLite(): void
|
public function testUpdateSucceedsForSQLite(): void
|
||||||
{
|
{
|
||||||
try {
|
Configuration::overrideMode(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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('update() fails when mode not set')]
|
||||||
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('byId() succeeds for PostgreSQL')]
|
||||||
public function testByIdSucceedsForPostgreSQL()
|
public function testByIdSucceedsForPostgreSQL(): void
|
||||||
{
|
{
|
||||||
try {
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
Configuration::$mode = Mode::PgSQL;
|
$this->assertEquals("UPDATE churro SET data = data - :bite::text[] WHERE data->>'id' = :id",
|
||||||
$this->assertEquals("UPDATE churro SET data = data - :bite WHERE data->>'id' = :id",
|
RemoveFields::byId('churro', Parameters::fieldNames(':bite', ['byte'])), 'UPDATE statement not correct');
|
||||||
RemoveFields::byId('churro', Parameters::fieldNames(':bite', ['byte'])),
|
|
||||||
'UPDATE statement not correct');
|
|
||||||
} finally {
|
|
||||||
Configuration::$mode = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('By ID succeeds for SQLite')]
|
#[TestDox('byId() succeeds for SQLite')]
|
||||||
public function testByIdSucceedsForSQLite()
|
public function testByIdSucceedsForSQLite(): void
|
||||||
{
|
{
|
||||||
try {
|
Configuration::overrideMode(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('byId() 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('byFields() succeeds for PostgreSQL')]
|
||||||
public function testByFieldsSucceedsForPostgreSQL()
|
public function testByFieldsSucceedsForPostgreSQL(): void
|
||||||
{
|
{
|
||||||
try {
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
Configuration::$mode = Mode::PgSQL;
|
$this->assertEquals("UPDATE enchilada SET data = data - :sauce::text[] WHERE data->>'cheese' = :queso",
|
||||||
$this->assertEquals("UPDATE enchilada SET data = data - :sauce WHERE data->>'cheese' = :queso",
|
RemoveFields::byFields('enchilada', [Field::equal('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('byFields() succeeds for SQLite')]
|
||||||
public function testByFieldsSucceedsForSQLite()
|
public function testByFieldsSucceedsForSQLite(): void
|
||||||
{
|
{
|
||||||
try {
|
Configuration::overrideMode(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::equal('side', 'beans', ':rice')],
|
||||||
Parameters::fieldNames(':filling', ['beef'])),
|
Parameters::fieldNames(':filling', ['beef'])),
|
||||||
'UPDATE statement not correct');
|
'UPDATE statement not correct');
|
||||||
} finally {
|
|
||||||
Configuration::$mode = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('byFields() fails when mode not set')]
|
||||||
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('byContains() succeeds for PostgreSQL')]
|
||||||
|
public function testByContainsSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(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('byContains() fails for non PostgreSQL')]
|
||||||
|
public function testByContainsFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
RemoveFields::byContains('', []);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('byJsonPath() succeeds for PostgreSQL')]
|
||||||
|
public function testByJsonPathSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(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('byJsonPath() fails for non PostgreSQL')]
|
||||||
|
public function testByJsonPathFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
RemoveFields::byJsonPath('', []);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,70 +1,216 @@
|
||||||
<?php declare(strict_types=1);
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
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
|
||||||
{
|
{
|
||||||
Configuration::$mode = Mode::SQLite;
|
Configuration::overrideMode(Mode::SQLite);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function tearDown(): void
|
protected function tearDown(): void
|
||||||
{
|
{
|
||||||
Configuration::$mode = null;
|
Configuration::overrideMode(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('selectFromTable() succeeds')]
|
||||||
public function testSelectFromTableSucceeds(): void
|
public function testSelectFromTableSucceeds(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals('SELECT data FROM testing', Query::selectFromTable('testing'),
|
$this->assertEquals('SELECT data FROM testing', Query::selectFromTable('testing'),
|
||||||
'Query not constructed correctly');
|
'Query not constructed correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('whereByFields() succeeds for single field')]
|
||||||
public function testWhereByFieldsSucceedsForSingleField(): void
|
public function testWhereByFieldsSucceedsForSingleField(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals("data->>'test_field' <= :it",
|
$this->assertEquals("data->>'test_field' <= :it",
|
||||||
Query::whereByFields([Field::LE('test_field', '', ':it')]), 'WHERE fragment not constructed correctly');
|
Query::whereByFields([Field::lessOrEqual('test_field', '', ':it')]),
|
||||||
|
'WHERE fragment not constructed correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testWhereByFieldsSucceedsForMultipleFields(): void
|
#[TestDox('whereByFields() succeeds for multiple fields All')]
|
||||||
|
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::lessOrEqual('test_field', '', ':it'), Field::equal('other_field', '', ':other')]),
|
||||||
'WHERE fragment not constructed correctly');
|
'WHERE fragment not constructed correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testWhereByFieldsSucceedsForMultipleFieldsWithOr(): void
|
#[TestDox('whereByFields() succeeds for multiple fields Any')]
|
||||||
|
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::lessOrEqual('test_field', '', ':it'), Field::equal('other_field', '', ':other')],
|
||||||
|
FieldMatch::Any),
|
||||||
'WHERE fragment not constructed correctly');
|
'WHERE fragment not constructed correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('Where by ID succeeds with default parameter')]
|
#[TestDox('whereById() succeeds with default parameter')]
|
||||||
public function testWhereByIdSucceedsWithDefaultParameter(): void
|
public function testWhereByIdSucceedsWithDefaultParameter(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals("data->>'id' = :id", Query::whereById(), 'WHERE fragment not constructed correctly');
|
$this->assertEquals("data->>'id' = :id", Query::whereById(), 'WHERE fragment not constructed correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
#[TestDox('Where by ID succeeds with specific parameter')]
|
#[TestDox('whereById() succeeds with specific parameter')]
|
||||||
public function testWhereByIdSucceedsWithSpecificParameter(): void
|
public function testWhereByIdSucceedsWithSpecificParameter(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals("data->>'id' = :di", Query::whereById(':di'), 'WHERE fragment not constructed correctly');
|
$this->assertEquals("data->>'id' = :di", Query::whereById(':di'), 'WHERE fragment not constructed correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testInsertSucceeds(): void
|
#[TestDox('whereDataContains() succeeds with default parameter')]
|
||||||
|
public function testWhereDataContainsSucceedsWithDefaultParameter(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals('INSERT INTO my_table VALUES (:data)', Query::insert('my_table'),
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
$this->assertEquals('data @> :criteria', Query::whereDataContains(),
|
||||||
|
'WHERE fragment not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('whereDataContains() succeeds with specific parameter')]
|
||||||
|
public function testWhereDataContainsSucceedsWithSpecifiedParameter(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
$this->assertEquals('data @> :it', Query::whereDataContains(':it'), 'WHERE fragment not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('whereDataContains() fails if not PostgreSQL')]
|
||||||
|
public function testWhereDataContainsFailsIfNotPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(null);
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Query::whereDataContains();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('whereJsonPathMatches() succeeds with default parameter')]
|
||||||
|
public function testWhereJsonPathMatchesSucceedsWithDefaultParameter(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
$this->assertEquals('jsonb_path_exists(data, :path::jsonpath)', Query::whereJsonPathMatches(),
|
||||||
|
'WHERE fragment not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('whereJsonPathMatches() succeeds with specified parameter')]
|
||||||
|
public function testWhereJsonPathMatchesSucceedsWithSpecifiedParameter(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
$this->assertEquals('jsonb_path_exists(data, :road::jsonpath)', Query::whereJsonPathMatches(':road'),
|
||||||
|
'WHERE fragment not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('whereJsonPathMatches() fails if not PostgreSQL')]
|
||||||
|
public function testWhereJsonPathMatchesFailsIfNotPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(null);
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Query::whereJsonPathMatches();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('insert() succeeds with no auto-ID for PostgreSQL')]
|
||||||
|
public function testInsertSucceedsWithNoAutoIdForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
$this->assertEquals('INSERT INTO test_tbl VALUES (:data)', Query::insert('test_tbl'),
|
||||||
'INSERT statement not constructed correctly');
|
'INSERT statement not constructed correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('insert() succeeds with no auto-ID for SQLite')]
|
||||||
|
public function testInsertSucceedsWithNoAutoIdForSQLite(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals('INSERT INTO test_tbl VALUES (:data)', Query::insert('test_tbl'),
|
||||||
|
'INSERT statement not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('insert() succeeds with auto numeric ID for PostgreSQL')]
|
||||||
|
public function testInsertSucceedsWithAutoNumericIdForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
$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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('insert() succeeds with auto numeric ID for SQLite')]
|
||||||
|
public function testInsertSucceedsWithAutoNumericIdForSQLite(): void
|
||||||
|
{
|
||||||
|
$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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('insert() succeeds with auto UUID for PostgreSQL')]
|
||||||
|
public function testInsertSucceedsWithAutoUuidForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
$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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('insert() succeeds with auto UUID for SQLite')]
|
||||||
|
public function testInsertSucceedsWithAutoUuidForSQLite(): void
|
||||||
|
{
|
||||||
|
$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');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('insert() succeeds with auto random string for PostgreSQL')]
|
||||||
|
public function testInsertSucceedsWithAutoRandomStringForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(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::$idStringLength = 16;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('insert() succeeds with auto random string for SQLite')]
|
||||||
|
public function testInsertSucceedsWithAutoRandomStringForSQLite(): void
|
||||||
|
{
|
||||||
|
$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");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('insert() fails when mode not set')]
|
||||||
|
public function testInsertFailsWhenModeNotSet(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Configuration::overrideMode(null);
|
||||||
|
Query::insert('kaboom');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('save() succeeds')]
|
||||||
public function testSaveSucceeds(): void
|
public function testSaveSucceeds(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals(
|
$this->assertEquals(
|
||||||
|
@ -72,9 +218,106 @@ class QueryTest extends TestCase
|
||||||
Query::save('test_tbl'), 'INSERT ON CONFLICT statement not constructed correctly');
|
Query::save('test_tbl'), 'INSERT ON CONFLICT statement not constructed correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testUpdateSucceeds()
|
#[TestDox('update() succeeds')]
|
||||||
|
public function testUpdateSucceeds(): void
|
||||||
{
|
{
|
||||||
$this->assertEquals("UPDATE testing SET data = :data WHERE data->>'id' = :id", Query::update('testing'),
|
$this->assertEquals("UPDATE testing SET data = :data WHERE data->>'id' = :id", Query::update('testing'),
|
||||||
'UPDATE statement not constructed correctly');
|
'UPDATE statement not constructed correctly');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[TestDox('orderBy() succeeds with no fields for PostgreSQL')]
|
||||||
|
public function testOrderBySucceedsWithNoFieldsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
$this->assertEquals('', Query::orderBy([]), 'ORDER BY should have been blank');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('orderBy() succeeds with no fields for SQLite')]
|
||||||
|
public function testOrderBySucceedsWithNoFieldsForSQLite(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals('', Query::orderBy([]), 'ORDER BY should have been blank');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('orderBy() succeeds with one field and no direction for PostgreSQL')]
|
||||||
|
public function testOrderBySucceedsWithOneFieldAndNoDirectionForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
$this->assertEquals(" ORDER BY data->>'TestField'", Query::orderBy([Field::named('TestField')]),
|
||||||
|
'ORDER BY not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('orderBy() succeeds with one field and no direction for SQLite')]
|
||||||
|
public function testOrderBySucceedsWithOneFieldAndNoDirectionForSQLite(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(" ORDER BY data->>'TestField'", Query::orderBy([Field::named('TestField')]),
|
||||||
|
'ORDER BY not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('orderBy() succeeds with one qualified field for PostgreSQL')]
|
||||||
|
public function testOrderBySucceedsWithOneQualifiedFieldForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
$field = Field::named('TestField');
|
||||||
|
$field->qualifier = 'qual';
|
||||||
|
$this->assertEquals(" ORDER BY qual.data->>'TestField'", Query::orderBy([$field]),
|
||||||
|
'ORDER BY not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('orderBy() succeeds with one qualified field for SQLite')]
|
||||||
|
public function testOrderBySucceedsWithOneQualifiedFieldForSQLite(): void
|
||||||
|
{
|
||||||
|
$field = Field::named('TestField');
|
||||||
|
$field->qualifier = 'qual';
|
||||||
|
$this->assertEquals(" ORDER BY qual.data->>'TestField'", Query::orderBy([$field]),
|
||||||
|
'ORDER BY not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('orderBy() succeeds with multiple fields and direction for PostgreSQL')]
|
||||||
|
public function testOrderBySucceedsWithMultipleFieldsAndDirectionForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
$this->assertEquals(" ORDER BY data#>>'{Nested,Test,Field}' DESC, data->>'AnotherField', data->>'It' DESC",
|
||||||
|
Query::orderBy(
|
||||||
|
[Field::named('Nested.Test.Field DESC'), Field::named('AnotherField'), Field::named('It DESC')]),
|
||||||
|
'ORDER BY not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('orderBy() succeeds with multiple fields and direction for SQLite')]
|
||||||
|
public function testOrderBySucceedsWithMultipleFieldsAndDirectionForSQLite(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(" ORDER BY data->'Nested'->'Test'->>'Field' DESC, data->>'AnotherField', data->>'It' DESC",
|
||||||
|
Query::orderBy(
|
||||||
|
[Field::named('Nested.Test.Field DESC'), Field::named('AnotherField'), Field::named('It DESC')]),
|
||||||
|
'ORDER BY not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('orderBy() succeeds with numeric field for PostgreSQL')]
|
||||||
|
public function testOrderBySucceedsWithNumericFieldForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
$this->assertEquals(" ORDER BY (data->>'Test')::numeric", Query::orderBy([Field::named('n:Test')]),
|
||||||
|
'ORDER BY not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('orderBy() succeeds with numeric field for SQLite')]
|
||||||
|
public function testOrderBySucceedsWithNumericFieldForSQLite(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(" ORDER BY data->>'Test'", Query::orderBy([Field::named('n:Test')]),
|
||||||
|
'ORDER BY not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('orderBy() succeeds with case-insensitive ordering for PostgreSQL')]
|
||||||
|
public function testOrderBySucceedsWithCaseInsensitiveOrderingForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::overrideMode(Mode::PgSQL);
|
||||||
|
$this->assertEquals(" ORDER BY LOWER(data#>>'{Test,Field}') DESC NULLS FIRST",
|
||||||
|
Query::orderBy([Field::named('i:Test.Field DESC NULLS FIRST')]), 'ORDER BY not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('orderBy() succeeds with case-insensitive ordering for SQLite')]
|
||||||
|
public function testOrderBySucceedsWithCaseInsensitiveOrderingForSQLite(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(" ORDER BY data->'Test'->>'Field' COLLATE NOCASE ASC NULLS LAST",
|
||||||
|
Query::orderBy([Field::named('i:Test.Field ASC NULLS LAST')]), 'ORDER BY not constructed correctly');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue
Block a user