Compare commits

..

3 Commits

Author SHA1 Message Date
20a2c50ae7 More WIP on test migration 2024-10-16 07:06:38 -04:00
f757a244b0 WIP on QueryTest migration 2024-10-13 21:33:01 -04:00
b48a2a9bf9 WIP on Pest test migration 2024-10-05 15:43:41 -04:00
43 changed files with 3318 additions and 1680 deletions

View File

@ -4,14 +4,10 @@ This library allows SQLite and PostgreSQL to be treated as document databases. I
## Add via Composer ## Add via Composer
[![Static Badge](https://img.shields.io/badge/v1.0.0--rc1-orange?label=php%208.2) [![Packagist Version](https://img.shields.io/packagist/v/bit-badger/pdo-document)](https://packagist.org/packages/bit-badger/pdo-document)
](https://packagist.org/packages/bit-badger/pdo-document#v1.0.0-rc1)     [![Packagist Version](https://img.shields.io/packagist/v/bit-badger/pdo-document?include_prereleases&label=php%208.4)
](https://packagist.org/packages/bit-badger/pdo-document)
`composer require bit-badger/pdo-document` `composer require bit-badger/pdo-document`
For the v1 series, the `DocumentList` type's members `hasItems` and `items` are functions; in the v2 series, they are properties. Additionally, the `Option` and `Result` types included in the project have a similar difference; see the [v1 README](https://git.bitbadger.solutions/bit-badger/inspired-by-fsharp/src/branch/v1/README.md) for PHP 8.2 or 8.3 and the [v2 README](https://git.bitbadger.solutions/bit-badger/inspired-by-fsharp/src/branch/main/README.md) for PHP 8.4. Both versions are supported; the v1 / v2 distinction helps composer make the right choice based on the target PHP version of your project.
## Configuration ## Configuration
### Connection Details ### Connection Details

View File

@ -19,15 +19,15 @@
}, },
"minimum-stability": "RC", "minimum-stability": "RC",
"require": { "require": {
"php": ">=8.4", "php": "8.2 - 8.3",
"bit-badger/inspired-by-fsharp": "^2", "bit-badger/inspired-by-fsharp": "^1",
"netresearch/jsonmapper": "^4", "netresearch/jsonmapper": "^4",
"ext-pdo": "*" "ext-pdo": "*"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "^11",
"square/pjson": "^0.5.0", "square/pjson": "^0.5.0",
"phpstan/phpstan": "^1.12" "phpstan/phpstan": "^1.12",
"pestphp/pest": "^3.2"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {
@ -47,5 +47,10 @@
}, },
"archive": { "archive": {
"exclude": [ "/tests", "/.gitattributes", "/.gitignore", "/.git", "/composer.lock" ] "exclude": [ "/tests", "/.gitattributes", "/.gitignore", "/.git", "/composer.lock" ]
},
"config": {
"allow-plugins": {
"pestphp/pest-plugin": true
}
} }
} }

2118
composer.lock generated

File diff suppressed because it is too large Load Diff

18
phpunit.xml Normal file
View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.3/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
>
<testsuites>
<testsuite name="Test Suite">
<directory suffix="Test.php">./tests</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory suffix=".php">./app</directory>
<directory suffix=".php">./src</directory>
</include>
</source>
</phpunit>

View File

@ -89,7 +89,7 @@ class Custom
*/ */
public static function array(string $query, array $parameters, Mapper $mapper): array public static function array(string $query, array $parameters, Mapper $mapper): array
{ {
return iterator_to_array(self::list($query, $parameters, $mapper)->items); return iterator_to_array(self::list($query, $parameters, $mapper)->items());
} }
/** /**

View File

@ -9,12 +9,13 @@ declare(strict_types=1);
namespace BitBadger\PDODocument; namespace BitBadger\PDODocument;
use Exception; use Exception;
use Stringable;
use Throwable; use Throwable;
/** /**
* Exceptions occurring during document processing * Exceptions occurring during document processing
*/ */
class DocumentException extends Exception class DocumentException extends Exception implements Stringable
{ {
/** /**
* Constructor * Constructor

View File

@ -44,17 +44,24 @@ class DocumentList
} }
} }
/** @var bool True if there are items still to be retrieved from the list, false if not */ /**
public bool $hasItems { * Does this list have items remaining?
get => !is_null($this->result); *
* @return bool True if there are items still to be retrieved from the list, false if not
*/
public function hasItems(): bool
{
return !is_null($this->result);
} }
/** /**
* @var Generator<TDoc> The items from the document list * The items from the query result
*
* @return Generator<TDoc> The items from the document list
* @throws DocumentException If this is called once the generator has been consumed * @throws DocumentException If this is called once the generator has been consumed
*/ */
public Generator $items { public function items(): Generator
get { {
if (!$this->result) { if (!$this->result) {
if ($this->isConsumed) { if ($this->isConsumed) {
throw new DocumentException('Cannot call items() multiple times'); throw new DocumentException('Cannot call items() multiple times');
@ -74,7 +81,6 @@ class DocumentList
$this->isConsumed = true; $this->isConsumed = true;
$this->result = null; $this->result = null;
} }
}
/** /**
* Map items by consuming the generator * Map items by consuming the generator
@ -86,7 +92,7 @@ class DocumentList
*/ */
public function map(callable $map): Generator public function map(callable $map): Generator
{ {
foreach ($this->items as $item) { foreach ($this->items() as $item) {
yield $map($item); yield $map($item);
} }
} }
@ -99,7 +105,7 @@ class DocumentList
*/ */
public function iter(callable $f): void public function iter(callable $f): void
{ {
foreach ($this->items as $item) { foreach ($this->items() as $item) {
$f($item); $f($item);
} }
} }
@ -116,7 +122,7 @@ class DocumentList
public function mapToArray(callable $keyFunc, callable $valueFunc): array public function mapToArray(callable $keyFunc, callable $valueFunc): array
{ {
$results = []; $results = [];
foreach ($this->items as $item) { foreach ($this->items() as $item) {
$results[$keyFunc($item)] = $valueFunc($item); $results[$keyFunc($item)] = $valueFunc($item);
} }
return $results; return $results;

View File

@ -0,0 +1,5 @@
<?php
test('example', function () {
expect(true)->toBeTrue();
});

53
tests/Pest.php Normal file
View File

@ -0,0 +1,53 @@
<?php
/*
|--------------------------------------------------------------------------
| Test Case
|--------------------------------------------------------------------------
|
| The closure you provide to your test functions is always bound to a specific PHPUnit test
| case class. By default, that class is "PHPUnit\Framework\TestCase". Of course, you may
| need to change it using the "pest()" function to bind a different classes or traits.
|
*/
// pest()->extend(Tests\TestCase::class)->in('Feature');
/*
|--------------------------------------------------------------------------
| Expectations
|--------------------------------------------------------------------------
|
| When you're writing tests, you often need to check that values meet certain conditions. The
| "expect()" function gives you access to a set of "expectations" methods that you can use
| to assert different things. Of course, you may extend the Expectation API at any time.
|
*/
expect()->extend('toBeOne', function () {
return $this->toBe(1);
});
/*
|--------------------------------------------------------------------------
| Functions
|--------------------------------------------------------------------------
|
| While Pest is very powerful out-of-the-box, you may have some testing code specific to your
| project that you don't want to repeat in every file. Here you can also expose helpers as
| global functions to help you to reduce the number of lines of code in your test files.
|
*/
/**
* Reset the database mode
*/
function reset_mode(): void
{
\BitBadger\PDODocument\Configuration::overrideMode(null);
}
function something()
{
// ..
}

10
tests/TestCase.php Normal file
View File

@ -0,0 +1,10 @@
<?php
namespace Tests;
use PHPUnit\Framework\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
//
}

View File

@ -0,0 +1,36 @@
<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
use BitBadger\PDODocument\{AutoId, Configuration, DocumentException};
pest()->group('unit');
describe('::$idField', function () {
test('has expected default value', function () {
expect(Configuration::$idField)->toBe('id');
});
});
describe('::$autoId', function () {
test('has expected default value', function () {
expect(Configuration::$autoId)->toBe(AutoId::None);
});
});
describe('::$idStringLength', function () {
test('has expected default value', function () {
expect(Configuration::$idStringLength)->toBe(16);
});
});
describe('::dbConn()', function () {
test('throws if DSN has not been set', function () {
Configuration::useDSN('');
expect(fn() => Configuration::dbConn())->toThrow(DocumentException::class);
});
});

View File

@ -0,0 +1,40 @@
<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
use BitBadger\PDODocument\DocumentException;
pest()->group('unit');
describe('Constructor', function () {
test('fills code and prior exception if provided', function () {
$priorEx = new Exception('Uh oh');
expect(new DocumentException('Test Exception', 17, $priorEx))
->not->toBeNull()
->getMessage()->toBe('Test Exception')
->getCode()->toBe(17)
->getPrevious()->toBe($priorEx);
});
test('uses expected code and prior exception if not provided', function () {
expect(new DocumentException('Oops'))
->not->toBeNull()
->getMessage()->toBe('Oops')
->getCode()->toBe(0)
->getPrevious()->toBeNull();
});
});
describe('->__toString()', function () {
test('excludes code if 0', function () {
$ex = new DocumentException('Test failure');
expect("$ex")->toBe("BitBadger\PDODocument\DocumentException: Test failure\n");
});
test('includes code if non-zero', function () {
$ex = new DocumentException('Oof', -6);
expect("$ex")->toBe("BitBadger\PDODocument\DocumentException: [-6] Oof\n");
});
});

View File

@ -0,0 +1,20 @@
<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
use BitBadger\PDODocument\FieldMatch;
pest()->group('unit');
describe('->toSQL()', function () {
test('returns AND for All', function () {
expect(FieldMatch::All)->toSQL()->toBe('AND');
});
test('returns OR for Any', function () {
expect(FieldMatch::Any)->toSQL()->toBe('OR');
});
});

418
tests/Unit/FieldTest.php Normal file
View File

@ -0,0 +1,418 @@
<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
use BitBadger\PDODocument\{Configuration, Field, Mode, Op};
pest()->group('unit');
describe('->appendParameter()', function () {
afterEach(function () { Configuration::overrideMode(null); });
test('appends no parameter for exists', function () {
expect(Field::exists('exists')->appendParameter([]))->toBeEmpty();
});
test('appends no parameter for notExists', function () {
expect(Field::notExists('absent')->appendParameter([]))->toBeEmpty();
});
test('appends two parameters for between', function () {
expect(Field::between('exists', 5, 9, '@num')->appendParameter([]))
->toHaveLength(2)
->toEqual(['@nummin' => 5, '@nummax' => 9]);
});
test('appends a parameter for each value for in', function () {
expect(Field::in('it', ['test', 'unit', 'great'], ':val')->appendParameter([]))
->toHaveLength(3)
->toEqual([':val_0' => 'test', ':val_1' => 'unit', ':val_2' => 'great']);
});
test('appends a parameter for each value for inArray [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
expect(Field::inArray('it', 'table', [2, 8, 64], ':bit')->appendParameter([]))
->toHaveLength(3)
->toEqual([':bit_0' => '2', ':bit_1' => '8', ':bit_2' => '64']);
})->group('postgresql');
test('appends a parameter for each value for inArray [SQLite]', function () {
Configuration::overrideMode(Mode::SQLite);
expect(Field::inArray('it', 'table', [2, 8, 64], ':bit')->appendParameter([]))
->toHaveLength(3)
->toEqual([':bit_0' => 2, ':bit_1' => 8, ':bit_2' => 64]);
})->group('sqlite');
test('appends a parameter for other operators', function () {
expect(Field::equal('the_field', 33, ':test')->appendParameter([]))
->toHaveLength(1)
->toEqual([':test' => 33]);
});
});
describe('->path()', function () {
afterEach(function () { Configuration::overrideMode(null); });
test('returns simple SQL path [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
expect(Field::equal('it', 'that'))->path()->toBe("data->>'it'");
})->group('postgresql');
test('returns simple SQL path [SQLite]', function () {
Configuration::overrideMode(Mode::SQLite);
expect(Field::equal('top', 'that'))->path()->toBe("data->>'top'");
})->group('sqlite');
test('returns nested SQL path [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
expect(Field::equal('parts.to.the.path', ''))->path()->toBe("data#>>'{parts,to,the,path}'");
})->group('postgresql');
test('returns nested SQL path [SQLite]', function () {
Configuration::overrideMode(Mode::SQLite);
expect(Field::equal('one.two.three', ''))->path()->toBe("data->'one'->'two'->>'three'");
})->group('sqlite');
test('returns simple JSON path [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
expect(Field::equal('it', 'that'))->path(true)->toBe("data->'it'");
})->group('postgresql');
test('returns simple JSON path [SQLite]', function () {
Configuration::overrideMode(Mode::SQLite);
expect(Field::equal('top', 'that'))->path(true)->toBe("data->'top'");
})->group('sqlite');
test('returns nested JSON path [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
expect(Field::equal('parts.to.the.path', ''))->path(true)->toBe("data#>'{parts,to,the,path}'");
})->group('postgresql');
test('returns nested JSON path [SQLite]', function () {
Configuration::overrideMode(Mode::SQLite);
expect(Field::equal('one.two.three', ''))->path(true)->toBe("data->'one'->'two'->'three'");
})->group('sqlite');
});
describe('->toWhere()', function () {
afterEach(function () { Configuration::overrideMode(null); });
test('generates IS NOT NULL for exists w/o qualifier [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
expect(Field::exists('that_field'))->toWhere()->toBe("data->>'that_field' IS NOT NULL");
})->group('postgresql');
test('generates IS NOT NULL for exists w/o qualifier [SQLite]', function () {
Configuration::overrideMode(Mode::SQLite);
expect(Field::exists('that_field'))->toWhere()->toBe("data->>'that_field' IS NOT NULL");
})->group('sqlite');
test('generates IS NULL for notExists w/o qualifier [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
expect(Field::notExists('a_field'))->toWhere()->toBe("data->>'a_field' IS NULL");
})->group('postgresql');
test('generates IS NULL for notExists w/o qualifier [SQLite]', function () {
Configuration::overrideMode(Mode::SQLite);
expect(Field::notExists('a_field'))->toWhere()->toBe("data->>'a_field' IS NULL");
})->group('sqlite');
test('generates BETWEEN for between w/o qualifier [SQLite]', function () {
Configuration::overrideMode(Mode::SQLite);
expect(Field::between('age', 13, 17, '@age'))->toWhere()->toBe("data->>'age' BETWEEN @agemin AND @agemax");
})->group('sqlite');
test('generates BETWEEN for between w/o qualifier, numeric range [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
expect(Field::between('age', 13, 17, '@age'))->toWhere()
->toBe("(data->>'age')::numeric BETWEEN @agemin AND @agemax");
})->group('postgresql');
test('generates BETWEEN for between w/o qualifier, non-numeric range [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
expect(Field::between('city', 'Atlanta', 'Chicago', ':city'))->toWhere()
->toBe("data->>'city' BETWEEN :citymin AND :citymax");
})->group('postgresql');
test('generates BETWEEN for between w/ qualifier [SQLite]', function () {
Configuration::overrideMode(Mode::SQLite);
$field = Field::between('age', 13, 17, '@age');
$field->qualifier = 'me';
expect($field)->toWhere()->toBe("me.data->>'age' BETWEEN @agemin AND @agemax");
})->group('sqlite');
test('generates BETWEEN for between w/ qualifier, numeric range [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
$field = Field::between('age', 13, 17, '@age');
$field->qualifier = 'me';
expect($field)->toWhere()->toBe("(me.data->>'age')::numeric BETWEEN @agemin AND @agemax");
})->group('postgresql');
test('generates BETWEEN for between w/ qualifier, non-numeric range [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
$field = Field::between('city', 'Atlanta', 'Chicago', ':city');
$field->qualifier = 'me';
expect($field)->toWhere()->toBe("me.data->>'city' BETWEEN :citymin AND :citymax");
})->group('postgresql');
test('generates IN for in, non-numeric values [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
expect(Field::in('test', ['Atlanta', 'Chicago'], ':city'))->toWhere()
->toBe("data->>'test' IN (:city_0, :city_1)");
})->group('postgresql');
test('generates IN for in, numeric values [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
expect(Field::in('even', [2, 4, 6], ':nbr'))->toWhere()
->toBe("(data->>'even')::numeric IN (:nbr_0, :nbr_1, :nbr_2)");
})->group('postgresql');
test('generates IN for in [SQLite]', function () {
Configuration::overrideMode(Mode::SQLite);
expect(Field::in('test', ['Atlanta', 'Chicago'], ':city'))->toWhere()
->toBe("data->>'test' IN (:city_0, :city_1)");
})->group('sqlite');
test('generates clause for inArray [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
expect(Field::inArray('even', 'tbl', [2, 4, 6, 8], ':it'))->toWhere()
->toBe("data->'even' ??| ARRAY[:it_0, :it_1, :it_2, :it_3]");
})->group('postgresql');
test('generates clause for inArray [SQLite]', function () {
Configuration::overrideMode(Mode::SQLite);
expect(Field::inArray('test', 'tbl', ['Atlanta', 'Chicago'], ':city'))->toWhere()
->toBe("EXISTS (SELECT 1 FROM json_each(tbl.data, '\$.test') WHERE value IN (:city_0, :city_1))");
})->group('sqlite');
test('generates clause for other operators w/o qualifier [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
expect(Field::equal('some_field', '', ':value'))->toWhere()->toBe("data->>'some_field' = :value");
})->group('postgresql');
test('generates clause for other operators w/o qualifier [SQLite]', function () {
Configuration::overrideMode(Mode::SQLite);
expect(Field::equal('some_field', '', ':value'))->toWhere()->toBe("data->>'some_field' = :value");
})->group('sqlite');
test('generates no-parameter clause w/ qualifier [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
$field = Field::exists('no_field');
$field->qualifier = 'test';
expect($field)->toWhere()->toBe("test.data->>'no_field' IS NOT NULL");
})->group('postgresql');
test('generates no-parameter clause w/ qualifier [SQLite]', function () {
Configuration::overrideMode(Mode::SQLite);
$field = Field::exists('no_field');
$field->qualifier = 'test';
expect($field)->toWhere()->toBe("test.data->>'no_field' IS NOT NULL");
})->group('sqlite');
test('generates parameter clause w/ qualifier [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
$field = Field::lessOrEqual('le_field', 18, ':it');
$field->qualifier = 'q';
expect($field)->toWhere()->toBe("(q.data->>'le_field')::numeric <= :it");
})->group('postgresql');
test('generates parameter clause w/ qualifier [SQLite]', function () {
Configuration::overrideMode(Mode::SQLite);
$field = Field::lessOrEqual('le_field', 18, ':it');
$field->qualifier = 'q';
expect($field)->toWhere()->toBe("q.data->>'le_field' <= :it");
})->group('sqlite');
});
describe('::equal()', function () {
test('creates Field w/o parameter', function () {
$field = Field::equal('my_test', 9);
expect($field)
->not->toBeNull()
->fieldName->toBe('my_test')
->op->toBe(Op::Equal)
->paramName->toBeEmpty()
->and($field->value)->toBe(9);
});
test('creates Field w/ parameter', function () {
$field = Field::equal('another_test', 'turkey', ':test');
expect($field)
->not->toBeNull()
->fieldName->toBe('another_test')
->op->toBe(Op::Equal)
->paramName->toBe(':test')
->and($field->value)->toBe('turkey');
});
});
describe('::greater()', function () {
test('creates Field w/o parameter', function () {
$field = Field::greater('your_test', 4);
expect($field)
->not->toBeNull()
->fieldName->toBe('your_test')
->op->toBe(Op::Greater)
->paramName->toBeEmpty()
->and($field->value)->toBe(4);
});
test('creates Field w/ parameter', function () {
$field = Field::greater('more_test', 'chicken', ':value');
expect($field)
->not->toBeNull()
->fieldName->toBe('more_test')
->op->toBe(Op::Greater)
->paramName->toBe(':value')
->and($field->value)->toBe('chicken');
});
});
describe('::greaterOrEqual()', function () {
test('creates Field w/o parameter', function () {
$field = Field::greaterOrEqual('their_test', 6);
expect($field)
->not->toBeNull()
->fieldName->toBe('their_test')
->op->toBe(Op::GreaterOrEqual)
->paramName->toBeEmpty()
->and($field->value)->toBe(6);
});
test('creates Field w/ parameter', function () {
$field = Field::greaterOrEqual('greater_test', 'poultry', ':cluck');
expect($field)
->not->toBeNull()
->fieldName->toBe('greater_test')
->op->toBe(Op::GreaterOrEqual)
->paramName->toBe(':cluck')
->and($field->value)->toBe('poultry');
});
});
describe('::less()', function () {
test('creates Field w/o parameter', function () {
$field = Field::less('z', 32);
expect($field)
->not->toBeNull()
->fieldName->toBe('z')
->op->toBe(Op::Less)
->paramName->toBeEmpty()
->and($field->value)->toBe(32);
});
test('creates Field w/ parameter', function () {
$field = Field::less('additional_test', 'fowl', ':boo');
expect($field)
->not->toBeNull()
->fieldName->toBe('additional_test')
->op->toBe(Op::Less)
->paramName->toBe(':boo')
->and($field->value)->toBe('fowl');
});
});
describe('::lessOrEqual()', function () {
test('creates Field w/o parameter', function () {
$field = Field::lessOrEqual('g', 87);
expect($field)
->not->toBeNull()
->fieldName->toBe('g')
->op->toBe(Op::LessOrEqual)
->paramName->toBeEmpty()
->and($field->value)->toBe(87);
});
test('creates Field w/ parameter', function () {
$field = Field::lessOrEqual('lesser_test', 'hen', ':woo');
expect($field)
->not->toBeNull()
->fieldName->toBe('lesser_test')
->op->toBe(Op::LessOrEqual)
->paramName->toBe(':woo')
->and($field->value)->toBe('hen');
});
});
describe('::notEqual()', function () {
test('creates Field w/o parameter', function () {
$field = Field::notEqual('j', 65);
expect($field)
->not->toBeNull()
->fieldName->toBe('j')
->op->toBe(Op::NotEqual)
->paramName->toBeEmpty()
->and($field->value)->toBe(65);
});
test('creates Field w/ parameter', function () {
$field = Field::notEqual('unequal_test', 'egg', ':zoo');
expect($field)
->not->toBeNull()
->fieldName->toBe('unequal_test')
->op->toBe(Op::NotEqual)
->paramName->toBe(':zoo')
->and($field->value)->toBe('egg');
});
});
describe('::between()', function () {
test('creates Field w/o parameter', function () {
$field = Field::between('k', 'alpha', 'zed');
expect($field)
->not->toBeNull()
->fieldName->toBe('k')
->op->toBe(Op::Between)
->paramName->toBeEmpty()
->and($field->value)->toEqual(['alpha', 'zed']);
});
test('creates Field w/ parameter', function () {
$field = Field::between('between_test', 18, 49, ':count');
expect($field)
->not->toBeNull()
->fieldName->toBe('between_test')
->op->toBe(Op::Between)
->paramName->toBe(':count')
->and($field->value)->toEqual([18, 49]);
});
});
describe('::in()', function () {
test('creates Field w/o parameter', function () {
$field = Field::in('test', [1, 2, 3]);
expect($field)
->not->toBeNull()
->fieldName->toBe('test')
->op->toBe(Op::In)
->paramName->toBeEmpty()
->and($field->value)->toEqual([1, 2, 3]);
});
test('creates Field w/ parameter', function () {
$field = Field::in('unit', ['a', 'b'], ':inParam');
expect($field)
->not->toBeNull()
->fieldName->toBe('unit')
->op->toBe(Op::In)
->paramName->toBe(':inParam')
->and($field->value)->toEqual(['a', 'b']);
});
});
describe('::inArray()', function () {
test('creates Field w/o parameter', function () {
$field = Field::inArray('test', 'tbl', [1, 2, 3]);
expect($field)
->not->toBeNull()
->fieldName->toBe('test')
->op->toBe(Op::InArray)
->paramName->toBeEmpty()
->and($field->value)->toEqual(['table' => 'tbl', 'values' => [1, 2, 3]]);
});
test('creates Field w/ parameter', function () {
$field = Field::inArray('unit', 'tab', ['a', 'b'], ':inAParam');
expect($field)
->not->toBeNull()
->fieldName->toBe('unit')
->op->toBe(Op::InArray)
->paramName->toBe(':inAParam')
->and($field->value)->toEqual(['table' => 'tab', 'values' => ['a', 'b']]);
});
});
describe('::exists()', function () {
test('creates Field', function () {
$field = Field::exists('be_there');
expect($field)
->not->toBeNull()
->fieldName->toBe('be_there')
->op->toBe(Op::Exists)
->paramName->toBeEmpty()
->and($field->value)->toBeEmpty();
});
});
describe('::notExists()', function () {
test('creates Field', function () {
$field = Field::notExists('be_absent');
expect($field)
->not->toBeNull()
->fieldName->toBe('be_absent')
->op->toBe(Op::NotExists)
->paramName->toBeEmpty()
->and($field->value)->toBeEmpty();
});
});
describe('::named()', function () {
test('creates Field', function () {
$field = Field::named('the_field');
expect($field)
->not->toBeNull()
->fieldName->toBe('the_field')
->op->toBe(Op::Equal)
->value->toBeEmpty()
->and($field->value)->toBeEmpty();
});
});

