Add classes and tests from common project
This commit is contained in:
parent
e91acee70f
commit
1164dc7cc5
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
.idea
|
||||
vendor
|
22
composer.json
Normal file
22
composer.json
Normal file
@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "bit-badger/pdo-document",
|
||||
"require": {
|
||||
"netresearch/jsonmapper": "^4"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "^11"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"BitBadger\\PDODocument\\": "./src",
|
||||
"BitBadger\\PDODocument\\Mapper\\": "./src/Mapper",
|
||||
"BitBadger\\PDODocument\\Query\\": "./src/Query"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"Test\\Unit\\": "./tests/unit",
|
||||
"Test\\Integration\\": "./tests/integration"
|
||||
}
|
||||
}
|
||||
}
|
1702
composer.lock
generated
Normal file
1702
composer.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
32
src/Configuration.php
Normal file
32
src/Configuration.php
Normal file
@ -0,0 +1,32 @@
|
||||
<?php declare(strict_types=1);
|
||||
|
||||
namespace BitBadger\PDODocument;
|
||||
|
||||
/**
|
||||
* Common configuration for the document library
|
||||
*/
|
||||
class Configuration
|
||||
{
|
||||
/** @var string The name of the ID field used in the database (will be treated as the primary key) */
|
||||
private static string $_idField = 'id';
|
||||
|
||||
/**
|
||||
* Configure the ID field used by the library
|
||||
*
|
||||
* @param string $name The name of the ID field within each document
|
||||
*/
|
||||
public static function useIdField(string $name): void
|
||||
{
|
||||
self::$_idField = $name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the ID field for documents within this library
|
||||
*
|
||||
* @return string The configured ID field
|
||||
*/
|
||||
public static function idField(): string
|
||||
{
|
||||
return self::$_idField;
|
||||
}
|
||||
}
|
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";
|
||||
}
|
||||
}
|
36
src/DocumentList.php
Normal file
36
src/DocumentList.php
Normal file
@ -0,0 +1,36 @@
|
||||
<?php declare(strict_types=1);
|
||||
|
||||
namespace BitBadger\PDODocument;
|
||||
|
||||
use Generator;
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
interface DocumentList
|
||||
{
|
||||
/**
|
||||
* The items from the query result
|
||||
*
|
||||
* @return Generator<TDoc> The query results as a lazily-iterated generator
|
||||
*/
|
||||
public function items(): Generator;
|
||||
|
||||
/**
|
||||
* Construct a new document list
|
||||
*
|
||||
* @param string $query The query to run to retrieve results
|
||||
* @param array $parameters An associative array of parameters for the query
|
||||
* @param Mapper<TDoc> $mapper A mapper to deserialize JSON documents
|
||||
* @return static The `DocumentList`-implementing instance
|
||||
*/
|
||||
public static function create(string $query, array $parameters, Mapper $mapper): static;
|
||||
|
||||
/**
|
||||
* Clean up database connection resources
|
||||
*/
|
||||
public function __destruct();
|
||||
}
|
176
src/Field.php
Normal file
176
src/Field.php
Normal file
@ -0,0 +1,176 @@
|
||||
<?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
|
||||
*/
|
||||
public function toWhere(): string
|
||||
{
|
||||
$criteria = match ($this->op) {
|
||||
Op::EX, Op::NEX => '',
|
||||
Op::BT => " {$this->paramName}min AND {$this->paramName}max",
|
||||
default => " $this->paramName"
|
||||
};
|
||||
$prefix = $this->qualifier == '' ? '' : "$this->qualifier.";
|
||||
return "{$prefix}data->>'$this->fieldName' " . $this->op->toString() . $criteria;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an equals (=) field criterion
|
||||
*
|
||||
* @param string $fieldName The name of the field against which the value will be compared
|
||||
* @param mixed $value The value for which equality will be checked
|
||||
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||
* @return static The field with the requested criterion
|
||||
*/
|
||||
public static function EQ(string $fieldName, mixed $value, string $paramName = ''): static
|
||||
{
|
||||
return new static($fieldName, Op::EQ, $value, $paramName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a greater than (>) field criterion
|
||||
*
|
||||
* @param string $fieldName The name of the field against which the value will be compared
|
||||
* @param mixed $value The value for the greater than comparison
|
||||
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||
* @return static The field with the requested criterion
|
||||
*/
|
||||
public static function GT(string $fieldName, mixed $value, string $paramName = ''): static
|
||||
{
|
||||
return new static($fieldName, Op::GT, $value, $paramName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a greater than or equal to (>=) field criterion
|
||||
*
|
||||
* @param string $fieldName The name of the field against which the value will be compared
|
||||
* @param mixed $value The value for the greater than or equal to comparison
|
||||
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||
* @return static The field with the requested criterion
|
||||
*/
|
||||
public static function GE(string $fieldName, mixed $value, string $paramName = ''): static
|
||||
{
|
||||
return new static($fieldName, Op::GE, $value, $paramName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a less than (<) field criterion
|
||||
*
|
||||
* @param string $fieldName The name of the field against which the value will be compared
|
||||
* @param mixed $value The value for the less than comparison
|
||||
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||
* @return static The field with the requested criterion
|
||||
*/
|
||||
public static function LT(string $fieldName, mixed $value, string $paramName = ''): static
|
||||
{
|
||||
return new static($fieldName, Op::LT, $value, $paramName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a less than or equal to (<=) field criterion
|
||||
*
|
||||
* @param string $fieldName The name of the field against which the value will be compared
|
||||
* @param mixed $value The value for the less than or equal to comparison
|
||||
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||
* @return static The field with the requested criterion
|
||||
*/
|
||||
public static function LE(string $fieldName, mixed $value, string $paramName = ''): static
|
||||
{
|
||||
return new static($fieldName, Op::LE, $value, $paramName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a not equals (<>) field criterion
|
||||
*
|
||||
* @param string $fieldName The name of the field against which the value will be compared
|
||||
* @param mixed $value The value for the not equals comparison
|
||||
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||
* @return static The field with the requested criterion
|
||||
*/
|
||||
public static function NE(string $fieldName, mixed $value, string $paramName = ''): static
|
||||
{
|
||||
return new static($fieldName, Op::NE, $value, $paramName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a BETWEEN field criterion
|
||||
*
|
||||
* @param string $fieldName The name of the field against which the value will be compared
|
||||
* @param mixed $minValue The lower value for range
|
||||
* @param mixed $maxValue The upper value for the range
|
||||
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
|
||||
* @return static The field with the requested criterion
|
||||
*/
|
||||
public static function BT(string $fieldName, mixed $minValue, mixed $maxValue, string $paramName = ''): static
|
||||
{
|
||||
return new static($fieldName, Op::BT, [$minValue, $maxValue], $paramName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an exists (IS NOT NULL) field criterion
|
||||
*
|
||||
* @param string $fieldName The name of the field for which existence will be checked
|
||||
* @return static The field with the requested criterion
|
||||
*/
|
||||
public static function EX(string $fieldName): static
|
||||
{
|
||||
return new static($fieldName, Op::EX, '', '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a not exists (IS NULL) field criterion
|
||||
*
|
||||
* @param string $fieldName The name of the field for which non-existence will be checked
|
||||
* @return static The field with the requested criterion
|
||||
*/
|
||||
public static function NEX(string $fieldName): static
|
||||
{
|
||||
return new static($fieldName, Op::NEX, '', '');
|
||||
}
|
||||
}
|
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;
|
||||
}
|
||||
}
|
43
src/Mapper/JsonMapper.php
Normal file
43
src/Mapper/JsonMapper.php
Normal file
@ -0,0 +1,43 @@
|
||||
<?php declare(strict_types=1);
|
||||
|
||||
namespace BitBadger\PDODocument\Mapper;
|
||||
|
||||
use BitBadger\PDODocument\DocumentException;
|
||||
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 JsonMapper 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);
|
||||
}
|
||||
}
|
||||
}
|
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 given
|
||||
*
|
||||
* @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]
|
||||
};
|
||||
}
|
||||
}
|
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"
|
||||
};
|
||||
}
|
||||
}
|
77
src/Query.php
Normal file
77
src/Query.php
Normal file
@ -0,0 +1,77 @@
|
||||
<?php declare(strict_types=1);
|
||||
|
||||
namespace BitBadger\PDODocument;
|
||||
|
||||
/**
|
||||
* 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 string $conjunction How to join multiple conditions (optional; defaults to AND)
|
||||
* @return string The WHERE clause fragment matching the given fields and parameter
|
||||
*/
|
||||
public static function whereByFields(array $fields, string $conjunction = 'AND'): string
|
||||
{
|
||||
return implode(" $conjunction ", 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)
|
||||
* @return string The WHERE clause fragment to match by ID
|
||||
*/
|
||||
public static function whereById(string $paramName = '@id'): string
|
||||
{
|
||||
return self::whereByFields([Field::EQ(Configuration::idField(), 0, $paramName)]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Query to insert a document
|
||||
*
|
||||
* @param string $tableName The name of the table into which a document should be inserted
|
||||
* @return string The INSERT statement for the given table
|
||||
*/
|
||||
public static function insert(string $tableName): string
|
||||
{
|
||||
return "INSERT INTO $tableName VALUES (@data)";
|
||||
}
|
||||
|
||||
/**
|
||||
* Query to save a document, inserting it if it does not exist and updating it if it does (AKA "upsert")
|
||||
*
|
||||
* @param string $tableName The name of the table into which a document should be saved
|
||||
* @return string The INSERT...ON CONFLICT query for the document
|
||||
*/
|
||||
public static function save(string $tableName): string
|
||||
{
|
||||
return self::insert($tableName)
|
||||
. " ON CONFLICT ((data->>'" . Configuration::idField() . "')) DO UPDATE SET data = EXCLUDED.data";
|
||||
}
|
||||
|
||||
/**
|
||||
* Query to update a document
|
||||
*
|
||||
* @param string $tableName The name of the table in which the document should be updated
|
||||
* @return string The UPDATE query for the document
|
||||
*/
|
||||
public static function update(string $tableName): string
|
||||
{
|
||||
return "UPDATE $tableName SET data = @data WHERE " . self::whereById();
|
||||
}
|
||||
}
|
36
src/Query/Count.php
Normal file
36
src/Query/Count.php
Normal file
@ -0,0 +1,36 @@
|
||||
<?php declare(strict_types=1);
|
||||
|
||||
namespace BitBadger\PDODocument\Query;
|
||||
|
||||
use BitBadger\PDODocument\Field;
|
||||
use BitBadger\PDODocument\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 string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
|
||||
* @return string The query to count documents using a field comparison
|
||||
*/
|
||||
public static function byFields(string $tableName, array $fields, string $conjunction = 'AND'): string
|
||||
{
|
||||
return self::all($tableName) . ' WHERE ' . Query::whereByFields($fields, $conjunction);
|
||||
}
|
||||
}
|
66
src/Query/Definition.php
Normal file
66
src/Query/Definition.php
Normal file
@ -0,0 +1,66 @@
|
||||
<?php declare(strict_types=1);
|
||||
|
||||
namespace BitBadger\PDODocument\Query;
|
||||
|
||||
use BitBadger\PDODocument\Configuration;
|
||||
|
||||
/**
|
||||
* 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)
|
||||
* @param string $dataType The data type used for the document column
|
||||
* @return string The CREATE TABLE statement for the document table
|
||||
*/
|
||||
public static function ensureTableFor(string $name, string $dataType): string
|
||||
{
|
||||
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()]));
|
||||
}
|
||||
}
|
36
src/Query/Delete.php
Normal file
36
src/Query/Delete.php
Normal file
@ -0,0 +1,36 @@
|
||||
<?php declare(strict_types=1);
|
||||
|
||||
namespace BitBadger\PDODocument\Query;
|
||||
|
||||
use BitBadger\PDODocument\Field;
|
||||
use BitBadger\PDODocument\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
|
||||
* @return string The DELETE statement to delete a document by its ID
|
||||
*/
|
||||
public static function byId(string $tableName): string
|
||||
{
|
||||
return "DELETE FROM $tableName WHERE " . Query::whereById();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
|
||||
* @return string The DELETE statement to delete documents via field comparison
|
||||
*/
|
||||
public static function byFields(string $tableName, array $fields, string $conjunction = 'AND'): string
|
||||
{
|
||||
return "DELETE FROM $tableName WHERE " . Query::whereByFields($fields, $conjunction);
|
||||
}
|
||||
}
|
48
src/Query/Exists.php
Normal file
48
src/Query/Exists.php
Normal file
@ -0,0 +1,48 @@
|
||||
<?php declare(strict_types=1);
|
||||
|
||||
namespace BitBadger\PDODocument\Query;
|
||||
|
||||
use BitBadger\PDODocument\Field;
|
||||
use BitBadger\PDODocument\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
|
||||
* @return string The query to determine document existence by ID
|
||||
*/
|
||||
public static function byId(string $tableName): string
|
||||
{
|
||||
return self::query($tableName, Query::whereById());
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
|
||||
* @return string The query to determine document existence by field comparison
|
||||
*/
|
||||
public static function byFields(string $tableName, array $fields, string $conjunction = 'AND'): string
|
||||
{
|
||||
return self::query($tableName, Query::whereByFields($fields, $conjunction));
|
||||
}
|
||||
}
|
36
src/Query/Find.php
Normal file
36
src/Query/Find.php
Normal file
@ -0,0 +1,36 @@
|
||||
<?php declare(strict_types=1);
|
||||
|
||||
namespace BitBadger\PDODocument\Query;
|
||||
|
||||
use BitBadger\PDODocument\Field;
|
||||
use BitBadger\PDODocument\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
|
||||
* @return string The SELECT statement to retrieve a document by its ID
|
||||
*/
|
||||
public static function byId(string $tableName): string
|
||||
{
|
||||
return Query::selectFromTable($tableName) . ' WHERE ' . Query::whereById();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
|
||||
* @return string The SELECT statement to retrieve documents by field comparison
|
||||
*/
|
||||
public static function byFields(string $tableName, array $fields, string $conjunction = 'AND'): string
|
||||
{
|
||||
return Query::selectFromTable($tableName) . ' WHERE ' . Query::whereByFields($fields, $conjunction);
|
||||
}
|
||||
}
|
0
tests/integration/.gitkeep
Normal file
0
tests/integration/.gitkeep
Normal file
28
tests/unit/ConfigurationTest.php
Normal file
28
tests/unit/ConfigurationTest.php
Normal file
@ -0,0 +1,28 @@
|
||||
<?php declare(strict_types=1);
|
||||
|
||||
namespace Test\Unit;
|
||||
|
||||
use BitBadger\PDODocument\Configuration;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* Unit tests for the Configuration class
|
||||
*/
|
||||
class ConfigurationTest extends TestCase
|
||||
{
|
||||
public function testIdFieldDefaultSucceeds(): void
|
||||
{
|
||||
$this->assertEquals('id', Configuration::idField(), 'Default ID field should be "id"');
|
||||
}
|
||||
|
||||
public function testUseIdFieldSucceeds()
|
||||
{
|
||||
try {
|
||||
Configuration::useIdField('EyeDee');
|
||||
$this->assertEquals('EyeDee', Configuration::idField(), 'ID field should have been updated');
|
||||
} finally {
|
||||
Configuration::useIdField('id');
|
||||
$this->assertEquals('id', Configuration::idField(), 'Default ID value should have been restored');
|
||||
}
|
||||
}
|
||||
}
|
46
tests/unit/DocumentExceptionTest.php
Normal file
46
tests/unit/DocumentExceptionTest.php
Normal file
@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace Test\Unit;
|
||||
|
||||
use BitBadger\PDODocument\DocumentException;
|
||||
use Exception;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* Unit tests for the DocumentException class
|
||||
*/
|
||||
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');
|
||||
}
|
||||
}
|
257
tests/unit/FieldTest.php
Normal file
257
tests/unit/FieldTest.php
Normal file
@ -0,0 +1,257 @@
|
||||
<?php declare(strict_types=1);
|
||||
|
||||
namespace Test\Unit;
|
||||
|
||||
use BitBadger\PDODocument\Field;
|
||||
use BitBadger\PDODocument\Op;
|
||||
use PHPUnit\Framework\Attributes\TestDox;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* Unit tests for the Field class
|
||||
*/
|
||||
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')]
|
||||
public function testToWhereSucceedsForEXWithoutQualifier(): void
|
||||
{
|
||||
$this->assertEquals("data->>'that_field' IS NOT NULL", Field::EX('that_field')->toWhere(),
|
||||
'WHERE fragment not generated correctly');
|
||||
}
|
||||
|
||||
#[TestDox('To where succeeds for NEX without qualifier')]
|
||||
public function testToWhereSucceedsForNEXWithoutQualifier(): void
|
||||
{
|
||||
$this->assertEquals("data->>'a_field' IS NULL", Field::NEX('a_field')->toWhere(),
|
||||
'WHERE fragment not generated correctly');
|
||||
}
|
||||
|
||||
#[TestDox('To where succeeds for BT without qualifier')]
|
||||
public function testToWhereSucceedsForBTWithoutQualifier(): void
|
||||
{
|
||||
$this->assertEquals("data->>'age' BETWEEN @agemin AND @agemax", Field::BT('age', 13, 17, '@age')->toWhere(),
|
||||
'WHERE fragment not generated correctly');
|
||||
}
|
||||
|
||||
public function testToWhereSucceedsForOthersWithoutQualifier(): void
|
||||
{
|
||||
$this->assertEquals("data->>'some_field' = @value", Field::EQ('some_field', '', '@value')->toWhere(),
|
||||
'WHERE fragment not generated correctly');
|
||||
}
|
||||
|
||||
public function testToWhereSucceedsWithQualifierNoParameter(): void
|
||||
{
|
||||
$field = Field::EX('no_field');
|
||||
$field->qualifier = 'test';
|
||||
$this->assertEquals("test.data->>'no_field' IS NOT NULL", $field->toWhere(),
|
||||
'WHERE fragment not generated correctly');
|
||||
}
|
||||
|
||||
public function testToWhereSucceedsWithQualifierAndParameter(): void
|
||||
{
|
||||
$field = Field::LE('le_field', 18, '@it');
|
||||
$field->qualifier = 'q';
|
||||
$this->assertEquals("q.data->>'le_field' <= @it", $field->toWhere(), 'WHERE fragment not generated correctly');
|
||||
}
|
||||
|
||||
#[TestDox('EQ succeeds without parameter')]
|
||||
public function testEQSucceedsWithoutParameter(): void
|
||||
{
|
||||
$field = Field::EQ('my_test', 9);
|
||||
$this->assertNotNull($field, 'The field should not have been null');
|
||||
$this->assertEquals('my_test', $field->fieldName, 'Field name not filled correctly');
|
||||
$this->assertEquals(Op::EQ, $field->op, 'Operation not filled correctly');
|
||||
$this->assertEquals(9, $field->value, 'Value not filled correctly');
|
||||
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||
}
|
||||
|
||||
#[TestDox('EQ succeeds with parameter')]
|
||||
public function testEQSucceedsWithParameter(): void
|
||||
{
|
||||
$field = Field::EQ('another_test', 'turkey', '@test');
|
||||
$this->assertNotNull($field, 'The field should not have been null');
|
||||
$this->assertEquals('another_test', $field->fieldName, 'Field name not filled correctly');
|
||||
$this->assertEquals(Op::EQ, $field->op, 'Operation not filled correctly');
|
||||
$this->assertEquals('turkey', $field->value, 'Value not filled correctly');
|
||||
$this->assertEquals('@test', $field->paramName, 'Parameter name not filled correctly');
|
||||
}
|
||||
|
||||
#[TestDox('GT succeeds without parameter')]
|
||||
public function testGTSucceedsWithoutParameter(): void
|
||||
{
|
||||
$field = Field::GT('your_test', 4);
|
||||
$this->assertNotNull($field, 'The field should not have been null');
|
||||
$this->assertEquals('your_test', $field->fieldName, 'Field name not filled correctly');
|
||||
$this->assertEquals(Op::GT, $field->op, 'Operation not filled correctly');
|
||||
$this->assertEquals(4, $field->value, 'Value not filled correctly');
|
||||
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||
}
|
||||
|
||||
#[TestDox('GT succeeds with parameter')]
|
||||
public function testGTSucceedsWithParameter(): void
|
||||
{
|
||||
$field = Field::GT('more_test', 'chicken', '@value');
|
||||
$this->assertNotNull($field, 'The field should not have been null');
|
||||
$this->assertEquals('more_test', $field->fieldName, 'Field name not filled correctly');
|
||||
$this->assertEquals(Op::GT, $field->op, 'Operation not filled correctly');
|
||||
$this->assertEquals('chicken', $field->value, 'Value not filled correctly');
|
||||
$this->assertEquals('@value', $field->paramName, 'Parameter name not filled correctly');
|
||||
}
|
||||
|
||||
#[TestDox('GE succeeds without parameter')]
|
||||
public function testGESucceedsWithoutParameter(): void
|
||||
{
|
||||
$field = Field::GE('their_test', 6);
|
||||
$this->assertNotNull($field, 'The field should not have been null');
|
||||
$this->assertEquals('their_test', $field->fieldName, 'Field name not filled correctly');
|
||||
$this->assertEquals(Op::GE, $field->op, 'Operation not filled correctly');
|
||||
$this->assertEquals(6, $field->value, 'Value not filled correctly');
|
||||
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||
}
|
||||
|
||||
#[TestDox('GE succeeds with parameter')]
|
||||
public function testGESucceedsWithParameter(): void
|
||||
{
|
||||
$field = Field::GE('greater_test', 'poultry', '@cluck');
|
||||
$this->assertNotNull($field, 'The field should not have been null');
|
||||
$this->assertEquals('greater_test', $field->fieldName, 'Field name not filled correctly');
|
||||
$this->assertEquals(Op::GE, $field->op, 'Operation not filled correctly');
|
||||
$this->assertEquals('poultry', $field->value, 'Value not filled correctly');
|
||||
$this->assertEquals('@cluck', $field->paramName, 'Parameter name not filled correctly');
|
||||
}
|
||||
|
||||
#[TestDox('LT succeeds without parameter')]
|
||||
public function testLTSucceedsWithoutParameter(): void
|
||||
{
|
||||
$field = Field::LT('z', 32);
|
||||
$this->assertNotNull($field, 'The field should not have been null');
|
||||
$this->assertEquals('z', $field->fieldName, 'Field name not filled correctly');
|
||||
$this->assertEquals(Op::LT, $field->op, 'Operation not filled correctly');
|
||||
$this->assertEquals(32, $field->value, 'Value not filled correctly');
|
||||
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||
}
|
||||
|
||||
#[TestDox('LT succeeds with parameter')]
|
||||
public function testLTSucceedsWithParameter(): void
|
||||
{
|
||||
$field = Field::LT('additional_test', 'fowl', '@boo');
|
||||
$this->assertNotNull($field, 'The field should not have been null');
|
||||
$this->assertEquals('additional_test', $field->fieldName, 'Field name not filled correctly');
|
||||
$this->assertEquals(Op::LT, $field->op, 'Operation not filled correctly');
|
||||
$this->assertEquals('fowl', $field->value, 'Value not filled correctly');
|
||||
$this->assertEquals('@boo', $field->paramName, 'Parameter name not filled correctly');
|
||||
}
|
||||
|
||||
#[TestDox('LE succeeds without parameter')]
|
||||
public function testLESucceedsWithoutParameter(): void
|
||||
{
|
||||
$field = Field::LE('g', 87);
|
||||
$this->assertNotNull($field, 'The field should not have been null');
|
||||
$this->assertEquals('g', $field->fieldName, 'Field name not filled correctly');
|
||||
$this->assertEquals(Op::LE, $field->op, 'Operation not filled correctly');
|
||||
$this->assertEquals(87, $field->value, 'Value not filled correctly');
|
||||
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||
}
|
||||
|
||||
#[TestDox('LE succeeds with parameter')]
|
||||
public function testLESucceedsWithParameter(): void
|
||||
{
|
||||
$field = Field::LE('lesser_test', 'hen', '@woo');
|
||||
$this->assertNotNull($field, 'The field should not have been null');
|
||||
$this->assertEquals('lesser_test', $field->fieldName, 'Field name not filled correctly');
|
||||
$this->assertEquals(Op::LE, $field->op, 'Operation not filled correctly');
|
||||
$this->assertEquals('hen', $field->value, 'Value not filled correctly');
|
||||
$this->assertEquals('@woo', $field->paramName, 'Parameter name not filled correctly');
|
||||
}
|
||||
|
||||
#[TestDox('NE succeeds without parameter')]
|
||||
public function testNESucceedsWithoutParameter(): void
|
||||
{
|
||||
$field = Field::NE('j', 65);
|
||||
$this->assertNotNull($field, 'The field should not have been null');
|
||||
$this->assertEquals('j', $field->fieldName, 'Field name not filled correctly');
|
||||
$this->assertEquals(Op::NE, $field->op, 'Operation not filled correctly');
|
||||
$this->assertEquals(65, $field->value, 'Value not filled correctly');
|
||||
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||
}
|
||||
|
||||
#[TestDox('NE succeeds with parameter')]
|
||||
public function testNESucceedsWithParameter(): void
|
||||
{
|
||||
$field = Field::NE('unequal_test', 'egg', '@zoo');
|
||||
$this->assertNotNull($field, 'The field should not have been null');
|
||||
$this->assertEquals('unequal_test', $field->fieldName, 'Field name not filled correctly');
|
||||
$this->assertEquals(Op::NE, $field->op, 'Operation not filled correctly');
|
||||
$this->assertEquals('egg', $field->value, 'Value not filled correctly');
|
||||
$this->assertEquals('@zoo', $field->paramName, 'Parameter name not filled correctly');
|
||||
}
|
||||
|
||||
#[TestDox('BT succeeds without parameter')]
|
||||
public function testBTSucceedsWithoutParameter(): void
|
||||
{
|
||||
$field = Field::BT('k', 'alpha', 'zed');
|
||||
$this->assertNotNull($field, 'The field should not have been null');
|
||||
$this->assertEquals('k', $field->fieldName, 'Field name not filled correctly');
|
||||
$this->assertEquals(Op::BT, $field->op, 'Operation not filled correctly');
|
||||
$this->assertEquals(['alpha', 'zed'], $field->value, 'Value not filled correctly');
|
||||
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||
}
|
||||
|
||||
#[TestDox('BT succeeds with parameter')]
|
||||
public function testBTSucceedsWithParameter(): void
|
||||
{
|
||||
$field = Field::BT('between_test', 18, 49, '@count');
|
||||
$this->assertNotNull($field, 'The field should not have been null');
|
||||
$this->assertEquals('between_test', $field->fieldName, 'Field name not filled correctly');
|
||||
$this->assertEquals(Op::BT, $field->op, 'Operation not filled correctly');
|
||||
$this->assertEquals([18, 49], $field->value, 'Value not filled correctly');
|
||||
$this->assertEquals('@count', $field->paramName, 'Parameter name not filled correctly');
|
||||
}
|
||||
|
||||
#[TestDox('EX succeeds')]
|
||||
public function testEXSucceeds(): void
|
||||
{
|
||||
$field = Field::EX('be_there');
|
||||
$this->assertNotNull($field, 'The field should not have been null');
|
||||
$this->assertEquals('be_there', $field->fieldName, 'Field name not filled correctly');
|
||||
$this->assertEquals(Op::EX, $field->op, 'Operation not filled correctly');
|
||||
$this->assertEquals('', $field->value, 'Value should have been blank');
|
||||
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||
}
|
||||
|
||||
#[TestDox('NEX succeeds')]
|
||||
public function testNEXSucceeds(): void
|
||||
{
|
||||
$field = Field::NEX('be_absent');
|
||||
$this->assertNotNull($field, 'The field should not have been null');
|
||||
$this->assertEquals('be_absent', $field->fieldName, 'Field name not filled correctly');
|
||||
$this->assertEquals(Op::NEX, $field->op, 'Operation not filled correctly');
|
||||
$this->assertEquals('', $field->value, 'Value should have been blank');
|
||||
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
|
||||
}
|
||||
}
|
19
tests/unit/Mapper/ArrayMapperTest.php
Normal file
19
tests/unit/Mapper/ArrayMapperTest.php
Normal file
@ -0,0 +1,19 @@
|
||||
<?php declare(strict_types=1);
|
||||
|
||||
namespace Test\Unit\Mapper;
|
||||
|
||||
use BitBadger\PDODocument\Mapper\ArrayMapper;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* Unit tests for the ArrayMapper class
|
||||
*/
|
||||
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');
|
||||
}
|
||||
}
|
57
tests/unit/Mapper/JsonMapperTest.php
Normal file
57
tests/unit/Mapper/JsonMapperTest.php
Normal file
@ -0,0 +1,57 @@
|
||||
<?php declare(strict_types=1);
|
||||
|
||||
namespace Test\Unit\Mapper;
|
||||
|
||||
use BitBadger\PDODocument\DocumentException;
|
||||
use BitBadger\PDODocument\Field;
|
||||
use BitBadger\PDODocument\Mapper\JsonMapper;
|
||||
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 JsonMapper class
|
||||
*/
|
||||
class JsonMapperTest extends TestCase
|
||||
{
|
||||
public function testConstructorSucceedsWithDefaultField(): void
|
||||
{
|
||||
$mapper = new JsonMapper(Field::class);
|
||||
$this->assertEquals('data', $mapper->fieldName, 'Default field name should have been "data"');
|
||||
}
|
||||
|
||||
public function testConstructorSucceedsWithSpecifiedField(): void
|
||||
{
|
||||
$mapper = new JsonMapper(Field::class, 'json');
|
||||
$this->assertEquals('json', $mapper->fieldName, 'Field name not recorded correctly');
|
||||
}
|
||||
|
||||
#[TestDox('Map succeeds with valid JSON')]
|
||||
public function testMapSucceedsWithValidJSON(): void
|
||||
{
|
||||
$doc = (new JsonMapper(TestDocument::class))->map(['data' => '{"id":7,"subDoc":{"id":22,"name":"tester"}}']);
|
||||
$this->assertNotNull($doc, 'The document should not have been null');
|
||||
$this->assertEquals(7, $doc->id, 'ID not filled correctly');
|
||||
$this->assertNotNull($doc->subDoc, 'The sub-document should not have been null');
|
||||
$this->assertEquals(22, $doc->subDoc->id, 'Sub-document ID not filled correctly');
|
||||
$this->assertEquals('tester', $doc->subDoc->name, 'Sub-document name not filled correctly');
|
||||
}
|
||||
|
||||
#[TestDox('Map fails with invalid JSON')]
|
||||
public function testMapFailsWithInvalidJSON(): void
|
||||
{
|
||||
$this->expectException(DocumentException::class);
|
||||
(new JsonMapper(TestDocument::class))->map(['data' => 'this is not valid']);
|
||||
}
|
||||
}
|
29
tests/unit/Mapper/StringMapperTest.php
Normal file
29
tests/unit/Mapper/StringMapperTest.php
Normal file
@ -0,0 +1,29 @@
|
||||
<?php declare(strict_types=1);
|
||||
|
||||
namespace Test\Unit\Mapper;
|
||||
|
||||
use BitBadger\PDODocument\Mapper\StringMapper;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
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');
|
||||
}
|
||||
}
|
67
tests/unit/OpTest.php
Normal file
67
tests/unit/OpTest.php
Normal file
@ -0,0 +1,67 @@
|
||||
<?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
|
||||
*/
|
||||
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');
|
||||
}
|
||||
}
|
26
tests/unit/Query/CountTest.php
Normal file
26
tests/unit/Query/CountTest.php
Normal file
@ -0,0 +1,26 @@
|
||||
<?php declare(strict_types=1);
|
||||
|
||||
namespace Test\Unit\Query;
|
||||
|
||||
use BitBadger\PDODocument\Field;
|
||||
use BitBadger\PDODocument\Query\Count;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* Unit tests for the Count class
|
||||
*/
|
||||
class CountTest extends TestCase
|
||||
{
|
||||
|
||||
public function testAllSucceeds()
|
||||
{
|
||||
$this->assertEquals('SELECT COUNT(*) FROM a_table', Count::all('a_table'),
|
||||
'SELECT statement not generated correctly');
|
||||
}
|
||||
|
||||
public function testByFieldsSucceeds()
|
||||
{
|
||||
$this->assertEquals("SELECT COUNT(*) FROM somewhere WHERE data->>'errors' > @errors",
|
||||
Count::byFields('somewhere', [Field::GT('errors', 10, '@errors')]));
|
||||
}
|
||||
}
|
38
tests/unit/Query/DefinitionTest.php
Normal file
38
tests/unit/Query/DefinitionTest.php
Normal file
@ -0,0 +1,38 @@
|
||||
<?php declare(strict_types=1);
|
||||
|
||||
namespace Test\Unit\Query;
|
||||
|
||||
use BitBadger\PDODocument\Query\Definition;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* Unit tests for the Definition class
|
||||
*/
|
||||
class DefinitionTest extends TestCase
|
||||
{
|
||||
public function testEnsureTableForSucceeds(): void
|
||||
{
|
||||
$this->assertEquals('CREATE TABLE IF NOT EXISTS documents (data JSON NOT NULL)',
|
||||
Definition::ensureTableFor('documents', 'JSON'), 'CREATE TABLE statement not generated correctly');
|
||||
}
|
||||
|
||||
public function testEnsureIndexOnSucceedsWithoutSchemaSingleAscendingField(): void
|
||||
{
|
||||
$this->assertEquals("CREATE INDEX IF NOT EXISTS idx_test_fields ON test ((data->>'details'))",
|
||||
Definition::ensureIndexOn('test', 'fields', ['details']), 'CREATE INDEX statement not generated correctly');
|
||||
}
|
||||
|
||||
public function testEnsureIndexOnSucceedsWithSchemaMultipleFields(): void
|
||||
{
|
||||
$this->assertEquals(
|
||||
"CREATE INDEX IF NOT EXISTS idx_testing_json ON sch.testing ((data->>'group'), (data->>'sub_group') DESC)",
|
||||
Definition::ensureIndexOn('sch.testing', 'json', ['group', 'sub_group DESC']),
|
||||
'CREATE INDEX statement not generated correctly');
|
||||
}
|
||||
|
||||
public function testEnsureKey(): void
|
||||
{
|
||||
$this->assertEquals("CREATE UNIQUE INDEX IF NOT EXISTS idx_tbl_key ON tbl ((data->>'id'))",
|
||||
Definition::ensureKey('tbl'), 'CREATE INDEX statement for document key not generated correctly');
|
||||
}
|
||||
}
|
26
tests/unit/Query/DeleteTest.php
Normal file
26
tests/unit/Query/DeleteTest.php
Normal file
@ -0,0 +1,26 @@
|
||||
<?php declare(strict_types=1);
|
||||
|
||||
namespace Test\Unit\Query;
|
||||
|
||||
use BitBadger\PDODocument\Field;
|
||||
use BitBadger\PDODocument\Query\Delete;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* Unit tests for the Delete class
|
||||
*/
|
||||
class DeleteTest extends TestCase
|
||||
{
|
||||
public function testByIdSucceeds(): void
|
||||
{
|
||||
$this->assertEquals("DELETE FROM over_there WHERE data->>'id' = @id", Delete::byId('over_there'),
|
||||
'DELETE statement not constructed correctly');
|
||||
}
|
||||
|
||||
public function testByFieldsSucceeds(): void
|
||||
{
|
||||
$this->assertEquals("DELETE FROM my_table WHERE data->>'value' < @max AND data->>'value' >= @min",
|
||||
Delete::byFields('my_table', [Field::LT('value', 99, '@max'), Field::GE('value', 18, '@min')]),
|
||||
'DELETE statement not constructed correctly');
|
||||
}
|
||||
}
|
32
tests/unit/Query/ExistsTest.php
Normal file
32
tests/unit/Query/ExistsTest.php
Normal file
@ -0,0 +1,32 @@
|
||||
<?php declare(strict_types=1);
|
||||
|
||||
namespace Test\Unit\Query;
|
||||
|
||||
use BitBadger\PDODocument\Field;
|
||||
use BitBadger\PDODocument\Query\Exists;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* Unit tests for the Exists class
|
||||
*/
|
||||
class ExistsTest extends TestCase
|
||||
{
|
||||
public function testQuerySucceeds(): void
|
||||
{
|
||||
$this->assertEquals('SELECT EXISTS (SELECT 1 FROM abc WHERE def)', Exists::query('abc', 'def'),
|
||||
'Existence query not generated correctly');
|
||||
}
|
||||
|
||||
public function testByIdSucceeds(): void
|
||||
{
|
||||
$this->assertEquals("SELECT EXISTS (SELECT 1 FROM dox WHERE data->>'id' = @id)", Exists::byId('dox'),
|
||||
'Existence query not generated correctly');
|
||||
}
|
||||
|
||||
public function testByFieldsSucceeds(): void
|
||||
{
|
||||
$this->assertEquals("SELECT EXISTS (SELECT 1 FROM box WHERE data->>'status' <> @status)",
|
||||
Exists::byFields('box', [Field::NE('status', 'occupied', '@status')]),
|
||||
'Existence query not generated correctly');
|
||||
}
|
||||
}
|
26
tests/unit/Query/FindTest.php
Normal file
26
tests/unit/Query/FindTest.php
Normal file
@ -0,0 +1,26 @@
|
||||
<?php declare(strict_types=1);
|
||||
|
||||
namespace Test\Unit\Query;
|
||||
|
||||
use BitBadger\PDODocument\Field;
|
||||
use BitBadger\PDODocument\Query\Find;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* Unit tests for the Find class
|
||||
*/
|
||||
class FindTest extends TestCase
|
||||
{
|
||||
public function testByIdSucceeds(): void
|
||||
{
|
||||
$this->assertEquals("SELECT data FROM here WHERE data->>'id' = @id", Find::byId('here'),
|
||||
'SELECT query not generated correctly');
|
||||
}
|
||||
|
||||
public function testByFieldsSucceeds(): void
|
||||
{
|
||||
$this->assertEquals("SELECT data FROM there WHERE data->>'active' = @act OR data->>'locked' = @lock",
|
||||
Find::byFields('there', [Field::EQ('active', true, '@act'), Field::EQ('locked', true, '@lock')], 'OR'),
|
||||
'SELECT query not generated correctly');
|
||||
}
|
||||
}
|
68
tests/unit/QueryTest.php
Normal file
68
tests/unit/QueryTest.php
Normal file
@ -0,0 +1,68 @@
|
||||
<?php declare(strict_types=1);
|
||||
|
||||
namespace Test\Unit;
|
||||
|
||||
use BitBadger\PDODocument\Field;
|
||||
use BitBadger\PDODocument\Query;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* Unit tests for the Query class
|
||||
*/
|
||||
class QueryTest extends TestCase
|
||||
{
|
||||
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 testWhereByFieldsSucceedsForMultipleFields(): void
|
||||
{
|
||||
$this->assertEquals("data->>'test_field' <= @it AND data->>'other_field' = @other",
|
||||
Query::whereByFields([Field::LE('test_field', '', '@it'), Field::EQ('other_field', '', '@other')]),
|
||||
'WHERE fragment not constructed correctly');
|
||||
}
|
||||
|
||||
public function testWhereByFieldsSucceedsForMultipleFieldsWithOr(): void
|
||||
{
|
||||
$this->assertEquals("data->>'test_field' <= @it OR data->>'other_field' = @other",
|
||||
Query::whereByFields([Field::LE('test_field', '', '@it'), Field::EQ('other_field', '', '@other')], 'OR'),
|
||||
'WHERE fragment not constructed correctly');
|
||||
}
|
||||
|
||||
public function testWhereByIdSucceedsWithDefaultParameter(): void
|
||||
{
|
||||
$this->assertEquals("data->>'id' = @id", Query::whereById(), 'WHERE fragment not constructed correctly');
|
||||
}
|
||||
|
||||
public function testWhereByIdSucceedsWithSpecificParameter(): void
|
||||
{
|
||||
$this->assertEquals("data->>'id' = @di", Query::whereById('@di'), 'WHERE fragment not constructed correctly');
|
||||
}
|
||||
|
||||
public function testInsertSucceeds(): void
|
||||
{
|
||||
$this->assertEquals('INSERT INTO my_table VALUES (@data)', Query::insert('my_table'),
|
||||
'INSERT statement not constructed correctly');
|
||||
}
|
||||
|
||||
public function testSaveSucceeds(): void
|
||||
{
|
||||
$this->assertEquals(
|
||||
"INSERT INTO test_tbl VALUES (@data) ON CONFLICT ((data->>'id')) DO UPDATE SET data = EXCLUDED.data",
|
||||
Query::save('test_tbl'), 'INSERT ON CONFLICT statement not constructed correctly');
|
||||
}
|
||||
|
||||
public function testUpdateSucceeds()
|
||||
{
|
||||
$this->assertEquals("UPDATE testing SET data = @data WHERE data->>'id' = @id", Query::update('testing'),
|
||||
'UPDATE statement not constructed correctly');
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user