Compare commits
6 Commits
a10ecbb1cd
...
v1.0.0-bet
| Author | SHA1 | Date | |
|---|---|---|---|
| 124426fa12 | |||
| 330e272187 | |||
| 1f1f06679f | |||
| 2902059cd4 | |||
| 17748354c4 | |||
| f784f3e52c |
4
.gitattributes
vendored
Normal file
4
.gitattributes
vendored
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
/.gitignore export-ignore
|
||||||
|
/.gitattributes export-ignore
|
||||||
|
/composer.lock export-ignore
|
||||||
|
/tests/**/* export-ignore
|
||||||
3
.gitignore
vendored
Normal file
3
.gitignore
vendored
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
.idea
|
||||||
|
vendor
|
||||||
|
*-tests.txt
|
||||||
33
README.md
33
README.md
@@ -1,3 +1,32 @@
|
|||||||
# pdo-document
|
# PDODocument
|
||||||
|
|
||||||
Bit Badger Documents PHP implementation with PDO
|
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
|
||||||
|
|
||||||
|
[](https://packagist.org/packages/bit-badger/pdo-document)
|
||||||
|
|
||||||
|
`composer require bit-badger/pdo-document`
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
### Connection Details
|
||||||
|
|
||||||
|
The static variable `Configuration::$pdoDSN` must be set to the [PDO data source name](https://www.php.net/manual/en/pdo.construct.php#refsect1-pdo.construct-parameters) for your database. `Configuration` also has `$username`, `$password`, and `$options` variables that will be used to construct the PDO object it will use for data access.
|
||||||
|
|
||||||
|
### Document Identifiers
|
||||||
|
|
||||||
|
Each document must have a unique identifier. By default, the library assumes that this is a property or array key named `id`, but this can be controlled by setting `Configuration::$idField`. Once documents exist, this should not be changed.
|
||||||
|
|
||||||
|
IDs can be generated automatically on insert. The `AutoId` enumeration has 4 values:
|
||||||
|
|
||||||
|
- `AutoId::None` is the default; no IDs will be generated
|
||||||
|
- `AutoId::Number` will assign max-ID-plus-one to documents with an ID of 0
|
||||||
|
- `AutoId::UUID` will generate a v4 <abbr title="Universally Unique Identifier">UUID</abbr> for documents with an empty `string` ID
|
||||||
|
- `AutoId::RandomString` will generate a string of letters and numbers for documents with an empty `string` ID; `Configuration::$idStringLength` controls the length of the generated string, and defaults to 16 characters
|
||||||
|
|
||||||
|
In all generated scenarios, if the ID value is not 0 or blank, that ID will be used instead of a generated one.
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
Documentation for this library is not complete (writing it is one of the goals before the “beta” tag is dropped); however, its structure is very similar to the .NET version, so [its documentation will help](https://bitbadger.solutions/open-source/relational-documents/basic-usage.html) until its project specific documentation is developed. Things like `Count.All()` become `Count::all`, and all the `byField` operations are named `byFields` and take an array of fields.
|
||||||
|
|||||||
45
composer.json
Normal file
45
composer.json
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
{
|
||||||
|
"name": "bit-badger/pdo-document",
|
||||||
|
"description": "Treat SQLite (and soon PostgreSQL) as a document store",
|
||||||
|
"keywords": ["database", "document", "sqlite", "pdo"],
|
||||||
|
"license": "MIT",
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "Daniel J. Summers",
|
||||||
|
"email": "daniel@bitbadger.solutions",
|
||||||
|
"homepage": "https://bitbadger.solutions",
|
||||||
|
"role": "Developer"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"support": {
|
||||||
|
"email": "daniel@bitbadger.solutions",
|
||||||
|
"source": "https://git.bitbadger.solutions/bit-badger/pdo-document",
|
||||||
|
"rss": "https://git.bitbadger.solutions/bit-badger/pdo-document.rss"
|
||||||
|
},
|
||||||
|
"require": {
|
||||||
|
"php": ">=8.2",
|
||||||
|
"netresearch/jsonmapper": "^4",
|
||||||
|
"ext-pdo": "*"
|
||||||
|
},
|
||||||
|
"require-dev": {
|
||||||
|
"phpunit/phpunit": "^11"
|
||||||
|
},
|
||||||
|
"autoload": {
|
||||||
|
"psr-4": {
|
||||||
|
"BitBadger\\PDODocument\\": "./src",
|
||||||
|
"BitBadger\\PDODocument\\Mapper\\": "./src/Mapper",
|
||||||
|
"BitBadger\\PDODocument\\Query\\": "./src/Query"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"autoload-dev": {
|
||||||
|
"psr-4": {
|
||||||
|
"Test\\Unit\\": "./tests/unit",
|
||||||
|
"Test\\Integration\\": "./tests/integration",
|
||||||
|
"Test\\Integration\\PostgreSQL\\": "./tests/integration/postgresql",
|
||||||
|
"Test\\Integration\\SQLite\\": "./tests/integration/sqlite"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"archive": {
|
||||||
|
"exclude": [ "/tests", "/.gitattributes", "/.gitignore", "/.git", "/composer.lock" ]
|
||||||
|
}
|
||||||
|
}
|
||||||
1705
composer.lock
generated
Normal file
1705
composer.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
52
src/AutoId.php
Normal file
52
src/AutoId.php
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
use Random\RandomException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How automatic ID generation should be performed
|
||||||
|
*/
|
||||||
|
enum AutoId
|
||||||
|
{
|
||||||
|
/** Do not automatically generate IDs */
|
||||||
|
case None;
|
||||||
|
|
||||||
|
/** New documents with a 0 ID should receive max ID plus one */
|
||||||
|
case Number;
|
||||||
|
|
||||||
|
/** New documents with a blank ID should receive a v4 UUID (Universally Unique Identifier) */
|
||||||
|
case UUID;
|
||||||
|
|
||||||
|
/** New documents with a blank ID should receive a random string (set `Configuration::$idStringLength`) */
|
||||||
|
case RandomString;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate a v4 UUID
|
||||||
|
*
|
||||||
|
* @return string The v4 UUID
|
||||||
|
* @throws RandomException If an appropriate source of randomness cannot be found
|
||||||
|
*/
|
||||||
|
public static function generateUUID(): string
|
||||||
|
{
|
||||||
|
// hat tip: https://stackoverflow.com/a/15875555/276707
|
||||||
|
$bytes = random_bytes(16);
|
||||||
|
|
||||||
|
$bytes[6] = chr(ord($bytes[6]) & 0x0f | 0x40); // set version to 0100
|
||||||
|
$bytes[8] = chr(ord($bytes[8]) & 0x3f | 0x80); // set bits 6-7 to 10
|
||||||
|
|
||||||
|
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate a random string ID
|
||||||
|
*
|
||||||
|
* @param int|null $length The length of string to generate (optional; defaults to configured ID string length)
|
||||||
|
* @return string A string filled with the hexadecimal representation of random bytes
|
||||||
|
* @throws RandomException If an appropriate source of randomness cannot be found
|
||||||
|
*/
|
||||||
|
public static function generateRandom(?int $length = null): string
|
||||||
|
{
|
||||||
|
return bin2hex(random_bytes(($length ?? Configuration::$idStringLength) / 2));
|
||||||
|
}
|
||||||
|
}
|
||||||
77
src/Configuration.php
Normal file
77
src/Configuration.php
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
use PDO;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Common configuration for the document library
|
||||||
|
*/
|
||||||
|
class Configuration
|
||||||
|
{
|
||||||
|
/** @var string The name of the ID field used in the database (will be treated as the primary key) */
|
||||||
|
public static string $idField = 'id';
|
||||||
|
|
||||||
|
/** @var AutoId The automatic ID generation process to use */
|
||||||
|
public static AutoId $autoId = AutoId::None;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var int The number of characters a string generated by `AutoId::RandomString` will have (must be an even number)
|
||||||
|
*/
|
||||||
|
public static int $idStringLength = 16;
|
||||||
|
|
||||||
|
/** @var string The data source name (DSN) of the connection string */
|
||||||
|
public static string $pdoDSN = '';
|
||||||
|
|
||||||
|
/** @var string|null The username to use to establish a data connection (use env PDO_DOC_USERNAME if possible) */
|
||||||
|
public static ?string $username = null;
|
||||||
|
|
||||||
|
/** @var string|null The password to use to establish a data connection (use env PDO_DOC_PASSWORD if possible) */
|
||||||
|
public static ?string $password = null;
|
||||||
|
|
||||||
|
/** @var array|null Options to use for connections (driver-specific) */
|
||||||
|
public static ?array $options = null;
|
||||||
|
|
||||||
|
/** @var Mode|null The mode in which the library is operating (filled after first connection if not configured) */
|
||||||
|
public static ?Mode $mode = null;
|
||||||
|
|
||||||
|
/** @var PDO|null The PDO instance to use for database commands */
|
||||||
|
private static ?PDO $_pdo = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve a new connection to the database
|
||||||
|
*
|
||||||
|
* @return PDO A new connection to the SQLite database with foreign key support enabled
|
||||||
|
* @throws DocumentException If this is called before a connection string is set
|
||||||
|
*/
|
||||||
|
public static function dbConn(): PDO
|
||||||
|
{
|
||||||
|
if (is_null(self::$_pdo)) {
|
||||||
|
if (empty(self::$pdoDSN)) {
|
||||||
|
throw new DocumentException('Please provide a data source name (DSN) before attempting data access');
|
||||||
|
}
|
||||||
|
self::$_pdo = new PDO(self::$pdoDSN, $_ENV['PDO_DOC_USERNAME'] ?? self::$username,
|
||||||
|
$_ENV['PDO_DOC_PASSWORD'] ?? self::$password, self::$options);
|
||||||
|
|
||||||
|
if (is_null(self::$mode)) {
|
||||||
|
$driver = 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clear the current PDO instance
|
||||||
|
*/
|
||||||
|
public static function resetPDO(): void
|
||||||
|
{
|
||||||
|
self::$_pdo = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
66
src/Count.php
Normal file
66
src/Count.php
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\Mapper\CountMapper;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Functions to count documents
|
||||||
|
*/
|
||||||
|
class Count
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Count all documents in a table
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which documents should be counted
|
||||||
|
* @return int The count of documents in the table
|
||||||
|
* @throws DocumentException If one is encountered
|
||||||
|
*/
|
||||||
|
public static function all(string $tableName): int
|
||||||
|
{
|
||||||
|
return Custom::scalar(Query\Count::all($tableName), [], new CountMapper());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Count matching documents using a comparison on JSON fields
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which documents should be counted
|
||||||
|
* @param array|Field[] $fields The field comparison to match
|
||||||
|
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
|
||||||
|
* @return int The count of documents matching the field comparison
|
||||||
|
* @throws DocumentException If one is encountered
|
||||||
|
*/
|
||||||
|
public static function byFields(string $tableName, array $fields, ?FieldMatch $match = null): int
|
||||||
|
{
|
||||||
|
$namedFields = Parameters::nameFields($fields);
|
||||||
|
return Custom::scalar(Query\Count::byFields($tableName, $namedFields, $match),
|
||||||
|
Parameters::addFields($namedFields, []), new CountMapper());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Count matching documents using a JSON containment query (`@>`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which documents should be counted
|
||||||
|
* @param array|object $criteria The criteria for the JSON containment query
|
||||||
|
* @return int The number of documents matching the JSON containment query
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function byContains(string $tableName, array|object $criteria): int
|
||||||
|
{
|
||||||
|
return Custom::scalar(Query\Count::byContains($tableName), Parameters::json(':criteria', $criteria),
|
||||||
|
new CountMapper());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Count matching documents using a JSON Path match query (`@?`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which documents should be counted
|
||||||
|
* @param string $path The JSON Path match string
|
||||||
|
* @return int The number of documents matching the given JSON Path criteria
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function byJsonPath(string $tableName, string $path): int
|
||||||
|
{
|
||||||
|
return Custom::scalar(Query\Count::byJsonPath($tableName), [':path' => $path], new CountMapper());
|
||||||
|
}
|
||||||
|
}
|
||||||
143
src/Custom.php
Normal file
143
src/Custom.php
Normal file
@@ -0,0 +1,143 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\Mapper\Mapper;
|
||||||
|
use PDO;
|
||||||
|
use PDOException;
|
||||||
|
use PDOStatement;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Functions to execute custom queries
|
||||||
|
*/
|
||||||
|
class Custom
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Prepare a query for execution and run it
|
||||||
|
*
|
||||||
|
* @param string $query The query to be run
|
||||||
|
* @param array $parameters The parameters for the query
|
||||||
|
* @return PDOStatement The result of executing the query
|
||||||
|
* @throws DocumentException If the query execution is unsuccessful
|
||||||
|
*/
|
||||||
|
public static function &runQuery(string $query, array $parameters): PDOStatement
|
||||||
|
{
|
||||||
|
$debug = defined('PDO_DOC_DEBUG_SQL');
|
||||||
|
try {
|
||||||
|
$stmt = Configuration::dbConn()->prepare($query);
|
||||||
|
} catch (PDOException $ex) {
|
||||||
|
$keyword = explode(' ', $query, 2)[0];
|
||||||
|
throw new DocumentException(
|
||||||
|
sprintf("Error executing %s statement: [%s] %s", $keyword, Configuration::dbConn()->errorCode(),
|
||||||
|
Configuration::dbConn()->errorInfo()[2]),
|
||||||
|
previous: $ex);
|
||||||
|
}
|
||||||
|
foreach ($parameters as $key => $value) {
|
||||||
|
if ($debug) echo "<pre>Binding $value to $key\n</pre>";
|
||||||
|
$dataType = match (true) {
|
||||||
|
is_bool($value) => PDO::PARAM_BOOL,
|
||||||
|
is_int($value) => PDO::PARAM_INT,
|
||||||
|
is_null($value) => PDO::PARAM_NULL,
|
||||||
|
default => PDO::PARAM_STR
|
||||||
|
};
|
||||||
|
$stmt->bindValue($key, $value, $dataType);
|
||||||
|
}
|
||||||
|
if ($debug) echo '<pre>SQL: ' . $stmt->queryString . '</pre>';
|
||||||
|
try {
|
||||||
|
if ($stmt->execute()) return $stmt;
|
||||||
|
} catch (PDOException $ex) {
|
||||||
|
$keyword = explode(' ', $query, 2)[0];
|
||||||
|
throw new DocumentException(
|
||||||
|
sprintf("Error executing %s statement: [%s] %s", $keyword, $stmt->errorCode(), $stmt->errorInfo()[2]),
|
||||||
|
previous: $ex);
|
||||||
|
}
|
||||||
|
$keyword = explode(' ', $query, 2)[0];
|
||||||
|
throw new DocumentException("Error executing $keyword statement: " . $stmt->errorCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute a query that returns a list of results (lazy)
|
||||||
|
*
|
||||||
|
* @template TDoc The domain type of the document to retrieve
|
||||||
|
* @param string $query The query to be executed
|
||||||
|
* @param array $parameters Parameters to use in executing the query
|
||||||
|
* @param Mapper<TDoc> $mapper Mapper to deserialize the result
|
||||||
|
* @return DocumentList<TDoc> The items matching the query
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function list(string $query, array $parameters, Mapper $mapper): DocumentList
|
||||||
|
{
|
||||||
|
return DocumentList::create($query, $parameters, $mapper);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute a query that returns an array of results (eager)
|
||||||
|
*
|
||||||
|
* @template TDoc The domain type of the document to retrieve
|
||||||
|
* @param string $query The query to be executed
|
||||||
|
* @param array $parameters Parameters to use in executing the query
|
||||||
|
* @param Mapper<TDoc> $mapper Mapper to deserialize the result
|
||||||
|
* @return TDoc[] The items matching the query
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function array(string $query, array $parameters, Mapper $mapper): array
|
||||||
|
{
|
||||||
|
return iterator_to_array(self::list($query, $parameters, $mapper)->items());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute a query that returns one or no results (returns false if not found)
|
||||||
|
*
|
||||||
|
* @template TDoc The domain type of the document to retrieve
|
||||||
|
* @param string $query The query to be executed (will have "LIMIT 1" appended)
|
||||||
|
* @param array $parameters Parameters to use in executing the query
|
||||||
|
* @param Mapper<TDoc> $mapper Mapper to deserialize the result
|
||||||
|
* @return false|TDoc The item if it is found, false if not
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function single(string $query, array $parameters, Mapper $mapper): mixed
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$stmt = &self::runQuery("$query LIMIT 1", $parameters);
|
||||||
|
return ($first = $stmt->fetch(PDO::FETCH_ASSOC)) ? $mapper->map($first) : false;
|
||||||
|
} finally {
|
||||||
|
$stmt = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute a query that does not return a value
|
||||||
|
*
|
||||||
|
* @param string $query The query to execute
|
||||||
|
* @param array $parameters Parameters to use in executing the query
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function nonQuery(string $query, array $parameters): void
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$stmt = &self::runQuery($query, $parameters);
|
||||||
|
} finally {
|
||||||
|
$stmt = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute a query that returns a scalar value
|
||||||
|
*
|
||||||
|
* @template T The scalar type to return
|
||||||
|
* @param string $query The query to retrieve the value
|
||||||
|
* @param array $parameters Parameters to use in executing the query
|
||||||
|
* @param Mapper<T> $mapper The mapper to obtain the result
|
||||||
|
* @return mixed|false|T The scalar value if found, false if not
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function scalar(string $query, array $parameters, Mapper $mapper): mixed
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$stmt = &self::runQuery($query, $parameters);
|
||||||
|
return ($first = $stmt->fetch(PDO::FETCH_NUM)) ? $mapper->map($first) : false;
|
||||||
|
} finally {
|
||||||
|
$stmt = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
46
src/Definition.php
Normal file
46
src/Definition.php
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Functions to create tables and indexes
|
||||||
|
*/
|
||||||
|
class Definition
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Ensure a document table exists
|
||||||
|
*
|
||||||
|
* @param string $name The name of the table to be created if it does not exist
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function ensureTable(string $name): void
|
||||||
|
{
|
||||||
|
Custom::nonQuery(Query\Definition::ensureTable($name), []);
|
||||||
|
Custom::nonQuery(Query\Definition::ensureKey($name), []);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ensure a field index exists on a document table
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table which should be indexed
|
||||||
|
* @param string $indexName The name of the index
|
||||||
|
* @param array $fields Fields which should be a part of this index
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function ensureFieldIndex(string $tableName, string $indexName, array $fields): void
|
||||||
|
{
|
||||||
|
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), []);
|
||||||
|
}
|
||||||
|
}
|
||||||
60
src/Delete.php
Normal file
60
src/Delete.php
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Functions to delete documents
|
||||||
|
*/
|
||||||
|
class Delete
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Delete a document by its ID
|
||||||
|
*
|
||||||
|
* @param string $tableName The table from which the document should be deleted
|
||||||
|
* @param mixed $docId The ID of the document to be deleted
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function byId(string $tableName, mixed $docId): void
|
||||||
|
{
|
||||||
|
Custom::nonQuery(Query\Delete::byId($tableName, $docId), Parameters::id($docId));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete documents by matching a comparison on JSON fields
|
||||||
|
*
|
||||||
|
* @param string $tableName The table from which documents should be deleted
|
||||||
|
* @param array|Field[] $fields The field comparison to match
|
||||||
|
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function byFields(string $tableName, array $fields, ?FieldMatch $match = null): void
|
||||||
|
{
|
||||||
|
$namedFields = Parameters::nameFields($fields);
|
||||||
|
Custom::nonQuery(Query\Delete::byFields($tableName, $namedFields, $match),
|
||||||
|
Parameters::addFields($namedFields, []));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete documents matching a JSON containment query (`@>`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The table from which documents should be deleted
|
||||||
|
* @param array|object $criteria The JSON containment query values
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function byContains(string $tableName, array|object $criteria): void
|
||||||
|
{
|
||||||
|
Custom::nonQuery(Query\Delete::byContains($tableName), Parameters::json(':criteria', $criteria));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete documents matching a JSON Path match query (`@?`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The table from which documents should be deleted
|
||||||
|
* @param string $path The JSON Path match string
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function byJsonPath(string $tableName, string $path): void
|
||||||
|
{
|
||||||
|
Custom::nonQuery(Query\Delete::byJsonPath($tableName), [':path' => $path]);
|
||||||
|
}
|
||||||
|
}
|
||||||
65
src/Document.php
Normal file
65
src/Document.php
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Functions that apply at a whole document level
|
||||||
|
*/
|
||||||
|
class Document
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Insert a new document
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table into which the document should be inserted
|
||||||
|
* @param array|object $document The document to be inserted
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function insert(string $tableName, array|object $document): void
|
||||||
|
{
|
||||||
|
$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")
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table to which the document should be saved
|
||||||
|
* @param array|object $document The document to be saved
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function save(string $tableName, array|object $document): void
|
||||||
|
{
|
||||||
|
Custom::nonQuery(Query::save($tableName), Parameters::json(':data', $document));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update (replace) an entire document by its ID
|
||||||
|
*
|
||||||
|
* @param string $tableName The table in which the document should be updated
|
||||||
|
* @param mixed $docId The ID of the document to be updated
|
||||||
|
* @param array|object $document The document to be updated
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function update(string $tableName, mixed $docId, array|object $document): void
|
||||||
|
{
|
||||||
|
Custom::nonQuery(Query::update($tableName),
|
||||||
|
array_merge(Parameters::id($docId), Parameters::json(':data', $document)));
|
||||||
|
}
|
||||||
|
}
|
||||||
30
src/DocumentException.php
Normal file
30
src/DocumentException.php
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
use Exception;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Exceptions occurring during document processing
|
||||||
|
*/
|
||||||
|
class DocumentException extends Exception
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Constructor
|
||||||
|
*
|
||||||
|
* @param string $message A message for the exception
|
||||||
|
* @param int $code The code for the exception (optional; defaults to 0)
|
||||||
|
* @param Throwable|null $previous The previous exception (optional; defaults to `null`)
|
||||||
|
*/
|
||||||
|
public function __construct(string $message, int $code = 0, ?Throwable $previous = null)
|
||||||
|
{
|
||||||
|
parent::__construct($message, $code, $previous);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function __toString(): string
|
||||||
|
{
|
||||||
|
$codeStr = $this->code == 0 ? '' : "[$this->code] ";
|
||||||
|
return __CLASS__ . ": $codeStr$this->message\n";
|
||||||
|
}
|
||||||
|
}
|
||||||
15
src/DocumentIndex.php
Normal file
15
src/DocumentIndex.php
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The type of index to generate for the document
|
||||||
|
*/
|
||||||
|
enum DocumentIndex
|
||||||
|
{
|
||||||
|
/** A GIN index with standard operations (all operators supported) */
|
||||||
|
case Full;
|
||||||
|
|
||||||
|
/** A GIN index with JSONPath operations (optimized for @>, @?, @@ operators) */
|
||||||
|
case Optimized;
|
||||||
|
}
|
||||||
83
src/DocumentList.php
Normal file
83
src/DocumentList.php
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\Mapper\Mapper;
|
||||||
|
use Generator;
|
||||||
|
use PDO;
|
||||||
|
use PDOStatement;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A lazy iterator of results in a list; implementations will create new connections to the database and close/dispose
|
||||||
|
* them as required once the results have been exhausted.
|
||||||
|
*
|
||||||
|
* @template TDoc The domain class for items returned by this list
|
||||||
|
*/
|
||||||
|
class DocumentList
|
||||||
|
{
|
||||||
|
/** @var TDoc|null $_first The first item from the results */
|
||||||
|
private mixed $_first = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Constructor
|
||||||
|
*
|
||||||
|
* @param PDOStatement|null $result The result of the query
|
||||||
|
* @param Mapper<TDoc> $mapper The mapper to deserialize JSON
|
||||||
|
*/
|
||||||
|
private function __construct(private ?PDOStatement &$result, private readonly Mapper $mapper)
|
||||||
|
{
|
||||||
|
if ($row = $this->result->fetch(PDO::FETCH_ASSOC)) {
|
||||||
|
$this->_first = $this->mapper->map($row);
|
||||||
|
} else {
|
||||||
|
$this->result = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Construct a new document list
|
||||||
|
*
|
||||||
|
* @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
|
||||||
|
*
|
||||||
|
* @return Generator<TDoc> The items from the document list
|
||||||
|
*/
|
||||||
|
public function items(): Generator
|
||||||
|
{
|
||||||
|
if (!$this->result) return;
|
||||||
|
yield $this->_first;
|
||||||
|
while ($row = $this->result->fetch(PDO::FETCH_ASSOC)) {
|
||||||
|
yield $this->mapper->map($row);
|
||||||
|
}
|
||||||
|
$this->result = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Does this list have items remaining?
|
||||||
|
*
|
||||||
|
* @return bool True if there are items still to be retrieved from the list, false if not
|
||||||
|
*/
|
||||||
|
public function hasItems(): bool
|
||||||
|
{
|
||||||
|
return !is_null($this->result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ensure the statement is destroyed if the generator is not exhausted
|
||||||
|
*/
|
||||||
|
public function __destruct()
|
||||||
|
{
|
||||||
|
if (!is_null($this->result)) $this->result = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
67
src/Exists.php
Normal file
67
src/Exists.php
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\Mapper\ExistsMapper;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Functions to determine if documents exist
|
||||||
|
*/
|
||||||
|
class Exists
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Determine if a document exists for the given ID
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which document existence should be determined
|
||||||
|
* @param mixed $docId The ID of the document whose existence should be determined
|
||||||
|
* @return bool True if the document exists, false if not
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function byId(string $tableName, mixed $docId): bool
|
||||||
|
{
|
||||||
|
return Custom::scalar(Query\Exists::byId($tableName, $docId), Parameters::id($docId), new ExistsMapper());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determine if a document exists using a comparison on JSON fields
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which document existence should be determined
|
||||||
|
* @param Field[] $fields The field comparison to match
|
||||||
|
* @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
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function byFields(string $tableName, array $fields, ?FieldMatch $match = null): bool
|
||||||
|
{
|
||||||
|
$namedFields = Parameters::nameFields($fields);
|
||||||
|
return Custom::scalar(Query\Exists::byFields($tableName, $namedFields, $match),
|
||||||
|
Parameters::addFields($namedFields, []), new ExistsMapper());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determine if documents exist by a JSON containment query (`@>`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which document existence should be determined
|
||||||
|
* @param array|object $criteria The criteria for the JSON containment query
|
||||||
|
* @return bool True if any documents match the JSON containment query, false if not
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function byContains(string $tableName, array|object $criteria): bool
|
||||||
|
{
|
||||||
|
return Custom::scalar(Query\Exists::byContains($tableName), Parameters::json(':criteria', $criteria),
|
||||||
|
new ExistsMapper());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determine if documents exist by a JSON Path match query (`@?`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which document existence should be determined
|
||||||
|
* @param string $path The JSON Path match string
|
||||||
|
* @return bool True if any documents match the JSON Path string, false if not
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function byJsonPath(string $tableName, string $path): bool
|
||||||
|
{
|
||||||
|
return Custom::scalar(Query\Exists::byJsonPath($tableName), [':path' => $path], new ExistsMapper());
|
||||||
|
}
|
||||||
|
}
|
||||||
190
src/Field.php
Normal file
190
src/Field.php
Normal file
@@ -0,0 +1,190 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Criteria for a field WHERE clause
|
||||||
|
*/
|
||||||
|
class Field
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Constructor
|
||||||
|
*
|
||||||
|
* NOTE: Use static construction methods rather than using this directly; different properties are required
|
||||||
|
* depending on the operation being performed. This is only public so it can be tested.
|
||||||
|
*
|
||||||
|
* @param string $fieldName The name of the field
|
||||||
|
* @param Op $op The operation by which the field will be compared
|
||||||
|
* @param mixed $value The value of the field
|
||||||
|
* @param string $paramName The name of the parameter to which this should be bound
|
||||||
|
* @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 string $paramName = '', public string $qualifier = '') { }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Append the parameter name and value to the given associative array
|
||||||
|
*
|
||||||
|
* @param array $existing The existing parameters
|
||||||
|
* @return array The given parameter array with this field's name and value appended
|
||||||
|
*/
|
||||||
|
public function appendParameter(array $existing): array
|
||||||
|
{
|
||||||
|
switch ($this->op) {
|
||||||
|
case Op::EX:
|
||||||
|
case Op::NEX:
|
||||||
|
break;
|
||||||
|
case Op::BT:
|
||||||
|
$existing["{$this->paramName}min"] = $this->value[0];
|
||||||
|
$existing["{$this->paramName}max"] = $this->value[1];
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
$existing[$this->paramName] = $this->value;
|
||||||
|
}
|
||||||
|
return $existing;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the WHERE clause fragment for this parameter
|
||||||
|
*
|
||||||
|
* @return string The WHERE clause fragment for this parameter
|
||||||
|
* @throws DocumentException If the database mode has not been set
|
||||||
|
*/
|
||||||
|
public function toWhere(): string
|
||||||
|
{
|
||||||
|
$fieldName = ($this->qualifier == '' ? '' : "$this->qualifier.") . 'data' . match (true) {
|
||||||
|
!str_contains($this->fieldName, '.') => "->>'$this->fieldName'",
|
||||||
|
Configuration::$mode == Mode::PgSQL => "#>>'{" . implode(',', explode('.', $this->fieldName)) . "}'",
|
||||||
|
Configuration::$mode == Mode::SQLite => "->>'" . implode("'->>'", explode('.', $this->fieldName)) . "'",
|
||||||
|
default => throw new DocumentException('Database mode not set; cannot make field WHERE clause')
|
||||||
|
};
|
||||||
|
$fieldPath = match (Configuration::$mode) {
|
||||||
|
Mode::PgSQL => match (true) {
|
||||||
|
$this->op == Op::BT => is_numeric($this->value[0]) ? "($fieldName)::numeric" : $fieldName,
|
||||||
|
is_numeric($this->value) => "($fieldName)::numeric",
|
||||||
|
default => $fieldName
|
||||||
|
},
|
||||||
|
default => $fieldName
|
||||||
|
};
|
||||||
|
$criteria = match ($this->op) {
|
||||||
|
Op::EX, Op::NEX => '',
|
||||||
|
Op::BT => " {$this->paramName}min AND {$this->paramName}max",
|
||||||
|
default => " $this->paramName"
|
||||||
|
};
|
||||||
|
return $fieldPath . ' ' . $this->op->toString() . $criteria;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create an equals (=) field criterion
|
||||||
|
*
|
||||||
|
* @param string $fieldName The name of the field against which the value will be compared
|
||||||
|
* @param mixed $value The value for which equality will be checked
|
||||||
|
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||||
|
* @return static The field with the requested criterion
|
||||||
|
*/
|
||||||
|
public static function EQ(string $fieldName, mixed $value, string $paramName = ''): static
|
||||||
|
{
|
||||||
|
return new static($fieldName, Op::EQ, $value, $paramName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a greater than (>) field criterion
|
||||||
|
*
|
||||||
|
* @param string $fieldName The name of the field against which the value will be compared
|
||||||
|
* @param mixed $value The value for the greater than comparison
|
||||||
|
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||||
|
* @return static The field with the requested criterion
|
||||||
|
*/
|
||||||
|
public static function GT(string $fieldName, mixed $value, string $paramName = ''): static
|
||||||
|
{
|
||||||
|
return new static($fieldName, Op::GT, $value, $paramName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a greater than or equal to (>=) field criterion
|
||||||
|
*
|
||||||
|
* @param string $fieldName The name of the field against which the value will be compared
|
||||||
|
* @param mixed $value The value for the greater than or equal to comparison
|
||||||
|
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||||
|
* @return static The field with the requested criterion
|
||||||
|
*/
|
||||||
|
public static function GE(string $fieldName, mixed $value, string $paramName = ''): static
|
||||||
|
{
|
||||||
|
return new static($fieldName, Op::GE, $value, $paramName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a less than (<) field criterion
|
||||||
|
*
|
||||||
|
* @param string $fieldName The name of the field against which the value will be compared
|
||||||
|
* @param mixed $value The value for the less than comparison
|
||||||
|
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||||
|
* @return static The field with the requested criterion
|
||||||
|
*/
|
||||||
|
public static function LT(string $fieldName, mixed $value, string $paramName = ''): static
|
||||||
|
{
|
||||||
|
return new static($fieldName, Op::LT, $value, $paramName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a less than or equal to (<=) field criterion
|
||||||
|
*
|
||||||
|
* @param string $fieldName The name of the field against which the value will be compared
|
||||||
|
* @param mixed $value The value for the less than or equal to comparison
|
||||||
|
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||||
|
* @return static The field with the requested criterion
|
||||||
|
*/
|
||||||
|
public static function LE(string $fieldName, mixed $value, string $paramName = ''): static
|
||||||
|
{
|
||||||
|
return new static($fieldName, Op::LE, $value, $paramName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a not equals (<>) field criterion
|
||||||
|
*
|
||||||
|
* @param string $fieldName The name of the field against which the value will be compared
|
||||||
|
* @param mixed $value The value for the not equals comparison
|
||||||
|
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||||
|
* @return static The field with the requested criterion
|
||||||
|
*/
|
||||||
|
public static function NE(string $fieldName, mixed $value, string $paramName = ''): static
|
||||||
|
{
|
||||||
|
return new static($fieldName, Op::NE, $value, $paramName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a BETWEEN field criterion
|
||||||
|
*
|
||||||
|
* @param string $fieldName The name of the field against which the value will be compared
|
||||||
|
* @param mixed $minValue The lower value for range
|
||||||
|
* @param mixed $maxValue The upper value for the range
|
||||||
|
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||||
|
* @return static The field with the requested criterion
|
||||||
|
*/
|
||||||
|
public static function BT(string $fieldName, mixed $minValue, mixed $maxValue, string $paramName = ''): static
|
||||||
|
{
|
||||||
|
return new static($fieldName, Op::BT, [$minValue, $maxValue], $paramName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create an exists (IS NOT NULL) field criterion
|
||||||
|
*
|
||||||
|
* @param string $fieldName The name of the field for which existence will be checked
|
||||||
|
* @return static The field with the requested criterion
|
||||||
|
*/
|
||||||
|
public static function EX(string $fieldName): static
|
||||||
|
{
|
||||||
|
return new static($fieldName, Op::EX, '', '');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a not exists (IS NULL) field criterion
|
||||||
|
*
|
||||||
|
* @param string $fieldName The name of the field for which non-existence will be checked
|
||||||
|
* @return static The field with the requested criterion
|
||||||
|
*/
|
||||||
|
public static function NEX(string $fieldName): static
|
||||||
|
{
|
||||||
|
return new static($fieldName, Op::NEX, '', '');
|
||||||
|
}
|
||||||
|
}
|
||||||
28
src/FieldMatch.php
Normal file
28
src/FieldMatch.php
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How multiple fields should be matched
|
||||||
|
*/
|
||||||
|
enum FieldMatch
|
||||||
|
{
|
||||||
|
/** Match all provided fields (`AND`) */
|
||||||
|
case All;
|
||||||
|
|
||||||
|
/** Match any provided fields (`OR`) */
|
||||||
|
case Any;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the SQL keyword for this enumeration value
|
||||||
|
*
|
||||||
|
* @return string The SQL keyword for this enumeration value
|
||||||
|
*/
|
||||||
|
public function toString(): string
|
||||||
|
{
|
||||||
|
return match ($this) {
|
||||||
|
FieldMatch::All => 'AND',
|
||||||
|
FieldMatch::Any => 'OR'
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
141
src/Find.php
Normal file
141
src/Find.php
Normal file
@@ -0,0 +1,141 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\Mapper\DocumentMapper;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Functions to find documents
|
||||||
|
*/
|
||||||
|
class Find
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Retrieve all documents in the given table
|
||||||
|
*
|
||||||
|
* @template TDoc The type of document to 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
|
||||||
|
* @return DocumentList<TDoc> A list of all documents from the table
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function all(string $tableName, string $className): DocumentList
|
||||||
|
{
|
||||||
|
return Custom::list(Query::selectFromTable($tableName), [], new DocumentMapper($className));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve a document by its ID (returns false if not found)
|
||||||
|
*
|
||||||
|
* @template TDoc The type of document to be retrieved
|
||||||
|
* @param string $tableName The table from which the document should be retrieved
|
||||||
|
* @param mixed $docId The ID of the document to retrieve
|
||||||
|
* @param class-string<TDoc> $className The name of the class to be retrieved
|
||||||
|
* @return false|TDoc The document if it exists, false if not
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function byId(string $tableName, mixed $docId, string $className): mixed
|
||||||
|
{
|
||||||
|
return Custom::single(Query\Find::byId($tableName, $docId), Parameters::id($docId),
|
||||||
|
new DocumentMapper($className));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve documents via a comparison on JSON fields
|
||||||
|
*
|
||||||
|
* @template TDoc The type of document to be retrieved
|
||||||
|
* @param string $tableName The table from which documents should be retrieved
|
||||||
|
* @param array|Field[] $fields The field comparison to match
|
||||||
|
* @param class-string<TDoc> $className The name of the class to be retrieved
|
||||||
|
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
|
||||||
|
* @return DocumentList<TDoc> A list of documents matching the given field comparison
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function byFields(string $tableName, array $fields, string $className,
|
||||||
|
?FieldMatch $match = null): DocumentList
|
||||||
|
{
|
||||||
|
$namedFields = Parameters::nameFields($fields);
|
||||||
|
return Custom::list(Query\Find::byFields($tableName, $namedFields, $match),
|
||||||
|
Parameters::addFields($namedFields, []), new DocumentMapper($className));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve documents via a JSON containment query (`@>`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @template TDoc The type of document to be retrieved
|
||||||
|
* @param string $tableName The name of the table from which documents should be retrieved
|
||||||
|
* @param array|object $criteria The criteria for the JSON containment query
|
||||||
|
* @param class-string<TDoc> $className The name of the class to be retrieved
|
||||||
|
* @return DocumentList<TDoc> A list of documents matching the JSON containment query
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function byContains(string $tableName, array|object $criteria, string $className): DocumentList
|
||||||
|
{
|
||||||
|
return Custom::list(Query\Find::byContains($tableName), Parameters::json(':criteria', $criteria),
|
||||||
|
new DocumentMapper($className));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve documents via a JSON Path match query (`@?`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @template TDoc The type of document to be retrieved
|
||||||
|
* @param string $tableName The name of the table from which documents should be retrieved
|
||||||
|
* @param string $path The JSON Path match string
|
||||||
|
* @param class-string<TDoc> $className The name of the class to be retrieved
|
||||||
|
* @return DocumentList<TDoc> A list of documents matching the JSON Path
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function byJsonPath(string $tableName, string $path, string $className): DocumentList
|
||||||
|
{
|
||||||
|
return Custom::list(Query\Find::byJsonPath($tableName), [':path' => $path], new DocumentMapper($className));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve documents via a comparison on JSON fields, returning only the first result
|
||||||
|
*
|
||||||
|
* @template TDoc The type of document to be retrieved
|
||||||
|
* @param string $tableName The table from which the document should be retrieved
|
||||||
|
* @param array|Field[] $fields The field comparison to match
|
||||||
|
* @param class-string<TDoc> $className The name of the class to be retrieved
|
||||||
|
* @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
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function firstByFields(string $tableName, array $fields, string $className,
|
||||||
|
?FieldMatch $match = null): mixed
|
||||||
|
{
|
||||||
|
$namedFields = Parameters::nameFields($fields);
|
||||||
|
return Custom::single(Query\Find::byFields($tableName, $namedFields, $match),
|
||||||
|
Parameters::addFields($namedFields, []), new DocumentMapper($className));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve documents via a JSON containment query (`@>`), returning only the first result (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @template TDoc The type of document to be retrieved
|
||||||
|
* @param string $tableName The name of the table from which documents should be retrieved
|
||||||
|
* @param array|object $criteria The criteria for the JSON containment query
|
||||||
|
* @param class-string<TDoc> $className The name of the class to be retrieved
|
||||||
|
* @return false|TDoc The first document matching the JSON containment query if any is found, false 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): mixed
|
||||||
|
{
|
||||||
|
return Custom::single(Query\Find::byContains($tableName), Parameters::json(':criteria', $criteria),
|
||||||
|
new DocumentMapper($className));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve documents via a JSON Path match query (`@?`), returning only the first result (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @template TDoc The type of document to be retrieved
|
||||||
|
* @param string $tableName The name of the table from which documents should be retrieved
|
||||||
|
* @param string $path The JSON Path match string
|
||||||
|
* @param class-string<TDoc> $className The name of the class to be retrieved
|
||||||
|
* @return false|TDoc The first document matching the JSON Path if any is found, false 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): mixed
|
||||||
|
{
|
||||||
|
return Custom::single(Query\Find::byJsonPath($tableName), [':path' => $path], new DocumentMapper($className));
|
||||||
|
}
|
||||||
|
}
|
||||||
17
src/Mapper/ArrayMapper.php
Normal file
17
src/Mapper/ArrayMapper.php
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument\Mapper;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A mapper that returns the associative array from the database
|
||||||
|
*/
|
||||||
|
class ArrayMapper implements Mapper
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @inheritDoc
|
||||||
|
*/
|
||||||
|
public function map(array $result): array
|
||||||
|
{
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
}
|
||||||
17
src/Mapper/CountMapper.php
Normal file
17
src/Mapper/CountMapper.php
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument\Mapper;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A mapper that returns the integer value of the first item in the results
|
||||||
|
*/
|
||||||
|
class CountMapper implements Mapper
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @inheritDoc
|
||||||
|
*/
|
||||||
|
public function map(array $result): int
|
||||||
|
{
|
||||||
|
return (int) $result[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
44
src/Mapper/DocumentMapper.php
Normal file
44
src/Mapper/DocumentMapper.php
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument\Mapper;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\DocumentException;
|
||||||
|
use JsonMapper;
|
||||||
|
use JsonMapper_Exception;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map domain class instances from JSON documents
|
||||||
|
*
|
||||||
|
* @template TDoc The type of document returned by this mapper
|
||||||
|
* @implements Mapper<TDoc> Provide a mapping from JSON
|
||||||
|
*/
|
||||||
|
class DocumentMapper implements Mapper
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Constructor
|
||||||
|
*
|
||||||
|
* @param class-string<TDoc> $className The type of class to be returned by this mapping
|
||||||
|
* @param string $fieldName The name of the field (optional; defaults to `data`)
|
||||||
|
*/
|
||||||
|
public function __construct(public string $className, public string $fieldName = 'data') { }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map a result to a domain class instance
|
||||||
|
*
|
||||||
|
* @param array $result An associative array representing a single database result
|
||||||
|
* @return TDoc The document, deserialized from its JSON representation
|
||||||
|
* @throws DocumentException If the JSON cannot be deserialized
|
||||||
|
*/
|
||||||
|
public function map(array $result): mixed
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$json = json_decode($result[$this->fieldName]);
|
||||||
|
if (is_null($json)) {
|
||||||
|
throw new DocumentException("Could not map document for $this->className: " . json_last_error_msg());
|
||||||
|
}
|
||||||
|
return (new JsonMapper())->map($json, $this->className);
|
||||||
|
} catch (JsonMapper_Exception $ex) {
|
||||||
|
throw new DocumentException("Could not map document for $this->className", previous: $ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
24
src/Mapper/ExistsMapper.php
Normal file
24
src/Mapper/ExistsMapper.php
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument\Mapper;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Configuration, DocumentException, Mode};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map an EXISTS result to a boolean value
|
||||||
|
*/
|
||||||
|
class ExistsMapper implements Mapper
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @inheritDoc
|
||||||
|
* @throws DocumentException If the database mode has not been set
|
||||||
|
*/
|
||||||
|
public function map(array $result): bool
|
||||||
|
{
|
||||||
|
return match (Configuration::$mode) {
|
||||||
|
Mode::PgSQL => (bool)$result[0],
|
||||||
|
Mode::SQLite => (int)$result[0] > 0,
|
||||||
|
default => throw new DocumentException('Database mode not set; cannot map existence result'),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
19
src/Mapper/Mapper.php
Normal file
19
src/Mapper/Mapper.php
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument\Mapper;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map an associative array of results to a domain class
|
||||||
|
*
|
||||||
|
* @template T The type of document retrieved by this mapper
|
||||||
|
*/
|
||||||
|
interface Mapper
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Map a result to the specified type
|
||||||
|
*
|
||||||
|
* @param array $result An associative array representing a single database result
|
||||||
|
* @return T The item mapped from the given result
|
||||||
|
*/
|
||||||
|
public function map(array $result): mixed;
|
||||||
|
}
|
||||||
30
src/Mapper/StringMapper.php
Normal file
30
src/Mapper/StringMapper.php
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument\Mapper;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map a string result from the
|
||||||
|
*
|
||||||
|
* @implements Mapper<string>
|
||||||
|
*/
|
||||||
|
class StringMapper implements Mapper
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Constructor
|
||||||
|
*
|
||||||
|
* @param string $fieldName The name of the field to be retrieved as a string
|
||||||
|
*/
|
||||||
|
public function __construct(public string $fieldName) { }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @inheritDoc
|
||||||
|
*/
|
||||||
|
public function map(array $result): ?string
|
||||||
|
{
|
||||||
|
return match (false) {
|
||||||
|
key_exists($this->fieldName, $result) => null,
|
||||||
|
is_string($result[$this->fieldName]) => "{$result[$this->fieldName]}",
|
||||||
|
default => $result[$this->fieldName]
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
15
src/Mode.php
Normal file
15
src/Mode.php
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The mode for queries generated by the library
|
||||||
|
*/
|
||||||
|
enum Mode
|
||||||
|
{
|
||||||
|
/** Storing documents in a PostgreSQL database */
|
||||||
|
case PgSQL;
|
||||||
|
|
||||||
|
/** Storing documents in a SQLite database */
|
||||||
|
case SQLite;
|
||||||
|
}
|
||||||
48
src/Op.php
Normal file
48
src/Op.php
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The types of logical operations allowed for JSON fields
|
||||||
|
*/
|
||||||
|
enum Op
|
||||||
|
{
|
||||||
|
/** Equals (=) */
|
||||||
|
case EQ;
|
||||||
|
/** Greater Than (>) */
|
||||||
|
case GT;
|
||||||
|
/** Greater Than or Equal To (>=) */
|
||||||
|
case GE;
|
||||||
|
/** Less Than (<) */
|
||||||
|
case LT;
|
||||||
|
/** Less Than or Equal To (<=) */
|
||||||
|
case LE;
|
||||||
|
/** Not Equal to (<>) */
|
||||||
|
case NE;
|
||||||
|
/** Between (BETWEEN) */
|
||||||
|
case BT;
|
||||||
|
/** Exists (IS NOT NULL) */
|
||||||
|
case EX;
|
||||||
|
/** Does Not Exist (IS NULL) */
|
||||||
|
case NEX;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the string representation of this operator
|
||||||
|
*
|
||||||
|
* @return string The operator to use in SQL statements
|
||||||
|
*/
|
||||||
|
public function toString(): string
|
||||||
|
{
|
||||||
|
return match ($this) {
|
||||||
|
Op::EQ => "=",
|
||||||
|
Op::GT => ">",
|
||||||
|
Op::GE => ">=",
|
||||||
|
Op::LT => "<",
|
||||||
|
Op::LE => "<=",
|
||||||
|
Op::NE => "<>",
|
||||||
|
Op::BT => "BETWEEN",
|
||||||
|
Op::EX => "IS NOT NULL",
|
||||||
|
Op::NEX => "IS NULL"
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
81
src/Parameters.php
Normal file
81
src/Parameters.php
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Functions to create parameters for queries
|
||||||
|
*/
|
||||||
|
class Parameters
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Create an ID parameter (name ":id", key will be treated as a string)
|
||||||
|
*
|
||||||
|
* @param mixed $key The key representing the ID of the document
|
||||||
|
* @return array|string[] An associative array with an "@id" parameter/value pair
|
||||||
|
*/
|
||||||
|
public static function id(mixed $key): array
|
||||||
|
{
|
||||||
|
return [':id' => is_int($key) || is_string($key) ? $key : "$key"];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a parameter with a JSON value
|
||||||
|
*
|
||||||
|
* @param string $name The name of the JSON parameter
|
||||||
|
* @param object|array $document The value that should be passed as a JSON string
|
||||||
|
* @return array An associative array with the named parameter/value pair
|
||||||
|
*/
|
||||||
|
public static function json(string $name, object|array $document): array
|
||||||
|
{
|
||||||
|
return [$name => json_encode($document, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fill in parameter names for any fields missing one
|
||||||
|
*
|
||||||
|
* @param array|Field[] $fields The fields for the query
|
||||||
|
* @return array|Field[] The fields, all with non-blank parameter names
|
||||||
|
*/
|
||||||
|
public static function nameFields(array $fields): array
|
||||||
|
{
|
||||||
|
for ($idx = 0; $idx < sizeof($fields); $idx++) {
|
||||||
|
if ($fields[$idx]->paramName == '') $fields[$idx]->paramName = ":field$idx";
|
||||||
|
}
|
||||||
|
return $fields;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add field parameters to the given set of parameters
|
||||||
|
*
|
||||||
|
* @param array|Field[] $fields The fields being compared in the query
|
||||||
|
* @param array $parameters An associative array of parameters to which the fields should be added
|
||||||
|
* @return array An associative array of parameter names and values with the fields added
|
||||||
|
*/
|
||||||
|
public static function addFields(array $fields, array $parameters): array
|
||||||
|
{
|
||||||
|
return array_reduce($fields, fn($carry, $item) => $item->appendParameter($carry), $parameters);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create JSON field name parameters for the given field names to the given parameter
|
||||||
|
*
|
||||||
|
* @param string $paramName The name of the parameter for the field names
|
||||||
|
* @param array|string[] $fieldNames The names of the fields for the parameter
|
||||||
|
* @return array An associative array of parameter/value pairs for the field names
|
||||||
|
* @throws DocumentException If the database mode has not been set
|
||||||
|
*/
|
||||||
|
public static function fieldNames(string $paramName, array $fieldNames): array
|
||||||
|
{
|
||||||
|
switch (Configuration::$mode) {
|
||||||
|
case Mode::PgSQL:
|
||||||
|
return [$paramName => "{" . implode(",", $fieldNames) . "}"];
|
||||||
|
case Mode::SQLite:
|
||||||
|
$it = [];
|
||||||
|
$idx = 0;
|
||||||
|
foreach ($fieldNames as $field) $it[$paramName . $idx++] = "$.$field";
|
||||||
|
return $it;
|
||||||
|
default:
|
||||||
|
throw new DocumentException('Database mode not set; cannot generate field name parameters');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
68
src/Patch.php
Normal file
68
src/Patch.php
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Functions to patch (partially update) documents
|
||||||
|
*/
|
||||||
|
class Patch
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Patch a document by its ID
|
||||||
|
*
|
||||||
|
* @param string $tableName The table in which the document should be patched
|
||||||
|
* @param mixed $docId The ID of the document to be patched
|
||||||
|
* @param array|object $patch The object with which the document should be patched (will be JSON-encoded)
|
||||||
|
* @throws DocumentException If any is encountered (database mode must be set)
|
||||||
|
*/
|
||||||
|
public static function byId(string $tableName, mixed $docId, array|object $patch): void
|
||||||
|
{
|
||||||
|
Custom::nonQuery(Query\Patch::byId($tableName, $docId),
|
||||||
|
array_merge(Parameters::id($docId), Parameters::json(':data', $patch)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Patch documents using a comparison on JSON fields
|
||||||
|
*
|
||||||
|
* @param string $tableName The table in which documents should be patched
|
||||||
|
* @param array|Field[] $fields The field comparison to match
|
||||||
|
* @param array|object $patch The object with which the documents should be patched (will be JSON-encoded)
|
||||||
|
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function byFields(string $tableName, array $fields, array|object $patch,
|
||||||
|
?FieldMatch $match = null): void
|
||||||
|
{
|
||||||
|
$namedFields = Parameters::nameFields($fields);
|
||||||
|
Custom::nonQuery(Query\Patch::byFields($tableName, $namedFields, $match),
|
||||||
|
Parameters::addFields($namedFields, Parameters::json(':data', $patch)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Patch documents using a JSON containment query (`@>`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The table in which documents should be patched
|
||||||
|
* @param array|object $criteria The JSON containment query values to match
|
||||||
|
* @param array|object $patch The object with which the documents should be patched (will be JSON-encoded)
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function byContains(string $tableName, array|object $criteria, array|object $patch): void
|
||||||
|
{
|
||||||
|
Custom::nonQuery(Query\Patch::byContains($tableName),
|
||||||
|
array_merge(Parameters::json(':criteria', $criteria), Parameters::json(':data', $patch)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Patch documents using a JSON Path match query (`@?`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The table in which documents should be patched
|
||||||
|
* @param string $path The JSON Path match string
|
||||||
|
* @param array|object $patch The object with which the documents should be patched (will be JSON-encoded)
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function byJsonPath(string $tableName, string $path, array|object $patch): void
|
||||||
|
{
|
||||||
|
Custom::nonQuery(Query\Patch::byJsonPath($tableName),
|
||||||
|
array_merge([':path' => $path], Parameters::json(':data', $patch)));
|
||||||
|
}
|
||||||
|
}
|
||||||
141
src/Query.php
Normal file
141
src/Query.php
Normal file
@@ -0,0 +1,141 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
use Random\RandomException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query construction functions
|
||||||
|
*/
|
||||||
|
class Query
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Create a SELECT clause to retrieve the document data from the given table
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table from which document data should be retrieved
|
||||||
|
* @return string The SELECT clause to retrieve a document from the given table
|
||||||
|
*/
|
||||||
|
public static function selectFromTable(string $tableName): string
|
||||||
|
{
|
||||||
|
return "SELECT data FROM $tableName";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a WHERE clause fragment to implement a comparison on fields in a JSON document
|
||||||
|
*
|
||||||
|
* @param Field[] $fields The field comparison to generate
|
||||||
|
* @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
|
||||||
|
* @throws DocumentException If the database mode has not been set
|
||||||
|
*/
|
||||||
|
public static function whereByFields(array $fields, ?FieldMatch $match = null): string
|
||||||
|
{
|
||||||
|
return implode(' ' . ($match ?? FieldMatch::All)->toString() . ' ',
|
||||||
|
array_map(fn($it) => $it->toWhere(), $fields));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a WHERE clause fragment to implement an ID-based query
|
||||||
|
*
|
||||||
|
* @param string $paramName The parameter name where the value of the ID will be provided (optional; default @id)
|
||||||
|
* @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
|
||||||
|
* @throws DocumentException If the database mode has not been set
|
||||||
|
*/
|
||||||
|
public static function whereById(string $paramName = ':id', mixed $docId = null): string
|
||||||
|
{
|
||||||
|
return self::whereByFields([Field::EQ(Configuration::$idField, $docId ?? '', $paramName)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a WHERE clause fragment to implement a JSON containment query (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $paramName The name of the parameter (optional; defaults to `:criteria`)
|
||||||
|
* @return string The WHERE clause fragment for a JSON containment query
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL
|
||||||
|
*/
|
||||||
|
public static function whereDataContains(string $paramName = ':criteria'): string
|
||||||
|
{
|
||||||
|
if (Configuration::$mode <> Mode::PgSQL) {
|
||||||
|
throw new DocumentException('JSON containment is only supported on PostgreSQL');
|
||||||
|
}
|
||||||
|
return "data @> $paramName";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a WHERE clause fragment to implement a JSON Path match query (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $paramName The name of the parameter (optional; defaults to `:path`)
|
||||||
|
* @return string The WHERE clause fragment for a JSON Path match query
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL
|
||||||
|
*/
|
||||||
|
public static function whereJsonPathMatches(string $paramName = ':path'): string
|
||||||
|
{
|
||||||
|
if (Configuration::$mode <> Mode::PgSQL) {
|
||||||
|
throw new DocumentException('JSON Path matching is only supported on PostgreSQL');
|
||||||
|
}
|
||||||
|
return "jsonb_path_exists(data, $paramName::jsonpath)";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create an `INSERT` statement for a document
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table into which the document will be inserted
|
||||||
|
* @param AutoId|null $autoId The version of automatic ID query to generate (optional, defaults to None)
|
||||||
|
* @return string The `INSERT` statement to insert a document
|
||||||
|
* @throws DocumentException If the database mode is not set
|
||||||
|
*/
|
||||||
|
public static function insert(string $tableName, ?AutoId $autoId = null): string
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$id = Configuration::$idField;
|
||||||
|
$values = match (Configuration::$mode) {
|
||||||
|
Mode::SQLite => match ($autoId ?? AutoId::None) {
|
||||||
|
AutoId::None => ':data',
|
||||||
|
AutoId::Number => "json_set(:data, '$.$id', "
|
||||||
|
. "(SELECT coalesce(max(data->>'$id'), 0) + 1 FROM $tableName))",
|
||||||
|
AutoId::UUID => "json_set(:data, '$.$id', '" . AutoId::generateUUID() . "')",
|
||||||
|
AutoId::RandomString => "json_set(:data, '$.$id', '" . AutoId::generateRandom() ."')"
|
||||||
|
},
|
||||||
|
Mode::PgSQL => match ($autoId ?? AutoId::None) {
|
||||||
|
AutoId::None => ':data',
|
||||||
|
AutoId::Number => ":data::jsonb || ('{\"$id\":' || "
|
||||||
|
. "(SELECT COALESCE(MAX((data->>'$id')::numeric), 0) + 1 "
|
||||||
|
. "FROM $tableName) || '}')::jsonb",
|
||||||
|
AutoId::UUID => ":data::jsonb || '{\"$id\":\"" . AutoId::generateUUID() . "\"}'",
|
||||||
|
AutoId::RandomString => ":data::jsonb || '{\"$id\":\"" . AutoId::generateRandom() . "\"}'",
|
||||||
|
},
|
||||||
|
default =>
|
||||||
|
throw new DocumentException('Database mode not set; cannot generate auto-ID INSERT statement'),
|
||||||
|
};
|
||||||
|
return "INSERT INTO $tableName VALUES ($values)";
|
||||||
|
} catch (RandomException $ex) {
|
||||||
|
throw new DocumentException('Unable to generate ID: ' . $ex->getMessage(), previous: $ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to save a document, inserting it if it does not exist and updating it if it does (AKA "upsert")
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table into which a document should be saved
|
||||||
|
* @return string The INSERT...ON CONFLICT query for the document
|
||||||
|
*/
|
||||||
|
public static function save(string $tableName): string
|
||||||
|
{
|
||||||
|
$id = Configuration::$idField;
|
||||||
|
return "INSERT INTO $tableName VALUES (:data) ON CONFLICT ((data->>'$id')) DO UPDATE SET data = EXCLUDED.data";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to update a document
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which the document should be updated
|
||||||
|
* @return string The UPDATE query for the document
|
||||||
|
* @throws DocumentException If the database mode has not been set
|
||||||
|
*/
|
||||||
|
public static function update(string $tableName): string
|
||||||
|
{
|
||||||
|
return "UPDATE $tableName SET data = :data WHERE " . self::whereById();
|
||||||
|
}
|
||||||
|
}
|
||||||
60
src/Query/Count.php
Normal file
60
src/Query/Count.php
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument\Query;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{DocumentException, Field, FieldMatch, Query};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Queries for counting documents
|
||||||
|
*/
|
||||||
|
class Count
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Query to count all documents in a table
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which documents should be counted
|
||||||
|
* @return string The query to count all documents in a table
|
||||||
|
*/
|
||||||
|
public static function all(string $tableName): string
|
||||||
|
{
|
||||||
|
return "SELECT COUNT(*) FROM $tableName";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to count matching documents using a text comparison on JSON fields
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which documents should be counted
|
||||||
|
* @param Field[] $fields The field comparison to match
|
||||||
|
* @param FieldMatch|null $match How to join multiple conditions (optional; defaults to All)
|
||||||
|
* @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, ?FieldMatch $match = null): string
|
||||||
|
{
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
92
src/Query/Definition.php
Normal file
92
src/Query/Definition.php
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument\Query;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Configuration, DocumentException, DocumentIndex, Mode};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Queries to define tables and indexes
|
||||||
|
*/
|
||||||
|
class Definition
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* SQL statement to create a document table
|
||||||
|
*
|
||||||
|
* @param string $name The name of the table (including schema, if applicable)
|
||||||
|
* @return string The CREATE TABLE statement for the document table
|
||||||
|
* @throws DocumentException If the database mode has not been set
|
||||||
|
*/
|
||||||
|
public static function ensureTable(string $name): string
|
||||||
|
{
|
||||||
|
$dataType = match (Configuration::$mode) {
|
||||||
|
Mode::PgSQL => 'JSONB',
|
||||||
|
Mode::SQLite => 'TEXT',
|
||||||
|
default => throw new DocumentException('Database mode not set; cannot make create table statement')
|
||||||
|
};
|
||||||
|
return "CREATE TABLE IF NOT EXISTS $name (data $dataType NOT NULL)";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Split a schema and table name
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table, possibly including the schema
|
||||||
|
* @return array|string[] An array with the schema at index 0 and the table name at index 1
|
||||||
|
*/
|
||||||
|
private static function splitSchemaAndTable(string $tableName): array
|
||||||
|
{
|
||||||
|
$parts = explode('.', $tableName);
|
||||||
|
return sizeof($parts) == 1 ? ["", $tableName] : [$parts[0], $parts[1]];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SQL statement to create an index on one or more fields in a JSON document
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table which should be indexed
|
||||||
|
* @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')
|
||||||
|
* @return string The CREATE INDEX statement to ensure the index exists
|
||||||
|
*/
|
||||||
|
public static function ensureIndexOn(string $tableName, string $indexName, array $fields): string
|
||||||
|
{
|
||||||
|
[, $tbl] = self::splitSchemaAndTable($tableName);
|
||||||
|
$jsonFields = implode(', ', array_map(function (string $field) {
|
||||||
|
$parts = explode(' ', $field);
|
||||||
|
$fieldName = sizeof($parts) == 1 ? $field : $parts[0];
|
||||||
|
$direction = sizeof($parts) < 2 ? "" : " $parts[1]";
|
||||||
|
return "(data->>'$fieldName')$direction";
|
||||||
|
}, $fields));
|
||||||
|
return "CREATE INDEX IF NOT EXISTS idx_{$tbl}_$indexName ON $tableName ($jsonFields)";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SQL statement to create a key index for a document table
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table whose key should be ensured
|
||||||
|
* @return string The CREATE INDEX statement to ensure the key index exists
|
||||||
|
*/
|
||||||
|
public static function ensureKey(string $tableName): string
|
||||||
|
{
|
||||||
|
return str_replace('INDEX', 'UNIQUE INDEX', self::ensureIndexOn($tableName, 'key', [Configuration::$idField]));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a document-wide index on a table (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table on which the document index should be created
|
||||||
|
* @param DocumentIndex $indexType The type of index to be created
|
||||||
|
* @return string The SQL statement to create an index on JSON documents in the specified table
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL
|
||||||
|
*/
|
||||||
|
public static function ensureDocumentIndexOn(string $tableName, DocumentIndex $indexType): string
|
||||||
|
{
|
||||||
|
if (Configuration::$mode <> Mode::PgSQL) {
|
||||||
|
throw new DocumentException('Document indexes are only supported on PostgreSQL');
|
||||||
|
}
|
||||||
|
[, $tbl] = self::splitSchemaAndTable($tableName);
|
||||||
|
$extraOps = match ($indexType) {
|
||||||
|
DocumentIndex::Full => '',
|
||||||
|
DocumentIndex::Optimized => ' jsonb_path_ops'
|
||||||
|
};
|
||||||
|
return "CREATE INDEX IF NOT EXISTS idx_{$tbl}_document ON $tableName USING GIN (data$extraOps)";
|
||||||
|
}
|
||||||
|
}
|
||||||
62
src/Query/Delete.php
Normal file
62
src/Query/Delete.php
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument\Query;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{DocumentException, Field, FieldMatch, Query};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Queries to delete documents
|
||||||
|
*/
|
||||||
|
class Delete
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Query to delete a document by its ID
|
||||||
|
*
|
||||||
|
* @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
|
||||||
|
* @throws DocumentException If the database mode has not been set
|
||||||
|
*/
|
||||||
|
public static function byId(string $tableName, mixed $docId = null): string
|
||||||
|
{
|
||||||
|
return "DELETE FROM $tableName WHERE " . Query::whereById(docId: $docId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to delete documents using a comparison on JSON fields
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table from which documents should be deleted
|
||||||
|
* @param Field[] $fields The field comparison to match
|
||||||
|
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
|
||||||
|
* @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, ?FieldMatch $match = null): string
|
||||||
|
{
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
74
src/Query/Exists.php
Normal file
74
src/Query/Exists.php
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument\Query;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{DocumentException, Field, FieldMatch, Query};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Queries to determine document existence
|
||||||
|
*/
|
||||||
|
class Exists
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* The shell of a query for an existence check
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which existence should be checked
|
||||||
|
* @param string $whereClause The conditions for which existence should be checked
|
||||||
|
* @return string The query to determine existence of documents
|
||||||
|
*/
|
||||||
|
public static function query(string $tableName, string $whereClause): string
|
||||||
|
{
|
||||||
|
return "SELECT EXISTS (SELECT 1 FROM $tableName WHERE $whereClause)";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 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
|
||||||
|
* @throws DocumentException If the database mode has not been set
|
||||||
|
*/
|
||||||
|
public static function byId(string $tableName, mixed $docId = null): string
|
||||||
|
{
|
||||||
|
return self::query($tableName, Query::whereById(docId: $docId));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to determine if documents exist using a comparison on JSON fields
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which document existence should be checked
|
||||||
|
* @param Field[] $fields The field comparison to match
|
||||||
|
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
|
||||||
|
* @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, ?FieldMatch $match = null): string
|
||||||
|
{
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
}
|
||||||
62
src/Query/Find.php
Normal file
62
src/Query/Find.php
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument\Query;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{DocumentException, Field, FieldMatch, Query};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Queries for retrieving documents
|
||||||
|
*/
|
||||||
|
class Find
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Query to retrieve a document by its ID
|
||||||
|
*
|
||||||
|
* @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
|
||||||
|
* @throws DocumentException If the database mode has not been set
|
||||||
|
*/
|
||||||
|
public static function byId(string $tableName, mixed $docId = null): string
|
||||||
|
{
|
||||||
|
return Query::selectFromTable($tableName) . ' WHERE ' . Query::whereById(docId: $docId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to retrieve documents using a comparison on JSON fields
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table from which documents should be retrieved
|
||||||
|
* @param Field[] $fields The field comparison to match
|
||||||
|
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
|
||||||
|
* @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, ?FieldMatch $match = null): string
|
||||||
|
{
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
80
src/Query/Patch.php
Normal file
80
src/Query/Patch.php
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument\Query;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Configuration, DocumentException, Field, FieldMatch, Mode, Query};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Queries to perform partial updates on documents
|
||||||
|
*/
|
||||||
|
class Patch
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Create an UPDATE statement to patch documents
|
||||||
|
*
|
||||||
|
* @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
|
||||||
|
* @return string The UPDATE statement to perform the patch
|
||||||
|
* @throws DocumentException If the database mode has not been set
|
||||||
|
*/
|
||||||
|
public static function update(string $tableName, string $whereClause): string
|
||||||
|
{
|
||||||
|
$setValue = match (Configuration::$mode) {
|
||||||
|
Mode::PgSQL => 'data || :data',
|
||||||
|
Mode::SQLite => 'json_patch(data, json(:data))',
|
||||||
|
default => throw new DocumentException('Database mode not set; cannot make patch statement')
|
||||||
|
};
|
||||||
|
return "UPDATE $tableName SET data = $setValue WHERE $whereClause";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 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
|
||||||
|
* @throws DocumentException If the database mode has not been set
|
||||||
|
*/
|
||||||
|
public static function byId(string $tableName, mixed $docId = null): string
|
||||||
|
{
|
||||||
|
return self::update($tableName, Query::whereById(docId: $docId));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to patch (partially update) a document via a comparison on a JSON field
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which documents should be patched
|
||||||
|
* @param array|Field[] $field The field comparison to match
|
||||||
|
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
|
||||||
|
* @return string The query to patch documents via field comparison
|
||||||
|
* @throws DocumentException If the database mode has not been set
|
||||||
|
*/
|
||||||
|
public static function byFields(string $tableName, array $field, ?FieldMatch $match = null): string
|
||||||
|
{
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
}
|
||||||
94
src/Query/RemoveFields.php
Normal file
94
src/Query/RemoveFields.php
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument\Query;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Configuration, DocumentException, Field, FieldMatch, Mode, Query};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Queries to remove fields from documents
|
||||||
|
*
|
||||||
|
* _NOTE: When using these queries to build custom functions, be aware that different databases use significantly
|
||||||
|
* different syntax. The `$parameters` passed to these functions should be run through `Parameters::fieldNames`
|
||||||
|
* function to generate them appropriately for the database currently being targeted._
|
||||||
|
*/
|
||||||
|
class RemoveFields
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* 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 array $parameters The parameter list for the query
|
||||||
|
* @param string $whereClause The body of the WHERE clause for the update
|
||||||
|
* @return string The UPDATE statement to remove fields from a JSON document
|
||||||
|
* @throws DocumentException If the database mode has not been set
|
||||||
|
*/
|
||||||
|
public static function update(string $tableName, array $parameters, string $whereClause): string
|
||||||
|
{
|
||||||
|
switch (Configuration::$mode) {
|
||||||
|
case Mode::PgSQL:
|
||||||
|
return "UPDATE $tableName SET data = data - " . array_keys($parameters)[0]
|
||||||
|
. "::text[] WHERE $whereClause";
|
||||||
|
case Mode::SQLite:
|
||||||
|
$paramNames = implode(', ', array_keys($parameters));
|
||||||
|
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
|
||||||
|
*
|
||||||
|
* @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 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
|
||||||
|
* @throws DocumentException If the database mode has not been set
|
||||||
|
*/
|
||||||
|
public static function byId(string $tableName, array $parameters, mixed $docId = null): string
|
||||||
|
{
|
||||||
|
return self::update($tableName, $parameters, Query::whereById(docId: $docId));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 array|Field[] $fields The field comparison to match
|
||||||
|
* @param array $parameters The parameter list for the query
|
||||||
|
* @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
|
||||||
|
* @throws DocumentException If the database mode has not been set
|
||||||
|
*/
|
||||||
|
public static function byFields(string $tableName, array $fields, array $parameters,
|
||||||
|
?FieldMatch $match = null): string
|
||||||
|
{
|
||||||
|
return self::update($tableName, $parameters, Query::whereByFields($fields, $match));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to remove fields from documents via a JSON containment query (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which documents should be manipulated
|
||||||
|
* @param array $parameters The parameter list for the query
|
||||||
|
* @return string The UPDATE statement to remove fields from documents via a JSON containment query
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL
|
||||||
|
*/
|
||||||
|
public static function byContains(string $tableName, array $parameters): string
|
||||||
|
{
|
||||||
|
return self::update($tableName, $parameters, Query::whereDataContains());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to remove fields from documents via a JSON Path match query (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which documents should be manipulated
|
||||||
|
* @param array $parameters The parameter list for the query
|
||||||
|
* @return string The UPDATE statement to remove fields from documents via a JSON Path match
|
||||||
|
* @throws DocumentException
|
||||||
|
*/
|
||||||
|
public static function byJsonPath(string $tableName, array $parameters): string
|
||||||
|
{
|
||||||
|
return self::update($tableName, $parameters, Query::whereJsonPathMatches());
|
||||||
|
}
|
||||||
|
}
|
||||||
72
src/RemoveFields.php
Normal file
72
src/RemoveFields.php
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Functions to remove fields from documents
|
||||||
|
*/
|
||||||
|
class RemoveFields
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Remove fields from a document by the document's ID
|
||||||
|
*
|
||||||
|
* @param string $tableName The table in which the document should have fields removed
|
||||||
|
* @param mixed $docId The ID of the document from which fields should be removed
|
||||||
|
* @param array|string[] $fieldNames The names of the fields to be removed
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function byId(string $tableName, mixed $docId, array $fieldNames): void
|
||||||
|
{
|
||||||
|
$nameParams = Parameters::fieldNames(':name', $fieldNames);
|
||||||
|
Custom::nonQuery(Query\RemoveFields::byId($tableName, $nameParams, $docId),
|
||||||
|
array_merge(Parameters::id($docId), $nameParams));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 array|Field[] $fields The field comparison to match
|
||||||
|
* @param array|string[] $fieldNames The names of the fields to be removed
|
||||||
|
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function byFields(string $tableName, array $fields, array $fieldNames,
|
||||||
|
?FieldMatch $match = null): void
|
||||||
|
{
|
||||||
|
$nameParams = Parameters::fieldNames(':name', $fieldNames);
|
||||||
|
$namedFields = Parameters::nameFields($fields);
|
||||||
|
Custom::nonQuery(Query\RemoveFields::byFields($tableName, $namedFields, $nameParams, $match),
|
||||||
|
Parameters::addFields($namedFields, $nameParams));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove fields from documents via a JSON containment query (`@>`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The table in which documents should have fields removed
|
||||||
|
* @param array|object $criteria The JSON containment query values
|
||||||
|
* @param array|string[] $fieldNames The names of the fields to be removed
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function byContains(string $tableName, array|object $criteria, array $fieldNames): void
|
||||||
|
{
|
||||||
|
$nameParams = Parameters::fieldNames(':name', $fieldNames);
|
||||||
|
Custom::nonQuery(Query\RemoveFields::byContains($tableName, $nameParams),
|
||||||
|
array_merge(Parameters::json(':criteria', $criteria), $nameParams));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove fields from documents via a JSON Path match query (`@?`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The table in which documents should have fields removed
|
||||||
|
* @param string $path The JSON Path match string
|
||||||
|
* @param array|string[] $fieldNames The names of the fields to be removed
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function byJsonPath(string $tableName, string $path, array $fieldNames): void
|
||||||
|
{
|
||||||
|
$nameParams = Parameters::fieldNames(':name', $fieldNames);
|
||||||
|
Custom::nonQuery(Query\RemoveFields::byJsonPath($tableName, $nameParams),
|
||||||
|
array_merge([':path' => $path], $nameParams));
|
||||||
|
}
|
||||||
|
}
|
||||||
11
tests/integration/NumDocument.php
Normal file
11
tests/integration/NumDocument.php
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A test document with a numeric ID
|
||||||
|
*/
|
||||||
|
class NumDocument
|
||||||
|
{
|
||||||
|
public function __construct(public int $id = 0, public string $value = '') { }
|
||||||
|
}
|
||||||
11
tests/integration/SubDocument.php
Normal file
11
tests/integration/SubDocument.php
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A sub-document for testing
|
||||||
|
*/
|
||||||
|
class SubDocument
|
||||||
|
{
|
||||||
|
public function __construct(public string $foo = '', public string $bar = '') { }
|
||||||
|
}
|
||||||
9
tests/integration/TestDocument.php
Normal file
9
tests/integration/TestDocument.php
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration;
|
||||||
|
|
||||||
|
class TestDocument
|
||||||
|
{
|
||||||
|
public function __construct(public string $id = '', public string $value = '', public int $num_value = 0,
|
||||||
|
public ?SubDocument $sub = null) { }
|
||||||
|
}
|
||||||
73
tests/integration/postgresql/CountTest.php
Normal file
73
tests/integration/postgresql/CountTest.php
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\PostgreSQL;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Count, Field};
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PostgreSQL integration tests for the Count class
|
||||||
|
*/
|
||||||
|
#[TestDox('Count (PostgreSQL integration)')]
|
||||||
|
class CountTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->dbName = ThrowawayDb::create();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
ThrowawayDb::destroy($this->dbName);
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testAllSucceeds(): void
|
||||||
|
{
|
||||||
|
$count = Count::all(ThrowawayDb::TABLE);
|
||||||
|
$this->assertEquals(5, $count, 'There should have been 5 matching documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceedsForANumericRange(): void
|
||||||
|
{
|
||||||
|
$count = Count::byFields(ThrowawayDb::TABLE, [Field::BT('num_value', 10, 20)]);
|
||||||
|
$this->assertEquals(3, $count, 'There should have been 3 matching documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceedsForANonNumericRange(): void
|
||||||
|
{
|
||||||
|
$count = Count::byFields(ThrowawayDb::TABLE, [Field::BT('value', 'aardvark', 'apple')]);
|
||||||
|
$this->assertEquals(1, $count, 'There should have been 1 matching document');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsSucceedsWhenDocumentsMatch(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(2, Count::byContains(ThrowawayDb::TABLE, ['value' => 'purple']),
|
||||||
|
'There should have been 2 matching documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsSucceedsWhenNoDocumentsMatch(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(0, Count::byContains(ThrowawayDb::TABLE, ['value' => 'magenta']),
|
||||||
|
'There should have been no matching documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds when documents match')]
|
||||||
|
public function testByJsonPathSucceedsWhenDocumentsMatch(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(2, Count::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ < 5)'),
|
||||||
|
'There should have been 2 matching documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds when no documents match')]
|
||||||
|
public function testByJsonPathSucceedsWhenNoDocumentsMatch(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(0, Count::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 100)'),
|
||||||
|
'There should have been no matching documents');
|
||||||
|
}
|
||||||
|
}
|
||||||
121
tests/integration/postgresql/CustomTest.php
Normal file
121
tests/integration/postgresql/CustomTest.php
Normal file
@@ -0,0 +1,121 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\PostgreSQL;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Count, Custom, DocumentException, Query};
|
||||||
|
use BitBadger\PDODocument\Mapper\{CountMapper, DocumentMapper};
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
use Test\Integration\TestDocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PostgreSQL integration tests for the Custom class
|
||||||
|
*/
|
||||||
|
#[TestDox('Custom (PostgreSQL integration)')]
|
||||||
|
class CustomTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
public function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->dbName = ThrowawayDb::create();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function tearDown(): void
|
||||||
|
{
|
||||||
|
ThrowawayDb::destroy($this->dbName);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testRunQuerySucceedsWithAValidQuery()
|
||||||
|
{
|
||||||
|
$stmt = &Custom::runQuery('SELECT data FROM ' . ThrowawayDb::TABLE . ' LIMIT 1', []);
|
||||||
|
try {
|
||||||
|
$this->assertNotNull($stmt, 'The statement should not have been null');
|
||||||
|
} finally {
|
||||||
|
$stmt = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testRunQueryFailsWithAnInvalidQuery()
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
$stmt = &Custom::runQuery('GRAB stuff FROM over_there UNTIL done', []);
|
||||||
|
try {
|
||||||
|
$this->assertTrue(false, 'This code should not be reached');
|
||||||
|
} finally {
|
||||||
|
$stmt = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testListSucceedsWhenDataIsFound()
|
||||||
|
{
|
||||||
|
$list = Custom::list(Query::selectFromTable(ThrowawayDb::TABLE), [], new DocumentMapper(TestDocument::class));
|
||||||
|
$this->assertNotNull($list, 'The document list should not be null');
|
||||||
|
$count = 0;
|
||||||
|
foreach ($list->items() as $ignored) $count++;
|
||||||
|
$this->assertEquals(5, $count, 'There should have been 5 documents in the list');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testListSucceedsWhenNoDataIsFound()
|
||||||
|
{
|
||||||
|
$list = Custom::list(
|
||||||
|
Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE (data->>'num_value')::numeric > :value",
|
||||||
|
[':value' => 100], new DocumentMapper(TestDocument::class));
|
||||||
|
$this->assertNotNull($list, 'The document list should not be null');
|
||||||
|
$this->assertFalse($list->hasItems(), 'There should have been no documents in the list');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testArraySucceedsWhenDataIsFound()
|
||||||
|
{
|
||||||
|
$array = Custom::array(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'sub' IS NOT NULL", [],
|
||||||
|
new DocumentMapper(TestDocument::class));
|
||||||
|
$this->assertNotNull($array, 'The document array should not be null');
|
||||||
|
$this->assertCount(2, $array, 'There should have been 2 documents in the array');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testArraySucceedsWhenNoDataIsFound()
|
||||||
|
{
|
||||||
|
$array = Custom::array(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'value' = :value",
|
||||||
|
[':value' => 'not there'], new DocumentMapper(TestDocument::class));
|
||||||
|
$this->assertNotNull($array, 'The document array should not be null');
|
||||||
|
$this->assertCount(0, $array, 'There should have been no documents in the array');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testSingleSucceedsWhenARowIsFound(): void
|
||||||
|
{
|
||||||
|
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id", [':id' => 'one'],
|
||||||
|
new DocumentMapper(TestDocument::class));
|
||||||
|
$this->assertNotNull($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('one', $doc->id, 'The incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testSingleSucceedsWhenARowIsNotFound(): void
|
||||||
|
{
|
||||||
|
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id",
|
||||||
|
[':id' => 'eighty'], new DocumentMapper(TestDocument::class));
|
||||||
|
$this->assertFalse($doc, 'There should not have been a document returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testNonQuerySucceedsWhenOperatingOnData()
|
||||||
|
{
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
$remaining = Count::all(ThrowawayDb::TABLE);
|
||||||
|
$this->assertEquals(0, $remaining, 'There should be no documents remaining in the table');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testNonQuerySucceedsWhenNoDataMatchesWhereClause()
|
||||||
|
{
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE . " WHERE (data->>'num_value')::numeric > :value",
|
||||||
|
[':value' => 100]);
|
||||||
|
$remaining = Count::all(ThrowawayDb::TABLE);
|
||||||
|
$this->assertEquals(5, $remaining, 'There should be 5 documents remaining in the table');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testScalarSucceeds()
|
||||||
|
{
|
||||||
|
$value = Custom::scalar("SELECT 5 AS it", [], new CountMapper());
|
||||||
|
$this->assertEquals(5, $value, 'The scalar value was not returned correctly');
|
||||||
|
}
|
||||||
|
}
|
||||||
78
tests/integration/postgresql/DefinitionTest.php
Normal file
78
tests/integration/postgresql/DefinitionTest.php
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\PostgreSQL;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Custom, Definition, DocumentException, DocumentIndex};
|
||||||
|
use BitBadger\PDODocument\Mapper\ExistsMapper;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PostgreSQL integration tests for the Definition class
|
||||||
|
*/
|
||||||
|
#[TestDox('Definition (PostgreSQL integration)')]
|
||||||
|
class DefinitionTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->dbName = ThrowawayDb::create(withData: false);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
ThrowawayDb::destroy($this->dbName);
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Does the given named object exist in the database?
|
||||||
|
*
|
||||||
|
* @param string $name The name of the object whose existence should be verified
|
||||||
|
* @return bool True if the object exists, false if not
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
private function itExists(string $name): bool
|
||||||
|
{
|
||||||
|
return Custom::scalar('SELECT EXISTS (SELECT 1 FROM pg_class WHERE relname = :name)',
|
||||||
|
[':name' => $name], new ExistsMapper());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testEnsureTableSucceeds(): void
|
||||||
|
{
|
||||||
|
$this->assertFalse($this->itExists('ensured'), 'The table should not exist already');
|
||||||
|
$this->assertFalse($this->itExists('idx_ensured_key'), 'The key index should not exist already');
|
||||||
|
Definition::ensureTable('ensured');
|
||||||
|
$this->assertTrue($this->itExists('ensured'), 'The table should now exist');
|
||||||
|
$this->assertTrue($this->itExists('idx_ensured_key'), 'The key index should now exist');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testEnsureFieldIndexSucceeds(): void
|
||||||
|
{
|
||||||
|
$this->assertFalse($this->itExists('idx_ensured_test'), 'The index should not exist already');
|
||||||
|
Definition::ensureTable('ensured');
|
||||||
|
Definition::ensureFieldIndex('ensured', 'test', ['name', 'age']);
|
||||||
|
$this->assertTrue($this->itExists('idx_ensured_test'), 'The index should now exist');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testEnsureDocumentIndexSucceedsForFull(): void
|
||||||
|
{
|
||||||
|
$docIdx = 'idx_' . ThrowawayDb::TABLE . '_document';
|
||||||
|
Definition::ensureTable(ThrowawayDb::TABLE);
|
||||||
|
$this->assertFalse($this->itExists($docIdx), 'The document index should not exist');
|
||||||
|
Definition::ensureDocumentIndex(ThrowawayDb::TABLE, DocumentIndex::Full);
|
||||||
|
$this->assertTrue($this->itExists($docIdx), 'The document index should now exist');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testEnsureDocumentIndexSucceedsForOptimized(): void
|
||||||
|
{
|
||||||
|
$docIdx = 'idx_' . ThrowawayDb::TABLE . '_document';
|
||||||
|
Definition::ensureTable(ThrowawayDb::TABLE);
|
||||||
|
$this->assertFalse($this->itExists($docIdx), 'The document index should not exist');
|
||||||
|
Definition::ensureDocumentIndex(ThrowawayDb::TABLE, DocumentIndex::Optimized);
|
||||||
|
$this->assertTrue($this->itExists($docIdx), 'The document index should now exist');
|
||||||
|
}
|
||||||
|
}
|
||||||
89
tests/integration/postgresql/DeleteTest.php
Normal file
89
tests/integration/postgresql/DeleteTest.php
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\PostgreSQL;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Count, Delete, Field};
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PostgreSQL integration tests for the Delete class
|
||||||
|
*/
|
||||||
|
#[TestDox('Delete (PostgreSQL integration)')]
|
||||||
|
class DeleteTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->dbName = ThrowawayDb::create();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
ThrowawayDb::destroy($this->dbName);
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds when a document is deleted')]
|
||||||
|
public function testByIdSucceedsWhenADocumentIsDeleted(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
||||||
|
Delete::byId(ThrowawayDb::TABLE, 'four');
|
||||||
|
$this->assertEquals(4, Count::all(ThrowawayDb::TABLE), 'There should have been 4 documents remaining');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds when a document is not deleted')]
|
||||||
|
public function testByIdSucceedsWhenADocumentIsNotDeleted(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
||||||
|
Delete::byId(ThrowawayDb::TABLE, 'negative four');
|
||||||
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents remaining');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceedsWhenDocumentsAreDeleted(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
||||||
|
Delete::byFields(ThrowawayDb::TABLE, [Field::NE('value', 'purple')]);
|
||||||
|
$this->assertEquals(2, Count::all(ThrowawayDb::TABLE), 'There should have been 2 documents remaining');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceedsWhenDocumentsAreNotDeleted(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
||||||
|
Delete::byFields(ThrowawayDb::TABLE, [Field::EQ('value', 'crimson')]);
|
||||||
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents remaining');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsSucceedsWhenDocumentsAreDeleted(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
||||||
|
Delete::byContains(ThrowawayDb::TABLE, ['value' => 'purple']);
|
||||||
|
$this->assertEquals(3, Count::all(ThrowawayDb::TABLE), 'There should have been 3 documents remaining');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsSucceedsWhenDocumentsAreNotDeleted(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
||||||
|
Delete::byContains(ThrowawayDb::TABLE, ['target' => 'acquired']);
|
||||||
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents remaining');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds when documents are deleted')]
|
||||||
|
public function testByJsonPathSucceedsWhenDocumentsAreDeleted(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
||||||
|
Delete::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ <> 0)');
|
||||||
|
$this->assertEquals(1, Count::all(ThrowawayDb::TABLE), 'There should have been 1 document remaining');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds when documents are not deleted')]
|
||||||
|
public function testByJsonPathSucceedsWhenDocumentsAreNotDeleted(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
||||||
|
Delete::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ < 0)');
|
||||||
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents remaining');
|
||||||
|
}
|
||||||
|
}
|
||||||
74
tests/integration/postgresql/DocumentListTest.php
Normal file
74
tests/integration/postgresql/DocumentListTest.php
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\PostgreSQL;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{DocumentList, Query};
|
||||||
|
use BitBadger\PDODocument\Mapper\DocumentMapper;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
use Test\Integration\TestDocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PostgreSQL integration tests for the DocumentList class
|
||||||
|
*/
|
||||||
|
#[TestDox('DocumentList (PostgreSQL integration)')]
|
||||||
|
class DocumentListTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->dbName = ThrowawayDb::create();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
ThrowawayDb::destroy($this->dbName);
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testCreateSucceeds(): void
|
||||||
|
{
|
||||||
|
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
|
||||||
|
new DocumentMapper(TestDocument::class));
|
||||||
|
$this->assertNotNull($list, 'There should have been a document list created');
|
||||||
|
$list = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testItems(): void
|
||||||
|
{
|
||||||
|
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
|
||||||
|
new DocumentMapper(TestDocument::class));
|
||||||
|
$this->assertNotNull($list, 'There should have been a document list created');
|
||||||
|
$count = 0;
|
||||||
|
foreach ($list->items() as $item) {
|
||||||
|
$this->assertContains($item->id, ['one', 'two', 'three', 'four', 'five'],
|
||||||
|
'An unexpected document ID was returned');
|
||||||
|
$count++;
|
||||||
|
}
|
||||||
|
$this->assertEquals(5, $count, 'There should have been 5 documents returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testHasItemsSucceedsWithEmptyResults(): void
|
||||||
|
{
|
||||||
|
$list = DocumentList::create(
|
||||||
|
Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE (data->>'num_value')::numeric < 0", [],
|
||||||
|
new DocumentMapper(TestDocument::class));
|
||||||
|
$this->assertNotNull($list, 'There should have been a document list created');
|
||||||
|
$this->assertFalse($list->hasItems(), 'There should be no items in the list');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testHasItemsSucceedsWithNonEmptyResults(): void
|
||||||
|
{
|
||||||
|
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
|
||||||
|
new DocumentMapper(TestDocument::class));
|
||||||
|
$this->assertNotNull($list, 'There should have been a document list created');
|
||||||
|
$this->assertTrue($list->hasItems(), 'There should be items in the list');
|
||||||
|
foreach ($list->items() as $ignored) {
|
||||||
|
$this->assertTrue($list->hasItems(), 'There should be items remaining in the list');
|
||||||
|
}
|
||||||
|
$this->assertFalse($list->hasItems(), 'There should be no remaining items in the list');
|
||||||
|
}
|
||||||
|
}
|
||||||
302
tests/integration/postgresql/DocumentTest.php
Normal file
302
tests/integration/postgresql/DocumentTest.php
Normal file
@@ -0,0 +1,302 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\PostgreSQL;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{AutoId, Configuration, Custom, Document, DocumentException, Field, Find, Query};
|
||||||
|
use BitBadger\PDODocument\Mapper\ArrayMapper;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
use Test\Integration\{NumDocument, SubDocument, TestDocument};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PostgreSQL integration tests for the Document class
|
||||||
|
*/
|
||||||
|
#[TestDox('Document (PostgreSQL integration)')]
|
||||||
|
class DocumentTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->dbName = ThrowawayDb::create();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
ThrowawayDb::destroy($this->dbName);
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for array no auto ID')]
|
||||||
|
public function testInsertSucceedsForArrayNoAutoId(): void
|
||||||
|
{
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => 'turkey', 'sub' => ['foo' => 'gobble', 'bar' => 'gobble']]);
|
||||||
|
$doc = Find::byId(ThrowawayDb::TABLE, 'turkey', TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document inserted');
|
||||||
|
$this->assertEquals('turkey', $doc->id, 'The ID was incorrect');
|
||||||
|
$this->assertEquals('', $doc->value, 'The value was incorrect');
|
||||||
|
$this->assertEquals(0, $doc->num_value, 'The numeric value was incorrect');
|
||||||
|
$this->assertNotNull($doc->sub, 'The sub-document should not have been null');
|
||||||
|
$this->assertEquals('gobble', $doc->sub->foo, 'The sub-document foo property was incorrect');
|
||||||
|
$this->assertEquals('gobble', $doc->sub->bar, 'The sub-document bar property was incorrect');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$obj = json_decode($doc['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->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$obj = json_decode($doc['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->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$obj = json_decode($doc['data']);
|
||||||
|
$this->assertEquals(7, $obj->id, 'The ID 7 should have been stored');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for array with auto UUID ID not provided')]
|
||||||
|
public function testInsertSucceedsForArrayWithAutoUuidIdNotProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::UUID;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => '', 'num_value' => 5]);
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 5)], TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertNotEmpty($doc->id, 'The ID should have been auto-generated');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for array with auto UUID ID with ID provided')]
|
||||||
|
public function testInsertSucceedsForArrayWithAutoUuidIdWithIdProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::UUID;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
$uuid = AutoId::generateUUID();
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => $uuid, 'value' => 'uuid', 'num_value' => 12]);
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 12)], TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals($uuid, $doc->id, 'The ID should not have been changed');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for array with auto string ID not provided')]
|
||||||
|
public function testInsertSucceedsForArrayWithAutoStringIdNotProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::RandomString;
|
||||||
|
Configuration::$idStringLength = 6;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => '', 'value' => 'new', 'num_value' => 8]);
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 8)], TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals(6, strlen($doc->id), 'The ID should have been auto-generated and had 6 characters');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
Configuration::$idStringLength = 16;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for array with auto string ID with ID provided')]
|
||||||
|
public function testInsertSucceedsForArrayWithAutoStringIdWithIdProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::RandomString;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => 'my-key', 'value' => 'old', 'num_value' => 3]);
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 3)], TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('my-key', $doc->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')));
|
||||||
|
$doc = Find::byId(ThrowawayDb::TABLE, 'turkey', TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document inserted');
|
||||||
|
$this->assertEquals('turkey', $doc->id, 'The ID was incorrect');
|
||||||
|
$this->assertEquals('', $doc->value, 'The value was incorrect');
|
||||||
|
$this->assertEquals(0, $doc->num_value, 'The numeric value was incorrect');
|
||||||
|
$this->assertNotNull($doc->sub, 'The sub-document should not have been null');
|
||||||
|
$this->assertEquals('gobble', $doc->sub->foo, 'The sub-document foo property was incorrect');
|
||||||
|
$this->assertEquals('gobble', $doc->sub->bar, 'The sub-document bar property was incorrect');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for object with auto number ID not provided')]
|
||||||
|
public function testInsertSucceedsForObjectWithAutoNumberIdNotProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::Number;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new NumDocument(value: 'taco'));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'taco')], NumDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals(1, $doc->id, 'The ID 1 should have been auto-generated');
|
||||||
|
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new NumDocument(value: 'burrito'));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'burrito')], NumDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals(2, $doc->id, 'The ID 2 should have been auto-generated');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for object with auto number ID with ID provided')]
|
||||||
|
public function testInsertSucceedsForObjectWithAutoNumberIdWithIdProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::Number;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new NumDocument(64, 'large'));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'large')], NumDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals(64, $doc->id, 'The ID 64 should have been stored');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for object with auto UUID ID not provided')]
|
||||||
|
public function testInsertSucceedsForObjectWithAutoUuidIdNotProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::UUID;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new TestDocument(value: 'something', num_value: 9));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EX('value')], TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertNotEmpty($doc->id, 'The ID should have been auto-generated');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for object with auto UUID ID with ID provided')]
|
||||||
|
public function testInsertSucceedsForObjectWithAutoUuidIdWithIdProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::UUID;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
$uuid = AutoId::generateUUID();
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new TestDocument($uuid, num_value: 14));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 14)], TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals($uuid, $doc->id, 'The ID should not have been changed');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for object with auto string ID not provided')]
|
||||||
|
public function testInsertSucceedsForObjectWithAutoStringIdNotProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::RandomString;
|
||||||
|
Configuration::$idStringLength = 40;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new TestDocument(num_value: 55));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 55)], TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals(40, strlen($doc->id), 'The ID should have been auto-generated and had 40 characters');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
Configuration::$idStringLength = 16;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for object with auto string ID with ID provided')]
|
||||||
|
public function testInsertSucceedsForObjectWithAutoStringIdWithIdProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::RandomString;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new TestDocument('my-key', num_value: 3));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 3)], TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('my-key', $doc->id, 'The ID should not have been changed');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testInsertFailsForDuplicateKey(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new TestDocument('one'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testSaveSucceedsWhenADocumentIsInserted(): void
|
||||||
|
{
|
||||||
|
Document::save(ThrowawayDb::TABLE, new TestDocument('test', sub: new SubDocument('a', 'b')));
|
||||||
|
$doc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testSaveSucceedsWhenADocumentIsUpdated(): void
|
||||||
|
{
|
||||||
|
Document::save(ThrowawayDb::TABLE, new TestDocument('two', num_value: 44));
|
||||||
|
$doc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals(44, $doc->num_value, 'The numeric value was not updated');
|
||||||
|
$this->assertNull($doc->sub, 'The sub-document should have been null');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testUpdateSucceedsWhenReplacingADocument(): void
|
||||||
|
{
|
||||||
|
Document::update(ThrowawayDb::TABLE, 'one', new TestDocument('one', 'howdy', 8, new SubDocument('y', 'z')));
|
||||||
|
$doc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('howdy', $doc->value, 'The value was incorrect');
|
||||||
|
$this->assertEquals(8, $doc->num_value, 'The numeric value was incorrect');
|
||||||
|
$this->assertNotNull($doc->sub, 'The sub-document should not have been null');
|
||||||
|
$this->assertEquals('y', $doc->sub->foo, 'The sub-document foo property was incorrect');
|
||||||
|
$this->assertEquals('z', $doc->sub->bar, 'The sub-document bar property was incorrect');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testUpdateSucceedsWhenNoDocumentIsReplaced(): void
|
||||||
|
{
|
||||||
|
Document::update(ThrowawayDb::TABLE, 'two-hundred', new TestDocument('200'));
|
||||||
|
$doc = Find::byId(ThrowawayDb::TABLE, 'two-hundred', TestDocument::class);
|
||||||
|
$this->assertFalse($doc, 'There should not have been a document returned');
|
||||||
|
}
|
||||||
|
}
|
||||||
80
tests/integration/postgresql/ExistsTest.php
Normal file
80
tests/integration/postgresql/ExistsTest.php
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\PostgreSQL;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Exists, Field};
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PostgreSQL integration tests for the Exists class
|
||||||
|
*/
|
||||||
|
#[TestDox('Exists (PostgreSQL integration)')]
|
||||||
|
class ExistsTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->dbName = ThrowawayDb::create();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
ThrowawayDb::destroy($this->dbName);
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds when a document exists')]
|
||||||
|
public function testByIdSucceedsWhenADocumentExists(): void
|
||||||
|
{
|
||||||
|
$this->assertTrue(Exists::byId(ThrowawayDb::TABLE, 'three'), 'There should have been an existing document');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds when a document does not exist')]
|
||||||
|
public function testByIdSucceedsWhenADocumentDoesNotExist(): void
|
||||||
|
{
|
||||||
|
$this->assertFalse(Exists::byId(ThrowawayDb::TABLE, 'seven'),
|
||||||
|
'There should not have been an existing document');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceedsWhenDocumentsExist(): void
|
||||||
|
{
|
||||||
|
$this->assertTrue(Exists::byFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 10)]),
|
||||||
|
'There should have been existing documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceedsWhenNoMatchingDocumentsExist(): void
|
||||||
|
{
|
||||||
|
$this->assertFalse(Exists::byFields(ThrowawayDb::TABLE, [Field::LT('nothing', 'none')]),
|
||||||
|
'There should not have been any existing documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsSucceedsWhenDocumentsExist(): void
|
||||||
|
{
|
||||||
|
$this->assertTrue(Exists::byContains(ThrowawayDb::TABLE, ['value' => 'purple']),
|
||||||
|
'There should have been existing documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsSucceedsWhenNoMatchingDocumentsExist(): void
|
||||||
|
{
|
||||||
|
$this->assertFalse(Exists::byContains(ThrowawayDb::TABLE, ['value' => 'violet']),
|
||||||
|
'There should not have been existing documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds when documents exist')]
|
||||||
|
public function testByJsonPathSucceedsWhenDocumentsExist(): void
|
||||||
|
{
|
||||||
|
$this->assertTrue(Exists::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ == 10)'),
|
||||||
|
'There should have been existing documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds when no matching documents exist')]
|
||||||
|
public function testByJsonPathSucceedsWhenNoMatchingDocumentsExist(): void
|
||||||
|
{
|
||||||
|
$this->assertFalse(Exists::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ == 10.1)'),
|
||||||
|
'There should have been existing documents');
|
||||||
|
}
|
||||||
|
}
|
||||||
184
tests/integration/postgresql/FindTest.php
Normal file
184
tests/integration/postgresql/FindTest.php
Normal file
@@ -0,0 +1,184 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\PostgreSQL;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Custom, Delete, Document, Field, Find};
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
use Test\Integration\{NumDocument, TestDocument};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PostgreSQL integration tests for the Find class
|
||||||
|
*/
|
||||||
|
#[TestDox('Find (PostgreSQL integration)')]
|
||||||
|
class FindTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->dbName = ThrowawayDb::create();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
ThrowawayDb::destroy($this->dbName);
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testAllSucceedsWhenThereIsData(): void
|
||||||
|
{
|
||||||
|
$docs = Find::all(ThrowawayDb::TABLE, TestDocument::class);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$count = 0;
|
||||||
|
foreach ($docs->items() as $ignored) $count++;
|
||||||
|
$this->assertEquals(5, $count, 'There should have been 5 documents in the list');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testAllSucceedsWhenThereIsNoData(): void
|
||||||
|
{
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
$docs = Find::all(ThrowawayDb::TABLE, TestDocument::class);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertFalse($docs->hasItems(), 'There should have been no documents in the list');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds when a document is found')]
|
||||||
|
public function testByIdSucceedsWhenADocumentIsFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('two', $doc->id, 'An incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds when a document is found with numeric ID')]
|
||||||
|
public function testByIdSucceedsWhenADocumentIsFoundWithNumericId(): void
|
||||||
|
{
|
||||||
|
Delete::byFields(ThrowawayDb::TABLE, [Field::NEX('absent')]);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => 18, 'value' => 'howdy']);
|
||||||
|
$doc = Find::byId(ThrowawayDb::TABLE, 18, NumDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals(18, $doc->id, 'An incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds when a document is not found')]
|
||||||
|
public function testByIdSucceedsWhenADocumentIsNotFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::byId(ThrowawayDb::TABLE, 'seventy-five', TestDocument::class);
|
||||||
|
$this->assertFalse($doc, 'There should not have been a document returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceedsWhenDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::GT('num_value', 15)], TestDocument::class);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$count = 0;
|
||||||
|
foreach ($docs->items() as $ignored) $count++;
|
||||||
|
$this->assertEquals(2, $count, 'There should have been 2 documents in the list');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceedsWhenNoDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::GT('num_value', 100)], TestDocument::class);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertFalse($docs->hasItems(), 'There should have been no documents in the list');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsSucceedsWhenDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$docs = Find::byContains(ThrowawayDb::TABLE, ['value' => 'purple'], TestDocument::class);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$count = 0;
|
||||||
|
foreach ($docs->items() as $ignored) $count++;
|
||||||
|
$this->assertEquals(2, $count, 'There should have been 2 documents in the list');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsSucceedsWhenNoDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$docs = Find::byContains(ThrowawayDb::TABLE, ['value' => 'indigo'], TestDocument::class);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertFalse($docs->hasItems(), 'The document list should be empty');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds when documents are found')]
|
||||||
|
public function testByJsonPathSucceedsWhenDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$docs = Find::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 10)', TestDocument::class);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$count = 0;
|
||||||
|
foreach ($docs->items() as $ignored) $count++;
|
||||||
|
$this->assertEquals(2, $count, 'There should have been 2 documents in the list');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds when no documents are found')]
|
||||||
|
public function testByJsonPathSucceedsWhenNoDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$docs = Find::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 100)', TestDocument::class);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertFalse($docs->hasItems(), 'The document list should be empty');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testFirstByFieldsSucceedsWhenADocumentIsFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'another')], TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('two', $doc->id, 'The incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testFirstByFieldsSucceedsWhenMultipleDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('sub.foo', 'green')], TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertContains($doc->id, ['two', 'four'], 'An incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testFirstByFieldsSucceedsWhenADocumentIsNotFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'absent')], TestDocument::class);
|
||||||
|
$this->assertFalse($doc, 'There should not have been a document returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testFirstByContainsSucceedsWhenADocumentIsFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByContains(ThrowawayDb::TABLE, ['value' => 'FIRST!'], TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('one', $doc->id, 'The incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testFirstByContainsSucceedsWhenMultipleDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByContains(ThrowawayDb::TABLE, ['value' => 'purple'], TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertContains($doc->id, ['four', 'five'], 'An incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testFirstByContainsSucceedsWhenADocumentIsNotFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByContains(ThrowawayDb::TABLE, ['value' => 'indigo'], TestDocument::class);
|
||||||
|
$this->assertFalse($doc, 'There should not have been a document returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('First by JSON Path succeeds when a document is found')]
|
||||||
|
public function testFirstByJsonPathSucceedsWhenADocumentIsFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ == 10)', TestDocument::class);
|
||||||
|
$this->assertEquals('two', $doc->id, 'The incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('First by JSON Path succeeds when multiple documents are found')]
|
||||||
|
public function testFirstByJsonPathSucceedsWhenMultipleDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 10)', TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertContains($doc->id, ['four', 'five'], 'An incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('First by JSON Path succeeds when a document is not found')]
|
||||||
|
public function testFirstByJsonPathSucceedsWhenADocumentIsNotFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 100)', TestDocument::class);
|
||||||
|
$this->assertFalse($doc, 'There should not have been a document returned');
|
||||||
|
}
|
||||||
|
}
|
||||||
104
tests/integration/postgresql/PatchTest.php
Normal file
104
tests/integration/postgresql/PatchTest.php
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\PostgreSQL;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Count, Exists, Field, Find, Patch};
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
use Test\Integration\TestDocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PostgreSQL integration tests for the Patch class
|
||||||
|
*/
|
||||||
|
#[TestDox('Patch (PostgreSQL integration)')]
|
||||||
|
class PatchTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->dbName = ThrowawayDb::create();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
ThrowawayDb::destroy($this->dbName);
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds when a document is updated')]
|
||||||
|
public function testByIdSucceedsWhenADocumentIsUpdated(): void
|
||||||
|
{
|
||||||
|
Patch::byId(ThrowawayDb::TABLE, 'one', ['num_value' => 44]);
|
||||||
|
$doc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals(44, $doc->num_value, 'The updated document is not correct');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds when no document is updated')]
|
||||||
|
public function testByIdSucceedsWhenNoDocumentIsUpdated(): void
|
||||||
|
{
|
||||||
|
$id = 'forty-seven';
|
||||||
|
$this->assertFalse(Exists::byId(ThrowawayDb::TABLE, $id), 'The document should not exist');
|
||||||
|
Patch::byId(ThrowawayDb::TABLE, $id, ['foo' => 'green']);
|
||||||
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceedsWhenADocumentIsUpdated(): void
|
||||||
|
{
|
||||||
|
Patch::byFields(ThrowawayDb::TABLE, [Field::EQ('value', 'purple')], ['num_value' => 77]);
|
||||||
|
$after = Count::byFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 77)]);
|
||||||
|
$this->assertEquals(2, $after, 'There should have been 2 documents updated');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceedsWhenNoDocumentIsUpdated(): void
|
||||||
|
{
|
||||||
|
$fields = [Field::EQ('value', 'burgundy')];
|
||||||
|
$this->assertEquals(0, Count::byFields(ThrowawayDb::TABLE, $fields), 'There should be no matching documents');
|
||||||
|
Patch::byFields(ThrowawayDb::TABLE, $fields, ['foo' => 'green']);
|
||||||
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsSucceedsWhenDocumentsAreUpdated(): void
|
||||||
|
{
|
||||||
|
Patch::byContains(ThrowawayDb::TABLE, ['value' => 'another'], ['num_value' => 12]);
|
||||||
|
$doc = Find::firstByContains(ThrowawayDb::TABLE, ['value' => 'another'], TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('two', $doc->id, 'An incorrect document was returned');
|
||||||
|
$this->assertEquals(12, $doc->num_value, 'The document was not patched');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsSucceedsWhenNoDocumentsAreUpdated(): void
|
||||||
|
{
|
||||||
|
$criteria = ['value' => 'updated'];
|
||||||
|
$this->assertEquals(0, Count::byContains(ThrowawayDb::TABLE, $criteria),
|
||||||
|
'There should be no matching documents');
|
||||||
|
Patch::byContains(ThrowawayDb::TABLE, $criteria, ['sub.foo' => 'green']);
|
||||||
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds when documents are updated')]
|
||||||
|
public function testByJsonPathSucceedsWhenDocumentsAreUpdated(): void
|
||||||
|
{
|
||||||
|
Patch::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 10)', ['value' => 'blue']);
|
||||||
|
$docs = Find::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 10)', TestDocument::class);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertTrue($docs->hasItems(), 'The document list should not be empty');
|
||||||
|
foreach ($docs->items() as $item) {
|
||||||
|
$this->assertContains($item->id, ['four', 'five'], 'An incorrect document was returned');
|
||||||
|
$this->assertEquals('blue', $item->value, 'The document was not patched');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds when documents are not updated')]
|
||||||
|
public function testByJsonPathSucceedsWhenDocumentsAreNotUpdated(): void
|
||||||
|
{
|
||||||
|
$path = '$.num_value ? (@ > 100)';
|
||||||
|
$this->assertEquals(0, Count::byJsonPath(ThrowawayDb::TABLE, $path),
|
||||||
|
'There should be no documents matching this path');
|
||||||
|
Patch::byJsonPath(ThrowawayDb::TABLE, $path, ['value' => 'blue']);
|
||||||
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
|
}
|
||||||
|
}
|
||||||
127
tests/integration/postgresql/RemoveFieldsTest.php
Normal file
127
tests/integration/postgresql/RemoveFieldsTest.php
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\PostgreSQL;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Field, Find, RemoveFields};
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
use Test\Integration\TestDocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PostgreSQL integration tests for the RemoveFields class
|
||||||
|
*/
|
||||||
|
#[TestDox('Remove Fields (PostgreSQL integration)')]
|
||||||
|
class RemoveFieldsTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->dbName = ThrowawayDb::create();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
ThrowawayDb::destroy($this->dbName);
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds when fields are removed')]
|
||||||
|
public function testByIdSucceedsWhenFieldsAreRemoved(): void
|
||||||
|
{
|
||||||
|
RemoveFields::byId(ThrowawayDb::TABLE, 'two', ['sub', 'value']);
|
||||||
|
$doc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('', $doc->value, 'Value should have been blank (its default value)');
|
||||||
|
$this->assertNull($doc->sub, 'Sub-document should have been null');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds when a field is not removed')]
|
||||||
|
public function testByIdSucceedsWhenAFieldIsNotRemoved(): void
|
||||||
|
{
|
||||||
|
RemoveFields::byId(ThrowawayDb::TABLE, 'one', ['a_field_that_does_not_exist']);
|
||||||
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds when no document is matched')]
|
||||||
|
public function testByIdSucceedsWhenNoDocumentIsMatched(): void
|
||||||
|
{
|
||||||
|
RemoveFields::byId(ThrowawayDb::TABLE, 'fifty', ['sub']);
|
||||||
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceedsWhenAFieldIsRemoved(): void
|
||||||
|
{
|
||||||
|
RemoveFields::byFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 17)], ['sub']);
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 17)], TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertNull($doc->sub, 'Sub-document should have been null');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceedsWhenAFieldIsNotRemoved(): void
|
||||||
|
{
|
||||||
|
RemoveFields::byFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 17)], ['nada']);
|
||||||
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceedsWhenNoDocumentIsMatched(): void
|
||||||
|
{
|
||||||
|
RemoveFields::byFields(ThrowawayDb::TABLE, [Field::NE('missing', 'nope')], ['value']);
|
||||||
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsSucceedsWhenAFieldIsRemoved(): void
|
||||||
|
{
|
||||||
|
$criteria = ['sub' => ['foo' => 'green']];
|
||||||
|
RemoveFields::byContains(ThrowawayDb::TABLE, $criteria, ['value']);
|
||||||
|
$docs = Find::byContains(ThrowawayDb::TABLE, $criteria, TestDocument::class);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertTrue($docs->hasItems(), 'The document list should not have been empty');
|
||||||
|
foreach ($docs->items() as $item) {
|
||||||
|
$this->assertContains($item->id, ['two', 'four'], 'An incorrect document was returned');
|
||||||
|
$this->assertEquals('', $item->value, 'The value field was not removed');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsSucceedsWhenAFieldIsNotRemoved(): void
|
||||||
|
{
|
||||||
|
RemoveFields::byContains(ThrowawayDb::TABLE, ['sub' => ['foo' => 'green']], ['invalid_field']);
|
||||||
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsSucceedsWhenNoDocumentIsMatched(): void
|
||||||
|
{
|
||||||
|
RemoveFields::byContains(ThrowawayDb::TABLE, ['value' => 'substantial'], ['num_value']);
|
||||||
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds when a field is removed')]
|
||||||
|
public function testByJsonPathSucceedsWhenAFieldIsRemoved(): void
|
||||||
|
{
|
||||||
|
$path = '$.value ? (@ == "purple")';
|
||||||
|
RemoveFields::byJsonPath(ThrowawayDb::TABLE, $path, ['sub']);
|
||||||
|
$docs = Find::byJsonPath(ThrowawayDb::TABLE, $path, TestDocument::class);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertTrue($docs->hasItems(), 'The document list should not have been empty');
|
||||||
|
foreach ($docs->items() as $item) {
|
||||||
|
$this->assertContains($item->id, ['four', 'five'], 'An incorrect document was returned');
|
||||||
|
$this->assertNull($item->sub, 'The sub field was not removed');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds when a field is not removed')]
|
||||||
|
public function testByJsonPathSucceedsWhenAFieldIsNotRemoved(): void
|
||||||
|
{
|
||||||
|
RemoveFields::byJsonPath(ThrowawayDb::TABLE, '$.value ? (@ == "purple")', ['submarine']);
|
||||||
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds when no document is matched')]
|
||||||
|
public function testByJsonPathSucceedsWhenNoDocumentIsMatched(): void
|
||||||
|
{
|
||||||
|
RemoveFields::byJsonPath(ThrowawayDb::TABLE, '$.value ? (@ == "mauve")', ['value']);
|
||||||
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
|
}
|
||||||
|
}
|
||||||
75
tests/integration/postgresql/ThrowawayDb.php
Normal file
75
tests/integration/postgresql/ThrowawayDb.php
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\PostgreSQL;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{AutoId, Configuration, Custom, Definition, Document, DocumentException, Mode};
|
||||||
|
use Random\RandomException;
|
||||||
|
use Test\Integration\{SubDocument, TestDocument};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Utilities to create and destroy a throwaway PostgreSQL database to use for testing
|
||||||
|
*/
|
||||||
|
class ThrowawayDb
|
||||||
|
{
|
||||||
|
/** @var string The table used for document manipulation */
|
||||||
|
public const TABLE = "test_table";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configure the document library for the given database (or the main PostgreSQL connection, if the database name
|
||||||
|
* is not provided; this is used for creating and dropping databases)
|
||||||
|
*
|
||||||
|
* @param string|null $dbName The name of the database to configure (optional, defaults to env or "postgres")
|
||||||
|
*/
|
||||||
|
private static function configure(?string $dbName = null): void
|
||||||
|
{
|
||||||
|
Configuration::$pdoDSN = sprintf("pgsql:host=%s;dbname=%s", $_ENV['PDO_DOC_PGSQL_HOST'] ?? 'localhost',
|
||||||
|
$dbName ?? $_ENV['PDO_DOC_PGSQL_DB'] ?? 'postgres');
|
||||||
|
Configuration::$username = $_ENV['PDO_DOC_PGSQL_USER'] ?? 'postgres';
|
||||||
|
Configuration::$password = $_ENV['PDO_DOC_PGSQL_PASS'] ?? 'postgres';
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
Configuration::resetPDO();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a throwaway PostgreSQL database
|
||||||
|
*
|
||||||
|
* @param bool $withData Whether to initialize this database with data (optional; defaults to `true`)
|
||||||
|
* @return string The name of the database (use to pass to `destroy` function at end of test)
|
||||||
|
* @throws DocumentException|RandomException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function create(bool $withData = true): string
|
||||||
|
{
|
||||||
|
$dbName = 'throwaway_' . AutoId::generateRandom(10);
|
||||||
|
self::configure();
|
||||||
|
Custom::nonQuery("CREATE DATABASE $dbName WITH OWNER " . Configuration::$username, []);
|
||||||
|
self::configure($dbName);
|
||||||
|
|
||||||
|
if ($withData) {
|
||||||
|
Definition::ensureTable(self::TABLE);
|
||||||
|
Document::insert(self::TABLE, new TestDocument('one', 'FIRST!', 0));
|
||||||
|
Document::insert(self::TABLE, new TestDocument('two', 'another', 10, new SubDocument('green', 'blue')));
|
||||||
|
Document::insert(self::TABLE, new TestDocument('three', '', 4));
|
||||||
|
Document::insert(self::TABLE, new TestDocument('four', 'purple', 17, new SubDocument('green', 'red')));
|
||||||
|
Document::insert(self::TABLE, new TestDocument('five', 'purple', 18));
|
||||||
|
}
|
||||||
|
|
||||||
|
return $dbName;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Destroy a throwaway PostgreSQL database
|
||||||
|
*
|
||||||
|
* @param string $dbName The name of the PostgreSQL database to be dropped
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function destroy(string $dbName): void
|
||||||
|
{
|
||||||
|
self::configure();
|
||||||
|
Custom::nonQuery("DROP DATABASE IF EXISTS $dbName WITH (FORCE)", []);
|
||||||
|
Configuration::$pdoDSN = '';
|
||||||
|
Configuration::$username = null;
|
||||||
|
Configuration::$password = null;
|
||||||
|
Configuration::$mode = null;
|
||||||
|
Configuration::resetPDO();
|
||||||
|
}
|
||||||
|
}
|
||||||
60
tests/integration/sqlite/CountTest.php
Normal file
60
tests/integration/sqlite/CountTest.php
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\SQLite;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Count, DocumentException, Field};
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SQLite integration tests for the Count class
|
||||||
|
*/
|
||||||
|
#[TestDox('Count (SQLite integration)')]
|
||||||
|
class CountTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->dbName = ThrowawayDb::create();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
ThrowawayDb::destroy($this->dbName);
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testAllSucceeds(): void
|
||||||
|
{
|
||||||
|
$count = Count::all(ThrowawayDb::TABLE);
|
||||||
|
$this->assertEquals(5, $count, 'There should have been 5 matching documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceedsForANumericRange(): void
|
||||||
|
{
|
||||||
|
$count = Count::byFields(ThrowawayDb::TABLE, [Field::BT('num_value', 10, 20)]);
|
||||||
|
$this->assertEquals(3, $count, 'There should have been 3 matching documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceedsForANonNumericRange(): void
|
||||||
|
{
|
||||||
|
$count = Count::byFields(ThrowawayDb::TABLE, [Field::BT('value', 'aardvark', 'apple')]);
|
||||||
|
$this->assertEquals(1, $count, 'There should have been 1 matching document');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Count::byContains('', []);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path fails')]
|
||||||
|
public function testByJsonPathFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Count::byJsonPath('', '');
|
||||||
|
}
|
||||||
|
}
|
||||||
119
tests/integration/sqlite/CustomTest.php
Normal file
119
tests/integration/sqlite/CustomTest.php
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\SQLite;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Count, Custom, DocumentException, Query};
|
||||||
|
use BitBadger\PDODocument\Mapper\{CountMapper, DocumentMapper};
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
use Test\Integration\TestDocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SQLite Integration tests for the Custom class
|
||||||
|
*/
|
||||||
|
#[TestDox('Custom (SQLite integration)')]
|
||||||
|
class CustomTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
public function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->dbName = ThrowawayDb::create();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function tearDown(): void
|
||||||
|
{
|
||||||
|
ThrowawayDb::destroy($this->dbName);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testRunQuerySucceedsWithAValidQuery()
|
||||||
|
{
|
||||||
|
$stmt = &Custom::runQuery('SELECT data FROM ' . ThrowawayDb::TABLE . ' LIMIT 1', []);
|
||||||
|
try {
|
||||||
|
$this->assertNotNull($stmt, 'The statement should not have been null');
|
||||||
|
} finally {
|
||||||
|
$stmt = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testRunQueryFailsWithAnInvalidQuery()
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
$stmt = &Custom::runQuery('GRAB stuff FROM over_there UNTIL done', []);
|
||||||
|
try {
|
||||||
|
$this->assertTrue(false, 'This code should not be reached');
|
||||||
|
} finally {
|
||||||
|
$stmt = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testListSucceedsWhenDataIsFound()
|
||||||
|
{
|
||||||
|
$list = Custom::list(Query::selectFromTable(ThrowawayDb::TABLE), [], new DocumentMapper(TestDocument::class));
|
||||||
|
$this->assertNotNull($list, 'The document list should not be null');
|
||||||
|
$count = 0;
|
||||||
|
foreach ($list->items() as $ignored) $count++;
|
||||||
|
$this->assertEquals(5, $count, 'There should have been 5 documents in the list');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testListSucceedsWhenNoDataIsFound()
|
||||||
|
{
|
||||||
|
$list = Custom::list(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'num_value' > :value",
|
||||||
|
[':value' => 100], new DocumentMapper(TestDocument::class));
|
||||||
|
$this->assertNotNull($list, 'The document list should not be null');
|
||||||
|
$this->assertFalse($list->hasItems(), 'There should have been no documents in the list');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testArraySucceedsWhenDataIsFound()
|
||||||
|
{
|
||||||
|
$array = Custom::array(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'sub' IS NOT NULL", [],
|
||||||
|
new DocumentMapper(TestDocument::class));
|
||||||
|
$this->assertNotNull($array, 'The document array should not be null');
|
||||||
|
$this->assertCount(2, $array, 'There should have been 2 documents in the array');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testArraySucceedsWhenNoDataIsFound()
|
||||||
|
{
|
||||||
|
$array = Custom::array(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'value' = :value",
|
||||||
|
[':value' => 'not there'], new DocumentMapper(TestDocument::class));
|
||||||
|
$this->assertNotNull($array, 'The document array should not be null');
|
||||||
|
$this->assertCount(0, $array, 'There should have been no documents in the array');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testSingleSucceedsWhenARowIsFound(): void
|
||||||
|
{
|
||||||
|
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id", [':id' => 'one'],
|
||||||
|
new DocumentMapper(TestDocument::class));
|
||||||
|
$this->assertNotNull($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('one', $doc->id, 'The incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testSingleSucceedsWhenARowIsNotFound(): void
|
||||||
|
{
|
||||||
|
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id",
|
||||||
|
[':id' => 'eighty'], new DocumentMapper(TestDocument::class));
|
||||||
|
$this->assertFalse($doc, 'There should not have been a document returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testNonQuerySucceedsWhenOperatingOnData()
|
||||||
|
{
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
$remaining = Count::all(ThrowawayDb::TABLE);
|
||||||
|
$this->assertEquals(0, $remaining, 'There should be no documents remaining in the table');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testNonQuerySucceedsWhenNoDataMatchesWhereClause()
|
||||||
|
{
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE . " WHERE data->>'num_value' > :value", [':value' => 100]);
|
||||||
|
$remaining = Count::all(ThrowawayDb::TABLE);
|
||||||
|
$this->assertEquals(5, $remaining, 'There should be 5 documents remaining in the table');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testScalarSucceeds()
|
||||||
|
{
|
||||||
|
$value = Custom::scalar("SELECT 5 AS it", [], new CountMapper());
|
||||||
|
$this->assertEquals(5, $value, 'The scalar value was not returned correctly');
|
||||||
|
}
|
||||||
|
}
|
||||||
66
tests/integration/sqlite/DefinitionTest.php
Normal file
66
tests/integration/sqlite/DefinitionTest.php
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Test\Integration\SQLite;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Custom, Definition, DocumentException, DocumentIndex};
|
||||||
|
use BitBadger\PDODocument\Mapper\ExistsMapper;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SQLite integration tests for the Definition class
|
||||||
|
*/
|
||||||
|
#[TestDox('Definition (SQLite integration)')]
|
||||||
|
class DefinitionTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
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 sqlite_master WHERE name = :name)',
|
||||||
|
[':name' => $name], new ExistsMapper());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testEnsureTableSucceeds(): void
|
||||||
|
{
|
||||||
|
$this->assertFalse($this->itExists('ensured'), 'The table should not exist already');
|
||||||
|
$this->assertFalse($this->itExists('idx_ensured_key'), 'The key index should not exist already');
|
||||||
|
Definition::ensureTable('ensured');
|
||||||
|
$this->assertTrue($this->itExists('ensured'), 'The table should now exist');
|
||||||
|
$this->assertTrue($this->itExists('idx_ensured_key'), 'The key index should now exist');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testEnsureFieldIndexSucceeds(): void
|
||||||
|
{
|
||||||
|
$this->assertFalse($this->itExists('idx_ensured_test'), 'The index should not exist already');
|
||||||
|
Definition::ensureTable('ensured');
|
||||||
|
Definition::ensureFieldIndex('ensured', 'test', ['name', 'age']);
|
||||||
|
$this->assertTrue($this->itExists('idx_ensured_test'), 'The index should now exist');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testEnsureDocumentIndexFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Definition::ensureDocumentIndex('nope', DocumentIndex::Full);
|
||||||
|
}
|
||||||
|
}
|
||||||
72
tests/integration/sqlite/DeleteTest.php
Normal file
72
tests/integration/sqlite/DeleteTest.php
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\SQLite;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Count, Delete, DocumentException, Field};
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SQLite integration tests for the Delete class
|
||||||
|
*/
|
||||||
|
#[TestDox('Delete (SQLite integration)')]
|
||||||
|
class DeleteTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->dbName = ThrowawayDb::create();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
ThrowawayDb::destroy($this->dbName);
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds when a document is deleted')]
|
||||||
|
public function testByIdSucceedsWhenADocumentIsDeleted(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
||||||
|
Delete::byId(ThrowawayDb::TABLE, 'four');
|
||||||
|
$this->assertEquals(4, Count::all(ThrowawayDb::TABLE), 'There should have been 4 documents remaining');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds when a document is not deleted')]
|
||||||
|
public function testByIdSucceedsWhenADocumentIsNotDeleted(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
||||||
|
Delete::byId(ThrowawayDb::TABLE, 'negative four');
|
||||||
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents remaining');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceedsWhenDocumentsAreDeleted(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
||||||
|
Delete::byFields(ThrowawayDb::TABLE, [Field::NE('value', 'purple')]);
|
||||||
|
$this->assertEquals(2, Count::all(ThrowawayDb::TABLE), 'There should have been 2 documents remaining');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceedsWhenDocumentsAreNotDeleted(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
||||||
|
Delete::byFields(ThrowawayDb::TABLE, [Field::EQ('value', 'crimson')]);
|
||||||
|
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents remaining');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Delete::byContains('', []);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path fails')]
|
||||||
|
public function testByJsonPathFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Delete::byJsonPath('', '');
|
||||||
|
}
|
||||||
|
}
|
||||||
73
tests/integration/sqlite/DocumentListTest.php
Normal file
73
tests/integration/sqlite/DocumentListTest.php
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\SQLite;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{DocumentList, Query};
|
||||||
|
use BitBadger\PDODocument\Mapper\DocumentMapper;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
use Test\Integration\TestDocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SQLite integration tests for the DocumentList class
|
||||||
|
*/
|
||||||
|
#[TestDox('DocumentList (SQLite integration)')]
|
||||||
|
class DocumentListTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->dbName = ThrowawayDb::create();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
ThrowawayDb::destroy($this->dbName);
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testCreateSucceeds(): void
|
||||||
|
{
|
||||||
|
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
|
||||||
|
new DocumentMapper(TestDocument::class));
|
||||||
|
$this->assertNotNull($list, 'There should have been a document list created');
|
||||||
|
$list = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testItems(): void
|
||||||
|
{
|
||||||
|
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
|
||||||
|
new DocumentMapper(TestDocument::class));
|
||||||
|
$this->assertNotNull($list, 'There should have been a document list created');
|
||||||
|
$count = 0;
|
||||||
|
foreach ($list->items() as $item) {
|
||||||
|
$this->assertContains($item->id, ['one', 'two', 'three', 'four', 'five'],
|
||||||
|
'An unexpected document ID was returned');
|
||||||
|
$count++;
|
||||||
|
}
|
||||||
|
$this->assertEquals(5, $count, 'There should have been 5 documents returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testHasItemsSucceedsWithEmptyResults(): void
|
||||||
|
{
|
||||||
|
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'num_value' < 0", [],
|
||||||
|
new DocumentMapper(TestDocument::class));
|
||||||
|
$this->assertNotNull($list, 'There should have been a document list created');
|
||||||
|
$this->assertFalse($list->hasItems(), 'There should be no items in the list');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testHasItemsSucceedsWithNonEmptyResults(): void
|
||||||
|
{
|
||||||
|
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
|
||||||
|
new DocumentMapper(TestDocument::class));
|
||||||
|
$this->assertNotNull($list, 'There should have been a document list created');
|
||||||
|
$this->assertTrue($list->hasItems(), 'There should be items in the list');
|
||||||
|
foreach ($list->items() as $ignored) {
|
||||||
|
$this->assertTrue($list->hasItems(), 'There should be items remaining in the list');
|
||||||
|
}
|
||||||
|
$this->assertFalse($list->hasItems(), 'There should be no remaining items in the list');
|
||||||
|
}
|
||||||
|
}
|
||||||
302
tests/integration/sqlite/DocumentTest.php
Normal file
302
tests/integration/sqlite/DocumentTest.php
Normal file
@@ -0,0 +1,302 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\SQLite;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{AutoId, Configuration, Custom, Document, DocumentException, Field, Find};
|
||||||
|
use BitBadger\PDODocument\Mapper\ArrayMapper;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
use Test\Integration\{NumDocument, SubDocument, TestDocument};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SQLite integration tests for the Document class
|
||||||
|
*/
|
||||||
|
#[TestDox('Document (SQLite 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']]);
|
||||||
|
$doc = Find::byId(ThrowawayDb::TABLE, 'turkey', TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document inserted');
|
||||||
|
$this->assertEquals('turkey', $doc->id, 'The ID was incorrect');
|
||||||
|
$this->assertEquals('', $doc->value, 'The value was incorrect');
|
||||||
|
$this->assertEquals(0, $doc->num_value, 'The numeric value was incorrect');
|
||||||
|
$this->assertNotNull($doc->sub, 'The sub-document should not have been null');
|
||||||
|
$this->assertEquals('gobble', $doc->sub->foo, 'The sub-document foo property was incorrect');
|
||||||
|
$this->assertEquals('gobble', $doc->sub->bar, 'The sub-document bar property was incorrect');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$obj = json_decode($doc['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->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$obj = json_decode($doc['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->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$obj = json_decode($doc['data']);
|
||||||
|
$this->assertEquals(7, $obj->id, 'The ID 7 should have been stored');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for array with auto UUID ID not provided')]
|
||||||
|
public function testInsertSucceedsForArrayWithAutoUuidIdNotProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::UUID;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => '', 'num_value' => 5]);
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 5)], TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertNotEmpty($doc->id, 'The ID should have been auto-generated');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for array with auto UUID ID with ID provided')]
|
||||||
|
public function testInsertSucceedsForArrayWithAutoUuidIdWithIdProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::UUID;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
$uuid = AutoId::generateUUID();
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => $uuid, 'value' => 'uuid', 'num_value' => 12]);
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 12)], TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals($uuid, $doc->id, 'The ID should not have been changed');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for array with auto string ID not provided')]
|
||||||
|
public function testInsertSucceedsForArrayWithAutoStringIdNotProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::RandomString;
|
||||||
|
Configuration::$idStringLength = 6;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => '', 'value' => 'new', 'num_value' => 8]);
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 8)], TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals(6, strlen($doc->id), 'The ID should have been auto-generated and had 6 characters');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
Configuration::$idStringLength = 16;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for array with auto string ID with ID provided')]
|
||||||
|
public function testInsertSucceedsForArrayWithAutoStringIdWithIdProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::RandomString;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => 'my-key', 'value' => 'old', 'num_value' => 3]);
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 3)], TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('my-key', $doc->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')));
|
||||||
|
$doc = Find::byId(ThrowawayDb::TABLE, 'turkey', TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document inserted');
|
||||||
|
$this->assertEquals('turkey', $doc->id, 'The ID was incorrect');
|
||||||
|
$this->assertEquals('', $doc->value, 'The value was incorrect');
|
||||||
|
$this->assertEquals(0, $doc->num_value, 'The numeric value was incorrect');
|
||||||
|
$this->assertNotNull($doc->sub, 'The sub-document should not have been null');
|
||||||
|
$this->assertEquals('gobble', $doc->sub->foo, 'The sub-document foo property was incorrect');
|
||||||
|
$this->assertEquals('gobble', $doc->sub->bar, 'The sub-document bar property was incorrect');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for object with auto number ID not provided')]
|
||||||
|
public function testInsertSucceedsForObjectWithAutoNumberIdNotProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::Number;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new NumDocument(value: 'taco'));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'taco')], NumDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals(1, $doc->id, 'The ID 1 should have been auto-generated');
|
||||||
|
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new NumDocument(value: 'burrito'));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'burrito')], NumDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals(2, $doc->id, 'The ID 2 should have been auto-generated');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for object with auto number ID with ID provided')]
|
||||||
|
public function testInsertSucceedsForObjectWithAutoNumberIdWithIdProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::Number;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new NumDocument(64, 'large'));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'large')], NumDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals(64, $doc->id, 'The ID 64 should have been stored');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for object with auto UUID ID not provided')]
|
||||||
|
public function testInsertSucceedsForObjectWithAutoUuidIdNotProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::UUID;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new TestDocument(value: 'something', num_value: 9));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EX('value')], TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertNotEmpty($doc->id, 'The ID should have been auto-generated');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for object with auto UUID ID with ID provided')]
|
||||||
|
public function testInsertSucceedsForObjectWithAutoUuidIdWithIdProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::UUID;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
$uuid = AutoId::generateUUID();
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new TestDocument($uuid, num_value: 14));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 14)], TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals($uuid, $doc->id, 'The ID should not have been changed');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for object with auto string ID not provided')]
|
||||||
|
public function testInsertSucceedsForObjectWithAutoStringIdNotProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::RandomString;
|
||||||
|
Configuration::$idStringLength = 40;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new TestDocument(num_value: 55));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 55)], TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals(40, strlen($doc->id), 'The ID should have been auto-generated and had 40 characters');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
Configuration::$idStringLength = 16;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds for object with auto string ID with ID provided')]
|
||||||
|
public function testInsertSucceedsForObjectWithAutoStringIdWithIdProvided(): void
|
||||||
|
{
|
||||||
|
Configuration::$autoId = AutoId::RandomString;
|
||||||
|
try {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new TestDocument('my-key', num_value: 3));
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 3)], TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('my-key', $doc->id, 'The ID should not have been changed');
|
||||||
|
} finally {
|
||||||
|
Configuration::$autoId = AutoId::None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testInsertFailsForDuplicateKey(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, new TestDocument('one'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testSaveSucceedsWhenADocumentIsInserted(): void
|
||||||
|
{
|
||||||
|
Document::save(ThrowawayDb::TABLE, new TestDocument('test', sub: new SubDocument('a', 'b')));
|
||||||
|
$doc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testSaveSucceedsWhenADocumentIsUpdated(): void
|
||||||
|
{
|
||||||
|
Document::save(ThrowawayDb::TABLE, new TestDocument('two', num_value: 44));
|
||||||
|
$doc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals(44, $doc->num_value, 'The numeric value was not updated');
|
||||||
|
$this->assertNull($doc->sub, 'The sub-document should have been null');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testUpdateSucceedsWhenReplacingADocument(): void
|
||||||
|
{
|
||||||
|
Document::update(ThrowawayDb::TABLE, 'one', new TestDocument('one', 'howdy', 8, new SubDocument('y', 'z')));
|
||||||
|
$doc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('howdy', $doc->value, 'The value was incorrect');
|
||||||
|
$this->assertEquals(8, $doc->num_value, 'The numeric value was incorrect');
|
||||||
|
$this->assertNotNull($doc->sub, 'The sub-document should not have been null');
|
||||||
|
$this->assertEquals('y', $doc->sub->foo, 'The sub-document foo property was incorrect');
|
||||||
|
$this->assertEquals('z', $doc->sub->bar, 'The sub-document bar property was incorrect');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testUpdateSucceedsWhenNoDocumentIsReplaced(): void
|
||||||
|
{
|
||||||
|
Document::update(ThrowawayDb::TABLE, 'two-hundred', new TestDocument('200'));
|
||||||
|
$doc = Find::byId(ThrowawayDb::TABLE, 'two-hundred', TestDocument::class);
|
||||||
|
$this->assertFalse($doc, 'There should not have been a document returned');
|
||||||
|
}
|
||||||
|
}
|
||||||
68
tests/integration/sqlite/ExistsTest.php
Normal file
68
tests/integration/sqlite/ExistsTest.php
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\SQLite;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{DocumentException, Exists, Field};
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SQLite integration tests for the Exists class
|
||||||
|
*/
|
||||||
|
#[TestDox('Exists (SQLite integration)')]
|
||||||
|
class ExistsTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->dbName = ThrowawayDb::create();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
ThrowawayDb::destroy($this->dbName);
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds when a document exists')]
|
||||||
|
public function testByIdSucceedsWhenADocumentExists(): void
|
||||||
|
{
|
||||||
|
$this->assertTrue(Exists::byId(ThrowawayDb::TABLE, 'three'), 'There should have been an existing document');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds when a document does not exist')]
|
||||||
|
public function testByIdSucceedsWhenADocumentDoesNotExist(): void
|
||||||
|
{
|
||||||
|
$this->assertFalse(Exists::byId(ThrowawayDb::TABLE, 'seven'),
|
||||||
|
'There should not have been an existing document');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceedsWhenDocumentsExist(): void
|
||||||
|
{
|
||||||
|
$this->assertTrue(Exists::byFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 10)]),
|
||||||
|
'There should have been existing documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceedsWhenNoMatchingDocumentsExist(): void
|
||||||
|
{
|
||||||
|
$this->assertFalse(Exists::byFields(ThrowawayDb::TABLE, [Field::LT('nothing', 'none')]),
|
||||||
|
'There should not have been any existing documents');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Exists::byContains('', []);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path fails')]
|
||||||
|
public function testByJsonPathFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Exists::byJsonPath('', '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
133
tests/integration/sqlite/FindTest.php
Normal file
133
tests/integration/sqlite/FindTest.php
Normal file
@@ -0,0 +1,133 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\SQLite;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Custom, Document, DocumentException, Field, Find};
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
use Test\Integration\TestDocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SQLite integration tests for the Find class
|
||||||
|
*/
|
||||||
|
#[TestDox('Find (SQLite integration)')]
|
||||||
|
class FindTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->dbName = ThrowawayDb::create();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
ThrowawayDb::destroy($this->dbName);
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testAllSucceedsWhenThereIsData(): void
|
||||||
|
{
|
||||||
|
$docs = Find::all(ThrowawayDb::TABLE, TestDocument::class);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$count = 0;
|
||||||
|
foreach ($docs->items() as $ignored) $count++;
|
||||||
|
$this->assertEquals(5, $count, 'There should have been 5 documents in the list');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testAllSucceedsWhenThereIsNoData(): void
|
||||||
|
{
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
$docs = Find::all(ThrowawayDb::TABLE, TestDocument::class);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertFalse($docs->hasItems(), 'There should have been no documents in the list');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds when a document is found')]
|
||||||
|
public function testByIdSucceedsWhenADocumentIsFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('two', $doc->id, 'An incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds when a document is found with numeric ID')]
|
||||||
|
public function testByIdSucceedsWhenADocumentIsFoundWithNumericId(): void
|
||||||
|
{
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => 18, 'value' => 'howdy']);
|
||||||
|
$doc = Find::byId(ThrowawayDb::TABLE, 18, TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('18', $doc->id, 'An incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds when a document is not found')]
|
||||||
|
public function testByIdSucceedsWhenADocumentIsNotFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::byId(ThrowawayDb::TABLE, 'seventy-five', TestDocument::class);
|
||||||
|
$this->assertFalse($doc, 'There should not have been a document returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceedsWhenDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::GT('num_value', 15)], TestDocument::class);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$count = 0;
|
||||||
|
foreach ($docs->items() as $ignored) $count++;
|
||||||
|
$this->assertEquals(2, $count, 'There should have been 2 documents in the list');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceedsWhenNoDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::GT('num_value', 100)], TestDocument::class);
|
||||||
|
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||||
|
$this->assertFalse($docs->hasItems(), 'There should have been no documents in the list');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Find::byContains('', [], TestDocument::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path fails')]
|
||||||
|
public function testByJsonPathFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Find::byJsonPath('', '', TestDocument::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testFirstByFieldsSucceedsWhenADocumentIsFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'another')], TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('two', $doc->id, 'The incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testFirstByFieldsSucceedsWhenMultipleDocumentsAreFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('sub.foo', 'green')], TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertContains($doc->id, ['two', 'four'], 'An incorrect document was returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testFirstByFieldsSucceedsWhenADocumentIsNotFound(): void
|
||||||
|
{
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'absent')], TestDocument::class);
|
||||||
|
$this->assertFalse($doc, 'There should not have been a document returned');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testFirstByContainsFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Find::firstByContains('', [], TestDocument::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('First by JSON Path fails')]
|
||||||
|
public function testFirstByJsonPathFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Find::firstByJsonPath('', '', TestDocument::class);
|
||||||
|
}
|
||||||
|
}
|
||||||
72
tests/integration/sqlite/PatchTest.php
Normal file
72
tests/integration/sqlite/PatchTest.php
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\SQLite;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Count, DocumentException, Field, Find, Patch};
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
use Test\Integration\TestDocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SQLite integration tests for the Patch class
|
||||||
|
*/
|
||||||
|
#[TestDox('Patch (SQLite integration)')]
|
||||||
|
class PatchTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->dbName = ThrowawayDb::create();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
ThrowawayDb::destroy($this->dbName);
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds when a document is updated')]
|
||||||
|
public function testByIdSucceedsWhenADocumentIsUpdated(): void
|
||||||
|
{
|
||||||
|
Patch::byId(ThrowawayDb::TABLE, 'one', ['num_value' => 44]);
|
||||||
|
$doc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals(44, $doc->num_value, 'The updated document is not correct');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds when no document is updated')]
|
||||||
|
public function testByIdSucceedsWhenNoDocumentIsUpdated(): void
|
||||||
|
{
|
||||||
|
Patch::byId(ThrowawayDb::TABLE, 'forty-seven', ['foo' => 'green']);
|
||||||
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceedsWhenADocumentIsUpdated(): void
|
||||||
|
{
|
||||||
|
Patch::byFields(ThrowawayDb::TABLE, [Field::EQ('value', 'purple')], ['num_value' => 77]);
|
||||||
|
$after = Count::byFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 77)]);
|
||||||
|
$this->assertEquals(2, $after, 'There should have been 2 documents updated');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceedsWhenNoDocumentIsUpdated(): void
|
||||||
|
{
|
||||||
|
Patch::byFields(ThrowawayDb::TABLE, [Field::EQ('value', 'burgundy')], ['foo' => 'green']);
|
||||||
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Patch::byContains('', [], []);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path fails')]
|
||||||
|
public function testByJsonPathFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Patch::byJsonPath('', '', []);
|
||||||
|
}
|
||||||
|
}
|
||||||
87
tests/integration/sqlite/RemoveFieldsTest.php
Normal file
87
tests/integration/sqlite/RemoveFieldsTest.php
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Integration\SQLite;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{DocumentException, Field, Find, RemoveFields};
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
use Test\Integration\TestDocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SQLite integration tests for the RemoveFields class
|
||||||
|
*/
|
||||||
|
#[TestDox('Remove Fields (SQLite integration)')]
|
||||||
|
class RemoveFieldsTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var string Database name for throwaway database */
|
||||||
|
private string $dbName;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->dbName = ThrowawayDb::create();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
ThrowawayDb::destroy($this->dbName);
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds when fields are removed')]
|
||||||
|
public function testByIdSucceedsWhenFieldsAreRemoved(): void
|
||||||
|
{
|
||||||
|
RemoveFields::byId(ThrowawayDb::TABLE, 'two', ['sub', 'value']);
|
||||||
|
$doc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertEquals('', $doc->value, 'Value should have been blank (its default value)');
|
||||||
|
$this->assertNull($doc->sub, 'Sub-document should have been null');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds when a field is not removed')]
|
||||||
|
public function testByIdSucceedsWhenAFieldIsNotRemoved(): void
|
||||||
|
{
|
||||||
|
RemoveFields::byId(ThrowawayDb::TABLE, 'one', ['a_field_that_does_not_exist']);
|
||||||
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds when no document is matched')]
|
||||||
|
public function testByIdSucceedsWhenNoDocumentIsMatched(): void
|
||||||
|
{
|
||||||
|
RemoveFields::byId(ThrowawayDb::TABLE, 'fifty', ['sub']);
|
||||||
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceedsWhenAFieldIsRemoved(): void
|
||||||
|
{
|
||||||
|
RemoveFields::byFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 17)], ['sub']);
|
||||||
|
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 17)], TestDocument::class);
|
||||||
|
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||||
|
$this->assertNull($doc->sub, 'Sub-document should have been null');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceedsWhenAFieldIsNotRemoved(): void
|
||||||
|
{
|
||||||
|
RemoveFields::byFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 17)], ['nada']);
|
||||||
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceedsWhenNoDocumentIsMatched(): void
|
||||||
|
{
|
||||||
|
RemoveFields::byFields(ThrowawayDb::TABLE, [Field::NE('missing', 'nope')], ['value']);
|
||||||
|
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByContainsFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
RemoveFields::byContains('', [], []);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path fails')]
|
||||||
|
public function testByJsonPathFails(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
RemoveFields::byJsonPath('', '', []);
|
||||||
|
}
|
||||||
|
}
|
||||||
53
tests/integration/sqlite/ThrowawayDb.php
Normal file
53
tests/integration/sqlite/ThrowawayDb.php
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Test\Integration\SQLite;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{AutoId, Configuration, Definition, Document, DocumentException, Mode};
|
||||||
|
use Random\RandomException;
|
||||||
|
use Test\Integration\{SubDocument, TestDocument};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Utilities to create and destroy a throwaway SQLite database to use for testing
|
||||||
|
*/
|
||||||
|
class ThrowawayDb
|
||||||
|
{
|
||||||
|
/** @var string The table used for document manipulation */
|
||||||
|
public const TABLE = "test_table";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a throwaway SQLite 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
|
||||||
|
{
|
||||||
|
$fileName = sprintf('throwaway-%s.db', AutoId::generateRandom(10));
|
||||||
|
Configuration::$pdoDSN = "sqlite:./$fileName";
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
Configuration::resetPDO();
|
||||||
|
|
||||||
|
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 $fileName;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Destroy a throwaway SQLite database
|
||||||
|
*
|
||||||
|
* @param string $fileName The name of the SQLite database to be deleted
|
||||||
|
*/
|
||||||
|
public static function destroy(string $fileName): void
|
||||||
|
{
|
||||||
|
Configuration::resetPDO();
|
||||||
|
if (file_exists("./$fileName")) unlink("./$fileName");
|
||||||
|
}
|
||||||
|
}
|
||||||
52
tests/unit/ConfigurationTest.php
Normal file
52
tests/unit/ConfigurationTest.php
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Unit;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{AutoId, Configuration, DocumentException};
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unit tests for the Configuration class
|
||||||
|
*/
|
||||||
|
#[TestDox('Configuration (Unit tests)')]
|
||||||
|
class ConfigurationTest extends TestCase
|
||||||
|
{
|
||||||
|
#[TestDox('ID field default succeeds')]
|
||||||
|
public function testIdFieldDefaultSucceeds(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals('id', Configuration::$idField, 'Default ID field should be "id"');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('ID field change succeeds')]
|
||||||
|
public function testIdFieldChangeSucceeds()
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
Configuration::$idField = 'EyeDee';
|
||||||
|
$this->assertEquals('EyeDee', Configuration::$idField, 'ID field should have been updated');
|
||||||
|
} finally {
|
||||||
|
Configuration::$idField = 'id';
|
||||||
|
$this->assertEquals('id', Configuration::$idField, 'Default ID value should have been restored');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Auto ID default succeeds')]
|
||||||
|
public function testAutoIdDefaultSucceeds(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(AutoId::None, Configuration::$autoId, 'Auto ID should default to None');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('ID string length default succeeds')]
|
||||||
|
public function testIdStringLengthDefaultSucceeds(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(16, Configuration::$idStringLength, 'ID string length should default to 16');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox("Db conn fails when no DSN specified")]
|
||||||
|
public function testDbConnFailsWhenNoDSNSpecified(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Configuration::$pdoDSN = '';
|
||||||
|
Configuration::dbConn();
|
||||||
|
}
|
||||||
|
}
|
||||||
48
tests/unit/DocumentExceptionTest.php
Normal file
48
tests/unit/DocumentExceptionTest.php
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Test\Unit;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\DocumentException;
|
||||||
|
use Exception;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unit tests for the DocumentException class
|
||||||
|
*/
|
||||||
|
#[TestDox('Document Exception (Unit tests)')]
|
||||||
|
class DocumentExceptionTest extends TestCase
|
||||||
|
{
|
||||||
|
public function testConstructorSucceedsWithCodeAndPriorException()
|
||||||
|
{
|
||||||
|
$priorEx = new Exception('Uh oh');
|
||||||
|
$ex = new DocumentException('Test Exception', 17, $priorEx);
|
||||||
|
$this->assertNotNull($ex, 'The exception should not have been null');
|
||||||
|
$this->assertEquals('Test Exception', $ex->getMessage(), 'Message not filled properly');
|
||||||
|
$this->assertEquals(17, $ex->getCode(), 'Code not filled properly');
|
||||||
|
$this->assertSame($priorEx, $ex->getPrevious(), 'Prior exception not filled properly');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testConstructorSucceedsWithoutCodeAndPriorException()
|
||||||
|
{
|
||||||
|
$ex = new DocumentException('Oops');
|
||||||
|
$this->assertNotNull($ex, 'The exception should not have been null');
|
||||||
|
$this->assertEquals('Oops', $ex->getMessage(), 'Message not filled properly');
|
||||||
|
$this->assertEquals(0, $ex->getCode(), 'Code not filled properly');
|
||||||
|
$this->assertNull($ex->getPrevious(), 'Prior exception should have been null');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testToStringSucceedsWithoutCode()
|
||||||
|
{
|
||||||
|
$ex = new DocumentException('Test failure');
|
||||||
|
$this->assertEquals("BitBadger\PDODocument\DocumentException: Test failure\n", "$ex",
|
||||||
|
'toString not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testToStringSucceedsWithCode()
|
||||||
|
{
|
||||||
|
$ex = new DocumentException('Oof', -6);
|
||||||
|
$this->assertEquals("BitBadger\PDODocument\DocumentException: [-6] Oof\n", "$ex",
|
||||||
|
'toString not generated correctly');
|
||||||
|
}
|
||||||
|
}
|
||||||
24
tests/unit/FieldMatchTest.php
Normal file
24
tests/unit/FieldMatchTest.php
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Unit;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\FieldMatch;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unit tests for the FieldMatch enum
|
||||||
|
*/
|
||||||
|
#[TestDox('Field Match (Unit tests)')]
|
||||||
|
class FieldMatchTest extends TestCase
|
||||||
|
{
|
||||||
|
public function testToStringSucceedsForAll(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals('AND', FieldMatch::All->toString(), 'All should have returned AND');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testToStringSucceedsForAny(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals('OR', FieldMatch::Any->toString(), 'Any should have returned OR');
|
||||||
|
}
|
||||||
|
}
|
||||||
447
tests/unit/FieldTest.php
Normal file
447
tests/unit/FieldTest.php
Normal file
@@ -0,0 +1,447 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Unit;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Configuration, Field, Mode, Op};
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unit tests for the Field class
|
||||||
|
*/
|
||||||
|
#[TestDox('Field (Unit tests)')]
|
||||||
|
class FieldTest extends TestCase
|
||||||
|
{
|
||||||
|
#[TestDox('Append parameter succeeds for EX')]
|
||||||
|
public function testAppendParameterSucceedsForEX(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals([], Field::EX('exists')->appendParameter([]), 'EX should not have appended a parameter');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Append parameter succeeds for NEX')]
|
||||||
|
public function testAppendParameterSucceedsForNEX(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals([], Field::NEX('absent')->appendParameter([]), 'NEX should not have appended a parameter');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Append parameter succeeds for BT')]
|
||||||
|
public function testAppendParameterSucceedsForBT(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(['@nummin' => 5, '@nummax' => 9], Field::BT('exists', 5, 9, '@num')->appendParameter([]),
|
||||||
|
'BT should have appended min and max parameters');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testAppendParameterSucceedsForOthers(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(['@test' => 33], Field::EQ('the_field', 33, '@test')->appendParameter([]),
|
||||||
|
'Field parameter not returned correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('To where succeeds for EX without qualifier for PostgreSQL')]
|
||||||
|
public function testToWhereSucceedsForEXWithoutQualifierForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
try {
|
||||||
|
$this->assertEquals("data->>'that_field' IS NOT NULL", Field::EX('that_field')->toWhere(),
|
||||||
|
'WHERE fragment not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('To where succeeds for EX without qualifier for SQLite')]
|
||||||
|
public function testToWhereSucceedsForEXWithoutQualifierForSQLite(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
try {
|
||||||
|
$this->assertEquals("data->>'that_field' IS NOT NULL", Field::EX('that_field')->toWhere(),
|
||||||
|
'WHERE fragment not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('To where succeeds for NEX without qualifier for PostgreSQL')]
|
||||||
|
public function testToWhereSucceedsForNEXWithoutQualifierForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
try {
|
||||||
|
$this->assertEquals("data->>'a_field' IS NULL", Field::NEX('a_field')->toWhere(),
|
||||||
|
'WHERE fragment not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('To where succeeds for NEX without qualifier for SQLite')]
|
||||||
|
public function testToWhereSucceedsForNEXWithoutQualifierForSQLite(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
try {
|
||||||
|
$this->assertEquals("data->>'a_field' IS NULL", Field::NEX('a_field')->toWhere(),
|
||||||
|
'WHERE fragment not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('To where succeeds for BT without qualifier for SQLite')]
|
||||||
|
public function testToWhereSucceedsForBTWithoutQualifierForSQLite(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
try {
|
||||||
|
$this->assertEquals("data->>'age' BETWEEN @agemin AND @agemax", Field::BT('age', 13, 17, '@age')->toWhere(),
|
||||||
|
'WHERE fragment not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('To where succeeds for BT without qualifier for PostgreSQL with numeric range')]
|
||||||
|
public function testToWhereSucceedsForBTWithoutQualifierForPostgreSQLWithNumericRange(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
try {
|
||||||
|
$this->assertEquals("(data->>'age')::numeric BETWEEN @agemin AND @agemax",
|
||||||
|
Field::BT('age', 13, 17, '@age')->toWhere(), 'WHERE fragment not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('To where succeeds for BT without qualifier for PostgreSQL with non-numeric range')]
|
||||||
|
public function testToWhereSucceedsForBTWithoutQualifierForPostgreSQLWithNonNumericRange(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
try {
|
||||||
|
$this->assertEquals("data->>'city' BETWEEN :citymin AND :citymax",
|
||||||
|
Field::BT('city', 'Atlanta', 'Chicago', ':city')->toWhere(), 'WHERE fragment not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('To where succeeds for BT with qualifier for SQLite')]
|
||||||
|
public function testToWhereSucceedsForBTWithQualifierForSQLite(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
try {
|
||||||
|
$field = Field::BT('age', 13, 17, '@age');
|
||||||
|
$field->qualifier = 'me';
|
||||||
|
$this->assertEquals("me.data->>'age' BETWEEN @agemin AND @agemax", $field->toWhere(),
|
||||||
|
'WHERE fragment not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('To where succeeds for BT with qualifier for PostgreSQL with numeric range')]
|
||||||
|
public function testToWhereSucceedsForBTWithQualifierForPostgreSQLWithNumericRange(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
try {
|
||||||
|
$field = Field::BT('age', 13, 17, '@age');
|
||||||
|
$field->qualifier = 'me';
|
||||||
|
$this->assertEquals("(me.data->>'age')::numeric BETWEEN @agemin AND @agemax", $field->toWhere(),
|
||||||
|
'WHERE fragment not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('To where succeeds for BT with qualifier for PostgreSQL with non-numeric range')]
|
||||||
|
public function testToWhereSucceedsForBTWithQualifierForPostgreSQLWithNonNumericRange(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
try {
|
||||||
|
$field = Field::BT('city', 'Atlanta', 'Chicago', ':city');
|
||||||
|
$field->qualifier = 'me';
|
||||||
|
$this->assertEquals("me.data->>'city' BETWEEN :citymin AND :citymax", $field->toWhere(),
|
||||||
|
'WHERE fragment not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('To where succeeds for others without qualifier for PostgreSQL')]
|
||||||
|
public function testToWhereSucceedsForOthersWithoutQualifierForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
try {
|
||||||
|
$this->assertEquals("data->>'some_field' = @value", Field::EQ('some_field', '', '@value')->toWhere(),
|
||||||
|
'WHERE fragment not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('To where succeeds for others without qualifier for SQLite')]
|
||||||
|
public function testToWhereSucceedsForOthersWithoutQualifierForSQLite(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
try {
|
||||||
|
$this->assertEquals("data->>'some_field' = @value", Field::EQ('some_field', '', '@value')->toWhere(),
|
||||||
|
'WHERE fragment not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('To where succeeds with qualifier no parameter for PostgreSQL')]
|
||||||
|
public function testToWhereSucceedsWithQualifierNoParameterForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
try {
|
||||||
|
$field = Field::EX('no_field');
|
||||||
|
$field->qualifier = 'test';
|
||||||
|
$this->assertEquals("test.data->>'no_field' IS NOT NULL", $field->toWhere(),
|
||||||
|
'WHERE fragment not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('To where succeeds with qualifier no parameter for SQLite')]
|
||||||
|
public function testToWhereSucceedsWithQualifierNoParameterForSQLite(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
try {
|
||||||
|
$field = Field::EX('no_field');
|
||||||
|
$field->qualifier = 'test';
|
||||||
|
$this->assertEquals("test.data->>'no_field' IS NOT NULL", $field->toWhere(),
|
||||||
|
'WHERE fragment not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('To where succeeds with qualifier and parameter for PostgreSQL')]
|
||||||
|
public function testToWhereSucceedsWithQualifierAndParameterForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
try {
|
||||||
|
$field = Field::LE('le_field', 18, '@it');
|
||||||
|
$field->qualifier = 'q';
|
||||||
|
$this->assertEquals("(q.data->>'le_field')::numeric <= @it", $field->toWhere(),
|
||||||
|
'WHERE fragment not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('To where succeeds with qualifier and parameter for SQLite')]
|
||||||
|
public function testToWhereSucceedsWithQualifierAndParameterForSQLite(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
try {
|
||||||
|
$field = Field::LE('le_field', 18, '@it');
|
||||||
|
$field->qualifier = 'q';
|
||||||
|
$this->assertEquals("q.data->>'le_field' <= @it", $field->toWhere(),
|
||||||
|
'WHERE fragment not generated correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('To where succeeds with sub-document for PostgreSQL')]
|
||||||
|
public function testToWhereSucceedsWithSubDocumentForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
try {
|
||||||
|
$field = Field::EQ('sub.foo.bar', 22, '@it');
|
||||||
|
$this->assertEquals("(data#>>'{sub,foo,bar}')::numeric = @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->assertEquals('my_test', $field->fieldName, 'Field name not filled correctly');
|
||||||
|
$this->assertEquals(Op::EQ, $field->op, 'Operation not filled correctly');
|
||||||
|
$this->assertEquals(9, $field->value, 'Value not filled correctly');
|
||||||
|
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('EQ succeeds with parameter')]
|
||||||
|
public function testEQSucceedsWithParameter(): void
|
||||||
|
{
|
||||||
|
$field = Field::EQ('another_test', 'turkey', '@test');
|
||||||
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
|
$this->assertEquals('another_test', $field->fieldName, 'Field name not filled correctly');
|
||||||
|
$this->assertEquals(Op::EQ, $field->op, 'Operation not filled correctly');
|
||||||
|
$this->assertEquals('turkey', $field->value, 'Value not filled correctly');
|
||||||
|
$this->assertEquals('@test', $field->paramName, 'Parameter name not filled correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('GT succeeds without parameter')]
|
||||||
|
public function testGTSucceedsWithoutParameter(): void
|
||||||
|
{
|
||||||
|
$field = Field::GT('your_test', 4);
|
||||||
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
|
$this->assertEquals('your_test', $field->fieldName, 'Field name not filled correctly');
|
||||||
|
$this->assertEquals(Op::GT, $field->op, 'Operation not filled correctly');
|
||||||
|
$this->assertEquals(4, $field->value, 'Value not filled correctly');
|
||||||
|
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('GT succeeds with parameter')]
|
||||||
|
public function testGTSucceedsWithParameter(): void
|
||||||
|
{
|
||||||
|
$field = Field::GT('more_test', 'chicken', '@value');
|
||||||
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
|
$this->assertEquals('more_test', $field->fieldName, 'Field name not filled correctly');
|
||||||
|
$this->assertEquals(Op::GT, $field->op, 'Operation not filled correctly');
|
||||||
|
$this->assertEquals('chicken', $field->value, 'Value not filled correctly');
|
||||||
|
$this->assertEquals('@value', $field->paramName, 'Parameter name not filled correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('GE succeeds without parameter')]
|
||||||
|
public function testGESucceedsWithoutParameter(): void
|
||||||
|
{
|
||||||
|
$field = Field::GE('their_test', 6);
|
||||||
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
|
$this->assertEquals('their_test', $field->fieldName, 'Field name not filled correctly');
|
||||||
|
$this->assertEquals(Op::GE, $field->op, 'Operation not filled correctly');
|
||||||
|
$this->assertEquals(6, $field->value, 'Value not filled correctly');
|
||||||
|
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('GE succeeds with parameter')]
|
||||||
|
public function testGESucceedsWithParameter(): void
|
||||||
|
{
|
||||||
|
$field = Field::GE('greater_test', 'poultry', '@cluck');
|
||||||
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
|
$this->assertEquals('greater_test', $field->fieldName, 'Field name not filled correctly');
|
||||||
|
$this->assertEquals(Op::GE, $field->op, 'Operation not filled correctly');
|
||||||
|
$this->assertEquals('poultry', $field->value, 'Value not filled correctly');
|
||||||
|
$this->assertEquals('@cluck', $field->paramName, 'Parameter name not filled correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('LT succeeds without parameter')]
|
||||||
|
public function testLTSucceedsWithoutParameter(): void
|
||||||
|
{
|
||||||
|
$field = Field::LT('z', 32);
|
||||||
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
|
$this->assertEquals('z', $field->fieldName, 'Field name not filled correctly');
|
||||||
|
$this->assertEquals(Op::LT, $field->op, 'Operation not filled correctly');
|
||||||
|
$this->assertEquals(32, $field->value, 'Value not filled correctly');
|
||||||
|
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('LT succeeds with parameter')]
|
||||||
|
public function testLTSucceedsWithParameter(): void
|
||||||
|
{
|
||||||
|
$field = Field::LT('additional_test', 'fowl', '@boo');
|
||||||
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
|
$this->assertEquals('additional_test', $field->fieldName, 'Field name not filled correctly');
|
||||||
|
$this->assertEquals(Op::LT, $field->op, 'Operation not filled correctly');
|
||||||
|
$this->assertEquals('fowl', $field->value, 'Value not filled correctly');
|
||||||
|
$this->assertEquals('@boo', $field->paramName, 'Parameter name not filled correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('LE succeeds without parameter')]
|
||||||
|
public function testLESucceedsWithoutParameter(): void
|
||||||
|
{
|
||||||
|
$field = Field::LE('g', 87);
|
||||||
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
|
$this->assertEquals('g', $field->fieldName, 'Field name not filled correctly');
|
||||||
|
$this->assertEquals(Op::LE, $field->op, 'Operation not filled correctly');
|
||||||
|
$this->assertEquals(87, $field->value, 'Value not filled correctly');
|
||||||
|
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('LE succeeds with parameter')]
|
||||||
|
public function testLESucceedsWithParameter(): void
|
||||||
|
{
|
||||||
|
$field = Field::LE('lesser_test', 'hen', '@woo');
|
||||||
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
|
$this->assertEquals('lesser_test', $field->fieldName, 'Field name not filled correctly');
|
||||||
|
$this->assertEquals(Op::LE, $field->op, 'Operation not filled correctly');
|
||||||
|
$this->assertEquals('hen', $field->value, 'Value not filled correctly');
|
||||||
|
$this->assertEquals('@woo', $field->paramName, 'Parameter name not filled correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('NE succeeds without parameter')]
|
||||||
|
public function testNESucceedsWithoutParameter(): void
|
||||||
|
{
|
||||||
|
$field = Field::NE('j', 65);
|
||||||
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
|
$this->assertEquals('j', $field->fieldName, 'Field name not filled correctly');
|
||||||
|
$this->assertEquals(Op::NE, $field->op, 'Operation not filled correctly');
|
||||||
|
$this->assertEquals(65, $field->value, 'Value not filled correctly');
|
||||||
|
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('NE succeeds with parameter')]
|
||||||
|
public function testNESucceedsWithParameter(): void
|
||||||
|
{
|
||||||
|
$field = Field::NE('unequal_test', 'egg', '@zoo');
|
||||||
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
|
$this->assertEquals('unequal_test', $field->fieldName, 'Field name not filled correctly');
|
||||||
|
$this->assertEquals(Op::NE, $field->op, 'Operation not filled correctly');
|
||||||
|
$this->assertEquals('egg', $field->value, 'Value not filled correctly');
|
||||||
|
$this->assertEquals('@zoo', $field->paramName, 'Parameter name not filled correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('BT succeeds without parameter')]
|
||||||
|
public function testBTSucceedsWithoutParameter(): void
|
||||||
|
{
|
||||||
|
$field = Field::BT('k', 'alpha', 'zed');
|
||||||
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
|
$this->assertEquals('k', $field->fieldName, 'Field name not filled correctly');
|
||||||
|
$this->assertEquals(Op::BT, $field->op, 'Operation not filled correctly');
|
||||||
|
$this->assertEquals(['alpha', 'zed'], $field->value, 'Value not filled correctly');
|
||||||
|
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('BT succeeds with parameter')]
|
||||||
|
public function testBTSucceedsWithParameter(): void
|
||||||
|
{
|
||||||
|
$field = Field::BT('between_test', 18, 49, '@count');
|
||||||
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
|
$this->assertEquals('between_test', $field->fieldName, 'Field name not filled correctly');
|
||||||
|
$this->assertEquals(Op::BT, $field->op, 'Operation not filled correctly');
|
||||||
|
$this->assertEquals([18, 49], $field->value, 'Value not filled correctly');
|
||||||
|
$this->assertEquals('@count', $field->paramName, 'Parameter name not filled correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('EX succeeds')]
|
||||||
|
public function testEXSucceeds(): void
|
||||||
|
{
|
||||||
|
$field = Field::EX('be_there');
|
||||||
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
|
$this->assertEquals('be_there', $field->fieldName, 'Field name not filled correctly');
|
||||||
|
$this->assertEquals(Op::EX, $field->op, 'Operation not filled correctly');
|
||||||
|
$this->assertEquals('', $field->value, 'Value should have been blank');
|
||||||
|
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('NEX succeeds')]
|
||||||
|
public function testNEXSucceeds(): void
|
||||||
|
{
|
||||||
|
$field = Field::NEX('be_absent');
|
||||||
|
$this->assertNotNull($field, 'The field should not have been null');
|
||||||
|
$this->assertEquals('be_absent', $field->fieldName, 'Field name not filled correctly');
|
||||||
|
$this->assertEquals(Op::NEX, $field->op, 'Operation not filled correctly');
|
||||||
|
$this->assertEquals('', $field->value, 'Value should have been blank');
|
||||||
|
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||||
|
}
|
||||||
|
}
|
||||||
21
tests/unit/Mapper/ArrayMapperTest.php
Normal file
21
tests/unit/Mapper/ArrayMapperTest.php
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Unit\Mapper;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\Mapper\ArrayMapper;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unit tests for the ArrayMapper class
|
||||||
|
*/
|
||||||
|
#[TestDox('Array Mapper (Unit tests)')]
|
||||||
|
class ArrayMapperTest extends TestCase
|
||||||
|
{
|
||||||
|
public function testMapSucceeds(): void
|
||||||
|
{
|
||||||
|
$result = ['one' => 2, 'three' => 4, 'eight' => 'five'];
|
||||||
|
$mapped = (new ArrayMapper())->map($result);
|
||||||
|
$this->assertSame($result, $mapped, 'The array mapper should return the parameter given to it');
|
||||||
|
}
|
||||||
|
}
|
||||||
19
tests/unit/Mapper/CountMapperTest.php
Normal file
19
tests/unit/Mapper/CountMapperTest.php
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Unit\Mapper;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\Mapper\CountMapper;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unit tests for the CountMapper class
|
||||||
|
*/
|
||||||
|
#[TestDox('Count Mapper (Unit tests)')]
|
||||||
|
class CountMapperTest extends TestCase
|
||||||
|
{
|
||||||
|
public function testMapSucceeds(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(5, (new CountMapper())->map([5, 8, 10]), 'Count not correct');
|
||||||
|
}
|
||||||
|
}
|
||||||
57
tests/unit/Mapper/DocumentMapperTest.php
Normal file
57
tests/unit/Mapper/DocumentMapperTest.php
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Unit\Mapper;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{DocumentException, Field};
|
||||||
|
use BitBadger\PDODocument\Mapper\DocumentMapper;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
// ** Test class hierarchy for serialization **
|
||||||
|
|
||||||
|
class SubDocument
|
||||||
|
{
|
||||||
|
public function __construct(public int $id = 0, public string $name = '') { }
|
||||||
|
}
|
||||||
|
|
||||||
|
class TestDocument
|
||||||
|
{
|
||||||
|
public function __construct(public int $id = 0, public SubDocument $subDoc = new SubDocument()) { }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unit tests for the DocumentMapper class
|
||||||
|
*/
|
||||||
|
#[TestDox('Document Mapper (Unit tests)')]
|
||||||
|
class DocumentMapperTest extends TestCase
|
||||||
|
{
|
||||||
|
public function testConstructorSucceedsWithDefaultField(): void
|
||||||
|
{
|
||||||
|
$mapper = new DocumentMapper(Field::class);
|
||||||
|
$this->assertEquals('data', $mapper->fieldName, 'Default field name should have been "data"');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testConstructorSucceedsWithSpecifiedField(): void
|
||||||
|
{
|
||||||
|
$mapper = new DocumentMapper(Field::class, 'json');
|
||||||
|
$this->assertEquals('json', $mapper->fieldName, 'Field name not recorded correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Map succeeds with valid JSON')]
|
||||||
|
public function testMapSucceedsWithValidJSON(): void
|
||||||
|
{
|
||||||
|
$doc = (new DocumentMapper(TestDocument::class))->map(['data' => '{"id":7,"subDoc":{"id":22,"name":"tester"}}']);
|
||||||
|
$this->assertNotNull($doc, 'The document should not have been null');
|
||||||
|
$this->assertEquals(7, $doc->id, 'ID not filled correctly');
|
||||||
|
$this->assertNotNull($doc->subDoc, 'The sub-document should not have been null');
|
||||||
|
$this->assertEquals(22, $doc->subDoc->id, 'Sub-document ID not filled correctly');
|
||||||
|
$this->assertEquals('tester', $doc->subDoc->name, 'Sub-document name not filled correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Map fails with invalid JSON')]
|
||||||
|
public function testMapFailsWithInvalidJSON(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
(new DocumentMapper(TestDocument::class))->map(['data' => 'this is not valid']);
|
||||||
|
}
|
||||||
|
}
|
||||||
44
tests/unit/Mapper/ExistsMapperTest.php
Normal file
44
tests/unit/Mapper/ExistsMapperTest.php
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Unit\Mapper;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Configuration, DocumentException, Mode};
|
||||||
|
use BitBadger\PDODocument\Mapper\ExistsMapper;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unit tests for the ExistsMapper class
|
||||||
|
*/
|
||||||
|
#[TestDox('Exists Mapper (Unit tests)')]
|
||||||
|
class ExistsMapperTest extends TestCase
|
||||||
|
{
|
||||||
|
#[TestDox('Map succeeds for PostgreSQL')]
|
||||||
|
public function testMapSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertFalse((new ExistsMapper())->map([false, 'nope']), 'Result should have been false');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Map succeeds for SQLite')]
|
||||||
|
public function testMapSucceedsForSQLite(): void
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
$this->assertTrue((new ExistsMapper())->map([1, 'yep']), 'Result should have been true');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testMapFailsWhenModeNotSet(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Configuration::$mode = null;
|
||||||
|
(new ExistsMapper())->map(['0']);
|
||||||
|
}
|
||||||
|
}
|
||||||
34
tests/unit/Mapper/StringMapperTest.php
Normal file
34
tests/unit/Mapper/StringMapperTest.php
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Unit\Mapper;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\Mapper\StringMapper;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unit tests for the StringMapper class
|
||||||
|
*/
|
||||||
|
#[TestDox('String Mapper (Unit tests)')]
|
||||||
|
class StringMapperTest extends TestCase
|
||||||
|
{
|
||||||
|
public function testMapSucceedsWhenFieldIsPresentAndString()
|
||||||
|
{
|
||||||
|
$result = ['test_field' => 'test_value'];
|
||||||
|
$mapper = new StringMapper('test_field');
|
||||||
|
$this->assertEquals('test_value', $mapper->map($result), 'String value not returned correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testMapSucceedsWhenFieldIsPresentAndNotString()
|
||||||
|
{
|
||||||
|
$result = ['a_number' => 6.7];
|
||||||
|
$mapper = new StringMapper('a_number');
|
||||||
|
$this->assertEquals('6.7', $mapper->map($result), 'Number value not returned correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testMapSucceedsWhenFieldIsNotPresent()
|
||||||
|
{
|
||||||
|
$mapper = new StringMapper('something_else');
|
||||||
|
$this->assertNull($mapper->map([]), 'Missing value not returned correctly');
|
||||||
|
}
|
||||||
|
}
|
||||||
68
tests/unit/OpTest.php
Normal file
68
tests/unit/OpTest.php
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Unit;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\Op;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unit tests for the Op enumeration
|
||||||
|
*/
|
||||||
|
#[TestDox('Op (Unit tests)')]
|
||||||
|
class OpTest extends TestCase
|
||||||
|
{
|
||||||
|
#[TestDox('To string succeeds for EQ')]
|
||||||
|
public function testToStringSucceedsForEQ(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals('=', Op::EQ->toString(), 'EQ operator incorrect');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('To string succeeds for GT')]
|
||||||
|
public function testToStringSucceedsForGT(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals('>', Op::GT->toString(), 'GT operator incorrect');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('To string succeeds for GE')]
|
||||||
|
public function testToStringSucceedsForGE(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals('>=', Op::GE->toString(), 'GE operator incorrect');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('To string succeeds for LT')]
|
||||||
|
public function testToStringSucceedsForLT(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals('<', Op::LT->toString(), 'LT operator incorrect');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('To string succeeds for LE')]
|
||||||
|
public function testToStringSucceedsForLE(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals('<=', Op::LE->toString(), 'LE operator incorrect');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('To string succeeds for NE')]
|
||||||
|
public function testToStringSucceedsForNE(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals('<>', Op::NE->toString(), 'NE operator incorrect');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('To string succeeds for BT')]
|
||||||
|
public function testToStringSucceedsForBT(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals('BETWEEN', Op::BT->toString(), 'BT operator incorrect');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('To string succeeds for EX')]
|
||||||
|
public function testToStringSucceedsForEX(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals('IS NOT NULL', Op::EX->toString(), 'EX operator incorrect');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('To string succeeds for NEX')]
|
||||||
|
public function testToStringSucceedsForNEX(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals('IS NULL', Op::NEX->toString(), 'NEX operator incorrect');
|
||||||
|
}
|
||||||
|
}
|
||||||
80
tests/unit/ParametersTest.php
Normal file
80
tests/unit/ParametersTest.php
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Unit;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Configuration, DocumentException, Field, Mode, Parameters};
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unit tests for the Parameters class
|
||||||
|
*/
|
||||||
|
#[TestDox('Parameters (Unit tests)')]
|
||||||
|
class ParametersTest extends TestCase
|
||||||
|
{
|
||||||
|
#[TestDox('ID succeeds with string')]
|
||||||
|
public function testIdSucceedsWithString(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals([':id' => 'key'], Parameters::id('key'), 'ID parameter not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('ID succeeds with non string')]
|
||||||
|
public function testIdSucceedsWithNonString(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals([':id' => '7'], Parameters::id(7), 'ID parameter not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testJsonSucceeds(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals([':it' => '{"id":18,"url":"https://www.unittest.com"}'],
|
||||||
|
Parameters::json(':it', ['id' => 18, 'url' => 'https://www.unittest.com']),
|
||||||
|
'JSON parameter not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testNameFieldsSucceeds(): void
|
||||||
|
{
|
||||||
|
$named = Parameters::nameFields([Field::EQ('it', 17), Field::EQ('also', 22, ':also'), Field::EQ('other', 24)]);
|
||||||
|
$this->assertCount(3, $named, 'There should be 3 parameters in the array');
|
||||||
|
$this->assertEquals(':field0', $named[0]->paramName, 'Parameter 1 not named correctly');
|
||||||
|
$this->assertEquals(':also', $named[1]->paramName, 'Parameter 2 not named correctly');
|
||||||
|
$this->assertEquals(':field2', $named[2]->paramName, 'Parameter 3 not named correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testAddFieldsSucceeds(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals([':a' => 1, ':b' => 'two', ':z' => 18],
|
||||||
|
Parameters::addFields([Field::EQ('b', 'two', ':b'), Field::EQ('z', 18, ':z')], [':a' => 1]),
|
||||||
|
'Field parameters not added correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Field names succeeds for PostgreSQL')]
|
||||||
|
public function testFieldNamesSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals([':names' => "{one,two,seven}"],
|
||||||
|
Parameters::fieldNames(':names', ['one', 'two', 'seven']), 'Field name parameters not correct');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Field names succeeds for SQLite')]
|
||||||
|
public function testFieldNamesSucceedsForSQLite(): void
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
$this->assertEquals([':it0' => '$.test', ':it1' => '$.unit', ':it2' => '$.wow'],
|
||||||
|
Parameters::fieldNames(':it', ['test', 'unit', 'wow']), 'Field name parameters not correct');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testFieldNamesFailsWhenModeNotSet(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Configuration::$mode = null;
|
||||||
|
Parameters::fieldNames('', []);
|
||||||
|
}
|
||||||
|
}
|
||||||
65
tests/unit/Query/CountTest.php
Normal file
65
tests/unit/Query/CountTest.php
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Unit\Query;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Configuration, DocumentException, Field, Mode};
|
||||||
|
use BitBadger\PDODocument\Query\Count;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unit tests for the Count class
|
||||||
|
*/
|
||||||
|
#[TestDox('Count Queries (Unit tests)')]
|
||||||
|
class CountTest extends TestCase
|
||||||
|
{
|
||||||
|
public function tearDown(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = null;
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testAllSucceeds(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals('SELECT COUNT(*) FROM a_table', Count::all('a_table'),
|
||||||
|
'SELECT statement not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceeds(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
$this->assertEquals("SELECT COUNT(*) FROM somewhere WHERE data->>'errors' > :errors",
|
||||||
|
Count::byFields('somewhere', [Field::GT('errors', 10, ':errors')]),
|
||||||
|
'SELECT statement not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By contains succeeds for PostgreSQL')]
|
||||||
|
public function testByContainsSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals('SELECT COUNT(*) FROM the_table WHERE data @> :criteria', Count::byContains('the_table'),
|
||||||
|
'SELECT statement not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By contains fails for non PostgreSQL')]
|
||||||
|
public function testByContainsFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Count::byContains('');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds for PostgreSQL')]
|
||||||
|
public function testByJsonPathSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals('SELECT COUNT(*) FROM a_table WHERE jsonb_path_exists(data, :path::jsonpath)',
|
||||||
|
Count::byJsonPath('a_table'), 'SELECT statement not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path fails for non PostgreSQL')]
|
||||||
|
public function testByJsonPathFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Count::byJsonPath('');
|
||||||
|
}
|
||||||
|
}
|
||||||
84
tests/unit/Query/DefinitionTest.php
Normal file
84
tests/unit/Query/DefinitionTest.php
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Unit\Query;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Configuration, DocumentException, DocumentIndex, Mode};
|
||||||
|
use BitBadger\PDODocument\Query\Definition;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unit tests for the Definition class
|
||||||
|
*/
|
||||||
|
#[TestDox('Definition Queries (Unit tests)')]
|
||||||
|
class DefinitionTest extends TestCase
|
||||||
|
{
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = null;
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Ensure table succeeds for PosgtreSQL')]
|
||||||
|
public function testEnsureTableSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals('CREATE TABLE IF NOT EXISTS documents (data JSONB NOT NULL)',
|
||||||
|
Definition::ensureTable('documents'), 'CREATE TABLE statement not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Ensure table succeeds for SQLite')]
|
||||||
|
public function testEnsureTableSucceedsForSQLite(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
$this->assertEquals('CREATE TABLE IF NOT EXISTS dox (data TEXT NOT NULL)', Definition::ensureTable('dox'),
|
||||||
|
'CREATE TABLE statement not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testEnsureTableFailsWhenModeNotSet(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Definition::ensureTable('boom');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testEnsureIndexOnSucceedsWithoutSchemaSingleAscendingField(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals("CREATE INDEX IF NOT EXISTS idx_test_fields ON test ((data->>'details'))",
|
||||||
|
Definition::ensureIndexOn('test', 'fields', ['details']), 'CREATE INDEX statement not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testEnsureIndexOnSucceedsWithSchemaMultipleFields(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(
|
||||||
|
"CREATE INDEX IF NOT EXISTS idx_testing_json ON sch.testing ((data->>'group'), (data->>'sub_group') DESC)",
|
||||||
|
Definition::ensureIndexOn('sch.testing', 'json', ['group', 'sub_group DESC']),
|
||||||
|
'CREATE INDEX statement not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testEnsureKeySucceeds(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals("CREATE UNIQUE INDEX IF NOT EXISTS idx_tbl_key ON tbl ((data->>'id'))",
|
||||||
|
Definition::ensureKey('tbl'), 'CREATE INDEX statement for document key not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testEnsureDocumentIndexOnSucceedsForSchemaAndFull(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals("CREATE INDEX IF NOT EXISTS idx_tbl_document ON my.tbl USING GIN (data)",
|
||||||
|
Definition::ensureDocumentIndexOn('my.tbl', DocumentIndex::Full));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testEnsureDocumentIndexOnSucceedsForNoSchemaAndOptimized(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals("CREATE INDEX IF NOT EXISTS idx_it_document ON it USING GIN (data jsonb_path_ops)",
|
||||||
|
Definition::ensureDocumentIndexOn('it', DocumentIndex::Optimized));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Ensure document index on fails for non PostgreSQL')]
|
||||||
|
public function testEnsureDocumentIndexOnFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Definition::ensureDocumentIndexOn('', DocumentIndex::Full);
|
||||||
|
}
|
||||||
|
}
|
||||||
66
tests/unit/Query/DeleteTest.php
Normal file
66
tests/unit/Query/DeleteTest.php
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Unit\Query;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Configuration, DocumentException, Field, Mode};
|
||||||
|
use BitBadger\PDODocument\Query\Delete;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unit tests for the Delete class
|
||||||
|
*/
|
||||||
|
#[TestDox('Delete Queries (Unit tests)')]
|
||||||
|
class DeleteTest extends TestCase
|
||||||
|
{
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds')]
|
||||||
|
public function testByIdSucceeds(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
$this->assertEquals("DELETE FROM over_there WHERE data->>'id' = :id", Delete::byId('over_there'),
|
||||||
|
'DELETE statement not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceeds(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
$this->assertEquals("DELETE FROM my_table WHERE data->>'value' < :max AND data->>'value' >= :min",
|
||||||
|
Delete::byFields('my_table', [Field::LT('value', 99, ':max'), Field::GE('value', 18, ':min')]),
|
||||||
|
'DELETE statement not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By contains succeeds for PostgreSQL')]
|
||||||
|
public function testByContainsSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals('DELETE FROM somewhere WHERE data @> :criteria', Delete::byContains('somewhere'),
|
||||||
|
'DELETE statement not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By contains fails for non PostgreSQL')]
|
||||||
|
public function testByContainsFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Delete::byContains('');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds for PostgreSQL')]
|
||||||
|
public function testByJsonPathSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals('DELETE FROM here WHERE jsonb_path_exists(data, :path::jsonpath)',
|
||||||
|
Delete::byJsonPath('here'), 'DELETE statement not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path fails for non PostgreSQL')]
|
||||||
|
public function testByJsonPathFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Delete::byJsonPath('');
|
||||||
|
}
|
||||||
|
}
|
||||||
73
tests/unit/Query/ExistsTest.php
Normal file
73
tests/unit/Query/ExistsTest.php
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Unit\Query;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Configuration, DocumentException, Field, Mode};
|
||||||
|
use BitBadger\PDODocument\Query\Exists;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unit tests for the Exists class
|
||||||
|
*/
|
||||||
|
#[TestDox('Exists Queries (Unit tests)')]
|
||||||
|
class ExistsTest extends TestCase
|
||||||
|
{
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testQuerySucceeds(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
$this->assertEquals('SELECT EXISTS (SELECT 1 FROM abc WHERE def)', Exists::query('abc', 'def'),
|
||||||
|
'Existence query not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds')]
|
||||||
|
public function testByIdSucceeds(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
$this->assertEquals("SELECT EXISTS (SELECT 1 FROM dox WHERE data->>'id' = :id)", Exists::byId('dox'),
|
||||||
|
'Existence query not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceeds(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
$this->assertEquals("SELECT EXISTS (SELECT 1 FROM box WHERE data->>'status' <> :status)",
|
||||||
|
Exists::byFields('box', [Field::NE('status', 'occupied', ':status')]),
|
||||||
|
'Existence query not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By contains succeeds for PostgreSQL')]
|
||||||
|
public function testByContainsSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals('SELECT EXISTS (SELECT 1 FROM pocket WHERE data @> :criteria)',
|
||||||
|
Exists::byContains('pocket'), 'Existence query not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By contains fails for non PostgreSQL')]
|
||||||
|
public function testByContainsFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Exists::byContains('');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds for PostgreSQL')]
|
||||||
|
public function testByJsonPathSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals('SELECT EXISTS (SELECT 1 FROM lint WHERE jsonb_path_exists(data, :path::jsonpath))',
|
||||||
|
Exists::byJsonPath('lint'), 'Existence query not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path fails for non PostgreSQL')]
|
||||||
|
public function testByJsonPathFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Exists::byJsonPath('');
|
||||||
|
}
|
||||||
|
}
|
||||||
67
tests/unit/Query/FindTest.php
Normal file
67
tests/unit/Query/FindTest.php
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Unit\Query;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Configuration, DocumentException, Field, FieldMatch, Mode};
|
||||||
|
use BitBadger\PDODocument\Query\Find;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unit tests for the Find class
|
||||||
|
*/
|
||||||
|
#[TestDox('Find Queries (Unit tests)')]
|
||||||
|
class FindTest extends TestCase
|
||||||
|
{
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds')]
|
||||||
|
public function testByIdSucceeds(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
$this->assertEquals("SELECT data FROM here WHERE data->>'id' = :id", Find::byId('here'),
|
||||||
|
'SELECT query not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsSucceeds(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
$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')],
|
||||||
|
FieldMatch::Any),
|
||||||
|
'SELECT query not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By contains succeeds for PostgreSQL')]
|
||||||
|
public function testByContainsSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals('SELECT data FROM disc WHERE data @> :criteria', Find::byContains('disc'),
|
||||||
|
'SELECT query not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By contains fails for non PostgreSQL')]
|
||||||
|
public function testByContainsFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Find::byContains('');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds for PostgreSQL')]
|
||||||
|
public function testByJsonPathSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals('SELECT data FROM light WHERE jsonb_path_exists(data, :path::jsonpath)',
|
||||||
|
Find::byJsonPath('light'), 'SELECT query not generated correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path fails for non PostgreSQL')]
|
||||||
|
public function testByJsonPathFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Find::byJsonPath('');
|
||||||
|
}
|
||||||
|
}
|
||||||
96
tests/unit/Query/PatchTest.php
Normal file
96
tests/unit/Query/PatchTest.php
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Unit\Query;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Configuration, DocumentException, Field, Mode};
|
||||||
|
use BitBadger\PDODocument\Query\Patch;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unit tests for the Patch class
|
||||||
|
*/
|
||||||
|
#[TestDox('Patch Queries (Unit tests)')]
|
||||||
|
class PatchTest extends TestCase
|
||||||
|
{
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = null;
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
|
#[TestDox('By ID succeeds for PostgreSQL')]
|
||||||
|
public function testByIdSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals("UPDATE doc_table SET data = data || :data WHERE data->>'id' = :id",
|
||||||
|
Patch::byId('doc_table'), 'Patch UPDATE statement is not correct');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds for SQLite')]
|
||||||
|
public function testByIdSucceedsForSQLite(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
$this->assertEquals("UPDATE my_table SET data = json_patch(data, json(:data)) WHERE data->>'id' = :id",
|
||||||
|
Patch::byId('my_table'), 'Patch UPDATE statement is not correct');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID fails when mode not set')]
|
||||||
|
public function testByIdFailsWhenModeNotSet(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Patch::byId('oof');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By fields succeeds for PostgreSQL')]
|
||||||
|
public function testByFieldsSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals("UPDATE that SET data = data || :data WHERE (data->>'something')::numeric < :some",
|
||||||
|
Patch::byFields('that', [Field::LT('something', 17, ':some')]), 'Patch UPDATE statement is not correct');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By fields succeeds for SQLite')]
|
||||||
|
public function testByFieldsSucceedsForSQLite(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
$this->assertEquals(
|
||||||
|
"UPDATE a_table SET data = json_patch(data, json(:data)) WHERE data->>'something' > :it",
|
||||||
|
Patch::byFields('a_table', [Field::GT('something', 17, ':it')]), 'Patch UPDATE statement is not correct');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsFailsWhenModeNotSet(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Patch::byFields('oops', []);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By contains succeeds for PostgreSQL')]
|
||||||
|
public function testByContainsSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals('UPDATE this SET data = data || :data WHERE data @> :criteria', Patch::byContains('this'),
|
||||||
|
'Patch UPDATE statement is not correct');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By contains fails for non PostgreSQL')]
|
||||||
|
public function testByContainsFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Patch::byContains('');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds for PostgreSQL')]
|
||||||
|
public function testByJsonPathSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals('UPDATE that SET data = data || :data WHERE jsonb_path_exists(data, :path::jsonpath)',
|
||||||
|
Patch::byJsonPath('that'), 'Patch UPDATE statement is not correct');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path fails for non PostgreSQL')]
|
||||||
|
public function testByJsonPathFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Patch::byJsonPath('');
|
||||||
|
}
|
||||||
|
}
|
||||||
127
tests/unit/Query/RemoveFieldsTest.php
Normal file
127
tests/unit/Query/RemoveFieldsTest.php
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Unit\Query;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Configuration, DocumentException, Field, Mode, Parameters};
|
||||||
|
use BitBadger\PDODocument\Query\RemoveFields;
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unit tests for the RemoveFields class
|
||||||
|
*/
|
||||||
|
#[TestDox('Remove Fields Queries (Unit tests)')]
|
||||||
|
class RemoveFieldsTest extends TestCase
|
||||||
|
{
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Update succeeds for PostgreSQL')]
|
||||||
|
public function testUpdateSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = 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
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
$this->assertEquals('UPDATE burrito SET data = json_remove(data, :name0, :name1, :name2) WHERE a = b',
|
||||||
|
RemoveFields::update('burrito', Parameters::fieldNames(':name', ['one', 'two', 'ten']), 'a = b'),
|
||||||
|
'UPDATE statement not correct');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testUpdateFailsWhenModeNotSet(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
RemoveFields::update('wow', [], '');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds for PostgreSQL')]
|
||||||
|
public function testByIdSucceedsForPostgreSQL()
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals("UPDATE churro SET data = data - :bite::text[] WHERE data->>'id' = :id",
|
||||||
|
RemoveFields::byId('churro', Parameters::fieldNames(':bite', ['byte'])), 'UPDATE statement not correct');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID succeeds for SQLite')]
|
||||||
|
public function testByIdSucceedsForSQLite()
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
$this->assertEquals("UPDATE quesadilla SET data = json_remove(data, :bite0) WHERE data->>'id' = :id",
|
||||||
|
RemoveFields::byId('quesadilla', Parameters::fieldNames(':bite', ['byte'])),
|
||||||
|
'UPDATE statement not correct');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By ID fails when mode not set')]
|
||||||
|
public function testByIdFailsWhenModeNotSet(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
RemoveFields::byId('oof', []);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By fields succeeds for PostgreSQL')]
|
||||||
|
public function testByFieldsSucceedsForPostgreSQL()
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals("UPDATE enchilada SET data = data - :sauce::text[] WHERE data->>'cheese' = :queso",
|
||||||
|
RemoveFields::byFields('enchilada', [Field::EQ('cheese', 'jack', ':queso')],
|
||||||
|
Parameters::fieldNames(':sauce', ['white'])),
|
||||||
|
'UPDATE statement not correct');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By fields succeeds for SQLite')]
|
||||||
|
public function testByFieldsSucceedsForSQLite()
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
$this->assertEquals(
|
||||||
|
"UPDATE chimichanga SET data = json_remove(data, :filling0) WHERE data->>'side' = :rice",
|
||||||
|
RemoveFields::byFields('chimichanga', [Field::EQ('side', 'beans', ':rice')],
|
||||||
|
Parameters::fieldNames(':filling', ['beef'])),
|
||||||
|
'UPDATE statement not correct');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testByFieldsFailsWhenModeNotSet(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
RemoveFields::byFields('boing', [], []);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By contains succeeds for PostgreSQL')]
|
||||||
|
public function testByContainsSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals('UPDATE food SET data = data - :drink::text[] WHERE data @> :criteria',
|
||||||
|
RemoveFields::byContains('food', Parameters::fieldNames(':drink', ['a', 'b'])),
|
||||||
|
'UPDATE statement not correct');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By contains fails for non PostgreSQL')]
|
||||||
|
public function testByContainsFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
RemoveFields::byContains('', []);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path succeeds for PostgreSQL')]
|
||||||
|
public function testByJsonPathSucceedsForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
$this->assertEquals(
|
||||||
|
'UPDATE dessert SET data = data - :cake::text[] WHERE jsonb_path_exists(data, :path::jsonpath)',
|
||||||
|
RemoveFields::byJsonPath('dessert', Parameters::fieldNames(':cake', ['b', 'c'])),
|
||||||
|
'UPDATE statement not correct');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('By JSON Path fails for non PostgreSQL')]
|
||||||
|
public function testByJsonPathFailsForNonPostgreSQL(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
RemoveFields::byJsonPath('', []);
|
||||||
|
}
|
||||||
|
}
|
||||||
259
tests/unit/QueryTest.php
Normal file
259
tests/unit/QueryTest.php
Normal file
@@ -0,0 +1,259 @@
|
|||||||
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Test\Unit;
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{AutoId, Configuration, DocumentException, Field, FieldMatch, Mode, Query};
|
||||||
|
use PHPUnit\Framework\Attributes\TestDox;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unit tests for the Query class
|
||||||
|
*/
|
||||||
|
#[TestDox('Query (Unit tests)')]
|
||||||
|
class QueryTest extends TestCase
|
||||||
|
{
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testSelectFromTableSucceeds(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals('SELECT data FROM testing', Query::selectFromTable('testing'),
|
||||||
|
'Query not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testWhereByFieldsSucceedsForSingleField(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals("data->>'test_field' <= :it",
|
||||||
|
Query::whereByFields([Field::LE('test_field', '', ':it')]), 'WHERE fragment not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testWhereByFieldsSucceedsForMultipleFieldsAll(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals("data->>'test_field' <= :it AND data->>'other_field' = :other",
|
||||||
|
Query::whereByFields([Field::LE('test_field', '', ':it'), Field::EQ('other_field', '', ':other')]),
|
||||||
|
'WHERE fragment not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testWhereByFieldsSucceedsForMultipleFieldsAny(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals("data->>'test_field' <= :it OR data->>'other_field' = :other",
|
||||||
|
Query::whereByFields([Field::LE('test_field', '', ':it'), Field::EQ('other_field', '', ':other')],
|
||||||
|
FieldMatch::Any),
|
||||||
|
'WHERE fragment not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Where by ID succeeds with default parameter')]
|
||||||
|
public function testWhereByIdSucceedsWithDefaultParameter(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals("data->>'id' = :id", Query::whereById(), 'WHERE fragment not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Where by ID succeeds with specific parameter')]
|
||||||
|
public function testWhereByIdSucceedsWithSpecificParameter(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals("data->>'id' = :di", Query::whereById(':di'), 'WHERE fragment not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testWhereDataContainsSucceedsWithDefaultParameter(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
try {
|
||||||
|
$this->assertEquals('data @> :criteria', Query::whereDataContains(),
|
||||||
|
'WHERE fragment not constructed correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testWhereDataContainsSucceedsWithSpecifiedParameter(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
try {
|
||||||
|
$this->assertEquals('data @> :it', Query::whereDataContains(':it'),
|
||||||
|
'WHERE fragment not constructed correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Where data contains fails if not PostgreSQL')]
|
||||||
|
public function testWhereDataContainsFailsIfNotPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = null;
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Query::whereDataContains();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Where JSON Path matches succeeds with default parameter')]
|
||||||
|
public function testWhereJsonPathMatchesSucceedsWithDefaultParameter(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
try {
|
||||||
|
$this->assertEquals('jsonb_path_exists(data, :path::jsonpath)', Query::whereJsonPathMatches(),
|
||||||
|
'WHERE fragment not constructed correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Where JSON Path matches succeeds with specified parameter')]
|
||||||
|
public function testWhereJsonPathMatchesSucceedsWithSpecifiedParameter(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
try {
|
||||||
|
$this->assertEquals('jsonb_path_exists(data, :road::jsonpath)', Query::whereJsonPathMatches(':road'),
|
||||||
|
'WHERE fragment not constructed correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Where JSON Path matches fails if not PostgreSQL')]
|
||||||
|
public function testWhereJsonPathMatchesFailsIfNotPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = null;
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Query::whereJsonPathMatches();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds with no auto-ID for PostgreSQL')]
|
||||||
|
public function testInsertSucceedsWithNoAutoIdForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
try {
|
||||||
|
$this->assertEquals('INSERT INTO test_tbl VALUES (:data)', Query::insert('test_tbl'),
|
||||||
|
'INSERT statement not constructed correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds with no auto-ID for SQLite')]
|
||||||
|
public function testInsertSucceedsWithNoAutoIdForSQLite(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
try {
|
||||||
|
$this->assertEquals('INSERT INTO test_tbl VALUES (:data)', Query::insert('test_tbl'),
|
||||||
|
'INSERT statement not constructed correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds with auto numeric ID for PostgreSQL')]
|
||||||
|
public function testInsertSucceedsWithAutoNumericIdForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
try {
|
||||||
|
$this->assertEquals(
|
||||||
|
"INSERT INTO test_tbl VALUES (:data::jsonb || ('{\"id\":' "
|
||||||
|
. "|| (SELECT COALESCE(MAX((data->>'id')::numeric), 0) + 1 FROM test_tbl) || '}')::jsonb)",
|
||||||
|
Query::insert('test_tbl', AutoId::Number), 'INSERT statement not constructed correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds with auto numeric ID for SQLite')]
|
||||||
|
public function testInsertSucceedsWithAutoNumericIdForSQLite(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
try {
|
||||||
|
$this->assertEquals(
|
||||||
|
"INSERT INTO test_tbl VALUES (json_set(:data, '$.id', "
|
||||||
|
. "(SELECT coalesce(max(data->>'id'), 0) + 1 FROM test_tbl)))",
|
||||||
|
Query::insert('test_tbl', AutoId::Number), 'INSERT statement not constructed correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds with auto UUID for PostgreSQL')]
|
||||||
|
public function testInsertSucceedsWithAutoUuidForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
try {
|
||||||
|
$query = Query::insert('test_tbl', AutoId::UUID);
|
||||||
|
$this->assertStringStartsWith("INSERT INTO test_tbl VALUES (:data::jsonb || '{\"id\":\"", $query,
|
||||||
|
'INSERT statement not constructed correctly');
|
||||||
|
$this->assertStringEndsWith("\"}')", $query, 'INSERT statement not constructed correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds with auto UUID for SQLite')]
|
||||||
|
public function testInsertSucceedsWithAutoUuidForSQLite(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
try {
|
||||||
|
$query = Query::insert('test_tbl', AutoId::UUID);
|
||||||
|
$this->assertStringStartsWith("INSERT INTO test_tbl VALUES (json_set(:data, '$.id', '", $query,
|
||||||
|
'INSERT statement not constructed correctly');
|
||||||
|
$this->assertStringEndsWith("'))", $query, 'INSERT statement not constructed correctly');
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds with auto random string for PostgreSQL')]
|
||||||
|
public function testInsertSucceedsWithAutoRandomStringForPostgreSQL(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::PgSQL;
|
||||||
|
Configuration::$idStringLength = 8;
|
||||||
|
try {
|
||||||
|
$query = Query::insert('test_tbl', AutoId::RandomString);
|
||||||
|
$this->assertStringStartsWith("INSERT INTO test_tbl VALUES (:data::jsonb || '{\"id\":\"", $query,
|
||||||
|
'INSERT statement not constructed correctly');
|
||||||
|
$this->assertStringEndsWith("\"}')", $query, 'INSERT statement not constructed correctly');
|
||||||
|
$id = str_replace(["INSERT INTO test_tbl VALUES (:data::jsonb || '{\"id\":\"", "\"}')"], '', $query);
|
||||||
|
$this->assertEquals(8, strlen($id), "Generated ID [$id] should have been 8 characters long");
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
Configuration::$idStringLength = 16;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[TestDox('Insert succeeds with auto random string for SQLite')]
|
||||||
|
public function testInsertSucceedsWithAutoRandomStringForSQLite(): void
|
||||||
|
{
|
||||||
|
Configuration::$mode = Mode::SQLite;
|
||||||
|
try {
|
||||||
|
$query = Query::insert('test_tbl', AutoId::RandomString);
|
||||||
|
$this->assertStringStartsWith("INSERT INTO test_tbl VALUES (json_set(:data, '$.id', '", $query,
|
||||||
|
'INSERT statement not constructed correctly');
|
||||||
|
$this->assertStringEndsWith("'))", $query, 'INSERT statement not constructed correctly');
|
||||||
|
$id = str_replace(["INSERT INTO test_tbl VALUES (json_set(:data, '$.id', '", "'))"], '', $query);
|
||||||
|
$this->assertEquals(16, strlen($id), "Generated ID [$id] should have been 16 characters long");
|
||||||
|
} finally {
|
||||||
|
Configuration::$mode = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testInsertFailsWhenModeNotSet(): void
|
||||||
|
{
|
||||||
|
$this->expectException(DocumentException::class);
|
||||||
|
Configuration::$mode = null;
|
||||||
|
Query::insert('kaboom');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testSaveSucceeds(): void
|
||||||
|
{
|
||||||
|
$this->assertEquals(
|
||||||
|
"INSERT INTO test_tbl VALUES (:data) ON CONFLICT ((data->>'id')) DO UPDATE SET data = EXCLUDED.data",
|
||||||
|
Query::save('test_tbl'), 'INSERT ON CONFLICT statement not constructed correctly');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testUpdateSucceeds()
|
||||||
|
{
|
||||||
|
$this->assertEquals("UPDATE testing SET data = :data WHERE data->>'id' = :id", Query::update('testing'),
|
||||||
|
'UPDATE statement not constructed correctly');
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user