23
tests/Unit/ModeTest.php Normal file
View File

@ -0,0 +1,23 @@
<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
use BitBadger\PDODocument\{DocumentException, Mode};
pest()->group('unit');
describe('::deriveFromDSN()', function () {
test('derives for PostgreSQL', function () {
expect(Mode::deriveFromDSN('pgsql:Host=localhost'))->toBe(Mode::PgSQL);
})->group('postgresql');
test('derives for SQLite', function () {
expect(Mode::deriveFromDSN('sqlite:data.db'))->toBe(Mode::SQLite);
})->group('sqlite');
test('throws for other drivers', function () {
expect(fn() => Mode::deriveFromDSN('mysql:Host=localhost'))->toThrow(DocumentException::class);
});
});

47
tests/Unit/OpTest.php Normal file
View File

@ -0,0 +1,47 @@
<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
use BitBadger\PDODocument\Op;
pest()->group('unit');
describe('->toSQL()', function () {
test('returns "=" for Equal', function () {
expect(Op::Equal)->toSQL()->toBe('=');
});
test('returns ">" for Greater', function () {
expect(Op::Greater)->toSQL()->toBe('>');
});
test('returns ">=" for GreaterOrEqual', function () {
expect(Op::GreaterOrEqual)->toSQL()->toBe('>=');
});
test('returns "<" for Less', function () {
expect(Op::Less)->toSQL()->toBe('<');
});
test('returns "<=" for LessOrEqual', function () {
expect(Op::LessOrEqual)->toSQL()->toBe('<=');
});
test('returns "<>" for NotEqual', function () {
expect(Op::NotEqual)->toSQL()->toBe('<>');
});
test('returns "BETWEEN" for Between', function () {
expect(Op::Between)->toSQL()->toBe('BETWEEN');
});
test('returns "IN" for In', function () {
expect(Op::In)->toSQL()->toBe('IN');
});
test('returns "?|" (escaped) for InArray', function () {
expect(Op::InArray)->toSQL()->toBe('??|');
});
test('returns "IS NOT NULL" for Exists', function () {
expect(Op::Exists)->toSQL()->toBe('IS NOT NULL');
});
test('returns "IS NULL" for NotExists', function () {
expect(Op::NotExists)->toSQL()->toBe('IS NULL');
});
});

View File

@ -0,0 +1,85 @@
<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
use BitBadger\PDODocument\{Configuration, DocumentException, Field, Mode, Parameters};
use Test\{PjsonDocument, PjsonId};
pest()->group('unit');
describe('::id()', function () {
test('creates string ID parameter', function () {
expect(Parameters::id('key'))->toEqual([':id' => 'key']);
});
test('creates string from numeric ID parameter', function () {
expect(Parameters::id(7))->toEqual([':id' => '7']);
});
});
describe('::json()', function () {
test('serializes an array', function () {
expect(Parameters::json(':it', ['id' => 18, 'url' => 'https://www.unittest.com']))
->toEqual([':it' => '{"id":18,"url":"https://www.unittest.com"}']);
});
test('serializes an array w/ an empty array value', function () {
expect(Parameters::json(':it', ['id' => 18, 'urls' => []]))->toEqual([':it' => '{"id":18,"urls":[]}']);
});
test('serializes a 1-D array w/ an empty array value', function () {
expect(Parameters::json(':it', ['urls' => []]))->toEqual([':it' => '{"urls":[]}']);
});
test('serializes a stdClass instance', function () {
$obj = new stdClass();
$obj->id = 19;
$obj->url = 'https://testhere.info';
expect(Parameters::json(':it', $obj))->toEqual([':it' => '{"id":19,"url":"https://testhere.info"}']);
});
test('serializes a Pjson class instance', function () {
expect(Parameters::json(':it', new PjsonDocument(new PjsonId('999'), 'a test', 98, 'nothing')))
->toEqual([':it' => '{"id":"999","name":"a test","num_value":98}']);
});
test('serializes an array of Pjson class instances', function () {
expect(Parameters::json(':it',
['pjson' => [new PjsonDocument(new PjsonId('997'), 'another test', 94, 'nothing')]]))
->toEqual([':it' => '{"pjson":[{"id":"997","name":"another test","num_value":94}]}']);
});
});
describe('::nameFields()', function () {
test('provides missing parameter names', function () {
$named = [Field::equal('it', 17), Field::equal('also', 22, ':also'), Field::equal('other', 24)];
Parameters::nameFields($named);
expect($named)
->toHaveLength(3)
->sequence(
fn($it) => $it->paramName->toBe(':field0'),
fn($it) => $it->paramName->toBe(':also'),
fn($it) => $it->paramName->toBe(':field2'));
});
});
describe('::addFields()', function () {
test('appends to an existing parameter array', function () {
expect(Parameters::addFields([Field::equal('b', 'two', ':b'), Field::equal('z', 18, ':z')], [':a' => 1]))
->toEqual([':a' => 1, ':b' => 'two', ':z' => 18]);
});
});
describe('::fieldNames()', function () {
afterEach(function () { Configuration::overrideMode(null); });
test('generates names [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
expect(Parameters::fieldNames(':names', ['one', 'two', 'seven']))->toEqual([':names' => "{one,two,seven}"]);
})->group('postgresql');
test('generates names [SQLite]', function () {
Configuration::overrideMode(Mode::SQLite);
expect(Parameters::fieldNames(':it', ['test', 'unit', 'wow']))
->toEqual([':it0' => '$.test', ':it1' => '$.unit', ':it2' => '$.wow']);
})->group('sqlite');
test('throws when mode is not set', function () {
expect(fn() => Parameters::fieldNames('', []))->toThrow(DocumentException::class);
});
});

201
tests/Unit/QueryTest.php Normal file
View File

@ -0,0 +1,201 @@
<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
use BitBadger\PDODocument\{AutoId, Configuration, DocumentException, Field, FieldMatch, Mode, Query};
pest()->group('unit');
beforeEach(function () { Configuration::overrideMode(Mode::SQLite); });
afterEach(function () { Configuration::overrideMode(null); });
describe('::selectFromTable()', function () {
test('correctly forms a query', function () {
expect(Query::selectFromTable('testing'))->toBe('SELECT data FROM testing');
});
});
describe('::whereByFields()', function () {
test('generates a single field correctly', function () {
expect(Query::whereByFields([Field::lessOrEqual('test_field', '', ':it')]))->toBe("data->>'test_field' <= :it");
});
test('generates all fields correctly', function () {
expect(Query::whereByFields(
[Field::lessOrEqual('test_field', '', ':it'), Field::equal('other_field', '', ':other')]))
->toBe("data->>'test_field' <= :it AND data->>'other_field' = :other",);
});
test('generates any field correctly', function () {
expect(Query::whereByFields(
[Field::lessOrEqual('test_field', '', ':it'), Field::equal('other_field', '', ':other')],
FieldMatch::Any))
->toBe("data->>'test_field' <= :it OR data->>'other_field' = :other");
});
});
describe('::whereById()', function () {
test('uses default parameter name', function () {
expect(Query::whereById())->toBe("data->>'id' = :id");
});
test('uses provided parameter name', function () {
expect(Query::whereById(':di'))->toBe("data->>'id' = :di");
});
});
describe('::whereDataContains()', function () {
test('uses default parameter [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
expect(Query::whereDataContains())->toBe('data @> :criteria');
});
test('uses provided parameter [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
expect(Query::whereDataContains(':it'))->toBe('data @> :it');
});
test('throws [SQLite]', function () {
expect(fn () => Query::whereDataContains())->toThrow(DocumentException::class);
});
});
describe('::whereJsonPathMatches()', function () {
test('uses default parameter [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
expect(Query::whereJsonPathMatches())->toBe('jsonb_path_exists(data, :path::jsonpath)');
});
test('uses provided parameter [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
expect(Query::whereJsonPathMatches(':road'))->toBe('jsonb_path_exists(data, :road::jsonpath)');
});
test('throws [SQLite]', function () {
expect(fn () => Query::whereJsonPathMatches())->toThrow(DocumentException::class);
});
});
describe('::insert()', function () {
test('generates with no auto-ID [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
expect(Query::insert('test_tbl'))->toBe('INSERT INTO test_tbl VALUES (:data)');
});
test('generates with no auto-ID [SQLite]', function () {
expect(Query::insert('test_tbl'))->toBe('INSERT INTO test_tbl VALUES (:data)');
});
test('generates with auto numeric ID [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
expect(Query::insert('test_tbl', AutoId::Number))
->toBe("INSERT INTO test_tbl VALUES (:data::jsonb || ('{\"id\":' "
. "|| (SELECT COALESCE(MAX((data->>'id')::numeric), 0) + 1 FROM test_tbl) || '}')::jsonb)");
});
test('generates with auto numeric ID [SQLite]', function () {
expect(Query::insert('test_tbl', AutoId::Number))
->toBe("INSERT INTO test_tbl VALUES (json_set(:data, '$.id', "
. "(SELECT coalesce(max(data->>'id'), 0) + 1 FROM test_tbl)))");
});
test('generates with auto UUID [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
expect(Query::insert('test_tbl', AutoId::UUID))
->toStartWith("INSERT INTO test_tbl VALUES (:data::jsonb || '{\"id\":\"")
->toEndWith("\"}')");
});
test('generates with auto UUID [SQLite]', function () {
expect(Query::insert('test_tbl', AutoId::UUID))
->toStartWith("INSERT INTO test_tbl VALUES (json_set(:data, '$.id', '")
->toEndWith("'))");
});
test('generates with auto random string [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
Configuration::$idStringLength = 8;
try {
$query = Query::insert('test_tbl', AutoId::RandomString);
expect($query)
->toStartWith("INSERT INTO test_tbl VALUES (:data::jsonb || '{\"id\":\"")
->toEndWith("\"}')")
->and(str_replace(["INSERT INTO test_tbl VALUES (:data::jsonb || '{\"id\":\"", "\"}')"], '', $query))
->toHaveLength(8);
} finally {
Configuration::$idStringLength = 16;
}
});
test('generates with auto random string [SQLite]', function () {
$query = Query::insert('test_tbl', AutoId::RandomString);
expect($query)
->toStartWith("INSERT INTO test_tbl VALUES (json_set(:data, '$.id', '")
->toEndWith("'))")
->and(str_replace(["INSERT INTO test_tbl VALUES (json_set(:data, '$.id', '", "'))"], '', $query))
->toHaveLength(16);
});
test('throws when mode not set', function () {
Configuration::overrideMode(null);
expect(fn () => Query::insert('kaboom'))->toThrow(DocumentException::class);
});
});
describe('::save()', function () {
test('generates the correct query', function () {
expect(Query::save('test_tbl'))
->toBe("INSERT INTO test_tbl VALUES (:data) ON CONFLICT ((data->>'id')) DO UPDATE SET data = EXCLUDED.data");
});
});
describe('::update()', function () {
test('generates the correct query', function () {
expect(Query::update('testing'))->toBe("UPDATE testing SET data = :data WHERE data->>'id' = :id");
});
});
describe('::orderBy()', function () {
test('returns blank for no criteria [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
expect(Query::orderBy([]))->toBeEmpty();
});
test('returns blank for no criteria [SQLite]', function () {
expect(Query::orderBy([]))->toBeEmpty();
});
test('generates one field with no direction [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
expect(Query::orderBy([Field::named('TestField')]))->toBe(" ORDER BY data->>'TestField'");
});
test('generates one field with no direction [SQLite]', function () {
expect(Query::orderBy([Field::named('TestField')]))->toBe(" ORDER BY data->>'TestField'");
});
test('generates with one qualified field [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
$field = Field::named('TestField');
$field->qualifier = 'qual';
expect(Query::orderBy([$field]))->toBe(" ORDER BY qual.data->>'TestField'");
});
test('generates with one qualified field [SQLite]', function () {
$field = Field::named('TestField');
$field->qualifier = 'qual';
expect(Query::orderBy([$field]))->toBe(" ORDER BY qual.data->>'TestField'");
});
test('generates with multiple fields and direction [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
expect(Query::orderBy(
[Field::named('Nested.Test.Field DESC'), Field::named('AnotherField'), Field::named('It DESC')]))
->toBe(" ORDER BY data#>>'{Nested,Test,Field}' DESC, data->>'AnotherField', data->>'It' DESC");
});
test('generates with multiple fields and direction [SQLite]', function () {
expect(Query::orderBy(
[Field::named('Nested.Test.Field DESC'), Field::named('AnotherField'), Field::named('It DESC')]))
->toBe(" ORDER BY data->'Nested'->'Test'->>'Field' DESC, data->>'AnotherField', data->>'It' DESC");
});
test('generates with numeric field [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
expect(Query::orderBy([Field::named('n:Test')]))->toBe(" ORDER BY (data->>'Test')::numeric");
});
test('generates with numeric field [SQLite]', function () {
expect(Query::orderBy([Field::named('n:Test')]))->toBe(" ORDER BY data->>'Test'");
});
test('generates case-insensitive ordering [PostgreSQL]', function () {
Configuration::overrideMode(Mode::PgSQL);
expect(Query::orderBy([Field::named('i:Test.Field DESC NULLS FIRST')]))
->toBe(" ORDER BY LOWER(data#>>'{Test,Field}') DESC NULLS FIRST");
});
test('generates case-insensitive ordering [SQLite]', function () {
expect(Query::orderBy([Field::named('i:Test.Field ASC NULLS LAST')]))
->toBe(" ORDER BY data->'Test'->>'Field' COLLATE NOCASE ASC NULLS LAST");
});
});

View File

@ -63,7 +63,7 @@ class CustomTest extends TestCase
$list = Custom::list(Query::selectFromTable(ThrowawayDb::TABLE), [], new DocumentMapper(TestDocument::class)); $list = Custom::list(Query::selectFromTable(ThrowawayDb::TABLE), [], new DocumentMapper(TestDocument::class));
$this->assertNotNull($list, 'The document list should not be null'); $this->assertNotNull($list, 'The document list should not be null');
$count = 0; $count = 0;
foreach ($list->items as $ignored) $count++; foreach ($list->items() as $ignored) $count++;
$this->assertEquals(5, $count, 'There should have been 5 documents in the list'); $this->assertEquals(5, $count, 'There should have been 5 documents in the list');
} }
@ -74,7 +74,7 @@ class CustomTest extends TestCase
Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE (data->>'num_value')::numeric > :value", Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE (data->>'num_value')::numeric > :value",
[':value' => 100], new DocumentMapper(TestDocument::class)); [':value' => 100], new DocumentMapper(TestDocument::class));
$this->assertNotNull($list, 'The document list should not be null'); $this->assertNotNull($list, 'The document list should not be null');
$this->assertFalse($list->hasItems, 'There should have been no documents in the list'); $this->assertFalse($list->hasItems(), 'There should have been no documents in the list');
} }
#[TestDox('array() succeeds when data is found')] #[TestDox('array() succeeds when data is found')]
@ -100,8 +100,8 @@ class CustomTest extends TestCase
{ {
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id", [':id' => 'one'], $doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id", [':id' => 'one'],
new DocumentMapper(TestDocument::class)); new DocumentMapper(TestDocument::class));
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals('one', $doc->value->id, 'The incorrect document was returned'); $this->assertEquals('one', $doc->get()->id, 'The incorrect document was returned');
} }
#[TestDox('single() succeeds when a row is not found')] #[TestDox('single() succeeds when a row is not found')]
@ -109,7 +109,7 @@ class CustomTest extends TestCase
{ {
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id", $doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id",
[':id' => 'eighty'], new DocumentMapper(TestDocument::class)); [':id' => 'eighty'], new DocumentMapper(TestDocument::class));
$this->assertTrue($doc->isNone, 'There should not have been a document returned'); $this->assertTrue($doc->isNone(), 'There should not have been a document returned');
} }
#[TestDox('nonQuery() succeeds when operating on data')] #[TestDox('nonQuery() succeeds when operating on data')]

View File

