Add Custom JSON, Json methods; WIP on tests
This commit is contained in:
parent
f6756d79f1
commit
46b079b237
@ -10,6 +10,7 @@ namespace BitBadger\PDODocument;
|
|||||||
|
|
||||||
use BitBadger\InspiredByFSharp\Option;
|
use BitBadger\InspiredByFSharp\Option;
|
||||||
use BitBadger\PDODocument\Mapper\Mapper;
|
use BitBadger\PDODocument\Mapper\Mapper;
|
||||||
|
use BitBadger\PDODocument\Mapper\StringMapper;
|
||||||
use PDO;
|
use PDO;
|
||||||
use PDOException;
|
use PDOException;
|
||||||
use PDOStatement;
|
use PDOStatement;
|
||||||
@ -93,7 +94,42 @@ class Custom
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Execute a query that returns one or no results (returns false if not found)
|
* Execute a query that returns a JSON string of results
|
||||||
|
*
|
||||||
|
* @param string $query The query to be executed
|
||||||
|
* @param array<string, mixed> $parameters Parameters to use in executing the query
|
||||||
|
* @return string A JSON array with the results (empty results will be `[]`)
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function jsonArray(string $query, array $parameters): string
|
||||||
|
{
|
||||||
|
return '[' . implode(',', self::array($query, $parameters, new StringMapper('data'))) . ']';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute a query, echoing the results to the output
|
||||||
|
*
|
||||||
|
* @param string $query The query to be executed
|
||||||
|
* @param array<string, mixed> $parameters Parameters to use in executing the query
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function outputJsonArray(string $query, array $parameters): void
|
||||||
|
{
|
||||||
|
$isFirst = true;
|
||||||
|
echo '[';
|
||||||
|
foreach (self::list($query, $parameters, new StringMapper('data'))->items as $doc) {
|
||||||
|
if ($isFirst) {
|
||||||
|
$isFirst = false;
|
||||||
|
} else {
|
||||||
|
echo ',';
|
||||||
|
}
|
||||||
|
echo $doc;
|
||||||
|
}
|
||||||
|
echo ']';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute a query that returns one or no results
|
||||||
*
|
*
|
||||||
* @template TDoc The domain type of the document to retrieve
|
* @template TDoc The domain type of the document to retrieve
|
||||||
* @param string $query The query to be executed (will have "LIMIT 1" appended)
|
* @param string $query The query to be executed (will have "LIMIT 1" appended)
|
||||||
@ -112,6 +148,19 @@ class Custom
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute a query that returns one or no JSON results
|
||||||
|
*
|
||||||
|
* @param string $query The query to be executed (will have "LIMIT 1" appended)
|
||||||
|
* @param array<string, mixed> $parameters Parameters to use in executing the query
|
||||||
|
* @return string The JSON document (returns `{}` if no document is found)
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function jsonSingle(string $query, array $parameters): string
|
||||||
|
{
|
||||||
|
return self::single($query, $parameters, new StringMapper('data'))->getOrDefault('{}');
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Execute a query that does not return a value
|
* Execute a query that does not return a value
|
||||||
*
|
*
|
||||||
|
@ -12,7 +12,7 @@ use BitBadger\InspiredByFSharp\Option;
|
|||||||
use BitBadger\PDODocument\Mapper\DocumentMapper;
|
use BitBadger\PDODocument\Mapper\DocumentMapper;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Functions to find documents
|
* Functions to retrieve documents as domain objects
|
||||||
*/
|
*/
|
||||||
class Find
|
class Find
|
||||||
{
|
{
|
||||||
|
244
src/Json.php
Normal file
244
src/Json.php
Normal file
@ -0,0 +1,244 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PDODocument;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Functions to retrieve and output documents as JSON
|
||||||
|
*/
|
||||||
|
class Json
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Retrieve all JSON documents in the given table
|
||||||
|
*
|
||||||
|
* @param string $tableName The table from which documents should be retrieved
|
||||||
|
* @param Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
|
||||||
|
* @return string A JSON array of all documents from the table
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function all(string $tableName, array $orderBy = []): string
|
||||||
|
{
|
||||||
|
return Custom::jsonArray(Query::selectFromTable($tableName) . Query::orderBy($orderBy), []);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve a JSON document by its ID
|
||||||
|
*
|
||||||
|
* @param string $tableName The table from which the document should be retrieved
|
||||||
|
* @param mixed $docId The ID of the document to retrieve
|
||||||
|
* @return string The JSON document if found, `{}` otherwise
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function byId(string $tableName, mixed $docId): string
|
||||||
|
{
|
||||||
|
return Custom::jsonSingle(Query\Find::byId($tableName, $docId), Parameters::id($docId));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve JSON documents via a comparison on JSON fields
|
||||||
|
*
|
||||||
|
* @param string $tableName 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)
|
||||||
|
* @param Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
|
||||||
|
* @return string A JSON array of documents matching the given field comparison
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function byFields(string $tableName, array $fields, ?FieldMatch $match = null,
|
||||||
|
array $orderBy = []): string
|
||||||
|
{
|
||||||
|
Parameters::nameFields($fields);
|
||||||
|
return Custom::jsonArray(Query\Find::byFields($tableName, $fields, $match) . Query::orderBy($orderBy),
|
||||||
|
Parameters::addFields($fields, []));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve JSON documents via a JSON containment query (`@>`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table from which documents should be retrieved
|
||||||
|
* @param mixed[]|object $criteria The criteria for the JSON containment query
|
||||||
|
* @param Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
|
||||||
|
* @return string A JSON array 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, array $orderBy = []): string
|
||||||
|
{
|
||||||
|
return Custom::jsonArray(Query\Find::byContains($tableName) . Query::orderBy($orderBy),
|
||||||
|
Parameters::json(':criteria', $criteria));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve JSON documents via a JSON Path match query (`@?`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table from which documents should be retrieved
|
||||||
|
* @param string $path The JSON Path match string
|
||||||
|
* @param Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
|
||||||
|
* @return string A JSON array 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, array $orderBy = []): string
|
||||||
|
{
|
||||||
|
return Custom::jsonArray(Query\Find::byJsonPath($tableName) . Query::orderBy($orderBy), [':path' => $path]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve JSON documents via a comparison on JSON fields, returning only the first result
|
||||||
|
*
|
||||||
|
* @param string $tableName The table from which the document should be retrieved
|
||||||
|
* @param Field[] $fields The field comparison to match
|
||||||
|
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
|
||||||
|
* @param Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
|
||||||
|
* @return string The first JSON document if any matches are found, `{}` otherwise
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function firstByFields(string $tableName, array $fields, ?FieldMatch $match = null,
|
||||||
|
array $orderBy = []): string
|
||||||
|
{
|
||||||
|
Parameters::nameFields($fields);
|
||||||
|
return Custom::jsonSingle(Query\Find::byFields($tableName, $fields, $match) . Query::orderBy($orderBy),
|
||||||
|
Parameters::addFields($fields, []));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve JSON documents via a JSON containment query (`@>`), returning only the first result (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table from which documents should be retrieved
|
||||||
|
* @param mixed[]|object $criteria The criteria for the JSON containment query
|
||||||
|
* @param Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
|
||||||
|
* @return string The first JSON document if any matches are found, `{}` otherwise
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function firstByContains(string $tableName, array|object $criteria, array $orderBy = []): string
|
||||||
|
{
|
||||||
|
return Custom::jsonSingle(Query\Find::byContains($tableName) . Query::orderBy($orderBy),
|
||||||
|
Parameters::json(':criteria', $criteria));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve JSON documents via a JSON Path match query (`@?`), returning only the first result (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table from which documents should be retrieved
|
||||||
|
* @param string $path The JSON Path match string
|
||||||
|
* @param Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
|
||||||
|
* @return string The first JSON document if any matches are found, `{}` otherwise
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function firstByJsonPath(string $tableName, string $path, array $orderBy = []): string
|
||||||
|
{
|
||||||
|
return Custom::jsonSingle(Query\Find::byJsonPath($tableName) . Query::orderBy($orderBy), [':path' => $path]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Output all JSON documents in the given table
|
||||||
|
*
|
||||||
|
* @param string $tableName The table from which documents should be retrieved
|
||||||
|
* @param Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function outputAll(string $tableName, array $orderBy = []): void
|
||||||
|
{
|
||||||
|
Custom::outputJsonArray(Query::selectFromTable($tableName) . Query::orderBy($orderBy), []);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Output a JSON document by its ID
|
||||||
|
*
|
||||||
|
* @param string $tableName The table from which the document should be retrieved
|
||||||
|
* @param mixed $docId The ID of the document to retrieve
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function outputById(string $tableName, mixed $docId): void
|
||||||
|
{
|
||||||
|
echo self::byId($tableName, $docId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Output JSON documents via a comparison on JSON fields
|
||||||
|
*
|
||||||
|
* @param string $tableName 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)
|
||||||
|
* @param Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function outputByFields(string $tableName, array $fields, ?FieldMatch $match = null,
|
||||||
|
array $orderBy = []): void
|
||||||
|
{
|
||||||
|
Parameters::nameFields($fields);
|
||||||
|
Custom::outputJsonArray(Query\Find::byFields($tableName, $fields, $match) . Query::orderBy($orderBy),
|
||||||
|
Parameters::addFields($fields, []));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Output JSON documents via a JSON containment query (`@>`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table from which documents should be retrieved
|
||||||
|
* @param mixed[]|object $criteria The criteria for the JSON containment query
|
||||||
|
* @param Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function outputByContains(string $tableName, array|object $criteria, array $orderBy = []): void
|
||||||
|
{
|
||||||
|
Custom::outputJsonArray(Query\Find::byContains($tableName) . Query::orderBy($orderBy),
|
||||||
|
Parameters::json(':criteria', $criteria));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Output JSON documents via a JSON Path match query (`@?`; PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table from which documents should be retrieved
|
||||||
|
* @param string $path The JSON Path match string
|
||||||
|
* @param Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function outputByJsonPath(string $tableName, string $path, array $orderBy = []): void
|
||||||
|
{
|
||||||
|
Custom::outputJsonArray(Query\Find::byJsonPath($tableName) . Query::orderBy($orderBy), [':path' => $path]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Output JSON documents via a comparison on JSON fields, returning only the first result
|
||||||
|
*
|
||||||
|
* @param string $tableName The table from which the document should be retrieved
|
||||||
|
* @param Field[] $fields The field comparison to match
|
||||||
|
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
|
||||||
|
* @param Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
|
||||||
|
* @throws DocumentException If any is encountered
|
||||||
|
*/
|
||||||
|
public static function outputFirstByFields(string $tableName, array $fields, ?FieldMatch $match = null,
|
||||||
|
array $orderBy = []): void
|
||||||
|
{
|
||||||
|
echo self::firstByFields($tableName, $fields, $match, $orderBy);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Output JSON documents via a JSON containment query (`@>`), returning only the first result (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table from which documents should be retrieved
|
||||||
|
* @param mixed[]|object $criteria The criteria for the JSON containment query
|
||||||
|
* @param Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function outputFirstByContains(string $tableName, array|object $criteria, array $orderBy = []): void
|
||||||
|
{
|
||||||
|
echo self::firstByContains($tableName, $criteria, $orderBy);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Output JSON documents via a JSON Path match query (`@?`), returning only the first result (PostgreSQL only)
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table from which documents should be retrieved
|
||||||
|
* @param string $path The JSON Path match string
|
||||||
|
* @param Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
|
||||||
|
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
|
||||||
|
*/
|
||||||
|
public static function outputFirstByJsonPath(string $tableName, string $path, array $orderBy = []): void
|
||||||
|
{
|
||||||
|
echo self::firstByJsonPath($tableName, $path, $orderBy);
|
||||||
|
}
|
||||||
|
}
|
@ -65,6 +65,36 @@ describe('::array()', function () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('::jsonArray()', function () {
|
||||||
|
test('returns non-empty array when data found', function () {
|
||||||
|
expect(Custom::jsonArray(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'sub' IS NOT NULL", []))
|
||||||
|
->toContain('[{', '},{', '}]');
|
||||||
|
});
|
||||||
|
test('returns empty array when no data found', function () {
|
||||||
|
expect(Custom::jsonArray(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'nothing' = '7'", []))
|
||||||
|
->toBe('[]');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('::outputJsonArray()', function () {
|
||||||
|
test('outputs non-empty array when data found', function () {
|
||||||
|
ob_clean();
|
||||||
|
ob_start();
|
||||||
|
Custom::outputJsonArray(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'sub' IS NOT NULL", []);
|
||||||
|
$json = ob_get_contents();
|
||||||
|
ob_end_clean();
|
||||||
|
expect($json)->toContain('[{', '},{', '}]');
|
||||||
|
});
|
||||||
|
test('outputs empty array when no data found', function () {
|
||||||
|
ob_clean();
|
||||||
|
ob_start();
|
||||||
|
Custom::outputJsonArray(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'nothing' = '7'", []);
|
||||||
|
$json = ob_get_contents();
|
||||||
|
ob_end_clean();
|
||||||
|
expect($json)->toBe('[]');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('::single()', function () {
|
describe('::single()', function () {
|
||||||
test('returns a document when one is found', function () {
|
test('returns a document when one is found', function () {
|
||||||
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id", [':id' => 'one'],
|
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id", [':id' => 'one'],
|
||||||
@ -78,6 +108,19 @@ describe('::single()', function () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('::jsonSingle()', function () {
|
||||||
|
test('returns a document when one is found', function () {
|
||||||
|
expect(Custom::jsonSingle('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id",
|
||||||
|
[':id' => 'one']))
|
||||||
|
->toStartWith('{"id":')->toContain('"one",')->toEndWith('}');
|
||||||
|
});
|
||||||
|
test('returns no document when one is not found', function () {
|
||||||
|
expect(Custom::jsonSingle('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id",
|
||||||
|
[':id' => 'eighty']))
|
||||||
|
->toBe('{}');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('::nonQuery()', function () {
|
describe('::nonQuery()', function () {
|
||||||
test('works when documents match the WHERE clause', function () {
|
test('works when documents match the WHERE clause', function () {
|
||||||
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
219
tests/Integration/PostgreSQL/JsonTest.php
Normal file
219
tests/Integration/PostgreSQL/JsonTest.php
Normal file
@ -0,0 +1,219 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
use BitBadger\PDODocument\{Custom, Delete, Document, Field, FieldMatch, Json};
|
||||||
|
use Test\Integration\{ArrayDocument, NumDocument, TestDocument};
|
||||||
|
use Test\Integration\PostgreSQL\ThrowawayDb;
|
||||||
|
|
||||||
|
pest()->group('integration', 'postgresql');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Expect document ordering by verifying the index of IDs against others
|
||||||
|
*
|
||||||
|
* @param string $json The JSON string to be searched
|
||||||
|
* @param array $ids The IDs to be verified
|
||||||
|
*/
|
||||||
|
function expect_doc_order(string $json, array $ids): void
|
||||||
|
{
|
||||||
|
for ($idx = 0; $idx < sizeof($ids) - 1; $idx++) {
|
||||||
|
expect(strpos($json, '"' . $ids[$idx] . '",'))
|
||||||
|
->toBeLessThan(strpos($json, '"' . $ids[$idx + 1] . '",'),
|
||||||
|
"ID $ids[$idx] should have occurred before ID {$ids[$idx + 1]} in JSON $json");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('::all()', function () {
|
||||||
|
test('retrieves data', function () {
|
||||||
|
expect(Json::all(ThrowawayDb::TABLE))
|
||||||
|
->toContain('{"id": "one",')
|
||||||
|
->toContain('{"id": "two",')
|
||||||
|
->toContain('{"id": "three",')
|
||||||
|
->toContain('{"id": "four",')
|
||||||
|
->toContain('{"id": "five",');
|
||||||
|
});
|
||||||
|
test('sorts data ascending', function () {
|
||||||
|
expect_doc_order(Json::all(ThrowawayDb::TABLE, [Field::named('id')]), ['five', 'four', 'one', 'three', 'two']);
|
||||||
|
});
|
||||||
|
test('sorts data descending', function () {
|
||||||
|
expect_doc_order(Json::all(ThrowawayDb::TABLE, [Field::named('id DESC')]),
|
||||||
|
['two', 'three', 'one', 'four', 'five']);
|
||||||
|
});
|
||||||
|
test('sorts data numerically', function () {
|
||||||
|
expect_doc_order(
|
||||||
|
Json::all(ThrowawayDb::TABLE, [Field::named('sub.foo NULLS LAST'), Field::named('n:num_value')]),
|
||||||
|
['two', 'four', 'one', 'three', 'five']);
|
||||||
|
});
|
||||||
|
test('retrieves empty results', function () {
|
||||||
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
expect(Json::all(ThrowawayDb::TABLE))->toBe('[]');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('::byId()', function () {
|
||||||
|
test('retrieves a document via string ID', function () {
|
||||||
|
expect(Json::byId(ThrowawayDb::TABLE, 'two'))->toStartWith('{')->toContain('"id": "two",')->toEndWith('}');
|
||||||
|
});
|
||||||
|
test('retrieves a document via numeric ID', function () {
|
||||||
|
Delete::byFields(ThrowawayDb::TABLE, [Field::notExists('absent')]);
|
||||||
|
Document::insert(ThrowawayDb::TABLE, ['id' => 18, 'value' => 'howdy']);
|
||||||
|
expect(Json::byId(ThrowawayDb::TABLE, 18))->toStartWith('{')->toContain('"id": 18,')->toEndWith('}');
|
||||||
|
});
|
||||||
|
test('returns "{}" when a document is not found', function () {
|
||||||
|
expect(Json::byId(ThrowawayDb::TABLE, 'seventy-five'))->toBe('{}');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
//describe('::byFields()', function () {
|
||||||
|
// test('retrieves matching documents', function () {
|
||||||
|
// $docs = Find::byFields(ThrowawayDb::TABLE, [Field::in('value', ['blue', 'purple']), Field::exists('sub')],
|
||||||
|
// TestDocument::class, FieldMatch::All);
|
||||||
|
// expect($docs)->not->toBeNull();
|
||||||
|
// $count = 0;
|
||||||
|
// foreach ($docs->items as $ignored) $count++;
|
||||||
|
// expect($count)->toBe(1);
|
||||||
|
// });
|
||||||
|
// test('retrieves ordered matching documents', function () {
|
||||||
|
// $docs = Find::byFields(ThrowawayDb::TABLE, [Field::equal('value', 'purple')], TestDocument::class,
|
||||||
|
// FieldMatch::All, [Field::named('id')]);
|
||||||
|
// expect($docs)->not->toBeNull()
|
||||||
|
// ->and(iterator_to_array($docs->map(fn ($it) => $it->id), false))->toBe(['five', 'four']);
|
||||||
|
// });
|
||||||
|
// test('retrieves documents matching a numeric IN clause', function () {
|
||||||
|
// $docs = Find::byFields(ThrowawayDb::TABLE, [Field::in('num_value', [2, 4, 6, 8])], TestDocument::class);
|
||||||
|
// expect($docs)->not->toBeNull();
|
||||||
|
// $count = 0;
|
||||||
|
// foreach ($docs->items as $ignored) $count++;
|
||||||
|
// expect($count)->toBe(1);
|
||||||
|
// });
|
||||||
|
// test('returns an empty list when no matching documents are found', function () {
|
||||||
|
// expect(Find::byFields(ThrowawayDb::TABLE, [Field::greater('num_value', 100)], TestDocument::class))
|
||||||
|
// ->not->toBeNull()
|
||||||
|
// ->hasItems->toBeFalse();
|
||||||
|
// });
|
||||||
|
// test('retrieves documents matching an inArray condition', function () {
|
||||||
|
// Delete::byFields(ThrowawayDb::TABLE, [Field::notExists('absentField')]);
|
||||||
|
// foreach (ArrayDocument::testDocuments() as $doc) Document::insert(ThrowawayDb::TABLE, $doc);
|
||||||
|
// $docs = Find::byFields(ThrowawayDb::TABLE, [Field::inArray('values', ThrowawayDb::TABLE, ['c'])],
|
||||||
|
// ArrayDocument::class);
|
||||||
|
// expect($docs)->not->toBeNull();
|
||||||
|
// $count = 0;
|
||||||
|
// foreach ($docs->items as $ignored) $count++;
|
||||||
|
// expect($count)->toBe(2);
|
||||||
|
// });
|
||||||
|
// test('returns an empty list when no documents match an inArray condition', function () {
|
||||||
|
// Delete::byFields(ThrowawayDb::TABLE, [Field::notExists('absentField')]);
|
||||||
|
// foreach (ArrayDocument::testDocuments() as $doc) Document::insert(ThrowawayDb::TABLE, $doc);
|
||||||
|
// expect(Find::byFields(ThrowawayDb::TABLE, [Field::inArray('values', ThrowawayDb::TABLE, ['j'])],
|
||||||
|
// ArrayDocument::class))
|
||||||
|
// ->not->toBeNull()
|
||||||
|
// ->hasItems->toBeFalse();
|
||||||
|
// });
|
||||||
|
//});
|
||||||
|
//
|
||||||
|
//describe('::byContains()', function () {
|
||||||
|
// test('retrieves matching documents', function () {
|
||||||
|
// $docs = Find::byContains(ThrowawayDb::TABLE, ['value' => 'purple'], TestDocument::class);
|
||||||
|
// expect($docs)->not->toBeNull();
|
||||||
|
// $count = 0;
|
||||||
|
// foreach ($docs->items as $ignored) $count++;
|
||||||
|
// expect($count)->toBe(2);
|
||||||
|
// });
|
||||||
|
// test('retrieves ordered matching documents', function () {
|
||||||
|
// $docs = Find::byContains(ThrowawayDb::TABLE, ['sub' => ['foo' => 'green']], TestDocument::class,
|
||||||
|
// [Field::named('value')]);
|
||||||
|
// expect($docs)
|
||||||
|
// ->not->toBeNull()
|
||||||
|
// ->and(iterator_to_array($docs->map(fn ($it) => $it->id), false))->toBe(['two', 'four']);
|
||||||
|
// });
|
||||||
|
// test('returns an empty list when no documents match', function () {
|
||||||
|
// expect(Find::byContains(ThrowawayDb::TABLE, ['value' => 'indigo'], TestDocument::class))
|
||||||
|
// ->not->toBeNull()
|
||||||
|
// ->hasItems->toBeFalse();
|
||||||
|
// });
|
||||||
|
//});
|
||||||
|
//
|
||||||
|
//describe('::byJsonPath()', function () {
|
||||||
|
// test('retrieves matching documents', function () {
|
||||||
|
// $docs = Find::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 10)', TestDocument::class);
|
||||||
|
// expect($docs)->not->toBeNull();
|
||||||
|
// $count = 0;
|
||||||
|
// foreach ($docs->items as $ignored) $count++;
|
||||||
|
// expect($count)->toBe(2);
|
||||||
|
// });
|
||||||
|
// test('retrieves ordered matching documents', function () {
|
||||||
|
// $docs = Find::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 10)', TestDocument::class,
|
||||||
|
// [Field::named('id')]);
|
||||||
|
// expect($docs)->not->toBeNull()
|
||||||
|
// ->and(iterator_to_array($docs->map(fn ($it) => $it->id), false))->toBe(['five', 'four']);
|
||||||
|
// });
|
||||||
|
// test('returns an empty list when no documents match', function () {
|
||||||
|
// expect(Find::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 100)', TestDocument::class))
|
||||||
|
// ->not->toBeNull()
|
||||||
|
// ->hasItems->toBeFalse();
|
||||||
|
// });
|
||||||
|
//});
|
||||||
|
//
|
||||||
|
//describe('::firstByFields()', function () {
|
||||||
|
// test('retrieves a matching document', function () {
|
||||||
|
// $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'another')], TestDocument::class);
|
||||||
|
// expect($doc)->isSome->toBeTrue()->and($doc->value)->id->toBe('two');
|
||||||
|
// });
|
||||||
|
// test('retrieves a document for multiple results', function () {
|
||||||
|
// $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('sub.foo', 'green')], TestDocument::class);
|
||||||
|
// expect($doc)->isSome->toBeTrue()->and(['two', 'four'])->toContain($doc->value->id);
|
||||||
|
// });
|
||||||
|
// test('retrieves a document for multiple ordered results', function () {
|
||||||
|
// $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('sub.foo', 'green')], TestDocument::class,
|
||||||
|
// orderBy: [Field::named('n:num_value DESC')]);
|
||||||
|
// expect($doc)->isSome->toBeTrue()->and($doc->value)->id->toBe('four');
|
||||||
|
// });
|
||||||
|
// test('returns None when no documents match', function () {
|
||||||
|
// expect(Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'absent')], TestDocument::class))
|
||||||
|
// ->isNone->toBeTrue();
|
||||||
|
// });
|
||||||
|
//});
|
||||||
|
//
|
||||||
|
//describe('::firstByContains()', function () {
|
||||||
|
// test('retrieves a matching document', function () {
|
||||||
|
// $doc = Find::firstByContains(ThrowawayDb::TABLE, ['value' => 'FIRST!'], TestDocument::class);
|
||||||
|
// expect($doc)->isSome->toBeTrue()->and($doc->value)->id->toBe('one');
|
||||||
|
// });
|
||||||
|
// test('retrieves a document for multiple results', function () {
|
||||||
|
// $doc = Find::firstByContains(ThrowawayDb::TABLE, ['value' => 'purple'], TestDocument::class);
|
||||||
|
// expect($doc)->isSome->toBeTrue()->and(['four', 'five'])->toContain($doc->value->id);
|
||||||
|
// });
|
||||||
|
// test('retrieves a document for multiple ordered results', function () {
|
||||||
|
// $doc = Find::firstByContains(ThrowawayDb::TABLE, ['value' => 'purple'], TestDocument::class,
|
||||||
|
// [Field::named('sub.bar NULLS FIRST')]);
|
||||||
|
// expect($doc)->isSome->toBeTrue()->and($doc->value)->id->toBe('five');
|
||||||
|
// });
|
||||||
|
// test('returns None when no documents match', function () {
|
||||||
|
// expect(Find::firstByContains(ThrowawayDb::TABLE, ['value' => 'indigo'], TestDocument::class))
|
||||||
|
// ->isNone->toBeTrue();
|
||||||
|
// });
|
||||||
|
//});
|
||||||
|
//
|
||||||
|
//describe('::firstByJsonPath()', function () {
|
||||||
|
// test('retrieves a matching document', function () {
|
||||||
|
// $doc = Find::firstByJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ == 10)', TestDocument::class);
|
||||||
|
// expect($doc)->isSome->toBeTrue()->and($doc->value)->id->toBe('two');
|
||||||
|
// });
|
||||||
|
// test('retrieves a document for multiple results', function () {
|
||||||
|
// $doc = Find::firstByJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 10)', TestDocument::class);
|
||||||
|
// expect($doc)->isSome->toBeTrue()->and(['four', 'five'])->toContain($doc->value->id);
|
||||||
|
// });
|
||||||
|
// test('retrieves a document for multiple ordered results', function () {
|
||||||
|
// $doc = Find::firstByJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 10)', TestDocument::class,
|
||||||
|
// [Field::named('id DESC')]);
|
||||||
|
// expect($doc)->isSome->toBeTrue()->and($doc->value)->id->toBe('four');
|
||||||
|
// });
|
||||||
|
// test('returns None when no documents match', function () {
|
||||||
|
// expect(Find::firstByJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 100)', TestDocument::class))
|
||||||
|
// ->isNone->toBeTrue();
|
||||||
|
// });
|
||||||
|
//});
|
@ -63,6 +63,36 @@ describe('::array()', function () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('::jsonArray()', function () {
|
||||||
|
test('returns non-empty array when data found', function () {
|
||||||
|
expect(Custom::jsonArray(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'sub' IS NOT NULL", []))
|
||||||
|
->toContain('[{', '},{', '}]');
|
||||||
|
});
|
||||||
|
test('returns empty array when no data found', function () {
|
||||||
|
expect(Custom::jsonArray(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'nothing' = '7'", []))
|
||||||
|
->toBe('[]');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('::outputJsonArray()', function () {
|
||||||
|
test('outputs non-empty array when data found', function () {
|
||||||
|
ob_clean();
|
||||||
|
ob_start();
|
||||||
|
Custom::outputJsonArray(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'sub' IS NOT NULL", []);
|
||||||
|
$json = ob_get_contents();
|
||||||
|
ob_end_clean();
|
||||||
|
expect($json)->toContain('[{', '},{', '}]');
|
||||||
|
});
|
||||||
|
test('outputs empty array when no data found', function () {
|
||||||
|
ob_clean();
|
||||||
|
ob_start();
|
||||||
|
Custom::outputJsonArray(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'nothing' = '7'", []);
|
||||||
|
$json = ob_get_contents();
|
||||||
|
ob_end_clean();
|
||||||
|
expect($json)->toBe('[]');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('::single()', function () {
|
describe('::single()', function () {
|
||||||
test('returns a document when one is found', function () {
|
test('returns a document when one is found', function () {
|
||||||
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id", [':id' => 'one'],
|
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id", [':id' => 'one'],
|
||||||
@ -76,6 +106,19 @@ describe('::single()', function () {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('::jsonSingle()', function () {
|
||||||
|
test('returns a document when one is found', function () {
|
||||||
|
expect(Custom::jsonSingle('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id",
|
||||||
|
[':id' => 'one']))
|
||||||
|
->toStartWith('{"id":"one",')->toEndWith('}');
|
||||||
|
});
|
||||||
|
test('returns no document when one is not found', function () {
|
||||||
|
expect(Custom::jsonSingle('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id",
|
||||||
|
[':id' => 'eighty']))
|
||||||
|
->toBe('{}');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('::nonQuery()', function () {
|
describe('::nonQuery()', function () {
|
||||||
test('works when documents match the WHERE clause', function () {
|
test('works when documents match the WHERE clause', function () {
|
||||||
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||||
|
Loading…
x
Reference in New Issue
Block a user