@ -44,14 +44,14 @@ class DocumentListTest extends TestCase
$list = null; $list = null;
} }
#[TestDox('items succeeds')] #[TestDox('items() succeeds')]
public function testItemsSucceeds(): void public function testItemsSucceeds(): void
{ {
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [], $list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
new DocumentMapper(TestDocument::class)); new DocumentMapper(TestDocument::class));
$this->assertNotNull($list, 'There should have been a document list created'); $this->assertNotNull($list, 'There should have been a document list created');
$count = 0; $count = 0;
foreach ($list->items as $item) { foreach ($list->items() as $item) {
$this->assertContains($item->id, ['one', 'two', 'three', 'four', 'five'], $this->assertContains($item->id, ['one', 'two', 'three', 'four', 'five'],
'An unexpected document ID was returned'); 'An unexpected document ID was returned');
$count++; $count++;
@ -59,40 +59,40 @@ class DocumentListTest extends TestCase
$this->assertEquals(5, $count, 'There should have been 5 documents returned'); $this->assertEquals(5, $count, 'There should have been 5 documents returned');
} }
#[TestDox('items fails when already consumed')] #[TestDox('items() fails when already consumed')]
public function testItemsFailsWhenAlreadyConsumed(): void public function testItemsFailsWhenAlreadyConsumed(): void
{ {
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [], $list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
new DocumentMapper(TestDocument::class)); new DocumentMapper(TestDocument::class));
$this->assertNotNull($list, 'There should have been a document list created'); $this->assertNotNull($list, 'There should have been a document list created');
$this->assertTrue($list->hasItems, 'There should be items in the list'); $this->assertTrue($list->hasItems(), 'There should be items in the list');
$ignored = iterator_to_array($list->items); $ignored = iterator_to_array($list->items());
$this->assertFalse($list->hasItems, 'The list should no longer have items'); $this->assertFalse($list->hasItems(), 'The list should no longer have items');
$this->expectException(DocumentException::class); $this->expectException(DocumentException::class);
iterator_to_array($list->items); iterator_to_array($list->items());
} }
#[TestDox('hasItems succeeds with empty results')] #[TestDox('hasItems() succeeds with empty results')]
public function testHasItemsSucceedsWithEmptyResults(): void public function testHasItemsSucceedsWithEmptyResults(): void
{ {
$list = DocumentList::create( $list = DocumentList::create(
Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE (data->>'num_value')::numeric < 0", [], Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE (data->>'num_value')::numeric < 0", [],
new DocumentMapper(TestDocument::class)); new DocumentMapper(TestDocument::class));
$this->assertNotNull($list, 'There should have been a document list created'); $this->assertNotNull($list, 'There should have been a document list created');
$this->assertFalse($list->hasItems, 'There should be no items in the list'); $this->assertFalse($list->hasItems(), 'There should be no items in the list');
} }
#[TestDox('hasItems succeeds with non-empty results')] #[TestDox('hasItems() succeeds with non-empty results')]
public function testHasItemsSucceedsWithNonEmptyResults(): void public function testHasItemsSucceedsWithNonEmptyResults(): void
{ {
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [], $list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
new DocumentMapper(TestDocument::class)); new DocumentMapper(TestDocument::class));
$this->assertNotNull($list, 'There should have been a document list created'); $this->assertNotNull($list, 'There should have been a document list created');
$this->assertTrue($list->hasItems, 'There should be items in the list'); $this->assertTrue($list->hasItems(), 'There should be items in the list');
foreach ($list->items as $ignored) { foreach ($list->items() as $ignored) {
$this->assertTrue($list->hasItems, 'There should be items remaining in the list'); $this->assertTrue($list->hasItems(), 'There should be items remaining in the list');
} }
$this->assertFalse($list->hasItems, 'There should be no remaining items in the list'); $this->assertFalse($list->hasItems(), 'There should be no remaining items in the list');
} }
#[TestDox('map() succeeds')] #[TestDox('map() succeeds')]
@ -101,7 +101,7 @@ class DocumentListTest extends TestCase
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [], $list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
new DocumentMapper(TestDocument::class)); new DocumentMapper(TestDocument::class));
$this->assertNotNull($list, 'There should have been a document list created'); $this->assertNotNull($list, 'There should have been a document list created');
$this->assertTrue($list->hasItems, 'There should be items in the list'); $this->assertTrue($list->hasItems(), 'There should be items in the list');
foreach ($list->map(fn($doc) => strrev($doc->id)) as $mapped) { foreach ($list->map(fn($doc) => strrev($doc->id)) as $mapped) {
$this->assertContains($mapped, ['eno', 'owt', 'eerht', 'ruof', 'evif'], $this->assertContains($mapped, ['eno', 'owt', 'eerht', 'ruof', 'evif'],
'An unexpected mapped value was returned'); 'An unexpected mapped value was returned');
@ -114,7 +114,7 @@ class DocumentListTest extends TestCase
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [], $list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
new DocumentMapper(TestDocument::class)); new DocumentMapper(TestDocument::class));
$this->assertNotNull($list, 'There should have been a document list created'); $this->assertNotNull($list, 'There should have been a document list created');
$this->assertTrue($list->hasItems, 'There should be items in the list'); $this->assertTrue($list->hasItems(), 'There should be items in the list');
$splats = []; $splats = [];
$list->iter(function ($doc) use (&$splats) { $splats[] = str_repeat('*', strlen($doc->id)); }); $list->iter(function ($doc) use (&$splats) { $splats[] = str_repeat('*', strlen($doc->id)); });
$this->assertEquals('*** *** ***** **** ****', implode(' ', $splats), $this->assertEquals('*** *** ***** **** ****', implode(' ', $splats),
@ -127,7 +127,7 @@ class DocumentListTest extends TestCase
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [], $list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
new DocumentMapper(TestDocument::class)); new DocumentMapper(TestDocument::class));
$this->assertNotNull($list, 'There should have been a document list created'); $this->assertNotNull($list, 'There should have been a document list created');
$this->assertTrue($list->hasItems, 'There should be items in the list'); $this->assertTrue($list->hasItems(), 'There should be items in the list');
$lookup = $list->mapToArray(fn($it) => $it->id, fn($it) => $it->value); $lookup = $list->mapToArray(fn($it) => $it->id, fn($it) => $it->value);
$expected = ['one' => 'FIRST!', 'two' => 'another', 'three' => '', 'four' => 'purple', 'five' => 'purple']; $expected = ['one' => 'FIRST!', 'two' => 'another', 'three' => '', 'four' => 'purple', 'five' => 'purple'];
$this->assertEquals($expected, $lookup, 'The array was not mapped correctly'); $this->assertEquals($expected, $lookup, 'The array was not mapped correctly');

View File

@ -40,8 +40,8 @@ class DocumentTest extends TestCase
{ {
Document::insert(ThrowawayDb::TABLE, ['id' => 'turkey', 'sub' => ['foo' => 'gobble', 'bar' => 'gobble']]); Document::insert(ThrowawayDb::TABLE, ['id' => 'turkey', 'sub' => ['foo' => 'gobble', 'bar' => 'gobble']]);
$tryDoc = Find::byId(ThrowawayDb::TABLE, 'turkey', TestDocument::class); $tryDoc = Find::byId(ThrowawayDb::TABLE, 'turkey', TestDocument::class);
$this->assertTrue($tryDoc->isSome, 'There should have been a document inserted'); $this->assertTrue($tryDoc->isSome(), 'There should have been a document inserted');
$doc = $tryDoc->value; $doc = $tryDoc->get();
$this->assertEquals('turkey', $doc->id, 'The ID was incorrect'); $this->assertEquals('turkey', $doc->id, 'The ID was incorrect');
$this->assertEquals('', $doc->value, 'The value was incorrect'); $this->assertEquals('', $doc->value, 'The value was incorrect');
$this->assertEquals(0, $doc->num_value, 'The numeric value was incorrect'); $this->assertEquals(0, $doc->num_value, 'The numeric value was incorrect');
@ -59,15 +59,15 @@ class DocumentTest extends TestCase
Document::insert(ThrowawayDb::TABLE, ['id' => 0, 'value' => 'new', 'num_value' => 8]); Document::insert(ThrowawayDb::TABLE, ['id' => 0, 'value' => 'new', 'num_value' => 8]);
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE, [], new ArrayMapper()); $doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE, [], new ArrayMapper());
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$obj = json_decode($doc->value['data']); $obj = json_decode($doc->get()['data']);
$this->assertEquals(1, $obj->id, 'The ID 1 should have been auto-generated'); $this->assertEquals(1, $obj->id, 'The ID 1 should have been auto-generated');
Document::insert(ThrowawayDb::TABLE, ['id' => 0, 'value' => 'again', 'num_value' => 7]); Document::insert(ThrowawayDb::TABLE, ['id' => 0, 'value' => 'again', 'num_value' => 7]);
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE " . Query::whereById(docId: 2), $doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE " . Query::whereById(docId: 2),
[':id' => 2], new ArrayMapper()); [':id' => 2], new ArrayMapper());
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$obj = json_decode($doc->value['data']); $obj = json_decode($doc->get()['data']);
$this->assertEquals(2, $obj->id, 'The ID 2 should have been auto-generated'); $this->assertEquals(2, $obj->id, 'The ID 2 should have been auto-generated');
} finally { } finally {
Configuration::$autoId = AutoId::None; Configuration::$autoId = AutoId::None;
@ -82,8 +82,8 @@ class DocumentTest extends TestCase
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []); Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
Document::insert(ThrowawayDb::TABLE, ['id' => 7, 'value' => 'new', 'num_value' => 8]); Document::insert(ThrowawayDb::TABLE, ['id' => 7, 'value' => 'new', 'num_value' => 8]);
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE, [], new ArrayMapper()); $doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE, [], new ArrayMapper());
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$obj = json_decode($doc->value['data']); $obj = json_decode($doc->get()['data']);
$this->assertEquals(7, $obj->id, 'The ID 7 should have been stored'); $this->assertEquals(7, $obj->id, 'The ID 7 should have been stored');
} finally { } finally {
Configuration::$autoId = AutoId::None; Configuration::$autoId = AutoId::None;
@ -98,8 +98,8 @@ class DocumentTest extends TestCase
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []); Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
Document::insert(ThrowawayDb::TABLE, ['id' => '', 'num_value' => 5]); Document::insert(ThrowawayDb::TABLE, ['id' => '', 'num_value' => 5]);
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 5)], TestDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 5)], TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertNotEmpty($doc->value->id, 'The ID should have been auto-generated'); $this->assertNotEmpty($doc->get()->id, 'The ID should have been auto-generated');
} finally { } finally {
Configuration::$autoId = AutoId::None; Configuration::$autoId = AutoId::None;
} }
@ -114,8 +114,8 @@ class DocumentTest extends TestCase
$uuid = AutoId::generateUUID(); $uuid = AutoId::generateUUID();
Document::insert(ThrowawayDb::TABLE, ['id' => $uuid, 'value' => 'uuid', 'num_value' => 12]); Document::insert(ThrowawayDb::TABLE, ['id' => $uuid, 'value' => 'uuid', 'num_value' => 12]);
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 12)], TestDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 12)], TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals($uuid, $doc->value->id, 'The ID should not have been changed'); $this->assertEquals($uuid, $doc->get()->id, 'The ID should not have been changed');
} finally { } finally {
Configuration::$autoId = AutoId::None; Configuration::$autoId = AutoId::None;
} }
@ -130,8 +130,8 @@ class DocumentTest extends TestCase
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []); Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
Document::insert(ThrowawayDb::TABLE, ['id' => '', 'value' => 'new', 'num_value' => 8]); Document::insert(ThrowawayDb::TABLE, ['id' => '', 'value' => 'new', 'num_value' => 8]);
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 8)], TestDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 8)], TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals(6, strlen($doc->value->id), $this->assertEquals(6, strlen($doc->get()->id),
'The ID should have been auto-generated and had 6 characters'); 'The ID should have been auto-generated and had 6 characters');
} finally { } finally {
Configuration::$autoId = AutoId::None; Configuration::$autoId = AutoId::None;
@ -147,8 +147,8 @@ class DocumentTest extends TestCase
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []); Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
Document::insert(ThrowawayDb::TABLE, ['id' => 'my-key', 'value' => 'old', 'num_value' => 3]); Document::insert(ThrowawayDb::TABLE, ['id' => 'my-key', 'value' => 'old', 'num_value' => 3]);
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 3)], TestDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 3)], TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals('my-key', $doc->value->id, 'The ID should not have been changed'); $this->assertEquals('my-key', $doc->get()->id, 'The ID should not have been changed');
} finally { } finally {
Configuration::$autoId = AutoId::None; Configuration::$autoId = AutoId::None;
} }
@ -159,8 +159,8 @@ class DocumentTest extends TestCase
{ {
Document::insert(ThrowawayDb::TABLE, new TestDocument('turkey', sub: new SubDocument('gobble', 'gobble'))); Document::insert(ThrowawayDb::TABLE, new TestDocument('turkey', sub: new SubDocument('gobble', 'gobble')));
$tryDoc = Find::byId(ThrowawayDb::TABLE, 'turkey', TestDocument::class); $tryDoc = Find::byId(ThrowawayDb::TABLE, 'turkey', TestDocument::class);
$this->assertTrue($tryDoc->isSome, 'There should have been a document inserted'); $this->assertTrue($tryDoc->isSome(), 'There should have been a document inserted');
$doc = $tryDoc->value; $doc = $tryDoc->get();
$this->assertEquals('turkey', $doc->id, 'The ID was incorrect'); $this->assertEquals('turkey', $doc->id, 'The ID was incorrect');
$this->assertEquals('', $doc->value, 'The value was incorrect'); $this->assertEquals('', $doc->value, 'The value was incorrect');
$this->assertEquals(0, $doc->num_value, 'The numeric value was incorrect'); $this->assertEquals(0, $doc->num_value, 'The numeric value was incorrect');
@ -178,13 +178,13 @@ class DocumentTest extends TestCase
Document::insert(ThrowawayDb::TABLE, new NumDocument(value: 'taco')); Document::insert(ThrowawayDb::TABLE, new NumDocument(value: 'taco'));
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'taco')], NumDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'taco')], NumDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals(1, $doc->value->id, 'The ID 1 should have been auto-generated'); $this->assertEquals(1, $doc->get()->id, 'The ID 1 should have been auto-generated');
Document::insert(ThrowawayDb::TABLE, new NumDocument(value: 'burrito')); Document::insert(ThrowawayDb::TABLE, new NumDocument(value: 'burrito'));
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'burrito')], NumDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'burrito')], NumDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals(2, $doc->value->id, 'The ID 2 should have been auto-generated'); $this->assertEquals(2, $doc->get()->id, 'The ID 2 should have been auto-generated');
} finally { } finally {
Configuration::$autoId = AutoId::None; Configuration::$autoId = AutoId::None;
} }
@ -198,8 +198,8 @@ class DocumentTest extends TestCase
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []); Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
Document::insert(ThrowawayDb::TABLE, new NumDocument(64, 'large')); Document::insert(ThrowawayDb::TABLE, new NumDocument(64, 'large'));
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'large')], NumDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'large')], NumDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals(64, $doc->value->id, 'The ID 64 should have been stored'); $this->assertEquals(64, $doc->get()->id, 'The ID 64 should have been stored');
} finally { } finally {
Configuration::$autoId = AutoId::None; Configuration::$autoId = AutoId::None;
} }
@ -213,8 +213,8 @@ class DocumentTest extends TestCase
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []); Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
Document::insert(ThrowawayDb::TABLE, new TestDocument(value: 'something', num_value: 9)); Document::insert(ThrowawayDb::TABLE, new TestDocument(value: 'something', num_value: 9));
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::exists('value')], TestDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::exists('value')], TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertNotEmpty($doc->value->id, 'The ID should have been auto-generated'); $this->assertNotEmpty($doc->get()->id, 'The ID should have been auto-generated');
} finally { } finally {
Configuration::$autoId = AutoId::None; Configuration::$autoId = AutoId::None;
} }
@ -229,8 +229,8 @@ class DocumentTest extends TestCase
$uuid = AutoId::generateUUID(); $uuid = AutoId::generateUUID();
Document::insert(ThrowawayDb::TABLE, new TestDocument($uuid, num_value: 14)); Document::insert(ThrowawayDb::TABLE, new TestDocument($uuid, num_value: 14));
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 14)], TestDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 14)], TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals($uuid, $doc->value->id, 'The ID should not have been changed'); $this->assertEquals($uuid, $doc->get()->id, 'The ID should not have been changed');
} finally { } finally {
Configuration::$autoId = AutoId::None; Configuration::$autoId = AutoId::None;
} }
@ -245,8 +245,8 @@ class DocumentTest extends TestCase
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []); Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
Document::insert(ThrowawayDb::TABLE, new TestDocument(num_value: 55)); Document::insert(ThrowawayDb::TABLE, new TestDocument(num_value: 55));
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 55)], TestDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 55)], TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals(40, strlen($doc->value->id), $this->assertEquals(40, strlen($doc->get()->id),
'The ID should have been auto-generated and had 40 characters'); 'The ID should have been auto-generated and had 40 characters');
} finally { } finally {
Configuration::$autoId = AutoId::None; Configuration::$autoId = AutoId::None;
@ -262,8 +262,8 @@ class DocumentTest extends TestCase
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []); Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
Document::insert(ThrowawayDb::TABLE, new TestDocument('my-key', num_value: 3)); Document::insert(ThrowawayDb::TABLE, new TestDocument('my-key', num_value: 3));
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 3)], TestDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 3)], TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals('my-key', $doc->value->id, 'The ID should not have been changed'); $this->assertEquals('my-key', $doc->get()->id, 'The ID should not have been changed');
} finally { } finally {
Configuration::$autoId = AutoId::None; Configuration::$autoId = AutoId::None;
} }
@ -281,7 +281,7 @@ class DocumentTest extends TestCase
{ {
Document::save(ThrowawayDb::TABLE, new TestDocument('test', sub: new SubDocument('a', 'b'))); Document::save(ThrowawayDb::TABLE, new TestDocument('test', sub: new SubDocument('a', 'b')));
$doc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class); $doc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
} }
#[TestDox('save() succeeds when a document is updated')] #[TestDox('save() succeeds when a document is updated')]
@ -289,8 +289,8 @@ class DocumentTest extends TestCase
{ {
Document::save(ThrowawayDb::TABLE, new TestDocument('two', num_value: 44)); Document::save(ThrowawayDb::TABLE, new TestDocument('two', num_value: 44));
$tryDoc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class); $tryDoc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class);
$this->assertTrue($tryDoc->isSome, 'There should have been a document returned'); $this->assertTrue($tryDoc->isSome(), 'There should have been a document returned');
$doc = $tryDoc->value; $doc = $tryDoc->get();
$this->assertEquals(44, $doc->num_value, 'The numeric value was not updated'); $this->assertEquals(44, $doc->num_value, 'The numeric value was not updated');
$this->assertNull($doc->sub, 'The sub-document should have been null'); $this->assertNull($doc->sub, 'The sub-document should have been null');
} }
@ -300,8 +300,8 @@ class DocumentTest extends TestCase
{ {
Document::update(ThrowawayDb::TABLE, 'one', new TestDocument('one', 'howdy', 8, new SubDocument('y', 'z'))); Document::update(ThrowawayDb::TABLE, 'one', new TestDocument('one', 'howdy', 8, new SubDocument('y', 'z')));
$tryDoc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class); $tryDoc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class);
$this->assertNotFalse($tryDoc->isSome, 'There should have been a document returned'); $this->assertNotFalse($tryDoc->isSome(), 'There should have been a document returned');
$doc = $tryDoc->value; $doc = $tryDoc->get();
$this->assertEquals('howdy', $doc->value, 'The value was incorrect'); $this->assertEquals('howdy', $doc->value, 'The value was incorrect');
$this->assertEquals(8, $doc->num_value, 'The numeric value was incorrect'); $this->assertEquals(8, $doc->num_value, 'The numeric value was incorrect');
$this->assertNotNull($doc->sub, 'The sub-document should not have been null'); $this->assertNotNull($doc->sub, 'The sub-document should not have been null');
@ -314,6 +314,6 @@ class DocumentTest extends TestCase
{ {
Document::update(ThrowawayDb::TABLE, 'two-hundred', new TestDocument('200')); Document::update(ThrowawayDb::TABLE, 'two-hundred', new TestDocument('200'));
$doc = Find::byId(ThrowawayDb::TABLE, 'two-hundred', TestDocument::class); $doc = Find::byId(ThrowawayDb::TABLE, 'two-hundred', TestDocument::class);
$this->assertTrue($doc->isNone, 'There should not have been a document returned'); $this->assertTrue($doc->isNone(), 'There should not have been a document returned');
} }
} }

View File

@ -39,9 +39,8 @@ class FindTest extends TestCase
{ {
$docs = Find::all(ThrowawayDb::TABLE, TestDocument::class); $docs = Find::all(ThrowawayDb::TABLE, TestDocument::class);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
$count = 0; $count = 0;
foreach ($docs->items as $ignored) $count++; foreach ($docs->items() as $ignored) $count++;
$this->assertEquals(5, $count, 'There should have been 5 documents in the list'); $this->assertEquals(5, $count, 'There should have been 5 documents in the list');
} }
@ -50,7 +49,6 @@ class FindTest extends TestCase
{ {
$docs = Find::all(ThrowawayDb::TABLE, TestDocument::class, [Field::named('id')]); $docs = Find::all(ThrowawayDb::TABLE, TestDocument::class, [Field::named('id')]);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
$ids = iterator_to_array($docs->map(fn ($it) => $it->id), false); $ids = iterator_to_array($docs->map(fn ($it) => $it->id), false);
$this->assertEquals(['five', 'four', 'one', 'three', 'two'], $ids, 'The documents were not ordered correctly'); $this->assertEquals(['five', 'four', 'one', 'three', 'two'], $ids, 'The documents were not ordered correctly');
} }
@ -60,7 +58,6 @@ class FindTest extends TestCase
{ {
$docs = Find::all(ThrowawayDb::TABLE, TestDocument::class, [Field::named('id DESC')]); $docs = Find::all(ThrowawayDb::TABLE, TestDocument::class, [Field::named('id DESC')]);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
$ids = iterator_to_array($docs->map(fn ($it) => $it->id), false); $ids = iterator_to_array($docs->map(fn ($it) => $it->id), false);
$this->assertEquals(['two', 'three', 'one', 'four', 'five'], $ids, 'The documents were not ordered correctly'); $this->assertEquals(['two', 'three', 'one', 'four', 'five'], $ids, 'The documents were not ordered correctly');
} }
@ -71,7 +68,6 @@ class FindTest extends TestCase
$docs = Find::all(ThrowawayDb::TABLE, TestDocument::class, $docs = Find::all(ThrowawayDb::TABLE, TestDocument::class,
[Field::named('sub.foo NULLS LAST'), Field::named('n:num_value')]); [Field::named('sub.foo NULLS LAST'), Field::named('n:num_value')]);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
$ids = iterator_to_array($docs->map(fn ($it) => $it->id), false); $ids = iterator_to_array($docs->map(fn ($it) => $it->id), false);
$this->assertEquals(['two', 'four', 'one', 'three', 'five'], $ids, 'The documents were not ordered correctly'); $this->assertEquals(['two', 'four', 'one', 'three', 'five'], $ids, 'The documents were not ordered correctly');
} }
@ -82,15 +78,15 @@ class FindTest extends TestCase
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []); Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
$docs = Find::all(ThrowawayDb::TABLE, TestDocument::class); $docs = Find::all(ThrowawayDb::TABLE, TestDocument::class);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertFalse($docs->hasItems, 'There should have been no documents in the list'); $this->assertFalse($docs->hasItems(), 'There should have been no documents in the list');
} }
#[TestDox('byId() succeeds when a document is found')] #[TestDox('byId() succeeds when a document is found')]
public function testByIdSucceedsWhenADocumentIsFound(): void public function testByIdSucceedsWhenADocumentIsFound(): void
{ {
$doc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class); $doc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals('two', $doc->value->id, 'An incorrect document was returned'); $this->assertEquals('two', $doc->get()->id, 'An incorrect document was returned');
} }
#[TestDox('byId() succeeds when a document is found with numeric ID')] #[TestDox('byId() succeeds when a document is found with numeric ID')]
@ -99,15 +95,15 @@ class FindTest extends TestCase
Delete::byFields(ThrowawayDb::TABLE, [Field::notExists('absent')]); Delete::byFields(ThrowawayDb::TABLE, [Field::notExists('absent')]);
Document::insert(ThrowawayDb::TABLE, ['id' => 18, 'value' => 'howdy']); Document::insert(ThrowawayDb::TABLE, ['id' => 18, 'value' => 'howdy']);
$doc = Find::byId(ThrowawayDb::TABLE, 18, NumDocument::class); $doc = Find::byId(ThrowawayDb::TABLE, 18, NumDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals(18, $doc->value->id, 'An incorrect document was returned'); $this->assertEquals(18, $doc->get()->id, 'An incorrect document was returned');
} }
#[TestDox('byId() succeeds when a document is not found')] #[TestDox('byId() succeeds when a document is not found')]
public function testByIdSucceedsWhenADocumentIsNotFound(): void public function testByIdSucceedsWhenADocumentIsNotFound(): void
{ {
$doc = Find::byId(ThrowawayDb::TABLE, 'seventy-five', TestDocument::class); $doc = Find::byId(ThrowawayDb::TABLE, 'seventy-five', TestDocument::class);
$this->assertTrue($doc->isNone, 'There should not have been a document returned'); $this->assertTrue($doc->isNone(), 'There should not have been a document returned');
} }
#[TestDox('byFields() succeeds when documents are found')] #[TestDox('byFields() succeeds when documents are found')]
@ -116,9 +112,8 @@ class FindTest extends TestCase
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::in('value', ['blue', 'purple']), Field::exists('sub')], $docs = Find::byFields(ThrowawayDb::TABLE, [Field::in('value', ['blue', 'purple']), Field::exists('sub')],
TestDocument::class, FieldMatch::All); TestDocument::class, FieldMatch::All);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
$count = 0; $count = 0;
foreach ($docs->items as $ignored) $count++; foreach ($docs->items() as $ignored) $count++;
$this->assertEquals(1, $count, 'There should have been 1 document in the list'); $this->assertEquals(1, $count, 'There should have been 1 document in the list');
} }
@ -128,7 +123,6 @@ class FindTest extends TestCase
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::equal('value', 'purple')], TestDocument::class, $docs = Find::byFields(ThrowawayDb::TABLE, [Field::equal('value', 'purple')], TestDocument::class,
FieldMatch::All, [Field::named('id')]); FieldMatch::All, [Field::named('id')]);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
$ids = iterator_to_array($docs->map(fn ($it) => $it->id), false); $ids = iterator_to_array($docs->map(fn ($it) => $it->id), false);
$this->assertEquals(['five', 'four'], $ids, 'The documents were not ordered correctly'); $this->assertEquals(['five', 'four'], $ids, 'The documents were not ordered correctly');
} }
@ -138,9 +132,8 @@ class FindTest extends TestCase
{ {
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::in('num_value', [2, 4, 6, 8])], TestDocument::class); $docs = Find::byFields(ThrowawayDb::TABLE, [Field::in('num_value', [2, 4, 6, 8])], TestDocument::class);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
$count = 0; $count = 0;
foreach ($docs->items as $ignored) $count++; foreach ($docs->items() as $ignored) $count++;
$this->assertEquals(1, $count, 'There should have been 1 document in the list'); $this->assertEquals(1, $count, 'There should have been 1 document in the list');
} }
@ -149,7 +142,7 @@ class FindTest extends TestCase
{ {
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::greater('num_value', 100)], TestDocument::class); $docs = Find::byFields(ThrowawayDb::TABLE, [Field::greater('num_value', 100)], TestDocument::class);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertFalse($docs->hasItems, 'There should have been no documents in the list'); $this->assertFalse($docs->hasItems(), 'There should have been no documents in the list');
} }
#[TestDox('byFields() succeeds for inArray when matching documents exist')] #[TestDox('byFields() succeeds for inArray when matching documents exist')]
@ -160,9 +153,8 @@ class FindTest extends TestCase
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::inArray('values', ThrowawayDb::TABLE, ['c'])], $docs = Find::byFields(ThrowawayDb::TABLE, [Field::inArray('values', ThrowawayDb::TABLE, ['c'])],
ArrayDocument::class); ArrayDocument::class);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
$count = 0; $count = 0;
foreach ($docs->items as $ignored) $count++; foreach ($docs->items() as $ignored) $count++;
$this->assertEquals(2, $count, 'There should have been 2 documents in the list'); $this->assertEquals(2, $count, 'There should have been 2 documents in the list');
} }
@ -174,7 +166,7 @@ class FindTest extends TestCase
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::inArray('values', ThrowawayDb::TABLE, ['j'])], $docs = Find::byFields(ThrowawayDb::TABLE, [Field::inArray('values', ThrowawayDb::TABLE, ['j'])],
ArrayDocument::class); ArrayDocument::class);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertFalse($docs->hasItems, 'There should have been no documents in the list'); $this->assertFalse($docs->hasItems(), 'There should have been no documents in the list');
} }
#[TestDox('byContains() succeeds when documents are found')] #[TestDox('byContains() succeeds when documents are found')]
@ -182,9 +174,8 @@ class FindTest extends TestCase
{ {
$docs = Find::byContains(ThrowawayDb::TABLE, ['value' => 'purple'], TestDocument::class); $docs = Find::byContains(ThrowawayDb::TABLE, ['value' => 'purple'], TestDocument::class);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
$count = 0; $count = 0;
foreach ($docs->items as $ignored) $count++; foreach ($docs->items() as $ignored) $count++;
$this->assertEquals(2, $count, 'There should have been 2 documents in the list'); $this->assertEquals(2, $count, 'There should have been 2 documents in the list');
} }
@ -194,7 +185,6 @@ class FindTest extends TestCase
$docs = Find::byContains(ThrowawayDb::TABLE, ['sub' => ['foo' => 'green']], TestDocument::class, $docs = Find::byContains(ThrowawayDb::TABLE, ['sub' => ['foo' => 'green']], TestDocument::class,
[Field::named('value')]); [Field::named('value')]);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
$ids = iterator_to_array($docs->map(fn ($it) => $it->id), false); $ids = iterator_to_array($docs->map(fn ($it) => $it->id), false);
$this->assertEquals(['two', 'four'], $ids, 'The documents were not ordered correctly'); $this->assertEquals(['two', 'four'], $ids, 'The documents were not ordered correctly');
} }
@ -204,7 +194,7 @@ class FindTest extends TestCase
{ {
$docs = Find::byContains(ThrowawayDb::TABLE, ['value' => 'indigo'], TestDocument::class); $docs = Find::byContains(ThrowawayDb::TABLE, ['value' => 'indigo'], TestDocument::class);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertFalse($docs->hasItems, 'The document list should be empty'); $this->assertFalse($docs->hasItems(), 'The document list should be empty');
} }
#[TestDox('byJsonPath() succeeds when documents are found')] #[TestDox('byJsonPath() succeeds when documents are found')]
@ -212,9 +202,8 @@ class FindTest extends TestCase
{ {
$docs = Find::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 10)', TestDocument::class); $docs = Find::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 10)', TestDocument::class);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
$count = 0; $count = 0;
foreach ($docs->items as $ignored) $count++; foreach ($docs->items() as $ignored) $count++;
$this->assertEquals(2, $count, 'There should have been 2 documents in the list'); $this->assertEquals(2, $count, 'There should have been 2 documents in the list');
} }
@ -224,7 +213,6 @@ class FindTest extends TestCase
$docs = Find::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 10)', TestDocument::class, $docs = Find::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 10)', TestDocument::class,
[Field::named('id')]); [Field::named('id')]);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
$ids = iterator_to_array($docs->map(fn ($it) => $it->id), false); $ids = iterator_to_array($docs->map(fn ($it) => $it->id), false);
$this->assertEquals(['five', 'four'], $ids, 'The documents were not ordered correctly'); $this->assertEquals(['five', 'four'], $ids, 'The documents were not ordered correctly');
} }
@ -234,23 +222,23 @@ class FindTest extends TestCase
{ {
$docs = Find::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 100)', TestDocument::class); $docs = Find::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 100)', TestDocument::class);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertFalse($docs->hasItems, 'The document list should be empty'); $this->assertFalse($docs->hasItems(), 'The document list should be empty');
} }
#[TestDox('firstByFields() succeeds when a document is found')] #[TestDox('firstByFields() succeeds when a document is found')]
public function testFirstByFieldsSucceedsWhenADocumentIsFound(): void public function testFirstByFieldsSucceedsWhenADocumentIsFound(): void
{ {
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'another')], TestDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'another')], TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals('two', $doc->value->id, 'The incorrect document was returned'); $this->assertEquals('two', $doc->get()->id, 'The incorrect document was returned');
} }
#[TestDox('firstByFields() succeeds when multiple documents are found')] #[TestDox('firstByFields() succeeds when multiple documents are found')]
public function testFirstByFieldsSucceedsWhenMultipleDocumentsAreFound(): void public function testFirstByFieldsSucceedsWhenMultipleDocumentsAreFound(): void
{ {
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('sub.foo', 'green')], TestDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('sub.foo', 'green')], TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertContains($doc->value->id, ['two', 'four'], 'An incorrect document was returned'); $this->assertContains($doc->get()->id, ['two', 'four'], 'An incorrect document was returned');
} }
#[TestDox('firstByFields() succeeds when multiple ordered documents are found')] #[TestDox('firstByFields() succeeds when multiple ordered documents are found')]
@ -258,31 +246,31 @@ class FindTest extends TestCase
{ {
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('sub.foo', 'green')], TestDocument::class, $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('sub.foo', 'green')], TestDocument::class,
orderBy: [Field::named('n:num_value DESC')]); orderBy: [Field::named('n:num_value DESC')]);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals('four', $doc->value->id, 'The incorrect document was returned'); $this->assertEquals('four', $doc->get()->id, 'The incorrect document was returned');
} }
#[TestDox('firstByFields() succeeds when a document is not found')] #[TestDox('firstByFields() succeeds when a document is not found')]
public function testFirstByFieldsSucceedsWhenADocumentIsNotFound(): void public function testFirstByFieldsSucceedsWhenADocumentIsNotFound(): void
{ {
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'absent')], TestDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'absent')], TestDocument::class);
$this->assertTrue($doc->isNone, 'There should not have been a document returned'); $this->assertTrue($doc->isNone(), 'There should not have been a document returned');
} }
#[TestDox('firstByContains() succeeds when a document is found')] #[TestDox('firstByContains() succeeds when a document is found')]
public function testFirstByContainsSucceedsWhenADocumentIsFound(): void public function testFirstByContainsSucceedsWhenADocumentIsFound(): void
{ {
$doc = Find::firstByContains(ThrowawayDb::TABLE, ['value' => 'FIRST!'], TestDocument::class); $doc = Find::firstByContains(ThrowawayDb::TABLE, ['value' => 'FIRST!'], TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals('one', $doc->value->id, 'The incorrect document was returned'); $this->assertEquals('one', $doc->get()->id, 'The incorrect document was returned');
} }
#[TestDox('firstByContains() succeeds when multiple documents are found')] #[TestDox('firstByContains() succeeds when multiple documents are found')]
public function testFirstByContainsSucceedsWhenMultipleDocumentsAreFound(): void public function testFirstByContainsSucceedsWhenMultipleDocumentsAreFound(): void
{ {
$doc = Find::firstByContains(ThrowawayDb::TABLE, ['value' => 'purple'], TestDocument::class); $doc = Find::firstByContains(ThrowawayDb::TABLE, ['value' => 'purple'], TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertContains($doc->value->id, ['four', 'five'], 'An incorrect document was returned'); $this->assertContains($doc->get()->id, ['four', 'five'], 'An incorrect document was returned');
} }
#[TestDox('firstByContains() succeeds when multiple ordered documents are found')] #[TestDox('firstByContains() succeeds when multiple ordered documents are found')]
@ -290,31 +278,31 @@ class FindTest extends TestCase
{ {
$doc = Find::firstByContains(ThrowawayDb::TABLE, ['value' => 'purple'], TestDocument::class, $doc = Find::firstByContains(ThrowawayDb::TABLE, ['value' => 'purple'], TestDocument::class,
[Field::named('sub.bar NULLS FIRST')]); [Field::named('sub.bar NULLS FIRST')]);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals('five', $doc->value->id, 'The incorrect document was returned'); $this->assertEquals('five', $doc->get()->id, 'The incorrect document was returned');
} }
#[TestDox('firstByContains() succeeds when a document is not found')] #[TestDox('firstByContains() succeeds when a document is not found')]
public function testFirstByContainsSucceedsWhenADocumentIsNotFound(): void public function testFirstByContainsSucceedsWhenADocumentIsNotFound(): void
{ {
$doc = Find::firstByContains(ThrowawayDb::TABLE, ['value' => 'indigo'], TestDocument::class); $doc = Find::firstByContains(ThrowawayDb::TABLE, ['value' => 'indigo'], TestDocument::class);
$this->assertTrue($doc->isNone, 'There should not have been a document returned'); $this->assertTrue($doc->isNone(), 'There should not have been a document returned');
} }
#[TestDox('firstByJsonPath() succeeds when a document is found')] #[TestDox('firstByJsonPath() succeeds when a document is found')]
public function testFirstByJsonPathSucceedsWhenADocumentIsFound(): void public function testFirstByJsonPathSucceedsWhenADocumentIsFound(): void
{ {
$doc = Find::firstByJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ == 10)', TestDocument::class); $doc = Find::firstByJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ == 10)', TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals('two', $doc->value->id, 'The incorrect document was returned'); $this->assertEquals('two', $doc->get()->id, 'The incorrect document was returned');
} }
#[TestDox('firstByJsonPath() succeeds when multiple documents are found')] #[TestDox('firstByJsonPath() succeeds when multiple documents are found')]
public function testFirstByJsonPathSucceedsWhenMultipleDocumentsAreFound(): void public function testFirstByJsonPathSucceedsWhenMultipleDocumentsAreFound(): void
{ {
$doc = Find::firstByJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 10)', TestDocument::class); $doc = Find::firstByJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 10)', TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertContains($doc->value->id, ['four', 'five'], 'An incorrect document was returned'); $this->assertContains($doc->get()->id, ['four', 'five'], 'An incorrect document was returned');
} }
#[TestDox('firstByJsonPath() succeeds when multiple ordered documents are found')] #[TestDox('firstByJsonPath() succeeds when multiple ordered documents are found')]
@ -322,14 +310,14 @@ class FindTest extends TestCase
{ {
$doc = Find::firstByJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 10)', TestDocument::class, $doc = Find::firstByJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 10)', TestDocument::class,
[Field::named('id DESC')]); [Field::named('id DESC')]);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals('four', $doc->value->id, 'The incorrect document was returned'); $this->assertEquals('four', $doc->get()->id, 'The incorrect document was returned');
} }
#[TestDox('firstByJsonPath() succeeds when a document is not found')] #[TestDox('firstByJsonPath() succeeds when a document is not found')]
public function testFirstByJsonPathSucceedsWhenADocumentIsNotFound(): void public function testFirstByJsonPathSucceedsWhenADocumentIsNotFound(): void
{ {
$doc = Find::firstByJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 100)', TestDocument::class); $doc = Find::firstByJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 100)', TestDocument::class);
$this->assertTrue($doc->isNone, 'There should not have been a document returned'); $this->assertTrue($doc->isNone(), 'There should not have been a document returned');
} }
} }

View File

@ -39,8 +39,8 @@ class PatchTest extends TestCase
{ {
Patch::byId(ThrowawayDb::TABLE, 'one', ['num_value' => 44]); Patch::byId(ThrowawayDb::TABLE, 'one', ['num_value' => 44]);
$doc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class); $doc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals(44, $doc->value->num_value, 'The updated document is not correct'); $this->assertEquals(44, $doc->get()->num_value, 'The updated document is not correct');
} }
#[TestDox('byId() succeeds when no document is updated')] #[TestDox('byId() succeeds when no document is updated')]
@ -74,8 +74,8 @@ class PatchTest extends TestCase
{ {
Patch::byContains(ThrowawayDb::TABLE, ['value' => 'another'], ['num_value' => 12]); Patch::byContains(ThrowawayDb::TABLE, ['value' => 'another'], ['num_value' => 12]);
$tryDoc = Find::firstByContains(ThrowawayDb::TABLE, ['value' => 'another'], TestDocument::class); $tryDoc = Find::firstByContains(ThrowawayDb::TABLE, ['value' => 'another'], TestDocument::class);
$this->assertTrue($tryDoc->isSome, 'There should have been a document returned'); $this->assertTrue($tryDoc->isSome(), 'There should have been a document returned');
$doc = $tryDoc->value; $doc = $tryDoc->get();
$this->assertEquals('two', $doc->id, 'An incorrect document was returned'); $this->assertEquals('two', $doc->id, 'An incorrect document was returned');
$this->assertEquals(12, $doc->num_value, 'The document was not patched'); $this->assertEquals(12, $doc->num_value, 'The document was not patched');
} }
@ -96,8 +96,8 @@ class PatchTest extends TestCase
Patch::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 10)', ['value' => 'blue']); Patch::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 10)', ['value' => 'blue']);
$docs = Find::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 10)', TestDocument::class); $docs = Find::byJsonPath(ThrowawayDb::TABLE, '$.num_value ? (@ > 10)', TestDocument::class);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertTrue($docs->hasItems, 'The document list should not be empty'); $this->assertTrue($docs->hasItems(), 'The document list should not be empty');
foreach ($docs->items as $item) { foreach ($docs->items() as $item) {
$this->assertContains($item->id, ['four', 'five'], 'An incorrect document was returned'); $this->assertContains($item->id, ['four', 'five'], 'An incorrect document was returned');
$this->assertEquals('blue', $item->value, 'The document was not patched'); $this->assertEquals('blue', $item->value, 'The document was not patched');
} }

View File

@ -39,8 +39,8 @@ class RemoveFieldsTest extends TestCase
{ {
RemoveFields::byId(ThrowawayDb::TABLE, 'two', ['sub', 'value']); RemoveFields::byId(ThrowawayDb::TABLE, 'two', ['sub', 'value']);
$tryDoc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class); $tryDoc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class);
$this->assertTrue($tryDoc->isSome, 'There should have been a document returned'); $this->assertTrue($tryDoc->isSome(), 'There should have been a document returned');
$doc = $tryDoc->value; $doc = $tryDoc->get();
$this->assertEquals('', $doc->value, 'Value should have been blank (its default value)'); $this->assertEquals('', $doc->value, 'Value should have been blank (its default value)');
$this->assertNull($doc->sub, 'Sub-document should have been null'); $this->assertNull($doc->sub, 'Sub-document should have been null');
} }
@ -64,8 +64,8 @@ class RemoveFieldsTest extends TestCase
{ {
RemoveFields::byFields(ThrowawayDb::TABLE, [Field::equal('num_value', 17)], ['sub']); RemoveFields::byFields(ThrowawayDb::TABLE, [Field::equal('num_value', 17)], ['sub']);
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 17)], TestDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 17)], TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertNull($doc->value->sub, 'Sub-document should have been null'); $this->assertNull($doc->get()->sub, 'Sub-document should have been null');
} }
#[TestDox('byFields() succeeds when a field is not removed')] #[TestDox('byFields() succeeds when a field is not removed')]
@ -89,8 +89,8 @@ class RemoveFieldsTest extends TestCase
RemoveFields::byContains(ThrowawayDb::TABLE, $criteria, ['value']); RemoveFields::byContains(ThrowawayDb::TABLE, $criteria, ['value']);
$docs = Find::byContains(ThrowawayDb::TABLE, $criteria, TestDocument::class); $docs = Find::byContains(ThrowawayDb::TABLE, $criteria, TestDocument::class);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertTrue($docs->hasItems, 'The document list should not have been empty'); $this->assertTrue($docs->hasItems(), 'The document list should not have been empty');
foreach ($docs->items as $item) { foreach ($docs->items() as $item) {
$this->assertContains($item->id, ['two', 'four'], 'An incorrect document was returned'); $this->assertContains($item->id, ['two', 'four'], 'An incorrect document was returned');
$this->assertEquals('', $item->value, 'The value field was not removed'); $this->assertEquals('', $item->value, 'The value field was not removed');
} }
@ -117,8 +117,8 @@ class RemoveFieldsTest extends TestCase
RemoveFields::byJsonPath(ThrowawayDb::TABLE, $path, ['sub']); RemoveFields::byJsonPath(ThrowawayDb::TABLE, $path, ['sub']);
$docs = Find::byJsonPath(ThrowawayDb::TABLE, $path, TestDocument::class); $docs = Find::byJsonPath(ThrowawayDb::TABLE, $path, TestDocument::class);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertTrue($docs->hasItems, 'The document list should not have been empty'); $this->assertTrue($docs->hasItems(), 'The document list should not have been empty');
foreach ($docs->items as $item) { foreach ($docs->items() as $item) {
$this->assertContains($item->id, ['four', 'five'], 'An incorrect document was returned'); $this->assertContains($item->id, ['four', 'five'], 'An incorrect document was returned');
$this->assertNull($item->sub, 'The sub field was not removed'); $this->assertNull($item->sub, 'The sub field was not removed');
} }

View File

@ -62,9 +62,8 @@ class CustomTest extends TestCase
{ {
$list = Custom::list(Query::selectFromTable(ThrowawayDb::TABLE), [], new DocumentMapper(TestDocument::class)); $list = Custom::list(Query::selectFromTable(ThrowawayDb::TABLE), [], new DocumentMapper(TestDocument::class));
$this->assertNotNull($list, 'The document list should not be null'); $this->assertNotNull($list, 'The document list should not be null');
$this->assertTrue($list->hasItems, 'There should have been documents in the list');
$count = 0; $count = 0;
foreach ($list->items as $ignored) $count++; foreach ($list->items() as $ignored) $count++;
$this->assertEquals(5, $count, 'There should have been 5 documents in the list'); $this->assertEquals(5, $count, 'There should have been 5 documents in the list');
} }
@ -74,7 +73,7 @@ class CustomTest extends TestCase
$list = Custom::list(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'num_value' > :value", $list = Custom::list(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'num_value' > :value",
[':value' => 100], new DocumentMapper(TestDocument::class)); [':value' => 100], new DocumentMapper(TestDocument::class));
$this->assertNotNull($list, 'The document list should not be null'); $this->assertNotNull($list, 'The document list should not be null');
$this->assertFalse($list->hasItems, 'There should have been no documents in the list'); $this->assertFalse($list->hasItems(), 'There should have been no documents in the list');
} }
#[TestDox('array() succeeds when data is found')] #[TestDox('array() succeeds when data is found')]
@ -100,8 +99,8 @@ class CustomTest extends TestCase
{ {
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id", [':id' => 'one'], $doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id", [':id' => 'one'],
new DocumentMapper(TestDocument::class)); new DocumentMapper(TestDocument::class));
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals('one', $doc->value->id, 'The incorrect document was returned'); $this->assertEquals('one', $doc->get()->id, 'The incorrect document was returned');
} }
#[TestDox('single() succeeds when a row is not found')] #[TestDox('single() succeeds when a row is not found')]
@ -109,7 +108,7 @@ class CustomTest extends TestCase
{ {
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id", $doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id",
[':id' => 'eighty'], new DocumentMapper(TestDocument::class)); [':id' => 'eighty'], new DocumentMapper(TestDocument::class));
$this->assertTrue($doc->isNone, 'There should not have been a document returned'); $this->assertTrue($doc->isNone(), 'There should not have been a document returned');
} }
#[TestDox('nonQuery() succeeds when operating on data')] #[TestDox('nonQuery() succeeds when operating on data')]

View File

@ -44,14 +44,14 @@ class DocumentListTest extends TestCase
$list = null; $list = null;
} }
#[TestDox('items succeeds')] #[TestDox('items() succeeds')]
public function testItemsSucceeds(): void public function testItemsSucceeds(): void
{ {
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [], $list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
new DocumentMapper(TestDocument::class)); new DocumentMapper(TestDocument::class));
$this->assertNotNull($list, 'There should have been a document list created'); $this->assertNotNull($list, 'There should have been a document list created');
$count = 0; $count = 0;
foreach ($list->items as $item) { foreach ($list->items() as $item) {
$this->assertContains($item->id, ['one', 'two', 'three', 'four', 'five'], $this->assertContains($item->id, ['one', 'two', 'three', 'four', 'five'],
'An unexpected document ID was returned'); 'An unexpected document ID was returned');
$count++; $count++;
@ -59,39 +59,39 @@ class DocumentListTest extends TestCase
$this->assertEquals(5, $count, 'There should have been 5 documents returned'); $this->assertEquals(5, $count, 'There should have been 5 documents returned');
} }
#[TestDox('items fails when already consumed')] #[TestDox('items() fails when already consumed')]
public function testItemsFailsWhenAlreadyConsumed(): void public function testItemsFailsWhenAlreadyConsumed(): void
{ {
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [], $list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
new DocumentMapper(TestDocument::class)); new DocumentMapper(TestDocument::class));
$this->assertNotNull($list, 'There should have been a document list created'); $this->assertNotNull($list, 'There should have been a document list created');
$this->assertTrue($list->hasItems, 'There should be items in the list'); $this->assertTrue($list->hasItems(), 'There should be items in the list');
$ignored = iterator_to_array($list->items); $ignored = iterator_to_array($list->items());
$this->assertFalse($list->hasItems, 'The list should no longer have items'); $this->assertFalse($list->hasItems(), 'The list should no longer have items');
$this->expectException(DocumentException::class); $this->expectException(DocumentException::class);
iterator_to_array($list->items); iterator_to_array($list->items());
} }
#[TestDox('hasItems succeeds with empty results')] #[TestDox('hasItems() succeeds with empty results')]
public function testHasItemsSucceedsWithEmptyResults(): void public function testHasItemsSucceedsWithEmptyResults(): void
{ {
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'num_value' < 0", [], $list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'num_value' < 0", [],
new DocumentMapper(TestDocument::class)); new DocumentMapper(TestDocument::class));
$this->assertNotNull($list, 'There should have been a document list created'); $this->assertNotNull($list, 'There should have been a document list created');
$this->assertFalse($list->hasItems, 'There should be no items in the list'); $this->assertFalse($list->hasItems(), 'There should be no items in the list');
} }
#[TestDox('hasItems succeeds with non-empty results')] #[TestDox('hasItems() succeeds with non-empty results')]
public function testHasItemsSucceedsWithNonEmptyResults(): void public function testHasItemsSucceedsWithNonEmptyResults(): void
{ {
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [], $list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
new DocumentMapper(TestDocument::class)); new DocumentMapper(TestDocument::class));
$this->assertNotNull($list, 'There should have been a document list created'); $this->assertNotNull($list, 'There should have been a document list created');
$this->assertTrue($list->hasItems, 'There should be items in the list'); $this->assertTrue($list->hasItems(), 'There should be items in the list');
foreach ($list->items as $ignored) { foreach ($list->items() as $ignored) {
$this->assertTrue($list->hasItems, 'There should be items remaining in the list'); $this->assertTrue($list->hasItems(), 'There should be items remaining in the list');
} }
$this->assertFalse($list->hasItems, 'There should be no remaining items in the list'); $this->assertFalse($list->hasItems(), 'There should be no remaining items in the list');
} }
#[TestDox('map() succeeds')] #[TestDox('map() succeeds')]
@ -100,7 +100,7 @@ class DocumentListTest extends TestCase
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [], $list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
new DocumentMapper(TestDocument::class)); new DocumentMapper(TestDocument::class));
$this->assertNotNull($list, 'There should have been a document list created'); $this->assertNotNull($list, 'There should have been a document list created');
$this->assertTrue($list->hasItems, 'There should be items in the list'); $this->assertTrue($list->hasItems(), 'There should be items in the list');
foreach ($list->map(fn($doc) => strrev($doc->id)) as $mapped) { foreach ($list->map(fn($doc) => strrev($doc->id)) as $mapped) {
$this->assertContains($mapped, ['eno', 'owt', 'eerht', 'ruof', 'evif'], $this->assertContains($mapped, ['eno', 'owt', 'eerht', 'ruof', 'evif'],
'An unexpected mapped value was returned'); 'An unexpected mapped value was returned');
@ -113,7 +113,7 @@ class DocumentListTest extends TestCase
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [], $list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
new DocumentMapper(TestDocument::class)); new DocumentMapper(TestDocument::class));
$this->assertNotNull($list, 'There should have been a document list created'); $this->assertNotNull($list, 'There should have been a document list created');
$this->assertTrue($list->hasItems, 'There should be items in the list'); $this->assertTrue($list->hasItems(), 'There should be items in the list');
$splats = []; $splats = [];
$list->iter(function ($doc) use (&$splats) { $splats[] = str_repeat('*', strlen($doc->id)); }); $list->iter(function ($doc) use (&$splats) { $splats[] = str_repeat('*', strlen($doc->id)); });
$this->assertEquals('*** *** ***** **** ****', implode(' ', $splats), $this->assertEquals('*** *** ***** **** ****', implode(' ', $splats),
@ -126,7 +126,7 @@ class DocumentListTest extends TestCase
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [], $list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
new DocumentMapper(TestDocument::class)); new DocumentMapper(TestDocument::class));
$this->assertNotNull($list, 'There should have been a document list created'); $this->assertNotNull($list, 'There should have been a document list created');
$this->assertTrue($list->hasItems, 'There should be items in the list'); $this->assertTrue($list->hasItems(), 'There should be items in the list');
$lookup = $list->mapToArray(fn($it) => $it->id, fn($it) => $it->value); $lookup = $list->mapToArray(fn($it) => $it->id, fn($it) => $it->value);
$expected = ['one' => 'FIRST!', 'two' => 'another', 'three' => '', 'four' => 'purple', 'five' => 'purple']; $expected = ['one' => 'FIRST!', 'two' => 'another', 'three' => '', 'four' => 'purple', 'five' => 'purple'];
$this->assertEquals($expected, $lookup, 'The array was not mapped correctly'); $this->assertEquals($expected, $lookup, 'The array was not mapped correctly');

View File

@ -40,8 +40,8 @@ class DocumentTest extends TestCase
{ {
Document::insert(ThrowawayDb::TABLE, ['id' => 'turkey', 'sub' => ['foo' => 'gobble', 'bar' => 'gobble']]); Document::insert(ThrowawayDb::TABLE, ['id' => 'turkey', 'sub' => ['foo' => 'gobble', 'bar' => 'gobble']]);
$tryDoc = Find::byId(ThrowawayDb::TABLE, 'turkey', TestDocument::class); $tryDoc = Find::byId(ThrowawayDb::TABLE, 'turkey', TestDocument::class);
$this->assertTrue($tryDoc->isSome, 'There should have been a document inserted'); $this->assertTrue($tryDoc->isSome(), 'There should have been a document inserted');
$doc = $tryDoc->value; $doc = $tryDoc->get();
$this->assertEquals('turkey', $doc->id, 'The ID was incorrect'); $this->assertEquals('turkey', $doc->id, 'The ID was incorrect');
$this->assertEquals('', $doc->value, 'The value was incorrect'); $this->assertEquals('', $doc->value, 'The value was incorrect');
$this->assertEquals(0, $doc->num_value, 'The numeric value was incorrect'); $this->assertEquals(0, $doc->num_value, 'The numeric value was incorrect');
@ -59,15 +59,15 @@ class DocumentTest extends TestCase
Document::insert(ThrowawayDb::TABLE, ['id' => 0, 'value' => 'new', 'num_value' => 8]); Document::insert(ThrowawayDb::TABLE, ['id' => 0, 'value' => 'new', 'num_value' => 8]);
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE, [], new ArrayMapper()); $doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE, [], new ArrayMapper());
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$obj = json_decode($doc->value['data']); $obj = json_decode($doc->get()['data']);
$this->assertEquals(1, $obj->id, 'The ID 1 should have been auto-generated'); $this->assertEquals(1, $obj->id, 'The ID 1 should have been auto-generated');
Document::insert(ThrowawayDb::TABLE, ['id' => 0, 'value' => 'again', 'num_value' => 7]); Document::insert(ThrowawayDb::TABLE, ['id' => 0, 'value' => 'again', 'num_value' => 7]);
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = 2", [], $doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = 2", [],
new ArrayMapper()); new ArrayMapper());
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$obj = json_decode($doc->value['data']); $obj = json_decode($doc->get()['data']);
$this->assertEquals(2, $obj->id, 'The ID 2 should have been auto-generated'); $this->assertEquals(2, $obj->id, 'The ID 2 should have been auto-generated');
} finally { } finally {
Configuration::$autoId = AutoId::None; Configuration::$autoId = AutoId::None;
@ -82,8 +82,8 @@ class DocumentTest extends TestCase
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []); Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
Document::insert(ThrowawayDb::TABLE, ['id' => 7, 'value' => 'new', 'num_value' => 8]); Document::insert(ThrowawayDb::TABLE, ['id' => 7, 'value' => 'new', 'num_value' => 8]);
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE, [], new ArrayMapper()); $doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE, [], new ArrayMapper());
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$obj = json_decode($doc->value['data']); $obj = json_decode($doc->get()['data']);
$this->assertEquals(7, $obj->id, 'The ID 7 should have been stored'); $this->assertEquals(7, $obj->id, 'The ID 7 should have been stored');
} finally { } finally {
Configuration::$autoId = AutoId::None; Configuration::$autoId = AutoId::None;
@ -98,8 +98,8 @@ class DocumentTest extends TestCase
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []); Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
Document::insert(ThrowawayDb::TABLE, ['id' => '', 'num_value' => 5]); Document::insert(ThrowawayDb::TABLE, ['id' => '', 'num_value' => 5]);
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 5)], TestDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 5)], TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertNotEmpty($doc->value->id, 'The ID should have been auto-generated'); $this->assertNotEmpty($doc->get()->id, 'The ID should have been auto-generated');
} finally { } finally {
Configuration::$autoId = AutoId::None; Configuration::$autoId = AutoId::None;
} }
@ -114,8 +114,8 @@ class DocumentTest extends TestCase
$uuid = AutoId::generateUUID(); $uuid = AutoId::generateUUID();
Document::insert(ThrowawayDb::TABLE, ['id' => $uuid, 'value' => 'uuid', 'num_value' => 12]); Document::insert(ThrowawayDb::TABLE, ['id' => $uuid, 'value' => 'uuid', 'num_value' => 12]);
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 12)], TestDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 12)], TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals($uuid, $doc->value->id, 'The ID should not have been changed'); $this->assertEquals($uuid, $doc->get()->id, 'The ID should not have been changed');
} finally { } finally {
Configuration::$autoId = AutoId::None; Configuration::$autoId = AutoId::None;
} }
@ -130,8 +130,8 @@ class DocumentTest extends TestCase
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []); Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
Document::insert(ThrowawayDb::TABLE, ['id' => '', 'value' => 'new', 'num_value' => 8]); Document::insert(ThrowawayDb::TABLE, ['id' => '', 'value' => 'new', 'num_value' => 8]);
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 8)], TestDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 8)], TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals(6, strlen($doc->value->id), $this->assertEquals(6, strlen($doc->get()->id),
'The ID should have been auto-generated and had 6 characters'); 'The ID should have been auto-generated and had 6 characters');
} finally { } finally {
Configuration::$autoId = AutoId::None; Configuration::$autoId = AutoId::None;
@ -147,8 +147,8 @@ class DocumentTest extends TestCase
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []); Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
Document::insert(ThrowawayDb::TABLE, ['id' => 'my-key', 'value' => 'old', 'num_value' => 3]); Document::insert(ThrowawayDb::TABLE, ['id' => 'my-key', 'value' => 'old', 'num_value' => 3]);
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 3)], TestDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 3)], TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals('my-key', $doc->value->id, 'The ID should not have been changed'); $this->assertEquals('my-key', $doc->get()->id, 'The ID should not have been changed');
} finally { } finally {
Configuration::$autoId = AutoId::None; Configuration::$autoId = AutoId::None;
} }
@ -159,8 +159,8 @@ class DocumentTest extends TestCase
{ {
Document::insert(ThrowawayDb::TABLE, new TestDocument('turkey', sub: new SubDocument('gobble', 'gobble'))); Document::insert(ThrowawayDb::TABLE, new TestDocument('turkey', sub: new SubDocument('gobble', 'gobble')));
$tryDoc = Find::byId(ThrowawayDb::TABLE, 'turkey', TestDocument::class); $tryDoc = Find::byId(ThrowawayDb::TABLE, 'turkey', TestDocument::class);
$this->assertNotFalse($tryDoc->isSome, 'There should have been a document inserted'); $this->assertNotFalse($tryDoc->isSome(), 'There should have been a document inserted');
$doc = $tryDoc->value; $doc = $tryDoc->get();
$this->assertEquals('turkey', $doc->id, 'The ID was incorrect'); $this->assertEquals('turkey', $doc->id, 'The ID was incorrect');
$this->assertEquals('', $doc->value, 'The value was incorrect'); $this->assertEquals('', $doc->value, 'The value was incorrect');
$this->assertEquals(0, $doc->num_value, 'The numeric value was incorrect'); $this->assertEquals(0, $doc->num_value, 'The numeric value was incorrect');
@ -178,13 +178,13 @@ class DocumentTest extends TestCase
Document::insert(ThrowawayDb::TABLE, new NumDocument(value: 'taco')); Document::insert(ThrowawayDb::TABLE, new NumDocument(value: 'taco'));
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'taco')], NumDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'taco')], NumDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals(1, $doc->value->id, 'The ID 1 should have been auto-generated'); $this->assertEquals(1, $doc->get()->id, 'The ID 1 should have been auto-generated');
Document::insert(ThrowawayDb::TABLE, new NumDocument(value: 'burrito')); Document::insert(ThrowawayDb::TABLE, new NumDocument(value: 'burrito'));
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'burrito')], NumDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'burrito')], NumDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals(2, $doc->value->id, 'The ID 2 should have been auto-generated'); $this->assertEquals(2, $doc->get()->id, 'The ID 2 should have been auto-generated');
} finally { } finally {
Configuration::$autoId = AutoId::None; Configuration::$autoId = AutoId::None;
} }
@ -198,8 +198,8 @@ class DocumentTest extends TestCase
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []); Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
Document::insert(ThrowawayDb::TABLE, new NumDocument(64, 'large')); Document::insert(ThrowawayDb::TABLE, new NumDocument(64, 'large'));
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'large')], NumDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'large')], NumDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals(64, $doc->value->id, 'The ID 64 should have been stored'); $this->assertEquals(64, $doc->get()->id, 'The ID 64 should have been stored');
} finally { } finally {
Configuration::$autoId = AutoId::None; Configuration::$autoId = AutoId::None;
} }
@ -213,8 +213,8 @@ class DocumentTest extends TestCase
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []); Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
Document::insert(ThrowawayDb::TABLE, new TestDocument(value: 'something', num_value: 9)); Document::insert(ThrowawayDb::TABLE, new TestDocument(value: 'something', num_value: 9));
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::exists('value')], TestDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::exists('value')], TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertNotEmpty($doc->value->id, 'The ID should have been auto-generated'); $this->assertNotEmpty($doc->get()->id, 'The ID should have been auto-generated');
} finally { } finally {
Configuration::$autoId = AutoId::None; Configuration::$autoId = AutoId::None;
} }
@ -229,8 +229,8 @@ class DocumentTest extends TestCase
$uuid = AutoId::generateUUID(); $uuid = AutoId::generateUUID();
Document::insert(ThrowawayDb::TABLE, new TestDocument($uuid, num_value: 14)); Document::insert(ThrowawayDb::TABLE, new TestDocument($uuid, num_value: 14));
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 14)], TestDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 14)], TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals($uuid, $doc->value->id, 'The ID should not have been changed'); $this->assertEquals($uuid, $doc->get()->id, 'The ID should not have been changed');
} finally { } finally {
Configuration::$autoId = AutoId::None; Configuration::$autoId = AutoId::None;
} }
@ -245,8 +245,8 @@ class DocumentTest extends TestCase
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []); Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
Document::insert(ThrowawayDb::TABLE, new TestDocument(num_value: 55)); Document::insert(ThrowawayDb::TABLE, new TestDocument(num_value: 55));
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 55)], TestDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 55)], TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals(40, strlen($doc->value->id), $this->assertEquals(40, strlen($doc->get()->id),
'The ID should have been auto-generated and had 40 characters'); 'The ID should have been auto-generated and had 40 characters');
} finally { } finally {
Configuration::$autoId = AutoId::None; Configuration::$autoId = AutoId::None;
@ -262,8 +262,8 @@ class DocumentTest extends TestCase
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []); Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
Document::insert(ThrowawayDb::TABLE, new TestDocument('my-key', num_value: 3)); Document::insert(ThrowawayDb::TABLE, new TestDocument('my-key', num_value: 3));
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 3)], TestDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 3)], TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals('my-key', $doc->value->id, 'The ID should not have been changed'); $this->assertEquals('my-key', $doc->get()->id, 'The ID should not have been changed');
} finally { } finally {
Configuration::$autoId = AutoId::None; Configuration::$autoId = AutoId::None;
} }
@ -281,7 +281,7 @@ class DocumentTest extends TestCase
{ {
Document::save(ThrowawayDb::TABLE, new TestDocument('test', sub: new SubDocument('a', 'b'))); Document::save(ThrowawayDb::TABLE, new TestDocument('test', sub: new SubDocument('a', 'b')));
$doc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class); $doc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
} }
#[TestDox('save() succeeds when a document is updated')] #[TestDox('save() succeeds when a document is updated')]
@ -289,8 +289,8 @@ class DocumentTest extends TestCase
{ {
Document::save(ThrowawayDb::TABLE, new TestDocument('two', num_value: 44)); Document::save(ThrowawayDb::TABLE, new TestDocument('two', num_value: 44));
$tryDoc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class); $tryDoc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class);
$this->assertTrue($tryDoc->isSome, 'There should have been a document returned'); $this->assertTrue($tryDoc->isSome(), 'There should have been a document returned');
$doc = $tryDoc->value; $doc = $tryDoc->get();
$this->assertEquals(44, $doc->num_value, 'The numeric value was not updated'); $this->assertEquals(44, $doc->num_value, 'The numeric value was not updated');
$this->assertNull($doc->sub, 'The sub-document should have been null'); $this->assertNull($doc->sub, 'The sub-document should have been null');
} }
@ -300,8 +300,8 @@ class DocumentTest extends TestCase
{ {
Document::update(ThrowawayDb::TABLE, 'one', new TestDocument('one', 'howdy', 8, new SubDocument('y', 'z'))); Document::update(ThrowawayDb::TABLE, 'one', new TestDocument('one', 'howdy', 8, new SubDocument('y', 'z')));
$tryDoc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class); $tryDoc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class);
$this->assertTrue($tryDoc->isSome, 'There should have been a document returned'); $this->assertTrue($tryDoc->isSome(), 'There should have been a document returned');
$doc = $tryDoc->value; $doc = $tryDoc->get();
$this->assertEquals('howdy', $doc->value, 'The value was incorrect'); $this->assertEquals('howdy', $doc->value, 'The value was incorrect');
$this->assertEquals(8, $doc->num_value, 'The numeric value was incorrect'); $this->assertEquals(8, $doc->num_value, 'The numeric value was incorrect');
$this->assertNotNull($doc->sub, 'The sub-document should not have been null'); $this->assertNotNull($doc->sub, 'The sub-document should not have been null');
@ -314,6 +314,6 @@ class DocumentTest extends TestCase
{ {
Document::update(ThrowawayDb::TABLE, 'two-hundred', new TestDocument('200')); Document::update(ThrowawayDb::TABLE, 'two-hundred', new TestDocument('200'));
$doc = Find::byId(ThrowawayDb::TABLE, 'two-hundred', TestDocument::class); $doc = Find::byId(ThrowawayDb::TABLE, 'two-hundred', TestDocument::class);
$this->assertTrue($doc->isNone, 'There should not have been a document returned'); $this->assertTrue($doc->isNone(), 'There should not have been a document returned');
} }
} }

View File

@ -40,9 +40,8 @@ class FindTest extends TestCase
{ {
$docs = Find::all(ThrowawayDb::TABLE, TestDocument::class); $docs = Find::all(ThrowawayDb::TABLE, TestDocument::class);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
$count = 0; $count = 0;
foreach ($docs->items as $ignored) $count++; foreach ($docs->items() as $ignored) $count++;
$this->assertEquals(5, $count, 'There should have been 5 documents in the list'); $this->assertEquals(5, $count, 'There should have been 5 documents in the list');
} }
@ -51,7 +50,6 @@ class FindTest extends TestCase
{ {
$docs = Find::all(ThrowawayDb::TABLE, TestDocument::class, [Field::named('id')]); $docs = Find::all(ThrowawayDb::TABLE, TestDocument::class, [Field::named('id')]);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
$ids = iterator_to_array($docs->map(fn ($it) => $it->id), false); $ids = iterator_to_array($docs->map(fn ($it) => $it->id), false);
$this->assertEquals(['five', 'four', 'one', 'three', 'two'], $ids, 'The documents were not ordered correctly'); $this->assertEquals(['five', 'four', 'one', 'three', 'two'], $ids, 'The documents were not ordered correctly');
} }
@ -61,7 +59,6 @@ class FindTest extends TestCase
{ {
$docs = Find::all(ThrowawayDb::TABLE, TestDocument::class, [Field::named('id DESC')]); $docs = Find::all(ThrowawayDb::TABLE, TestDocument::class, [Field::named('id DESC')]);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
$ids = iterator_to_array($docs->map(fn ($it) => $it->id), false); $ids = iterator_to_array($docs->map(fn ($it) => $it->id), false);
$this->assertEquals(['two', 'three', 'one', 'four', 'five'], $ids, 'The documents were not ordered correctly'); $this->assertEquals(['two', 'three', 'one', 'four', 'five'], $ids, 'The documents were not ordered correctly');
} }
@ -72,7 +69,6 @@ class FindTest extends TestCase
$docs = Find::all(ThrowawayDb::TABLE, TestDocument::class, $docs = Find::all(ThrowawayDb::TABLE, TestDocument::class,
[Field::named('sub.foo NULLS LAST'), Field::named('n:num_value')]); [Field::named('sub.foo NULLS LAST'), Field::named('n:num_value')]);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
$ids = iterator_to_array($docs->map(fn ($it) => $it->id), false); $ids = iterator_to_array($docs->map(fn ($it) => $it->id), false);
$this->assertEquals(['two', 'four', 'one', 'three', 'five'], $ids, 'The documents were not ordered correctly'); $this->assertEquals(['two', 'four', 'one', 'three', 'five'], $ids, 'The documents were not ordered correctly');
} }
@ -83,15 +79,15 @@ class FindTest extends TestCase
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []); Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
$docs = Find::all(ThrowawayDb::TABLE, TestDocument::class); $docs = Find::all(ThrowawayDb::TABLE, TestDocument::class);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertFalse($docs->hasItems, 'There should have been no documents in the list'); $this->assertFalse($docs->hasItems(), 'There should have been no documents in the list');
} }
#[TestDox('byId() succeeds when a document is found')] #[TestDox('byId() succeeds when a document is found')]
public function testByIdSucceedsWhenADocumentIsFound(): void public function testByIdSucceedsWhenADocumentIsFound(): void
{ {
$doc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class); $doc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals('two', $doc->value->id, 'An incorrect document was returned'); $this->assertEquals('two', $doc->get()->id, 'An incorrect document was returned');
} }
#[TestDox('byId() succeeds when a document is found with numeric ID')] #[TestDox('byId() succeeds when a document is found with numeric ID')]
@ -99,15 +95,15 @@ class FindTest extends TestCase
{ {
Document::insert(ThrowawayDb::TABLE, ['id' => 18, 'value' => 'howdy']); Document::insert(ThrowawayDb::TABLE, ['id' => 18, 'value' => 'howdy']);
$doc = Find::byId(ThrowawayDb::TABLE, 18, TestDocument::class); $doc = Find::byId(ThrowawayDb::TABLE, 18, TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals('18', $doc->value->id, 'An incorrect document was returned'); $this->assertEquals('18', $doc->get()->id, 'An incorrect document was returned');
} }
#[TestDox('byId() succeeds when a document is not found')] #[TestDox('byId() succeeds when a document is not found')]
public function testByIdSucceedsWhenADocumentIsNotFound(): void public function testByIdSucceedsWhenADocumentIsNotFound(): void
{ {
$doc = Find::byId(ThrowawayDb::TABLE, 'seventy-five', TestDocument::class); $doc = Find::byId(ThrowawayDb::TABLE, 'seventy-five', TestDocument::class);
$this->assertTrue($doc->isNone, 'There should not have been a document returned'); $this->assertTrue($doc->isNone(), 'There should not have been a document returned');
} }
#[TestDox('byFields() succeeds when documents are found')] #[TestDox('byFields() succeeds when documents are found')]
@ -116,9 +112,8 @@ class FindTest extends TestCase
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::in('value', ['blue', 'purple']), Field::exists('sub')], $docs = Find::byFields(ThrowawayDb::TABLE, [Field::in('value', ['blue', 'purple']), Field::exists('sub')],
TestDocument::class, FieldMatch::All); TestDocument::class, FieldMatch::All);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
$count = 0; $count = 0;
foreach ($docs->items as $ignored) $count++; foreach ($docs->items() as $ignored) $count++;
$this->assertEquals(1, $count, 'There should have been 1 document in the list'); $this->assertEquals(1, $count, 'There should have been 1 document in the list');
} }
@ -128,7 +123,6 @@ class FindTest extends TestCase
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::equal('value', 'purple')], TestDocument::class, $docs = Find::byFields(ThrowawayDb::TABLE, [Field::equal('value', 'purple')], TestDocument::class,
FieldMatch::All, [Field::named('id')]); FieldMatch::All, [Field::named('id')]);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
$ids = iterator_to_array($docs->map(fn ($it) => $it->id), false); $ids = iterator_to_array($docs->map(fn ($it) => $it->id), false);
$this->assertEquals(['five', 'four'], $ids, 'The documents were not ordered correctly'); $this->assertEquals(['five', 'four'], $ids, 'The documents were not ordered correctly');
} }
@ -138,9 +132,8 @@ class FindTest extends TestCase
{ {
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::in('num_value', [2, 4, 6, 8])], TestDocument::class); $docs = Find::byFields(ThrowawayDb::TABLE, [Field::in('num_value', [2, 4, 6, 8])], TestDocument::class);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
$count = 0; $count = 0;
foreach ($docs->items as $ignored) $count++; foreach ($docs->items() as $ignored) $count++;
$this->assertEquals(1, $count, 'There should have been 1 document in the list'); $this->assertEquals(1, $count, 'There should have been 1 document in the list');
} }
@ -149,7 +142,7 @@ class FindTest extends TestCase
{ {
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::greater('num_value', 100)], TestDocument::class); $docs = Find::byFields(ThrowawayDb::TABLE, [Field::greater('num_value', 100)], TestDocument::class);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertFalse($docs->hasItems, 'There should have been no documents in the list'); $this->assertFalse($docs->hasItems(), 'There should have been no documents in the list');
} }
#[TestDox('byFields() succeeds for inArray when matching documents exist')] #[TestDox('byFields() succeeds for inArray when matching documents exist')]
@ -160,9 +153,8 @@ class FindTest extends TestCase
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::inArray('values', ThrowawayDb::TABLE, ['c'])], $docs = Find::byFields(ThrowawayDb::TABLE, [Field::inArray('values', ThrowawayDb::TABLE, ['c'])],
ArrayDocument::class); ArrayDocument::class);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertTrue($docs->hasItems, 'There should have been documents in the list');
$count = 0; $count = 0;
foreach ($docs->items as $ignored) $count++; foreach ($docs->items() as $ignored) $count++;
$this->assertEquals(2, $count, 'There should have been 2 documents in the list'); $this->assertEquals(2, $count, 'There should have been 2 documents in the list');
} }
@ -174,7 +166,7 @@ class FindTest extends TestCase
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::inArray('values', ThrowawayDb::TABLE, ['j'])], $docs = Find::byFields(ThrowawayDb::TABLE, [Field::inArray('values', ThrowawayDb::TABLE, ['j'])],
ArrayDocument::class); ArrayDocument::class);
$this->assertNotNull($docs, 'There should have been a document list returned'); $this->assertNotNull($docs, 'There should have been a document list returned');
$this->assertFalse($docs->hasItems, 'There should have been no documents in the list'); $this->assertFalse($docs->hasItems(), 'There should have been no documents in the list');
} }
#[TestDox('byContains() fails')] #[TestDox('byContains() fails')]
@ -195,16 +187,16 @@ class FindTest extends TestCase
public function testFirstByFieldsSucceedsWhenADocumentIsFound(): void public function testFirstByFieldsSucceedsWhenADocumentIsFound(): void
{ {
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'another')], TestDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'another')], TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals('two', $doc->value->id, 'The incorrect document was returned'); $this->assertEquals('two', $doc->get()->id, 'The incorrect document was returned');
} }
#[TestDox('firstByFields() succeeds when multiple documents are found')] #[TestDox('firstByFields() succeeds when multiple documents are found')]
public function testFirstByFieldsSucceedsWhenMultipleDocumentsAreFound(): void public function testFirstByFieldsSucceedsWhenMultipleDocumentsAreFound(): void
{ {
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('sub.foo', 'green')], TestDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('sub.foo', 'green')], TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertContains($doc->value->id, ['two', 'four'], 'An incorrect document was returned'); $this->assertContains($doc->get()->id, ['two', 'four'], 'An incorrect document was returned');
} }
#[TestDox('firstByFields() succeeds when multiple ordered documents are found')] #[TestDox('firstByFields() succeeds when multiple ordered documents are found')]
@ -212,15 +204,15 @@ class FindTest extends TestCase
{ {
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('sub.foo', 'green')], TestDocument::class, $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('sub.foo', 'green')], TestDocument::class,
orderBy: [Field::named('n:num_value DESC')]); orderBy: [Field::named('n:num_value DESC')]);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals('four', $doc->value->id, 'The incorrect document was returned'); $this->assertEquals('four', $doc->get()->id, 'The incorrect document was returned');
} }
#[TestDox('firstByFields() succeeds when a document is not found')] #[TestDox('firstByFields() succeeds when a document is not found')]
public function testFirstByFieldsSucceedsWhenADocumentIsNotFound(): void public function testFirstByFieldsSucceedsWhenADocumentIsNotFound(): void
{ {
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'absent')], TestDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('value', 'absent')], TestDocument::class);
$this->assertTrue($doc->isNone, 'There should not have been a document returned'); $this->assertTrue($doc->isNone(), 'There should not have been a document returned');
} }
#[TestDox('firstByContains() fails')] #[TestDox('firstByContains() fails')]

View File

@ -39,8 +39,8 @@ class PatchTest extends TestCase
{ {
Patch::byId(ThrowawayDb::TABLE, 'one', ['num_value' => 44]); Patch::byId(ThrowawayDb::TABLE, 'one', ['num_value' => 44]);
$doc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class); $doc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertEquals(44, $doc->value->num_value, 'The updated document is not correct'); $this->assertEquals(44, $doc->get()->num_value, 'The updated document is not correct');
} }
#[TestDox('byId() succeeds when no document is updated')] #[TestDox('byId() succeeds when no document is updated')]

View File

@ -39,8 +39,8 @@ class RemoveFieldsTest extends TestCase
{ {
RemoveFields::byId(ThrowawayDb::TABLE, 'two', ['sub', 'value']); RemoveFields::byId(ThrowawayDb::TABLE, 'two', ['sub', 'value']);
$tryDoc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class); $tryDoc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class);
$this->assertTrue($tryDoc->isSome, 'There should have been a document returned'); $this->assertTrue($tryDoc->isSome(), 'There should have been a document returned');
$doc = $tryDoc->value; $doc = $tryDoc->get();
$this->assertEquals('', $doc->value, 'Value should have been blank (its default value)'); $this->assertEquals('', $doc->value, 'Value should have been blank (its default value)');
$this->assertNull($doc->sub, 'Sub-document should have been null'); $this->assertNull($doc->sub, 'Sub-document should have been null');
} }
@ -64,8 +64,8 @@ class RemoveFieldsTest extends TestCase
{ {
RemoveFields::byFields(ThrowawayDb::TABLE, [Field::equal('num_value', 17)], ['sub']); RemoveFields::byFields(ThrowawayDb::TABLE, [Field::equal('num_value', 17)], ['sub']);
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 17)], TestDocument::class); $doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::equal('num_value', 17)], TestDocument::class);
$this->assertTrue($doc->isSome, 'There should have been a document returned'); $this->assertTrue($doc->isSome(), 'There should have been a document returned');
$this->assertNull($doc->value->sub, 'Sub-document should have been null'); $this->assertNull($doc->get()->sub, 'Sub-document should have been null');
} }
#[TestDox('byFields() succeeds when a field is not removed')] #[TestDox('byFields() succeeds when a field is not removed')]

View File

@ -1,58 +0,0 @@
<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
namespace Test\Unit;
use BitBadger\PDODocument\{AutoId, Configuration, DocumentException};
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
/**
* Unit tests for the Configuration class
*/
#[TestDox('Configuration (Unit tests)')]
class ConfigurationTest extends TestCase
{
#[TestDox('id default succeeds')]
public function testIdFieldDefaultSucceeds(): void
{
$this->assertEquals('id', Configuration::$idField, 'Default ID field should be "id"');
}
#[TestDox('id change succeeds')]
public function testIdFieldChangeSucceeds(): void
{
try {
Configuration::$idField = 'EyeDee';
$this->assertEquals('EyeDee', Configuration::$idField, 'ID field should have been updated');
} finally {
Configuration::$idField = 'id';
$this->assertEquals('id', Configuration::$idField, 'Default ID value should have been restored');
}
}
#[TestDox('autoId default succeeds')]
public function testAutoIdDefaultSucceeds(): void
{
$this->assertEquals(AutoId::None, Configuration::$autoId, 'Auto ID should default to None');
}
#[TestDox('idStringLength default succeeds')]
public function testIdStringLengthDefaultSucceeds(): void
{
$this->assertEquals(16, Configuration::$idStringLength, 'ID string length should default to 16');
}
#[TestDox("dbConn() fails when no DSN specified")]
public function testDbConnFailsWhenNoDSNSpecified(): void
{
$this->expectException(DocumentException::class);
Configuration::useDSN('');
Configuration::dbConn();
}
}

View File

@ -1,56 +0,0 @@
<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
namespace Test\Unit;
use BitBadger\PDODocument\DocumentException;
use Exception;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
/**
* Unit tests for the DocumentException class
*/
#[TestDox('Document Exception (Unit tests)')]
class DocumentExceptionTest extends TestCase
{
public function testConstructorSucceedsWithCodeAndPriorException(): void
{
$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(): void
{
$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');
}
#[TestDox('toString() succeeds without code')]
public function testToStringSucceedsWithoutCode(): void
{
$ex = new DocumentException('Test failure');
$this->assertEquals("BitBadger\PDODocument\DocumentException: Test failure\n", "$ex",
'toString not generated correctly');
}
#[TestDox('toString() succeeds with code')]
public function testToStringSucceedsWithCode(): void
{
$ex = new DocumentException('Oof', -6);
$this->assertEquals("BitBadger\PDODocument\DocumentException: [-6] Oof\n", "$ex",
'toString not generated correctly');
}
}

View File

@ -1,32 +0,0 @@
<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
namespace Test\Unit;
use BitBadger\PDODocument\FieldMatch;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
/**
* Unit tests for the FieldMatch enum
*/
#[TestDox('Field Match (Unit tests)')]
class FieldMatchTest extends TestCase
{
#[TestDox('toSQL() succeeds for All')]
public function testToSQLSucceedsForAll(): void
{
$this->assertEquals('AND', FieldMatch::All->toSQL(), 'All should have returned AND');
}
#[TestDox('toSQL() succeeds for Any')]
public function testToSQLSucceedsForAny(): void
{
$this->assertEquals('OR', FieldMatch::Any->toSQL(), 'Any should have returned OR');
}
}

View File

@ -1,683 +0,0 @@
<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
namespace Test\Unit;
use BitBadger\PDODocument\{Configuration, Field, Mode, Op};
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
/**
* Unit tests for the Field class
*/
#[TestDox('Field (Unit tests)')]
class FieldTest extends TestCase
{
#[TestDox('appendParameter() succeeds for exists')]
public function testAppendParameterSucceedsForExists(): void
{
$this->assertEquals([], Field::exists('exists')->appendParameter([]),
'exists should not have appended a parameter');
}
#[TestDox('appendParameter() succeeds for notExists')]
public function testAppendParameterSucceedsForNotExists(): void
{
$this->assertEquals([], Field::notExists('absent')->appendParameter([]),
'notExists should not have appended a parameter');
}
#[TestDox('appendParameter() succeeds for between')]
public function testAppendParameterSucceedsForBetween(): void
{
$this->assertEquals(['@nummin' => 5, '@nummax' => 9],
Field::between('exists', 5, 9, '@num')->appendParameter([]),
'Between should have appended min and max parameters');
}
#[TestDox('appendParameter() succeeds for in')]
public function testAppendParameterSucceedsForIn(): void
{
$this->assertEquals([':val_0' => 'test', ':val_1' => 'unit', ':val_2' => 'great'],
Field::in('it', ['test', 'unit', 'great'], ':val')->appendParameter([]),
'In should have appended 3 parameters for the input values');
}
#[TestDox('appendParameter() succeeds for inArray for PostgreSQL')]
public function testAppendParameterSucceedsForInArrayForPostgreSQL(): void
{
Configuration::overrideMode(Mode::PgSQL);
try {
$this->assertEquals([':bit_0' => '2', ':bit_1' => '8', ':bit_2' => '64'],
Field::inArray('it', 'table', [2, 8, 64], ':bit')->appendParameter([]),
'InArray should have appended 3 string parameters for the input values');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('appendParameter() succeeds for inArray for SQLite')]
public function testAppendParameterSucceedsForInArrayForSQLite(): void
{
Configuration::overrideMode(Mode::SQLite);
try {
$this->assertEquals([':bit_0' => 2, ':bit_1' => 8, ':bit_2' => 64],
Field::inArray('it', 'table', [2, 8, 64], ':bit')->appendParameter([]),
'InArray should have appended 3 parameters for the input values');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('appendParameter() succeeds for others')]
public function testAppendParameterSucceedsForOthers(): void
{
$this->assertEquals(['@test' => 33], Field::equal('the_field', 33, '@test')->appendParameter([]),
'Field parameter not returned correctly');
}
#[TestDox('path() succeeds for simple SQL path for PostgreSQL')]
public function testPathSucceedsForSimpleSqlPathForPostgreSQL(): void
{
Configuration::overrideMode(Mode::PgSQL);
try {
$this->assertEquals("data->>'it'", Field::equal('it', 'that')->path(),
'SQL value path not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('path() succeeds for simple SQL path for SQLite')]
public function testPathSucceedsForSimpleSqlPathForSQLite(): void
{
Configuration::overrideMode(Mode::SQLite);
try {
$this->assertEquals("data->>'top'", Field::equal('top', 'that')->path(),
'SQL value path not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('path() succeeds for nested SQL path for PostgreSQL')]
public function testPathSucceedsForNestedSqlPathForPostgreSQL(): void
{
Configuration::overrideMode(Mode::PgSQL);
try {
$this->assertEquals("data#>>'{parts,to,the,path}'", Field::equal('parts.to.the.path', '')->path(),
'SQL value path not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('path() succeeds for nested SQL path for SQLite')]
public function testPathSucceedsForNestedSqlPathForSQLite(): void
{
Configuration::overrideMode(Mode::SQLite);
try {
$this->assertEquals("data->'one'->'two'->>'three'", Field::equal('one.two.three', '')->path(),
'SQL value path not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('path() succeeds for simple JSON path for PostgreSQL')]
public function testPathSucceedsForSimpleJsonPathForPostgreSQL(): void
{
Configuration::overrideMode(Mode::PgSQL);
try {
$this->assertEquals("data->'it'", Field::equal('it', 'that')->path(true),
'JSON value path not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('path() succeeds for simple JSON path for SQLite')]
public function testPathSucceedsForSimpleJsonPathForSQLite(): void
{
Configuration::overrideMode(Mode::SQLite);
try {
$this->assertEquals("data->'top'", Field::equal('top', 'that')->path(true),
'JSON value path not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('path() succeeds for nested JSON path for PostgreSQL')]
public function testPathSucceedsForNestedJsonPathForPostgreSQL(): void
{
Configuration::overrideMode(Mode::PgSQL);
try {
$this->assertEquals("data#>'{parts,to,the,path}'", Field::equal('parts.to.the.path', '')->path(true),
'JSON value path not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('path() succeeds for nested JSON path for SQLite')]
public function testPathSucceedsForNestedJsonPathForSQLite(): void
{
Configuration::overrideMode(Mode::SQLite);
try {
$this->assertEquals("data->'one'->'two'->'three'", Field::equal('one.two.three', '')->path(true),
'SQL value path not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('toWhere() succeeds for exists without qualifier for PostgreSQL')]
public function testToWhereSucceedsForExistsWithoutQualifierForPostgreSQL(): void
{
Configuration::overrideMode(Mode::PgSQL);
try {
$this->assertEquals("data->>'that_field' IS NOT NULL", Field::exists('that_field')->toWhere(),
'WHERE fragment not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('toWhere() succeeds for exists without qualifier for SQLite')]
public function testToWhereSucceedsForExistsWithoutQualifierForSQLite(): void
{
Configuration::overrideMode(Mode::SQLite);
try {
$this->assertEquals("data->>'that_field' IS NOT NULL", Field::exists('that_field')->toWhere(),
'WHERE fragment not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('toWhere() succeeds for notExists without qualifier for PostgreSQL')]
public function testToWhereSucceedsForNotExistsWithoutQualifierForPostgreSQL(): void
{
Configuration::overrideMode(Mode::PgSQL);
try {
$this->assertEquals("data->>'a_field' IS NULL", Field::notExists('a_field')->toWhere(),
'WHERE fragment not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('toWhere() succeeds for notExists without qualifier for SQLite')]
public function testToWhereSucceedsForNotExistsWithoutQualifierForSQLite(): void
{
Configuration::overrideMode(Mode::SQLite);
try {
$this->assertEquals("data->>'a_field' IS NULL", Field::notExists('a_field')->toWhere(),
'WHERE fragment not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('toWhere() succeeds for between without qualifier for SQLite')]
public function testToWhereSucceedsForBetweenWithoutQualifierForSQLite(): void
{
Configuration::overrideMode(Mode::SQLite);
try {
$this->assertEquals("data->>'age' BETWEEN @agemin AND @agemax",
Field::between('age', 13, 17, '@age')->toWhere(), 'WHERE fragment not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('toWhere() succeeds for between without qualifier for PostgreSQL with numeric range')]
public function testToWhereSucceedsForBetweenWithoutQualifierForPostgreSQLWithNumericRange(): void
{
Configuration::overrideMode(Mode::PgSQL);
try {
$this->assertEquals("(data->>'age')::numeric BETWEEN @agemin AND @agemax",
Field::between('age', 13, 17, '@age')->toWhere(), 'WHERE fragment not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('toWhere() succeeds for between without qualifier for PostgreSQL with non-numeric range')]
public function testToWhereSucceedsForBetweenWithoutQualifierForPostgreSQLWithNonNumericRange(): void
{
Configuration::overrideMode(Mode::PgSQL);
try {
$this->assertEquals("data->>'city' BETWEEN :citymin AND :citymax",
Field::between('city', 'Atlanta', 'Chicago', ':city')->toWhere(),
'WHERE fragment not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('toWhere() succeeds for between with qualifier for SQLite')]
public function testToWhereSucceedsForBetweenWithQualifierForSQLite(): void
{
Configuration::overrideMode(Mode::SQLite);
try {
$field = Field::between('age', 13, 17, '@age');
$field->qualifier = 'me';
$this->assertEquals("me.data->>'age' BETWEEN @agemin AND @agemax", $field->toWhere(),
'WHERE fragment not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('toWhere() succeeds for between with qualifier for PostgreSQL with numeric range')]
public function testToWhereSucceedsForBetweenWithQualifierForPostgreSQLWithNumericRange(): void
{
Configuration::overrideMode(Mode::PgSQL);
try {
$field = Field::between('age', 13, 17, '@age');
$field->qualifier = 'me';
$this->assertEquals("(me.data->>'age')::numeric BETWEEN @agemin AND @agemax", $field->toWhere(),
'WHERE fragment not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('toWhere() succeeds for between with qualifier for PostgreSQL with non-numeric range')]
public function testToWhereSucceedsForBetweenWithQualifierForPostgreSQLWithNonNumericRange(): void
{
Configuration::overrideMode(Mode::PgSQL);
try {
$field = Field::between('city', 'Atlanta', 'Chicago', ':city');
$field->qualifier = 'me';
$this->assertEquals("me.data->>'city' BETWEEN :citymin AND :citymax", $field->toWhere(),
'WHERE fragment not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('toWhere() succeeds for in for PostgreSQL with non-numeric values')]
public function testToWhereSucceedsForInForPostgreSQLWithNonNumericValues(): void
{
Configuration::overrideMode(Mode::PgSQL);
try {
$field = Field::in('test', ['Atlanta', 'Chicago'], ':city');
$this->assertEquals("data->>'test' IN (:city_0, :city_1)", $field->toWhere(),
'WHERE fragment not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('toWhere() succeeds for in for PostgreSQL with numeric values')]
public function testToWhereSucceedsForInForPostgreSQLWithNumericValues(): void
{
Configuration::overrideMode(Mode::PgSQL);
try {
$field = Field::in('even', [2, 4, 6], ':nbr');
$this->assertEquals("(data->>'even')::numeric IN (:nbr_0, :nbr_1, :nbr_2)", $field->toWhere(),
'WHERE fragment not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('toWhere() succeeds for in for SQLite')]
public function testToWhereSucceedsForInForSQLite(): void
{
Configuration::overrideMode(Mode::SQLite);
try {
$field = Field::in('test', ['Atlanta', 'Chicago'], ':city');
$this->assertEquals("data->>'test' IN (:city_0, :city_1)", $field->toWhere(),
'WHERE fragment not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('toWhere() succeeds for inArray for PostgreSQL')]
public function testToWhereSucceedsForInArrayForPostgreSQL(): void
{
Configuration::overrideMode(Mode::PgSQL);
try {
$field = Field::inArray('even', 'tbl', [2, 4, 6, 8], ':it');
$this->assertEquals("data->'even' ??| ARRAY[:it_0, :it_1, :it_2, :it_3]", $field->toWhere(),
'WHERE fragment not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('toWhere() succeeds for inArray for SQLite')]
public function testToWhereSucceedsForInArrayForSQLite(): void
{
Configuration::overrideMode(Mode::SQLite);
try {
$field = Field::inArray('test', 'tbl', ['Atlanta', 'Chicago'], ':city');
$this->assertEquals(
"EXISTS (SELECT 1 FROM json_each(tbl.data, '\$.test') WHERE value IN (:city_0, :city_1))",
$field->toWhere(), 'WHERE fragment not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('toWhere() succeeds for others without qualifier for PostgreSQL')]
public function testToWhereSucceedsForOthersWithoutQualifierForPostgreSQL(): void
{
Configuration::overrideMode(Mode::PgSQL);
try {
$this->assertEquals("data->>'some_field' = @value", Field::equal('some_field', '', '@value')->toWhere(),
'WHERE fragment not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('toWhere() succeeds for others without qualifier for SQLite')]
public function testToWhereSucceedsForOthersWithoutQualifierForSQLite(): void
{
Configuration::overrideMode(Mode::SQLite);
try {
$this->assertEquals("data->>'some_field' = @value", Field::equal('some_field', '', '@value')->toWhere(),
'WHERE fragment not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('toWhere() succeeds with qualifier no parameter for PostgreSQL')]
public function testToWhereSucceedsWithQualifierNoParameterForPostgreSQL(): void
{
Configuration::overrideMode(Mode::PgSQL);
try {
$field = Field::exists('no_field');
$field->qualifier = 'test';
$this->assertEquals("test.data->>'no_field' IS NOT NULL", $field->toWhere(),
'WHERE fragment not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('toWhere() succeeds with qualifier no parameter for SQLite')]
public function testToWhereSucceedsWithQualifierNoParameterForSQLite(): void
{
Configuration::overrideMode(Mode::SQLite);
try {
$field = Field::exists('no_field');
$field->qualifier = 'test';
$this->assertEquals("test.data->>'no_field' IS NOT NULL", $field->toWhere(),
'WHERE fragment not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('toWhere() succeeds with qualifier and parameter for PostgreSQL')]
public function testToWhereSucceedsWithQualifierAndParameterForPostgreSQL(): void
{
Configuration::overrideMode(Mode::PgSQL);
try {
$field = Field::lessOrEqual('le_field', 18, '@it');
$field->qualifier = 'q';
$this->assertEquals("(q.data->>'le_field')::numeric <= @it", $field->toWhere(),
'WHERE fragment not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('toWhere() succeeds with qualifier and parameter for SQLite')]
public function testToWhereSucceedsWithQualifierAndParameterForSQLite(): void
{
Configuration::overrideMode(Mode::SQLite);
try {
$field = Field::lessOrEqual('le_field', 18, '@it');
$field->qualifier = 'q';
$this->assertEquals("q.data->>'le_field' <= @it", $field->toWhere(),
'WHERE fragment not generated correctly');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('equal() succeeds without parameter')]
public function testEqualSucceedsWithoutParameter(): void
{
$field = Field::equal('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::Equal, $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('equal() succeeds with parameter')]
public function testEqualSucceedsWithParameter(): void
{
$field = Field::equal('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::Equal, $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('greater() succeeds without parameter')]
public function testGreaterSucceedsWithoutParameter(): void
{
$field = Field::greater('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::Greater, $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('greater() succeeds with parameter')]
public function testGreaterSucceedsWithParameter(): void
{
$field = Field::greater('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::Greater, $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('greaterOrEqual() succeeds without parameter')]
public function testGreaterOrEqualSucceedsWithoutParameter(): void
{
$field = Field::greaterOrEqual('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::GreaterOrEqual, $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('greaterOrEqual() succeeds with parameter')]
public function testGreaterOrEqualSucceedsWithParameter(): void
{
$field = Field::greaterOrEqual('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::GreaterOrEqual, $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('less() succeeds without parameter')]
public function testLessSucceedsWithoutParameter(): void
{
$field = Field::less('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::Less, $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('less() succeeds with parameter')]
public function testLessSucceedsWithParameter(): void
{
$field = Field::less('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::Less, $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('lessOrEqual() succeeds without parameter')]
public function testLessOrEqualSucceedsWithoutParameter(): void
{
$field = Field::lessOrEqual('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::LessOrEqual, $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('lessOrEqual() succeeds with parameter')]
public function testLessOrEqualSucceedsWithParameter(): void
{
$field = Field::lessOrEqual('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::LessOrEqual, $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('notEqual() succeeds without parameter')]
public function testNotEqualSucceedsWithoutParameter(): void
{
$field = Field::notEqual('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::NotEqual, $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('notEqual() succeeds with parameter')]
public function testNotEqualSucceedsWithParameter(): void
{
$field = Field::notEqual('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::NotEqual, $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('between() succeeds without parameter')]
public function testBetweenSucceedsWithoutParameter(): void
{
$field = Field::between('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::Between, $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('between() succeeds with parameter')]
public function testBetweenSucceedsWithParameter(): void
{
$field = Field::between('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::Between, $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('in() succeeds without parameter')]
public function testInSucceedsWithoutParameter(): void
{
$field = Field::in('test', [1, 2, 3]);
$this->assertNotNull($field, 'The field should not have been null');
$this->assertEquals('test', $field->fieldName, 'Field name not filled correctly');
$this->assertEquals(Op::In, $field->op, 'Operation not filled correctly');
$this->assertEquals([1, 2, 3], $field->value, 'Value not filled correctly');
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
}
#[TestDox('in() succeeds with parameter')]
public function testInSucceedsWithParameter(): void
{
$field = Field::in('unit', ['a', 'b'], '@inParam');
$this->assertNotNull($field, 'The field should not have been null');
$this->assertEquals('unit', $field->fieldName, 'Field name not filled correctly');
$this->assertEquals(Op::In, $field->op, 'Operation not filled correctly');
$this->assertEquals(['a', 'b'], $field->value, 'Value not filled correctly');
$this->assertEquals('@inParam', $field->paramName, 'Parameter name not filled correctly');
}
#[TestDox('inArray() succeeds without parameter')]
public function testInArraySucceedsWithoutParameter(): void
{
$field = Field::inArray('test', 'tbl', [1, 2, 3]);
$this->assertNotNull($field, 'The field should not have been null');
$this->assertEquals('test', $field->fieldName, 'Field name not filled correctly');
$this->assertEquals(Op::InArray, $field->op, 'Operation not filled correctly');
$this->assertEquals(['table' => 'tbl', 'values' => [1, 2, 3]], $field->value, 'Value not filled correctly');
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
}
#[TestDox('inArray() succeeds with parameter')]
public function testInArraySucceedsWithParameter(): void
{
$field = Field::inArray('unit', 'tab', ['a', 'b'], '@inAParam');
$this->assertNotNull($field, 'The field should not have been null');
$this->assertEquals('unit', $field->fieldName, 'Field name not filled correctly');
$this->assertEquals(Op::InArray, $field->op, 'Operation not filled correctly');
$this->assertEquals(['table' => 'tab', 'values' => ['a', 'b']], $field->value, 'Value not filled correctly');
$this->assertEquals('@inAParam', $field->paramName, 'Parameter name not filled correctly');
}
#[TestDox('exists() succeeds')]
public function testExistsSucceeds(): void
{
$field = Field::exists('be_there');
$this->assertNotNull($field, 'The field should not have been null');
$this->assertEquals('be_there', $field->fieldName, 'Field name not filled correctly');
$this->assertEquals(Op::Exists, $field->op, 'Operation not filled correctly');
$this->assertEquals('', $field->value, 'Value should have been blank');
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
}
#[TestDox('notExists() succeeds')]
public function testNotExistsSucceeds(): void
{
$field = Field::notExists('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::NotExists, $field->op, 'Operation not filled correctly');
$this->assertEquals('', $field->value, 'Value should have been blank');
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
}
#[TestDox('named() succeeds')]
public function testNamedSucceeds(): void
{
$field = Field::named('the_field');
$this->assertNotNull($field, 'The field should not have been null');
$this->assertEquals('the_field', $field->fieldName, 'Field name not filled correctly');
$this->assertEquals(Op::Equal, $field->op, 'Operation not filled correctly');
$this->assertEquals('', $field->value, 'Value should have been blank');
$this->assertEquals('', $field->paramName, 'Parameter name should have been blank');
}
}

View File

@ -22,7 +22,7 @@ class ArrayMapperTest extends TestCase
public function testMapSucceeds(): void public function testMapSucceeds(): void
{ {
$result = ['one' => 2, 'three' => 4, 'eight' => 'five']; $result = ['one' => 2, 'three' => 4, 'eight' => 'five'];
$mapped = new ArrayMapper()->map($result); $mapped = (new ArrayMapper())->map($result);
$this->assertSame($result, $mapped, 'The array mapper should return the parameter given to it'); $this->assertSame($result, $mapped, 'The array mapper should return the parameter given to it');
} }
} }

View File

@ -21,6 +21,6 @@ class CountMapperTest extends TestCase
#[TestDox('map() succeeds')] #[TestDox('map() succeeds')]
public function testMapSucceeds(): void public function testMapSucceeds(): void
{ {
$this->assertEquals(5, new CountMapper()->map([5, 8, 10]), 'Count not correct'); $this->assertEquals(5, (new CountMapper())->map([5, 8, 10]), 'Count not correct');
} }
} }

View File

@ -47,7 +47,7 @@ class DocumentMapperTest extends TestCase
#[TestDox('map() succeeds with valid JSON')] #[TestDox('map() succeeds with valid JSON')]
public function testMapSucceedsWithValidJSON(): void public function testMapSucceedsWithValidJSON(): void
{ {
$doc = new DocumentMapper(TestDocument::class)->map(['data' => '{"id":7,"subDoc":{"id":22,"name":"tester"}}']); $doc = (new DocumentMapper(TestDocument::class))->map(['data' => '{"id":7,"subDoc":{"id":22,"name":"tester"}}']);
$this->assertNotNull($doc, 'The document should not have been null'); $this->assertNotNull($doc, 'The document should not have been null');
$this->assertEquals(7, $doc->id, 'ID not filled correctly'); $this->assertEquals(7, $doc->id, 'ID not filled correctly');
$this->assertNotNull($doc->subDoc, 'The sub-document should not have been null'); $this->assertNotNull($doc->subDoc, 'The sub-document should not have been null');
@ -58,7 +58,7 @@ class DocumentMapperTest extends TestCase
#[TestDox('map() succeeds with valid JSON for Pjson class')] #[TestDox('map() succeeds with valid JSON for Pjson class')]
public function testMapSucceedsWithValidJSONForPjsonClass(): void public function testMapSucceedsWithValidJSONForPjsonClass(): void
{ {
$doc = new DocumentMapper(PjsonDocument::class)->map(['data' => '{"id":"seven","name":"bob","num_value":8}']); $doc = (new DocumentMapper(PjsonDocument::class))->map(['data' => '{"id":"seven","name":"bob","num_value":8}']);
$this->assertNotNull($doc, 'The document should not have been null'); $this->assertNotNull($doc, 'The document should not have been null');
$this->assertEquals(new PjsonId('seven'), $doc->id, 'ID not filled correctly'); $this->assertEquals(new PjsonId('seven'), $doc->id, 'ID not filled correctly');
$this->assertEquals('bob', $doc->name, 'Name not filled correctly'); $this->assertEquals('bob', $doc->name, 'Name not filled correctly');
@ -70,13 +70,13 @@ class DocumentMapperTest extends TestCase
public function testMapFailsWithInvalidJSON(): void public function testMapFailsWithInvalidJSON(): void
{ {
$this->expectException(DocumentException::class); $this->expectException(DocumentException::class);
new DocumentMapper(TestDocument::class)->map(['data' => 'this is not valid']); (new DocumentMapper(TestDocument::class))->map(['data' => 'this is not valid']);
} }
#[TestDox('map() fails with invalid JSON for Pjson class')] #[TestDox('map() fails with invalid JSON for Pjson class')]
public function testMapFailsWithInvalidJSONForPjsonClass(): void public function testMapFailsWithInvalidJSONForPjsonClass(): void
{ {
$this->expectException(DocumentException::class); $this->expectException(DocumentException::class);
new DocumentMapper(PjsonDocument::class)->map(['data' => 'not even close']); (new DocumentMapper(PjsonDocument::class))->map(['data' => 'not even close']);
} }
} }

View File

@ -24,7 +24,7 @@ class ExistsMapperTest extends TestCase
{ {
try { try {
Configuration::overrideMode(Mode::PgSQL); Configuration::overrideMode(Mode::PgSQL);
$this->assertFalse(new ExistsMapper()->map([false, 'nope']), 'Result should have been false'); $this->assertFalse((new ExistsMapper())->map([false, 'nope']), 'Result should have been false');
} finally { } finally {
Configuration::overrideMode(null); Configuration::overrideMode(null);
} }
@ -35,7 +35,7 @@ class ExistsMapperTest extends TestCase
{ {
try { try {
Configuration::overrideMode(Mode::SQLite); Configuration::overrideMode(Mode::SQLite);
$this->assertTrue(new ExistsMapper()->map([1, 'yep']), 'Result should have been true'); $this->assertTrue((new ExistsMapper())->map([1, 'yep']), 'Result should have been true');
} finally { } finally {
Configuration::overrideMode(null); Configuration::overrideMode(null);
} }
@ -46,6 +46,6 @@ class ExistsMapperTest extends TestCase
{ {
$this->expectException(DocumentException::class); $this->expectException(DocumentException::class);
Configuration::overrideMode(null); Configuration::overrideMode(null);
new ExistsMapper()->map(['0']); (new ExistsMapper())->map(['0']);
} }
} }

View File

@ -1,39 +0,0 @@
<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
namespace Test\Unit;
use BitBadger\PDODocument\{DocumentException, Mode};
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
/**
* Unit tests for the Mode enumeration
*/
#[TestDox('Mode (Unit tests)')]
class ModeTest extends TestCase
{
#[TestDox('deriveFromDSN() succeeds for PostgreSQL')]
public function testDeriveFromDSNSucceedsForPostgreSQL(): void
{
$this->assertEquals(Mode::PgSQL, Mode::deriveFromDSN('pgsql:Host=localhost'), 'PostgreSQL mode incorrect');
}
#[TestDox('deriveFromDSN() succeeds for SQLite')]
public function testDeriveFromDSNSucceedsForSQLite(): void
{
$this->assertEquals(Mode::SQLite, Mode::deriveFromDSN('sqlite:data.db'), 'SQLite mode incorrect');
}
#[TestDox('deriveFromDSN() fails for MySQL')]
public function testDeriveFromDSNFailsForMySQL(): void
{
$this->expectException(DocumentException::class);
Mode::deriveFromDSN('mysql:Host=localhost');
}
}

View File

@ -1,86 +0,0 @@
<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
namespace Test\Unit;
use BitBadger\PDODocument\Op;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
/**
* Unit tests for the Op enumeration
*/
#[TestDox('Op (Unit tests)')]
class OpTest extends TestCase
{
#[TestDox('toSQL() succeeds for Equal')]
public function testToSQLSucceedsForEqual(): void
{
$this->assertEquals('=', Op::Equal->toSQL(), 'Equal SQL operator incorrect');
}
#[TestDox('toSQL() succeeds for Greater')]
public function testToSQLSucceedsForGreater(): void
{
$this->assertEquals('>', Op::Greater->toSQL(), 'Greater SQL operator incorrect');
}
#[TestDox('toSQL() succeeds for GreaterOrEqual')]
public function testToSQLSucceedsForGreaterOrEqual(): void
{
$this->assertEquals('>=', Op::GreaterOrEqual->toSQL(), 'GreaterOrEqual SQL operator incorrect');
}
#[TestDox('toSQL() succeeds for Less')]
public function testToSQLSucceedsForLess(): void
{
$this->assertEquals('<', Op::Less->toSQL(), 'Less SQL operator incorrect');
}
#[TestDox('toSQL() succeeds for LessOrEqual')]
public function testToSQLSucceedsForLessOrEqual(): void
{
$this->assertEquals('<=', Op::LessOrEqual->toSQL(), 'LessOrEqual SQL operator incorrect');
}
#[TestDox('toSQL() succeeds for NotEqual')]
public function testToSQLSucceedsForNotEqual(): void
{
$this->assertEquals('<>', Op::NotEqual->toSQL(), 'NotEqual SQL operator incorrect');
}
#[TestDox('toSQL() succeeds for Between')]
public function testToSQLSucceedsForBetween(): void
{
$this->assertEquals('BETWEEN', Op::Between->toSQL(), 'Between SQL operator incorrect');
}
#[TestDox('toSQL() succeeds for In')]
public function testToSQLSucceedsForIn(): void
{
$this->assertEquals('IN', Op::In->toSQL(), 'In SQL operator incorrect');
}
#[TestDox('toSQL() succeeds for InArray')]
public function testToSQLSucceedsForInArray(): void
{
$this->assertEquals('??|', Op::InArray->toSQL(), 'InArray SQL operator incorrect');
}
#[TestDox('toSQL() succeeds for Exists')]
public function testToSQLSucceedsForExists(): void
{
$this->assertEquals('IS NOT NULL', Op::Exists->toSQL(), 'Exists SQL operator incorrect');
}
#[TestDox('toSQL() succeeds for NotExists')]
public function testToSQLSucceedsForNEX(): void
{
$this->assertEquals('IS NULL', Op::NotExists->toSQL(), 'NotExists SQL operator incorrect');
}
}

View File

@ -1,134 +0,0 @@
<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
namespace Test\Unit;
use BitBadger\PDODocument\{Configuration, DocumentException, Field, Mode, Parameters};
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
use stdClass;
use Test\{PjsonDocument, PjsonId};
/**
* Unit tests for the Parameters class
*/
#[TestDox('Parameters (Unit tests)')]
class ParametersTest extends TestCase
{
#[TestDox('id() succeeds with string')]
public function testIdSucceedsWithString(): void
{
$this->assertEquals([':id' => 'key'], Parameters::id('key'), 'ID parameter not constructed correctly');
}
#[TestDox('id() succeeds with non string')]
public function testIdSucceedsWithNonString(): void
{
$this->assertEquals([':id' => '7'], Parameters::id(7), 'ID parameter not constructed correctly');
}
#[TestDox('json() succeeds for array')]
public function testJsonSucceedsForArray(): void
{
$this->assertEquals([':it' => '{"id":18,"url":"https://www.unittest.com"}'],
Parameters::json(':it', ['id' => 18, 'url' => 'https://www.unittest.com']),
'JSON parameter not constructed correctly');
}
#[TestDox('json() succeeds for array with empty array parameter')]
public function testJsonSucceedsForArrayWithEmptyArrayParameter(): void
{
$this->assertEquals([':it' => '{"id":18,"urls":[]}'], Parameters::json(':it', ['id' => 18, 'urls' => []]),
'JSON parameter not constructed correctly');
}
#[TestDox('json() succeeds for 1D array with empty array parameter')]
public function testJsonSucceedsFor1DArrayWithEmptyArrayParameter(): void
{
$this->assertEquals([':it' => '{"urls":[]}'], Parameters::json(':it', ['urls' => []]),
'JSON parameter not constructed correctly');
}
#[TestDox('json() succeeds for stdClass')]
public function testJsonSucceedsForStdClass(): void
{
$obj = new stdClass();
$obj->id = 19;
$obj->url = 'https://testhere.info';
$this->assertEquals([':it' => '{"id":19,"url":"https://testhere.info"}'], Parameters::json(':it', $obj),
'JSON parameter not constructed correctly');
}
#[TestDox('json() succeeds for Pjson class')]
public function testJsonSucceedsForPjsonClass(): void
{
$this->assertEquals([':it' => '{"id":"999","name":"a test","num_value":98}'],
Parameters::json(':it', new PjsonDocument(new PjsonId('999'), 'a test', 98, 'nothing')),
'JSON parameter not constructed correctly');
}
#[TestDox('json() succeeds for array of Pjson class')]
public function testJsonSucceedsForArrayOfPjsonClass(): void
{
$this->assertEquals([':it' => '{"pjson":[{"id":"997","name":"another test","num_value":94}]}'],
Parameters::json(':it',
['pjson' => [new PjsonDocument(new PjsonId('997'), 'another test', 94, 'nothing')]]),
'JSON parameter not constructed correctly');
}
#[TestDox('nameFields() succeeds')]
public function testNameFieldsSucceeds(): void
{
$named = [Field::equal('it', 17), Field::equal('also', 22, ':also'), Field::equal('other', 24)];
Parameters::nameFields($named);
$this->assertCount(3, $named, 'There should be 3 parameters in the array');
$this->assertEquals(':field0', $named[0]->paramName, 'Parameter 1 not named correctly');
$this->assertEquals(':also', $named[1]->paramName, 'Parameter 2 not named correctly');
$this->assertEquals(':field2', $named[2]->paramName, 'Parameter 3 not named correctly');
}
#[TestDox('addFields() succeeds')]
public function testAddFieldsSucceeds(): void
{
$this->assertEquals([':a' => 1, ':b' => 'two', ':z' => 18],
Parameters::addFields([Field::equal('b', 'two', ':b'), Field::equal('z', 18, ':z')], [':a' => 1]),
'Field parameters not added correctly');
}
#[TestDox('fieldNames() succeeds for PostgreSQL')]
public function testFieldNamesSucceedsForPostgreSQL(): void
{
try {
Configuration::overrideMode(Mode::PgSQL);
$this->assertEquals([':names' => "{one,two,seven}"],
Parameters::fieldNames(':names', ['one', 'two', 'seven']), 'Field name parameters not correct');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('fieldNames() succeeds for SQLite')]
public function testFieldNamesSucceedsForSQLite(): void
{
try {
Configuration::overrideMode(Mode::SQLite);
$this->assertEquals([':it0' => '$.test', ':it1' => '$.unit', ':it2' => '$.wow'],
Parameters::fieldNames(':it', ['test', 'unit', 'wow']), 'Field name parameters not correct');
} finally {
Configuration::overrideMode(null);
}
}
#[TestDox('fieldNames() fails when mode not set')]
public function testFieldNamesFailsWhenModeNotSet(): void
{
$this->expectException(DocumentException::class);
Configuration::overrideMode(null);
Parameters::fieldNames('', []);
}
}

View File

@ -25,7 +25,7 @@ class DefinitionTest extends TestCase
parent::tearDown(); parent::tearDown();
} }
#[TestDox('ensureTable() succeeds for PostgreSQL')] #[TestDox('ensureTable() succeeds for PosgtreSQL')]
public function testEnsureTableSucceedsForPostgreSQL(): void public function testEnsureTableSucceedsForPostgreSQL(): void
{ {
Configuration::overrideMode(Mode::PgSQL); Configuration::overrideMode(Mode::PgSQL);

View File

@ -1,323 +0,0 @@
<?php
/**
* @author Daniel J. Summers <daniel@bitbadger.solutions>
* @license MIT
*/
declare(strict_types=1);
namespace Test\Unit;
use BitBadger\PDODocument\{AutoId, Configuration, DocumentException, Field, FieldMatch, Mode, Query};
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
/**
* Unit tests for the Query class
*/
#[TestDox('Query (Unit tests)')]
class QueryTest extends TestCase
{
protected function setUp(): void
{
Configuration::overrideMode(Mode::SQLite);
}
protected function tearDown(): void
{
Configuration::overrideMode(null);
}
#[TestDox('selectFromTable() succeeds')]
public function testSelectFromTableSucceeds(): void
{
$this->assertEquals('SELECT data FROM testing', Query::selectFromTable('testing'),
'Query not constructed correctly');
}
#[TestDox('whereByFields() succeeds for single field')]
public function testWhereByFieldsSucceedsForSingleField(): void
{
$this->assertEquals("data->>'test_field' <= :it",
Query::whereByFields([Field::lessOrEqual('test_field', '', ':it')]),
'WHERE fragment not constructed correctly');
}
#[TestDox('whereByFields() succeeds for multiple fields All')]
public function testWhereByFieldsSucceedsForMultipleFieldsAll(): void
{
$this->assertEquals("data->>'test_field' <= :it AND data->>'other_field' = :other",
Query::whereByFields(
[Field::lessOrEqual('test_field', '', ':it'), Field::equal('other_field', '', ':other')]),
'WHERE fragment not constructed correctly');
}
#[TestDox('whereByFields() succeeds for multiple fields Any')]
public function testWhereByFieldsSucceedsForMultipleFieldsAny(): void
{
$this->assertEquals("data->>'test_field' <= :it OR data->>'other_field' = :other",
Query::whereByFields(
[Field::lessOrEqual('test_field', '', ':it'), Field::equal('other_field', '', ':other')],
FieldMatch::Any),
'WHERE fragment not constructed correctly');
}
#[TestDox('whereById() succeeds with default parameter')]
public function testWhereByIdSucceedsWithDefaultParameter(): void
{
$this->assertEquals("data->>'id' = :id", Query::whereById(), 'WHERE fragment not constructed correctly');
}
#[TestDox('whereById() succeeds with specific parameter')]
public function testWhereByIdSucceedsWithSpecificParameter(): void
{
$this->assertEquals("data->>'id' = :di", Query::whereById(':di'), 'WHERE fragment not constructed correctly');
}
#[TestDox('whereDataContains() succeeds with default parameter')]
public function testWhereDataContainsSucceedsWithDefaultParameter(): void
{
Configuration::overrideMode(Mode::PgSQL);
$this->assertEquals('data @> :criteria', Query::whereDataContains(),
'WHERE fragment not constructed correctly');
}
#[TestDox('whereDataContains() succeeds with specific parameter')]
public function testWhereDataContainsSucceedsWithSpecifiedParameter(): void
{
Configuration::overrideMode(Mode::PgSQL);
$this->assertEquals('data @> :it', Query::whereDataContains(':it'), 'WHERE fragment not constructed correctly');
}
#[TestDox('whereDataContains() fails if not PostgreSQL')]
public function testWhereDataContainsFailsIfNotPostgreSQL(): void
{
Configuration::overrideMode(null);
$this->expectException(DocumentException::class);
Query::whereDataContains();
}
#[TestDox('whereJsonPathMatches() succeeds with default parameter')]
public function testWhereJsonPathMatchesSucceedsWithDefaultParameter(): void
{
Configuration::overrideMode(Mode::PgSQL);
$this->assertEquals('jsonb_path_exists(data, :path::jsonpath)', Query::whereJsonPathMatches(),
'WHERE fragment not constructed correctly');
}
#[TestDox('whereJsonPathMatches() succeeds with specified parameter')]
public function testWhereJsonPathMatchesSucceedsWithSpecifiedParameter(): void
{
Configuration::overrideMode(Mode::PgSQL);
$this->assertEquals('jsonb_path_exists(data, :road::jsonpath)', Query::whereJsonPathMatches(':road'),
'WHERE fragment not constructed correctly');
}
#[TestDox('whereJsonPathMatches() fails if not PostgreSQL')]
public function testWhereJsonPathMatchesFailsIfNotPostgreSQL(): void
{
Configuration::overrideMode(null);
$this->expectException(DocumentException::class);
Query::whereJsonPathMatches();
}
#[TestDox('insert() succeeds with no auto-ID for PostgreSQL')]
public function testInsertSucceedsWithNoAutoIdForPostgreSQL(): void
{
Configuration::overrideMode(Mode::PgSQL);
$this->assertEquals('INSERT INTO test_tbl VALUES (:data)', Query::insert('test_tbl'),
'INSERT statement not constructed correctly');
}
#[TestDox('insert() succeeds with no auto-ID for SQLite')]
public function testInsertSucceedsWithNoAutoIdForSQLite(): void
{
$this->assertEquals('INSERT INTO test_tbl VALUES (:data)', Query::insert('test_tbl'),
'INSERT statement not constructed correctly');
}
#[TestDox('insert() succeeds with auto numeric ID for PostgreSQL')]
public function testInsertSucceedsWithAutoNumericIdForPostgreSQL(): void
{
Configuration::overrideMode(Mode::PgSQL);
$this->assertEquals(
"INSERT INTO test_tbl VALUES (:data::jsonb || ('{\"id\":' "
. "|| (SELECT COALESCE(MAX((data->>'id')::numeric), 0) + 1 FROM test_tbl) || '}')::jsonb)",
Query::insert('test_tbl', AutoId::Number), 'INSERT statement not constructed correctly');
}
#[TestDox('insert() succeeds with auto numeric ID for SQLite')]
public function testInsertSucceedsWithAutoNumericIdForSQLite(): void
{
$this->assertEquals(
"INSERT INTO test_tbl VALUES (json_set(:data, '$.id', "
. "(SELECT coalesce(max(data->>'id'), 0) + 1 FROM test_tbl)))",
Query::insert('test_tbl', AutoId::Number), 'INSERT statement not constructed correctly');
}
#[TestDox('insert() succeeds with auto UUID for PostgreSQL')]
public function testInsertSucceedsWithAutoUuidForPostgreSQL(): void
{
Configuration::overrideMode(Mode::PgSQL);
$query = Query::insert('test_tbl', AutoId::UUID);
$this->assertStringStartsWith("INSERT INTO test_tbl VALUES (:data::jsonb || '{\"id\":\"", $query,
'INSERT statement not constructed correctly');
$this->assertStringEndsWith("\"}')", $query, 'INSERT statement not constructed correctly');
}
#[TestDox('insert() succeeds with auto UUID for SQLite')]
public function testInsertSucceedsWithAutoUuidForSQLite(): void
{
$query = Query::insert('test_tbl', AutoId::UUID);
$this->assertStringStartsWith("INSERT INTO test_tbl VALUES (json_set(:data, '$.id', '", $query,
'INSERT statement not constructed correctly');
$this->assertStringEndsWith("'))", $query, 'INSERT statement not constructed correctly');
}
#[TestDox('insert() succeeds with auto random string for PostgreSQL')]
public function testInsertSucceedsWithAutoRandomStringForPostgreSQL(): void
{
Configuration::overrideMode(Mode::PgSQL);
Configuration::$idStringLength = 8;
try {
$query = Query::insert('test_tbl', AutoId::RandomString);
$this->assertStringStartsWith("INSERT INTO test_tbl VALUES (:data::jsonb || '{\"id\":\"", $query,
'INSERT statement not constructed correctly');
$this->assertStringEndsWith("\"}')", $query, 'INSERT statement not constructed correctly');
$id = str_replace(["INSERT INTO test_tbl VALUES (:data::jsonb || '{\"id\":\"", "\"}')"], '', $query);
$this->assertEquals(8, strlen($id), "Generated ID [$id] should have been 8 characters long");
} finally {
Configuration::$idStringLength = 16;
}
}
#[TestDox('insert() succeeds with auto random string for SQLite')]
public function testInsertSucceedsWithAutoRandomStringForSQLite(): void
{
$query = Query::insert('test_tbl', AutoId::RandomString);
$this->assertStringStartsWith("INSERT INTO test_tbl VALUES (json_set(:data, '$.id', '", $query,
'INSERT statement not constructed correctly');
$this->assertStringEndsWith("'))", $query, 'INSERT statement not constructed correctly');
$id = str_replace(["INSERT INTO test_tbl VALUES (json_set(:data, '$.id', '", "'))"], '', $query);
$this->assertEquals(16, strlen($id), "Generated ID [$id] should have been 16 characters long");
}
#[TestDox('insert() fails when mode not set')]
public function testInsertFailsWhenModeNotSet(): void
{
$this->expectException(DocumentException::class);
Configuration::overrideMode(null);
Query::insert('kaboom');
}
#[TestDox('save() succeeds')]
public function testSaveSucceeds(): void
{
$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');
}
#[TestDox('update() succeeds')]
public function testUpdateSucceeds(): void
{
$this->assertEquals("UPDATE testing SET data = :data WHERE data->>'id' = :id", Query::update('testing'),
'UPDATE statement not constructed correctly');
}
#[TestDox('orderBy() succeeds with no fields for PostgreSQL')]
public function testOrderBySucceedsWithNoFieldsForPostgreSQL(): void
{
Configuration::overrideMode(Mode::PgSQL);
$this->assertEquals('', Query::orderBy([]), 'ORDER BY should have been blank');
}
#[TestDox('orderBy() succeeds with no fields for SQLite')]
public function testOrderBySucceedsWithNoFieldsForSQLite(): void
{
$this->assertEquals('', Query::orderBy([]), 'ORDER BY should have been blank');
}
#[TestDox('orderBy() succeeds with one field and no direction for PostgreSQL')]
public function testOrderBySucceedsWithOneFieldAndNoDirectionForPostgreSQL(): void
{
Configuration::overrideMode(Mode::PgSQL);
$this->assertEquals(" ORDER BY data->>'TestField'", Query::orderBy([Field::named('TestField')]),
'ORDER BY not constructed correctly');
}
#[TestDox('orderBy() succeeds with one field and no direction for SQLite')]
public function testOrderBySucceedsWithOneFieldAndNoDirectionForSQLite(): void
{
$this->assertEquals(" ORDER BY data->>'TestField'", Query::orderBy([Field::named('TestField')]),
'ORDER BY not constructed correctly');
}
#[TestDox('orderBy() succeeds with one qualified field for PostgreSQL')]
public function testOrderBySucceedsWithOneQualifiedFieldForPostgreSQL(): void
{
Configuration::overrideMode(Mode::PgSQL);
$field = Field::named('TestField');
$field->qualifier = 'qual';
$this->assertEquals(" ORDER BY qual.data->>'TestField'", Query::orderBy([$field]),
'ORDER BY not constructed correctly');
}
#[TestDox('orderBy() succeeds with one qualified field for SQLite')]
public function testOrderBySucceedsWithOneQualifiedFieldForSQLite(): void
{
$field = Field::named('TestField');
$field->qualifier = 'qual';
$this->assertEquals(" ORDER BY qual.data->>'TestField'", Query::orderBy([$field]),
'ORDER BY not constructed correctly');
}
#[TestDox('orderBy() succeeds with multiple fields and direction for PostgreSQL')]
public function testOrderBySucceedsWithMultipleFieldsAndDirectionForPostgreSQL(): void
{
Configuration::overrideMode(Mode::PgSQL);
$this->assertEquals(" ORDER BY data#>>'{Nested,Test,Field}' DESC, data->>'AnotherField', data->>'It' DESC",
Query::orderBy(
[Field::named('Nested.Test.Field DESC'), Field::named('AnotherField'), Field::named('It DESC')]),
'ORDER BY not constructed correctly');
}
#[TestDox('orderBy() succeeds with multiple fields and direction for SQLite')]
public function testOrderBySucceedsWithMultipleFieldsAndDirectionForSQLite(): void
{
$this->assertEquals(" ORDER BY data->'Nested'->'Test'->>'Field' DESC, data->>'AnotherField', data->>'It' DESC",
Query::orderBy(
[Field::named('Nested.Test.Field DESC'), Field::named('AnotherField'), Field::named('It DESC')]),
'ORDER BY not constructed correctly');
}
#[TestDox('orderBy() succeeds with numeric field for PostgreSQL')]
public function testOrderBySucceedsWithNumericFieldForPostgreSQL(): void
{
Configuration::overrideMode(Mode::PgSQL);
$this->assertEquals(" ORDER BY (data->>'Test')::numeric", Query::orderBy([Field::named('n:Test')]),
'ORDER BY not constructed correctly');
}
#[TestDox('orderBy() succeeds with numeric field for SQLite')]
public function testOrderBySucceedsWithNumericFieldForSQLite(): void
{
$this->assertEquals(" ORDER BY data->>'Test'", Query::orderBy([Field::named('n:Test')]),
'ORDER BY not constructed correctly');
}
#[TestDox('orderBy() succeeds with case-insensitive ordering for PostgreSQL')]
public function testOrderBySucceedsWithCaseInsensitiveOrderingForPostgreSQL(): void
{
Configuration::overrideMode(Mode::PgSQL);
$this->assertEquals(" ORDER BY LOWER(data#>>'{Test,Field}') DESC NULLS FIRST",
Query::orderBy([Field::named('i:Test.Field DESC NULLS FIRST')]), 'ORDER BY not constructed correctly');
}
#[TestDox('orderBy() succeeds with case-insensitive ordering for SQLite')]
public function testOrderBySucceedsWithCaseInsensitiveOrderingForSQLite(): void
{
$this->assertEquals(" ORDER BY data->'Test'->>'Field' COLLATE NOCASE ASC NULLS LAST",
Query::orderBy([Field::named('i:Test.Field ASC NULLS LAST')]), 'ORDER BY not constructed correctly');
}
}