Add PostgreSQL Support #3
1
.gitignore
vendored
1
.gitignore
vendored
|
@ -1,2 +1,3 @@
|
|||
.idea
|
||||
vendor
|
||||
*-tests.txt
|
||||
|
|
|
@ -4,7 +4,7 @@ This library allows SQLite (and, by v1.0.0-beta1, PostgreSQL) to be treated as a
|
|||
|
||||
## Add via Composer
|
||||
|
||||
![Packagist Version](https://img.shields.io/packagist/v/bit-badger/pdo-document)
|
||||
[![Packagist Version](https://img.shields.io/packagist/v/bit-badger/pdo-document)](https://packagist.org/packages/bit-badger/pdo-document)
|
||||
|
||||
`composer require bit-badger/pdo-document`
|
||||
|
||||
|
|
|
@ -35,6 +35,7 @@
|
|||
"psr-4": {
|
||||
"Test\\Unit\\": "./tests/unit",
|
||||
"Test\\Integration\\": "./tests/integration",
|
||||
"Test\\Integration\\PostgreSQL\\": "./tests/integration/postgresql",
|
||||
"Test\\Integration\\SQLite\\": "./tests/integration/sqlite"
|
||||
}
|
||||
},
|
||||
|
|
12
composer.lock
generated
12
composer.lock
generated
|
@ -619,16 +619,16 @@
|
|||
},
|
||||
{
|
||||
"name": "phpunit/phpunit",
|
||||
"version": "11.2.0",
|
||||
"version": "11.2.1",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/sebastianbergmann/phpunit.git",
|
||||
"reference": "705eba0190afe04bc057f565ad843267717cf109"
|
||||
"reference": "1b8775732e9c401bda32df3ffbdf90dec7533ceb"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/705eba0190afe04bc057f565ad843267717cf109",
|
||||
"reference": "705eba0190afe04bc057f565ad843267717cf109",
|
||||
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/1b8775732e9c401bda32df3ffbdf90dec7533ceb",
|
||||
"reference": "1b8775732e9c401bda32df3ffbdf90dec7533ceb",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
|
@ -699,7 +699,7 @@
|
|||
"support": {
|
||||
"issues": "https://github.com/sebastianbergmann/phpunit/issues",
|
||||
"security": "https://github.com/sebastianbergmann/phpunit/security/policy",
|
||||
"source": "https://github.com/sebastianbergmann/phpunit/tree/11.2.0"
|
||||
"source": "https://github.com/sebastianbergmann/phpunit/tree/11.2.1"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
|
@ -715,7 +715,7 @@
|
|||
"type": "tidelift"
|
||||
}
|
||||
],
|
||||
"time": "2024-06-07T04:48:50+00:00"
|
||||
"time": "2024-06-11T07:30:35+00:00"
|
||||
},
|
||||
{
|
||||
"name": "sebastian/cli-parser",
|
||||
|
|
|
@ -41,11 +41,12 @@ enum AutoId
|
|||
/**
|
||||
* Generate a random string ID
|
||||
*
|
||||
* @param int|null $length The length of string to generate (optional; defaults to configured ID string length)
|
||||
* @return string A string filled with the hexadecimal representation of random bytes
|
||||
* @throws RandomException If an appropriate source of randomness cannot be found
|
||||
*/
|
||||
public static function generateRandom(): string
|
||||
public static function generateRandom(?int $length = null): string
|
||||
{
|
||||
return bin2hex(random_bytes(Configuration::$idStringLength / 2));
|
||||
return bin2hex(random_bytes(($length ?? Configuration::$idStringLength) / 2));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -16,7 +16,7 @@ class Delete
|
|||
*/
|
||||
public static function byId(string $tableName, mixed $docId): void
|
||||
{
|
||||
Custom::nonQuery(Query\Delete::byId($tableName), Parameters::id($docId));
|
||||
Custom::nonQuery(Query\Delete::byId($tableName, $docId), Parameters::id($docId));
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -19,7 +19,7 @@ class Exists
|
|||
*/
|
||||
public static function byId(string $tableName, mixed $docId): bool
|
||||
{
|
||||
return Custom::scalar(Query\Exists::byId($tableName), Parameters::id($docId), new ExistsMapper());
|
||||
return Custom::scalar(Query\Exists::byId($tableName, $docId), Parameters::id($docId), new ExistsMapper());
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -52,23 +52,25 @@ class Field
|
|||
*/
|
||||
public function toWhere(): string
|
||||
{
|
||||
$fieldName = ($this->qualifier == '' ? '' : "$this->qualifier.") . 'data' . match (true) {
|
||||
!str_contains($this->fieldName, '.') => "->>'$this->fieldName'",
|
||||
Configuration::$mode == Mode::PgSQL => "#>>'{" . implode(',', explode('.', $this->fieldName)) . "}'",
|
||||
Configuration::$mode == Mode::SQLite => "->>'" . implode("'->>'", explode('.', $this->fieldName)) . "'",
|
||||
default => throw new DocumentException('Database mode not set; cannot make field WHERE clause')
|
||||
};
|
||||
$fieldPath = match (Configuration::$mode) {
|
||||
Mode::PgSQL => match (true) {
|
||||
$this->op == Op::BT => is_numeric($this->value[0]) ? "($fieldName)::numeric" : $fieldName,
|
||||
is_numeric($this->value) => "($fieldName)::numeric",
|
||||
default => $fieldName
|
||||
},
|
||||
default => $fieldName
|
||||
};
|
||||
$criteria = match ($this->op) {
|
||||
Op::EX, Op::NEX => '',
|
||||
Op::BT => " {$this->paramName}min AND {$this->paramName}max",
|
||||
default => " $this->paramName"
|
||||
};
|
||||
$prefix = $this->qualifier == '' ? '' : "$this->qualifier.";
|
||||
$fieldPath = match (Configuration::$mode) {
|
||||
Mode::SQLite => "{$prefix}data->>'"
|
||||
. (str_contains($this->fieldName, '.')
|
||||
? implode("'->>'", explode('.', $this->fieldName))
|
||||
: $this->fieldName)
|
||||
. "'",
|
||||
Mode::PgSQL => $this->op == Op::BT && is_numeric($this->value[0])
|
||||
? "({$prefix}data->>'$this->fieldName')::numeric"
|
||||
: "{$prefix}data->>'$this->fieldName'",
|
||||
default => throw new DocumentException('Database mode not set; cannot make field WHERE clause')
|
||||
};
|
||||
return $fieldPath . ' ' . $this->op->toString() . $criteria;
|
||||
}
|
||||
|
||||
|
|
|
@ -35,7 +35,8 @@ class Find
|
|||
*/
|
||||
public static function byId(string $tableName, mixed $docId, string $className): mixed
|
||||
{
|
||||
return Custom::single(Query\Find::byId($tableName), Parameters::id($docId), new DocumentMapper($className));
|
||||
return Custom::single(Query\Find::byId($tableName, $docId), Parameters::id($docId),
|
||||
new DocumentMapper($className));
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -68,7 +68,7 @@ class Parameters
|
|||
{
|
||||
switch (Configuration::$mode) {
|
||||
case Mode::PgSQL:
|
||||
return [$paramName => "ARRAY['" . implode("','", $fieldNames) . "']"];
|
||||
return [$paramName => "{" . implode(",", $fieldNames) . "}"];
|
||||
case Mode::SQLite:
|
||||
$it = [];
|
||||
$idx = 0;
|
||||
|
|
|
@ -17,7 +17,7 @@ class Patch
|
|||
*/
|
||||
public static function byId(string $tableName, mixed $docId, array|object $patch): void
|
||||
{
|
||||
Custom::nonQuery(Query\Patch::byId($tableName),
|
||||
Custom::nonQuery(Query\Patch::byId($tableName, $docId),
|
||||
array_merge(Parameters::id($docId), Parameters::json(':data', $patch)));
|
||||
}
|
||||
|
||||
|
|
|
@ -38,12 +38,14 @@ class Query
|
|||
* Create a WHERE clause fragment to implement an ID-based query
|
||||
*
|
||||
* @param string $paramName The parameter name where the value of the ID will be provided (optional; default @id)
|
||||
* @param mixed $docId The ID of the document to be retrieved; used to determine type for potential JSON field
|
||||
* casts (optional; string ID assumed if no value is provided)
|
||||
* @return string The WHERE clause fragment to match by ID
|
||||
* @throws DocumentException If the database mode has not been set
|
||||
*/
|
||||
public static function whereById(string $paramName = ':id'): string
|
||||
public static function whereById(string $paramName = ':id', mixed $docId = null): string
|
||||
{
|
||||
return self::whereByFields([Field::EQ(Configuration::$idField, 0, $paramName)]);
|
||||
return self::whereByFields([Field::EQ(Configuration::$idField, $docId ?? '', $paramName)]);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -68,10 +70,11 @@ class Query
|
|||
},
|
||||
Mode::PgSQL => match ($autoId ?? AutoId::None) {
|
||||
AutoId::None => ':data',
|
||||
AutoId::Number => ":data || ('{\"$id\":' || "
|
||||
. "(SELECT COALESCE(MAX(data->>'$id'), 0) + 1 FROM $tableName) || '}')",
|
||||
AutoId::UUID => ":data || '{\"$id\":\"" . AutoId::generateUUID() . "\"}'",
|
||||
AutoId::RandomString => ":data || '{\"$id\":\"" . AutoId::generateRandom() . "\"}'",
|
||||
AutoId::Number => ":data::jsonb || ('{\"$id\":' || "
|
||||
. "(SELECT COALESCE(MAX((data->>'$id')::numeric), 0) + 1 "
|
||||
. "FROM $tableName) || '}')::jsonb",
|
||||
AutoId::UUID => ":data::jsonb || '{\"$id\":\"" . AutoId::generateUUID() . "\"}'",
|
||||
AutoId::RandomString => ":data::jsonb || '{\"$id\":\"" . AutoId::generateRandom() . "\"}'",
|
||||
},
|
||||
default =>
|
||||
throw new DocumentException('Database mode not set; cannot generate auto-ID INSERT statement'),
|
||||
|
|
|
@ -13,12 +13,13 @@ class Delete
|
|||
* Query to delete a document by its ID
|
||||
*
|
||||
* @param string $tableName The name of the table from which a document should be deleted
|
||||
* @param mixed $docId The ID of the document to be deleted (optional; string ID assumed)
|
||||
* @return string The DELETE statement to delete a document by its ID
|
||||
* @throws DocumentException If the database mode has not been set
|
||||
*/
|
||||
public static function byId(string $tableName): string
|
||||
public static function byId(string $tableName, mixed $docId = null): string
|
||||
{
|
||||
return "DELETE FROM $tableName WHERE " . Query::whereById();
|
||||
return "DELETE FROM $tableName WHERE " . Query::whereById(docId: $docId);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -25,12 +25,13 @@ class Exists
|
|||
* Query to determine if a document exists for the given ID
|
||||
*
|
||||
* @param string $tableName The name of the table in which document existence should be checked
|
||||
* @param mixed $docId The ID of the document whose existence should be checked (optional; string ID assumed)
|
||||
* @return string The query to determine document existence by ID
|
||||
* @throws DocumentException If the database mode has not been set
|
||||
*/
|
||||
public static function byId(string $tableName): string
|
||||
public static function byId(string $tableName, mixed $docId = null): string
|
||||
{
|
||||
return self::query($tableName, Query::whereById());
|
||||
return self::query($tableName, Query::whereById(docId: $docId));
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -13,12 +13,13 @@ class Find
|
|||
* Query to retrieve a document by its ID
|
||||
*
|
||||
* @param string $tableName The name of the table from which a document should be retrieved
|
||||
* @param mixed $docId The ID of the document to be retrieved (optional; string ID assumed)
|
||||
* @return string The SELECT statement to retrieve a document by its ID
|
||||
* @throws DocumentException If the database mode has not been set
|
||||
*/
|
||||
public static function byId(string $tableName): string
|
||||
public static function byId(string $tableName, mixed $docId = null): string
|
||||
{
|
||||
return Query::selectFromTable($tableName) . ' WHERE ' . Query::whereById();
|
||||
return Query::selectFromTable($tableName) . ' WHERE ' . Query::whereById(docId: $docId);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -31,12 +31,13 @@ class Patch
|
|||
* Query to patch (partially update) a document by its ID
|
||||
*
|
||||
* @param string $tableName The name of the table in which a document should be patched
|
||||
* @param mixed $docId The ID of the document to be patched (optional; string ID assumed)
|
||||
* @return string The query to patch a document by its ID
|
||||
* @throws DocumentException If the database mode has not been set
|
||||
*/
|
||||
public static function byId(string $tableName): string
|
||||
public static function byId(string $tableName, mixed $docId = null): string
|
||||
{
|
||||
return self::update($tableName, Query::whereById());
|
||||
return self::update($tableName, Query::whereById(docId: $docId));
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -26,7 +26,8 @@ class RemoveFields
|
|||
{
|
||||
switch (Configuration::$mode) {
|
||||
case Mode::PgSQL:
|
||||
return "UPDATE $tableName SET data = data - " . array_keys($parameters)[0] . " WHERE $whereClause";
|
||||
return "UPDATE $tableName SET data = data - " . array_keys($parameters)[0]
|
||||
. "::text[] WHERE $whereClause";
|
||||
case Mode::SQLite:
|
||||
$paramNames = implode(', ', array_keys($parameters));
|
||||
return "UPDATE $tableName SET data = json_remove(data, $paramNames) WHERE $whereClause";
|
||||
|
@ -40,12 +41,13 @@ class RemoveFields
|
|||
*
|
||||
* @param string $tableName The name of the table in which the document should be manipulated
|
||||
* @param array $parameters The parameter list for the query
|
||||
* @param mixed $docId The ID of the document from which fields should be removed (optional; string ID assumed)
|
||||
* @return string The UPDATE statement to remove fields from a document by its ID
|
||||
* @throws DocumentException If the database mode has not been set
|
||||
*/
|
||||
public static function byId(string $tableName, array $parameters): string
|
||||
public static function byId(string $tableName, array $parameters, mixed $docId = null): string
|
||||
{
|
||||
return self::update($tableName, $parameters, Query::whereById());
|
||||
return self::update($tableName, $parameters, Query::whereById(docId: $docId));
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -18,7 +18,7 @@ class RemoveFields
|
|||
public static function byId(string $tableName, mixed $docId, array $fieldNames): void
|
||||
{
|
||||
$nameParams = Parameters::fieldNames(':name', $fieldNames);
|
||||
Custom::nonQuery(Query\RemoveFields::byId($tableName, $nameParams),
|
||||
Custom::nonQuery(Query\RemoveFields::byId($tableName, $nameParams, $docId),
|
||||
array_merge(Parameters::id($docId), $nameParams));
|
||||
}
|
||||
|
||||
|
|
47
tests/integration/postgresql/CountTest.php
Normal file
47
tests/integration/postgresql/CountTest.php
Normal file
|
@ -0,0 +1,47 @@
|
|||
<?php declare(strict_types=1);
|
||||
|
||||
namespace Test\Integration\PostgreSQL;
|
||||
|
||||
use BitBadger\PDODocument\{Count, Field};
|
||||
use PHPUnit\Framework\Attributes\TestDox;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* PostgreSQL integration tests for the Count class
|
||||
*/
|
||||
#[TestDox('Count (PostgreSQL integration)')]
|
||||
class CountTest extends TestCase
|
||||
{
|
||||
/** @var string Database name for throwaway database */
|
||||
private string $dbName;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->dbName = ThrowawayDb::create();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
ThrowawayDb::destroy($this->dbName);
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function testAllSucceeds(): void
|
||||
{
|
||||
$count = Count::all(ThrowawayDb::TABLE);
|
||||
$this->assertEquals(5, $count, 'There should have been 5 matching documents');
|
||||
}
|
||||
|
||||
public function testByFieldsSucceedsForANumericRange(): void
|
||||
{
|
||||
$count = Count::byFields(ThrowawayDb::TABLE, [Field::BT('num_value', 10, 20)]);
|
||||
$this->assertEquals(3, $count, 'There should have been 3 matching documents');
|
||||
}
|
||||
|
||||
public function testByFieldsSucceedsForANonNumericRange(): void
|
||||
{
|
||||
$count = Count::byFields(ThrowawayDb::TABLE, [Field::BT('value', 'aardvark', 'apple')]);
|
||||
$this->assertEquals(1, $count, 'There should have been 1 matching document');
|
||||
}
|
||||
}
|
121
tests/integration/postgresql/CustomTest.php
Normal file
121
tests/integration/postgresql/CustomTest.php
Normal file
|
@ -0,0 +1,121 @@
|
|||
<?php declare(strict_types=1);
|
||||
|
||||
namespace Test\Integration\PostgreSQL;
|
||||
|
||||
use BitBadger\PDODocument\{Count, Custom, DocumentException, Query};
|
||||
use BitBadger\PDODocument\Mapper\{CountMapper, DocumentMapper};
|
||||
use PHPUnit\Framework\Attributes\TestDox;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Test\Integration\TestDocument;
|
||||
|
||||
/**
|
||||
* PostgreSQL integration tests for the Custom class
|
||||
*/
|
||||
#[TestDox('Custom (PostgreSQL integration)')]
|
||||
class CustomTest extends TestCase
|
||||
{
|
||||
/** @var string Database name for throwaway database */
|
||||
private string $dbName;
|
||||
|
||||
public function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->dbName = ThrowawayDb::create();
|
||||
}
|
||||
|
||||
public function tearDown(): void
|
||||
{
|
||||
ThrowawayDb::destroy($this->dbName);
|
||||
}
|
||||
|
||||
public function testRunQuerySucceedsWithAValidQuery()
|
||||
{
|
||||
$stmt = &Custom::runQuery('SELECT data FROM ' . ThrowawayDb::TABLE . ' LIMIT 1', []);
|
||||
try {
|
||||
$this->assertNotNull($stmt, 'The statement should not have been null');
|
||||
} finally {
|
||||
$stmt = null;
|
||||
}
|
||||
}
|
||||
|
||||
public function testRunQueryFailsWithAnInvalidQuery()
|
||||
{
|
||||
$this->expectException(DocumentException::class);
|
||||
$stmt = &Custom::runQuery('GRAB stuff FROM over_there UNTIL done', []);
|
||||
try {
|
||||
$this->assertTrue(false, 'This code should not be reached');
|
||||
} finally {
|
||||
$stmt = null;
|
||||
}
|
||||
}
|
||||
|
||||
public function testListSucceedsWhenDataIsFound()
|
||||
{
|
||||
$list = Custom::list(Query::selectFromTable(ThrowawayDb::TABLE), [], new DocumentMapper(TestDocument::class));
|
||||
$this->assertNotNull($list, 'The document list should not be null');
|
||||
$count = 0;
|
||||
foreach ($list->items() as $ignored) $count++;
|
||||
$this->assertEquals(5, $count, 'There should have been 5 documents in the list');
|
||||
}
|
||||
|
||||
public function testListSucceedsWhenNoDataIsFound()
|
||||
{
|
||||
$list = Custom::list(
|
||||
Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE (data->>'num_value')::numeric > :value",
|
||||
[':value' => 100], new DocumentMapper(TestDocument::class));
|
||||
$this->assertNotNull($list, 'The document list should not be null');
|
||||
$this->assertFalse($list->hasItems(), 'There should have been no documents in the list');
|
||||
}
|
||||
|
||||
public function testArraySucceedsWhenDataIsFound()
|
||||
{
|
||||
$array = Custom::array(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'sub' IS NOT NULL", [],
|
||||
new DocumentMapper(TestDocument::class));
|
||||
$this->assertNotNull($array, 'The document array should not be null');
|
||||
$this->assertCount(2, $array, 'There should have been 2 documents in the array');
|
||||
}
|
||||
|
||||
public function testArraySucceedsWhenNoDataIsFound()
|
||||
{
|
||||
$array = Custom::array(Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE data->>'value' = :value",
|
||||
[':value' => 'not there'], new DocumentMapper(TestDocument::class));
|
||||
$this->assertNotNull($array, 'The document array should not be null');
|
||||
$this->assertCount(0, $array, 'There should have been no documents in the array');
|
||||
}
|
||||
|
||||
public function testSingleSucceedsWhenARowIsFound(): void
|
||||
{
|
||||
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id", [':id' => 'one'],
|
||||
new DocumentMapper(TestDocument::class));
|
||||
$this->assertNotNull($doc, 'There should have been a document returned');
|
||||
$this->assertEquals('one', $doc->id, 'The incorrect document was returned');
|
||||
}
|
||||
|
||||
public function testSingleSucceedsWhenARowIsNotFound(): void
|
||||
{
|
||||
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE data->>'id' = :id",
|
||||
[':id' => 'eighty'], new DocumentMapper(TestDocument::class));
|
||||
$this->assertFalse($doc, 'There should not have been a document returned');
|
||||
}
|
||||
|
||||
public function testNonQuerySucceedsWhenOperatingOnData()
|
||||
{
|
||||
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||
$remaining = Count::all(ThrowawayDb::TABLE);
|
||||
$this->assertEquals(0, $remaining, 'There should be no documents remaining in the table');
|
||||
}
|
||||
|
||||
public function testNonQuerySucceedsWhenNoDataMatchesWhereClause()
|
||||
{
|
||||
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE . " WHERE (data->>'num_value')::numeric > :value",
|
||||
[':value' => 100]);
|
||||
$remaining = Count::all(ThrowawayDb::TABLE);
|
||||
$this->assertEquals(5, $remaining, 'There should be 5 documents remaining in the table');
|
||||
}
|
||||
|
||||
public function testScalarSucceeds()
|
||||
{
|
||||
$value = Custom::scalar("SELECT 5 AS it", [], new CountMapper());
|
||||
$this->assertEquals(5, $value, 'The scalar value was not returned correctly');
|
||||
}
|
||||
}
|
60
tests/integration/postgresql/DefinitionTest.php
Normal file
60
tests/integration/postgresql/DefinitionTest.php
Normal file
|
@ -0,0 +1,60 @@
|
|||
<?php declare(strict_types=1);
|
||||
|
||||
namespace Test\Integration\PostgreSQL;
|
||||
|
||||
use BitBadger\PDODocument\{Custom, Definition, DocumentException};
|
||||
use BitBadger\PDODocument\Mapper\ExistsMapper;
|
||||
use PHPUnit\Framework\Attributes\TestDox;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* PostgreSQL integration tests for the Definition class
|
||||
*/
|
||||
#[TestDox('Definition (PostgreSQL integration)')]
|
||||
class DefinitionTest extends TestCase
|
||||
{
|
||||
/** @var string Database name for throwaway database */
|
||||
private string $dbName;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->dbName = ThrowawayDb::create(withData: false);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
ThrowawayDb::destroy($this->dbName);
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* Does the given named object exist in the database?
|
||||
*
|
||||
* @param string $name The name of the object whose existence should be verified
|
||||
* @return bool True if the object exists, false if not
|
||||
* @throws DocumentException If any is encountered
|
||||
*/
|
||||
private function itExists(string $name): bool
|
||||
{
|
||||
return Custom::scalar('SELECT EXISTS (SELECT 1 FROM pg_class WHERE relname = :name)',
|
||||
[':name' => $name], new ExistsMapper());
|
||||
}
|
||||
|
||||
public function testEnsureTableSucceeds()
|
||||
{
|
||||
$this->assertFalse($this->itExists('ensured'), 'The table should not exist already');
|
||||
$this->assertFalse($this->itExists('idx_ensured_key'), 'The key index should not exist already');
|
||||
Definition::ensureTable('ensured');
|
||||
$this->assertTrue($this->itExists('ensured'), 'The table should now exist');
|
||||
$this->assertTrue($this->itExists('idx_ensured_key'), 'The key index should now exist');
|
||||
}
|
||||
|
||||
public function testEnsureFieldIndexSucceeds()
|
||||
{
|
||||
$this->assertFalse($this->itExists('idx_ensured_test'), 'The index should not exist already');
|
||||
Definition::ensureTable('ensured');
|
||||
Definition::ensureFieldIndex('ensured', 'test', ['name', 'age']);
|
||||
$this->assertTrue($this->itExists('idx_ensured_test'), 'The index should now exist');
|
||||
}
|
||||
}
|
59
tests/integration/postgresql/DeleteTest.php
Normal file
59
tests/integration/postgresql/DeleteTest.php
Normal file
|
@ -0,0 +1,59 @@
|
|||
<?php declare(strict_types=1);
|
||||
|
||||
namespace Test\Integration\PostgreSQL;
|
||||
|
||||
use BitBadger\PDODocument\{Count, Delete, Field};
|
||||
use PHPUnit\Framework\Attributes\TestDox;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* PostgreSQL integration tests for the Delete class
|
||||
*/
|
||||
#[TestDox('Delete (PostgreSQL integration)')]
|
||||
class DeleteTest extends TestCase
|
||||
{
|
||||
/** @var string Database name for throwaway database */
|
||||
private string $dbName;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->dbName = ThrowawayDb::create();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
ThrowawayDb::destroy($this->dbName);
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
#[TestDox('By ID succeeds when a document is deleted')]
|
||||
public function testByIdSucceedsWhenADocumentIsDeleted(): void
|
||||
{
|
||||
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
||||
Delete::byId(ThrowawayDb::TABLE, 'four');
|
||||
$this->assertEquals(4, Count::all(ThrowawayDb::TABLE), 'There should have been 4 documents remaining');
|
||||
}
|
||||
|
||||
#[TestDox('By ID succeeds when a document is not deleted')]
|
||||
public function testByIdSucceedsWhenADocumentIsNotDeleted(): void
|
||||
{
|
||||
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
||||
Delete::byId(ThrowawayDb::TABLE, 'negative four');
|
||||
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents remaining');
|
||||
}
|
||||
|
||||
public function testByFieldsSucceedsWhenDocumentsAreDeleted(): void
|
||||
{
|
||||
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
||||
Delete::byFields(ThrowawayDb::TABLE, [Field::NE('value', 'purple')]);
|
||||
$this->assertEquals(2, Count::all(ThrowawayDb::TABLE), 'There should have been 2 documents remaining');
|
||||
}
|
||||
|
||||
public function testByFieldsSucceedsWhenDocumentsAreNotDeleted(): void
|
||||
{
|
||||
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents to start');
|
||||
Delete::byFields(ThrowawayDb::TABLE, [Field::EQ('value', 'crimson')]);
|
||||
$this->assertEquals(5, Count::all(ThrowawayDb::TABLE), 'There should have been 5 documents remaining');
|
||||
}
|
||||
}
|
74
tests/integration/postgresql/DocumentListTest.php
Normal file
74
tests/integration/postgresql/DocumentListTest.php
Normal file
|
@ -0,0 +1,74 @@
|
|||
<?php declare(strict_types=1);
|
||||
|
||||
namespace Test\Integration\PostgreSQL;
|
||||
|
||||
use BitBadger\PDODocument\{DocumentList, Query};
|
||||
use BitBadger\PDODocument\Mapper\DocumentMapper;
|
||||
use PHPUnit\Framework\Attributes\TestDox;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Test\Integration\TestDocument;
|
||||
|
||||
/**
|
||||
* PostgreSQL integration tests for the DocumentList class
|
||||
*/
|
||||
#[TestDox('DocumentList (PostgreSQL integration)')]
|
||||
class DocumentListTest extends TestCase
|
||||
{
|
||||
/** @var string Database name for throwaway database */
|
||||
private string $dbName;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->dbName = ThrowawayDb::create();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
ThrowawayDb::destroy($this->dbName);
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function testCreateSucceeds(): void
|
||||
{
|
||||
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
|
||||
new DocumentMapper(TestDocument::class));
|
||||
$this->assertNotNull($list, 'There should have been a document list created');
|
||||
$list = null;
|
||||
}
|
||||
|
||||
public function testItems(): void
|
||||
{
|
||||
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
|
||||
new DocumentMapper(TestDocument::class));
|
||||
$this->assertNotNull($list, 'There should have been a document list created');
|
||||
$count = 0;
|
||||
foreach ($list->items() as $item) {
|
||||
$this->assertContains($item->id, ['one', 'two', 'three', 'four', 'five'],
|
||||
'An unexpected document ID was returned');
|
||||
$count++;
|
||||
}
|
||||
$this->assertEquals(5, $count, 'There should have been 5 documents returned');
|
||||
}
|
||||
|
||||
public function testHasItemsSucceedsWithEmptyResults(): void
|
||||
{
|
||||
$list = DocumentList::create(
|
||||
Query::selectFromTable(ThrowawayDb::TABLE) . " WHERE (data->>'num_value')::numeric < 0", [],
|
||||
new DocumentMapper(TestDocument::class));
|
||||
$this->assertNotNull($list, 'There should have been a document list created');
|
||||
$this->assertFalse($list->hasItems(), 'There should be no items in the list');
|
||||
}
|
||||
|
||||
public function testHasItemsSucceedsWithNonEmptyResults(): void
|
||||
{
|
||||
$list = DocumentList::create(Query::selectFromTable(ThrowawayDb::TABLE), [],
|
||||
new DocumentMapper(TestDocument::class));
|
||||
$this->assertNotNull($list, 'There should have been a document list created');
|
||||
$this->assertTrue($list->hasItems(), 'There should be items in the list');
|
||||
foreach ($list->items() as $ignored) {
|
||||
$this->assertTrue($list->hasItems(), 'There should be items remaining in the list');
|
||||
}
|
||||
$this->assertFalse($list->hasItems(), 'There should be no remaining items in the list');
|
||||
}
|
||||
}
|
302
tests/integration/postgresql/DocumentTest.php
Normal file
302
tests/integration/postgresql/DocumentTest.php
Normal file
|
@ -0,0 +1,302 @@
|
|||
<?php declare(strict_types=1);
|
||||
|
||||
namespace Test\Integration\PostgreSQL;
|
||||
|
||||
use BitBadger\PDODocument\{AutoId, Configuration, Custom, Document, DocumentException, Field, Find, Query};
|
||||
use BitBadger\PDODocument\Mapper\ArrayMapper;
|
||||
use PHPUnit\Framework\Attributes\TestDox;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Test\Integration\{NumDocument, SubDocument, TestDocument};
|
||||
|
||||
/**
|
||||
* PostgreSQL integration tests for the Document class
|
||||
*/
|
||||
#[TestDox('Document (PostgreSQL integration)')]
|
||||
class DocumentTest extends TestCase
|
||||
{
|
||||
/** @var string Database name for throwaway database */
|
||||
private string $dbName;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->dbName = ThrowawayDb::create();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
ThrowawayDb::destroy($this->dbName);
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
#[TestDox('Insert succeeds for array no auto ID')]
|
||||
public function testInsertSucceedsForArrayNoAutoId(): void
|
||||
{
|
||||
Document::insert(ThrowawayDb::TABLE, ['id' => 'turkey', 'sub' => ['foo' => 'gobble', 'bar' => 'gobble']]);
|
||||
$doc = Find::byId(ThrowawayDb::TABLE, 'turkey', TestDocument::class);
|
||||
$this->assertNotFalse($doc, 'There should have been a document inserted');
|
||||
$this->assertEquals('turkey', $doc->id, 'The ID was incorrect');
|
||||
$this->assertEquals('', $doc->value, 'The value was incorrect');
|
||||
$this->assertEquals(0, $doc->num_value, 'The numeric value was incorrect');
|
||||
$this->assertNotNull($doc->sub, 'The sub-document should not have been null');
|
||||
$this->assertEquals('gobble', $doc->sub->foo, 'The sub-document foo property was incorrect');
|
||||
$this->assertEquals('gobble', $doc->sub->bar, 'The sub-document bar property was incorrect');
|
||||
}
|
||||
|
||||
#[TestDox('Insert succeeds for array with auto number ID not provided')]
|
||||
public function testInsertSucceedsForArrayWithAutoNumberIdNotProvided(): void
|
||||
{
|
||||
Configuration::$autoId = AutoId::Number;
|
||||
try {
|
||||
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||
|
||||
Document::insert(ThrowawayDb::TABLE, ['id' => 0, 'value' => 'new', 'num_value' => 8]);
|
||||
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE, [], new ArrayMapper());
|
||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||
$obj = json_decode($doc['data']);
|
||||
$this->assertEquals(1, $obj->id, 'The ID 1 should have been auto-generated');
|
||||
|
||||
Document::insert(ThrowawayDb::TABLE, ['id' => 0, 'value' => 'again', 'num_value' => 7]);
|
||||
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE . " WHERE " . Query::whereById(docId: 2),
|
||||
[':id' => 2], new ArrayMapper());
|
||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||
$obj = json_decode($doc['data']);
|
||||
$this->assertEquals(2, $obj->id, 'The ID 2 should have been auto-generated');
|
||||
} finally {
|
||||
Configuration::$autoId = AutoId::None;
|
||||
}
|
||||
}
|
||||
|
||||
#[TestDox('Insert succeeds for array with auto number ID with ID provided')]
|
||||
public function testInsertSucceedsForArrayWithAutoNumberIdWithIdProvided(): void
|
||||
{
|
||||
Configuration::$autoId = AutoId::Number;
|
||||
try {
|
||||
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||
Document::insert(ThrowawayDb::TABLE, ['id' => 7, 'value' => 'new', 'num_value' => 8]);
|
||||
$doc = Custom::single('SELECT data FROM ' . ThrowawayDb::TABLE, [], new ArrayMapper());
|
||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||
$obj = json_decode($doc['data']);
|
||||
$this->assertEquals(7, $obj->id, 'The ID 7 should have been stored');
|
||||
} finally {
|
||||
Configuration::$autoId = AutoId::None;
|
||||
}
|
||||
}
|
||||
|
||||
#[TestDox('Insert succeeds for array with auto UUID ID not provided')]
|
||||
public function testInsertSucceedsForArrayWithAutoUuidIdNotProvided(): void
|
||||
{
|
||||
Configuration::$autoId = AutoId::UUID;
|
||||
try {
|
||||
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||
Document::insert(ThrowawayDb::TABLE, ['id' => '', 'num_value' => 5]);
|
||||
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 5)], TestDocument::class);
|
||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||
$this->assertNotEmpty($doc->id, 'The ID should have been auto-generated');
|
||||
} finally {
|
||||
Configuration::$autoId = AutoId::None;
|
||||
}
|
||||
}
|
||||
|
||||
#[TestDox('Insert succeeds for array with auto UUID ID with ID provided')]
|
||||
public function testInsertSucceedsForArrayWithAutoUuidIdWithIdProvided(): void
|
||||
{
|
||||
Configuration::$autoId = AutoId::UUID;
|
||||
try {
|
||||
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||
$uuid = AutoId::generateUUID();
|
||||
Document::insert(ThrowawayDb::TABLE, ['id' => $uuid, 'value' => 'uuid', 'num_value' => 12]);
|
||||
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 12)], TestDocument::class);
|
||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||
$this->assertEquals($uuid, $doc->id, 'The ID should not have been changed');
|
||||
} finally {
|
||||
Configuration::$autoId = AutoId::None;
|
||||
}
|
||||
}
|
||||
|
||||
#[TestDox('Insert succeeds for array with auto string ID not provided')]
|
||||
public function testInsertSucceedsForArrayWithAutoStringIdNotProvided(): void
|
||||
{
|
||||
Configuration::$autoId = AutoId::RandomString;
|
||||
Configuration::$idStringLength = 6;
|
||||
try {
|
||||
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||
Document::insert(ThrowawayDb::TABLE, ['id' => '', 'value' => 'new', 'num_value' => 8]);
|
||||
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 8)], TestDocument::class);
|
||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||
$this->assertEquals(6, strlen($doc->id), 'The ID should have been auto-generated and had 6 characters');
|
||||
} finally {
|
||||
Configuration::$autoId = AutoId::None;
|
||||
Configuration::$idStringLength = 16;
|
||||
}
|
||||
}
|
||||
|
||||
#[TestDox('Insert succeeds for array with auto string ID with ID provided')]
|
||||
public function testInsertSucceedsForArrayWithAutoStringIdWithIdProvided(): void
|
||||
{
|
||||
Configuration::$autoId = AutoId::RandomString;
|
||||
try {
|
||||
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||
Document::insert(ThrowawayDb::TABLE, ['id' => 'my-key', 'value' => 'old', 'num_value' => 3]);
|
||||
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 3)], TestDocument::class);
|
||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||
$this->assertEquals('my-key', $doc->id, 'The ID should not have been changed');
|
||||
} finally {
|
||||
Configuration::$autoId = AutoId::None;
|
||||
}
|
||||
}
|
||||
|
||||
#[TestDox('Insert succeeds for object no auto ID')]
|
||||
public function testInsertSucceedsForObjectNoAutoId(): void
|
||||
{
|
||||
Document::insert(ThrowawayDb::TABLE, new TestDocument('turkey', sub: new SubDocument('gobble', 'gobble')));
|
||||
$doc = Find::byId(ThrowawayDb::TABLE, 'turkey', TestDocument::class);
|
||||
$this->assertNotFalse($doc, 'There should have been a document inserted');
|
||||
$this->assertEquals('turkey', $doc->id, 'The ID was incorrect');
|
||||
$this->assertEquals('', $doc->value, 'The value was incorrect');
|
||||
$this->assertEquals(0, $doc->num_value, 'The numeric value was incorrect');
|
||||
$this->assertNotNull($doc->sub, 'The sub-document should not have been null');
|
||||
$this->assertEquals('gobble', $doc->sub->foo, 'The sub-document foo property was incorrect');
|
||||
$this->assertEquals('gobble', $doc->sub->bar, 'The sub-document bar property was incorrect');
|
||||
}
|
||||
|
||||
#[TestDox('Insert succeeds for object with auto number ID not provided')]
|
||||
public function testInsertSucceedsForObjectWithAutoNumberIdNotProvided(): void
|
||||
{
|
||||
Configuration::$autoId = AutoId::Number;
|
||||
try {
|
||||
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||
|
||||
Document::insert(ThrowawayDb::TABLE, new NumDocument(value: 'taco'));
|
||||
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'taco')], NumDocument::class);
|
||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||
$this->assertEquals(1, $doc->id, 'The ID 1 should have been auto-generated');
|
||||
|
||||
Document::insert(ThrowawayDb::TABLE, new NumDocument(value: 'burrito'));
|
||||
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'burrito')], NumDocument::class);
|
||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||
$this->assertEquals(2, $doc->id, 'The ID 2 should have been auto-generated');
|
||||
} finally {
|
||||
Configuration::$autoId = AutoId::None;
|
||||
}
|
||||
}
|
||||
|
||||
#[TestDox('Insert succeeds for object with auto number ID with ID provided')]
|
||||
public function testInsertSucceedsForObjectWithAutoNumberIdWithIdProvided(): void
|
||||
{
|
||||
Configuration::$autoId = AutoId::Number;
|
||||
try {
|
||||
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||
Document::insert(ThrowawayDb::TABLE, new NumDocument(64, 'large'));
|
||||
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'large')], NumDocument::class);
|
||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||
$this->assertEquals(64, $doc->id, 'The ID 64 should have been stored');
|
||||
} finally {
|
||||
Configuration::$autoId = AutoId::None;
|
||||
}
|
||||
}
|
||||
|
||||
#[TestDox('Insert succeeds for object with auto UUID ID not provided')]
|
||||
public function testInsertSucceedsForObjectWithAutoUuidIdNotProvided(): void
|
||||
{
|
||||
Configuration::$autoId = AutoId::UUID;
|
||||
try {
|
||||
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||
Document::insert(ThrowawayDb::TABLE, new TestDocument(value: 'something', num_value: 9));
|
||||
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EX('value')], TestDocument::class);
|
||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||
$this->assertNotEmpty($doc->id, 'The ID should have been auto-generated');
|
||||
} finally {
|
||||
Configuration::$autoId = AutoId::None;
|
||||
}
|
||||
}
|
||||
|
||||
#[TestDox('Insert succeeds for object with auto UUID ID with ID provided')]
|
||||
public function testInsertSucceedsForObjectWithAutoUuidIdWithIdProvided(): void
|
||||
{
|
||||
Configuration::$autoId = AutoId::UUID;
|
||||
try {
|
||||
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||
$uuid = AutoId::generateUUID();
|
||||
Document::insert(ThrowawayDb::TABLE, new TestDocument($uuid, num_value: 14));
|
||||
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 14)], TestDocument::class);
|
||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||
$this->assertEquals($uuid, $doc->id, 'The ID should not have been changed');
|
||||
} finally {
|
||||
Configuration::$autoId = AutoId::None;
|
||||
}
|
||||
}
|
||||
|
||||
#[TestDox('Insert succeeds for object with auto string ID not provided')]
|
||||
public function testInsertSucceedsForObjectWithAutoStringIdNotProvided(): void
|
||||
{
|
||||
Configuration::$autoId = AutoId::RandomString;
|
||||
Configuration::$idStringLength = 40;
|
||||
try {
|
||||
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||
Document::insert(ThrowawayDb::TABLE, new TestDocument(num_value: 55));
|
||||
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 55)], TestDocument::class);
|
||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||
$this->assertEquals(40, strlen($doc->id), 'The ID should have been auto-generated and had 40 characters');
|
||||
} finally {
|
||||
Configuration::$autoId = AutoId::None;
|
||||
Configuration::$idStringLength = 16;
|
||||
}
|
||||
}
|
||||
|
||||
#[TestDox('Insert succeeds for object with auto string ID with ID provided')]
|
||||
public function testInsertSucceedsForObjectWithAutoStringIdWithIdProvided(): void
|
||||
{
|
||||
Configuration::$autoId = AutoId::RandomString;
|
||||
try {
|
||||
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||
Document::insert(ThrowawayDb::TABLE, new TestDocument('my-key', num_value: 3));
|
||||
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 3)], TestDocument::class);
|
||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||
$this->assertEquals('my-key', $doc->id, 'The ID should not have been changed');
|
||||
} finally {
|
||||
Configuration::$autoId = AutoId::None;
|
||||
}
|
||||
}
|
||||
|
||||
public function testInsertFailsForDuplicateKey(): void
|
||||
{
|
||||
$this->expectException(DocumentException::class);
|
||||
Document::insert(ThrowawayDb::TABLE, new TestDocument('one'));
|
||||
}
|
||||
|
||||
public function testSaveSucceedsWhenADocumentIsInserted(): void
|
||||
{
|
||||
Document::save(ThrowawayDb::TABLE, new TestDocument('test', sub: new SubDocument('a', 'b')));
|
||||
$doc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class);
|
||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||
}
|
||||
|
||||
public function testSaveSucceedsWhenADocumentIsUpdated(): void
|
||||
{
|
||||
Document::save(ThrowawayDb::TABLE, new TestDocument('two', num_value: 44));
|
||||
$doc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class);
|
||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||
$this->assertEquals(44, $doc->num_value, 'The numeric value was not updated');
|
||||
$this->assertNull($doc->sub, 'The sub-document should have been null');
|
||||
}
|
||||
|
||||
public function testUpdateSucceedsWhenReplacingADocument(): void
|
||||
{
|
||||
Document::update(ThrowawayDb::TABLE, 'one', new TestDocument('one', 'howdy', 8, new SubDocument('y', 'z')));
|
||||
$doc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class);
|
||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||
$this->assertEquals('howdy', $doc->value, 'The value was incorrect');
|
||||
$this->assertEquals(8, $doc->num_value, 'The numeric value was incorrect');
|
||||
$this->assertNotNull($doc->sub, 'The sub-document should not have been null');
|
||||
$this->assertEquals('y', $doc->sub->foo, 'The sub-document foo property was incorrect');
|
||||
$this->assertEquals('z', $doc->sub->bar, 'The sub-document bar property was incorrect');
|
||||
}
|
||||
|
||||
public function testUpdateSucceedsWhenNoDocumentIsReplaced(): void
|
||||
{
|
||||
Document::update(ThrowawayDb::TABLE, 'two-hundred', new TestDocument('200'));
|
||||
$doc = Find::byId(ThrowawayDb::TABLE, 'two-hundred', TestDocument::class);
|
||||
$this->assertFalse($doc, 'There should not have been a document returned');
|
||||
}
|
||||
}
|
54
tests/integration/postgresql/ExistsTest.php
Normal file
54
tests/integration/postgresql/ExistsTest.php
Normal file
|
@ -0,0 +1,54 @@
|
|||
<?php declare(strict_types=1);
|
||||
|
||||
namespace Test\Integration\PostgreSQL;
|
||||
|
||||
use BitBadger\PDODocument\{Exists, Field};
|
||||
use PHPUnit\Framework\Attributes\TestDox;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* PostgreSQL integration tests for the Exists class
|
||||
*/
|
||||
#[TestDox('Exists (PostgreSQL integration)')]
|
||||
class ExistsTest extends TestCase
|
||||
{
|
||||
/** @var string Database name for throwaway database */
|
||||
private string $dbName;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->dbName = ThrowawayDb::create();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
ThrowawayDb::destroy($this->dbName);
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
#[TestDox('By ID succeeds when a document exists')]
|
||||
public function testByIdSucceedsWhenADocumentExists(): void
|
||||
{
|
||||
$this->assertTrue(Exists::byId(ThrowawayDb::TABLE, 'three'), 'There should have been an existing document');
|
||||
}
|
||||
|
||||
#[TestDox('By ID succeeds when a document does not exist')]
|
||||
public function testByIdSucceedsWhenADocumentDoesNotExist(): void
|
||||
{
|
||||
$this->assertFalse(Exists::byId(ThrowawayDb::TABLE, 'seven'),
|
||||
'There should not have been an existing document');
|
||||
}
|
||||
|
||||
public function testByFieldsSucceedsWhenDocumentsExist(): void
|
||||
{
|
||||
$this->assertTrue(Exists::byFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 10)]),
|
||||
'There should have been existing documents');
|
||||
}
|
||||
|
||||
public function testByFieldsSucceedsWhenNoMatchingDocumentsExist(): void
|
||||
{
|
||||
$this->assertFalse(Exists::byFields(ThrowawayDb::TABLE, [Field::LT('nothing', 'none')]),
|
||||
'There should not have been any existing documents');
|
||||
}
|
||||
}
|
108
tests/integration/postgresql/FindTest.php
Normal file
108
tests/integration/postgresql/FindTest.php
Normal file
|
@ -0,0 +1,108 @@
|
|||
<?php declare(strict_types=1);
|
||||
|
||||
namespace Test\Integration\PostgreSQL;
|
||||
|
||||
use BitBadger\PDODocument\{Custom, Delete, Document, Field, Find};
|
||||
use PHPUnit\Framework\Attributes\TestDox;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Test\Integration\{NumDocument, TestDocument};
|
||||
|
||||
/**
|
||||
* PostgreSQL integration tests for the Find class
|
||||
*/
|
||||
#[TestDox('Find (PostgreSQL integration)')]
|
||||
class FindTest extends TestCase
|
||||
{
|
||||
/** @var string Database name for throwaway database */
|
||||
private string $dbName;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->dbName = ThrowawayDb::create();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
ThrowawayDb::destroy($this->dbName);
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function testAllSucceedsWhenThereIsData(): void
|
||||
{
|
||||
$docs = Find::all(ThrowawayDb::TABLE, TestDocument::class);
|
||||
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||
$count = 0;
|
||||
foreach ($docs->items() as $ignored) $count++;
|
||||
$this->assertEquals(5, $count, 'There should have been 5 documents in the list');
|
||||
}
|
||||
|
||||
public function testAllSucceedsWhenThereIsNoData(): void
|
||||
{
|
||||
Custom::nonQuery('DELETE FROM ' . ThrowawayDb::TABLE, []);
|
||||
$docs = Find::all(ThrowawayDb::TABLE, TestDocument::class);
|
||||
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||
$this->assertFalse($docs->hasItems(), 'There should have been no documents in the list');
|
||||
}
|
||||
|
||||
#[TestDox('By ID succeeds when a document is found')]
|
||||
public function testByIdSucceedsWhenADocumentIsFound(): void
|
||||
{
|
||||
$doc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class);
|
||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||
$this->assertEquals('two', $doc->id, 'An incorrect document was returned');
|
||||
}
|
||||
|
||||
#[TestDox('By ID succeeds when a document is found with numeric ID')]
|
||||
public function testByIdSucceedsWhenADocumentIsFoundWithNumericId(): void
|
||||
{
|
||||
Delete::byFields(ThrowawayDb::TABLE, [Field::NEX('absent')]);
|
||||
Document::insert(ThrowawayDb::TABLE, ['id' => 18, 'value' => 'howdy']);
|
||||
$doc = Find::byId(ThrowawayDb::TABLE, 18, NumDocument::class);
|
||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||
$this->assertEquals(18, $doc->id, 'An incorrect document was returned');
|
||||
}
|
||||
|
||||
#[TestDox('By ID succeeds when a document is not found')]
|
||||
public function testByIdSucceedsWhenADocumentIsNotFound(): void
|
||||
{
|
||||
$doc = Find::byId(ThrowawayDb::TABLE, 'seventy-five', TestDocument::class);
|
||||
$this->assertFalse($doc, 'There should not have been a document returned');
|
||||
}
|
||||
|
||||
public function testByFieldsSucceedsWhenDocumentsAreFound(): void
|
||||
{
|
||||
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::GT('num_value', 15)], TestDocument::class);
|
||||
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||
$count = 0;
|
||||
foreach ($docs->items() as $ignored) $count++;
|
||||
$this->assertEquals(2, $count, 'There should have been 2 documents in the list');
|
||||
}
|
||||
|
||||
public function testByFieldsSucceedsWhenNoDocumentsAreFound(): void
|
||||
{
|
||||
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::GT('num_value', 100)], TestDocument::class);
|
||||
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||
$this->assertFalse($docs->hasItems(), 'There should have been no documents in the list');
|
||||
}
|
||||
|
||||
public function testFirstByFieldsSucceedsWhenADocumentIsFound(): void
|
||||
{
|
||||
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'another')], TestDocument::class);
|
||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||
$this->assertEquals('two', $doc->id, 'The incorrect document was returned');
|
||||
}
|
||||
|
||||
public function testFirstByFieldsSucceedsWhenMultipleDocumentsAreFound(): void
|
||||
{
|
||||
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('sub.foo', 'green')], TestDocument::class);
|
||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||
$this->assertContains($doc->id, ['two', 'four'], 'An incorrect document was returned');
|
||||
}
|
||||
|
||||
public function testFirstByFieldsSucceedsWhenADocumentIsNotFound(): void
|
||||
{
|
||||
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('value', 'absent')], TestDocument::class);
|
||||
$this->assertFalse($doc, 'There should not have been a document returned');
|
||||
}
|
||||
}
|
59
tests/integration/postgresql/PatchTest.php
Normal file
59
tests/integration/postgresql/PatchTest.php
Normal file
|
@ -0,0 +1,59 @@
|
|||
<?php declare(strict_types=1);
|
||||
|
||||
namespace Test\Integration\PostgreSQL;
|
||||
|
||||
use BitBadger\PDODocument\{Count, Field, Find, Patch};
|
||||
use PHPUnit\Framework\Attributes\TestDox;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Test\Integration\TestDocument;
|
||||
|
||||
/**
|
||||
* PostgreSQL integration tests for the Patch class
|
||||
*/
|
||||
#[TestDox('Patch (PostgreSQL integration)')]
|
||||
class PatchTest extends TestCase
|
||||
{
|
||||
/** @var string Database name for throwaway database */
|
||||
private string $dbName;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->dbName = ThrowawayDb::create();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
ThrowawayDb::destroy($this->dbName);
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
#[TestDox('By ID succeeds when a document is updated')]
|
||||
public function testByIdSucceedsWhenADocumentIsUpdated(): void
|
||||
{
|
||||
Patch::byId(ThrowawayDb::TABLE, 'one', ['num_value' => 44]);
|
||||
$doc = Find::byId(ThrowawayDb::TABLE, 'one', TestDocument::class);
|
||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||
$this->assertEquals(44, $doc->num_value, 'The updated document is not correct');
|
||||
}
|
||||
|
||||
#[TestDox('By ID succeeds when no document is updated')]
|
||||
public function testByIdSucceedsWhenNoDocumentIsUpdated(): void
|
||||
{
|
||||
Patch::byId(ThrowawayDb::TABLE, 'forty-seven', ['foo' => 'green']);
|
||||
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||
}
|
||||
|
||||
public function testByFieldsSucceedsWhenADocumentIsUpdated(): void
|
||||
{
|
||||
Patch::byFields(ThrowawayDb::TABLE, [Field::EQ('value', 'purple')], ['num_value' => 77]);
|
||||
$after = Count::byFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 77)]);
|
||||
$this->assertEquals(2, $after, 'There should have been 2 documents updated');
|
||||
}
|
||||
|
||||
public function testByFieldsSucceedsWhenNoDocumentIsUpdated(): void
|
||||
{
|
||||
Patch::byFields(ThrowawayDb::TABLE, [Field::EQ('value', 'burgundy')], ['foo' => 'green']);
|
||||
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||
}
|
||||
}
|
74
tests/integration/postgresql/RemoveFieldsTest.php
Normal file
74
tests/integration/postgresql/RemoveFieldsTest.php
Normal file
|
@ -0,0 +1,74 @@
|
|||
<?php declare(strict_types=1);
|
||||
|
||||
namespace Test\Integration\PostgreSQL;
|
||||
|
||||
use BitBadger\PDODocument\{Field, Find, RemoveFields};
|
||||
use PHPUnit\Framework\Attributes\TestDox;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Test\Integration\TestDocument;
|
||||
|
||||
/**
|
||||
* PostgreSQL integration tests for the RemoveFields class
|
||||
*/
|
||||
#[TestDox('Remove Fields (PostgreSQL integration)')]
|
||||
class RemoveFieldsTest extends TestCase
|
||||
{
|
||||
/** @var string Database name for throwaway database */
|
||||
private string $dbName;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->dbName = ThrowawayDb::create();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
ThrowawayDb::destroy($this->dbName);
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
#[TestDox('By ID succeeds when fields are removed')]
|
||||
public function testByIdSucceedsWhenFieldsAreRemoved(): void
|
||||
{
|
||||
RemoveFields::byId(ThrowawayDb::TABLE, 'two', ['sub', 'value']);
|
||||
$doc = Find::byId(ThrowawayDb::TABLE, 'two', TestDocument::class);
|
||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||
$this->assertEquals('', $doc->value, 'Value should have been blank (its default value)');
|
||||
$this->assertNull($doc->sub, 'Sub-document should have been null');
|
||||
}
|
||||
|
||||
#[TestDox('By ID succeeds when a field is not removed')]
|
||||
public function testByIdSucceedsWhenAFieldIsNotRemoved(): void
|
||||
{
|
||||
RemoveFields::byId(ThrowawayDb::TABLE, 'one', ['a_field_that_does_not_exist']);
|
||||
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||
}
|
||||
|
||||
#[TestDox('By ID succeeds when no document is matched')]
|
||||
public function testByIdSucceedsWhenNoDocumentIsMatched(): void
|
||||
{
|
||||
RemoveFields::byId(ThrowawayDb::TABLE, 'fifty', ['sub']);
|
||||
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||
}
|
||||
|
||||
public function testByFieldsSucceedsWhenAFieldIsRemoved(): void
|
||||
{
|
||||
RemoveFields::byFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 17)], ['sub']);
|
||||
$doc = Find::firstByFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 17)], TestDocument::class);
|
||||
$this->assertNotFalse($doc, 'There should have been a document returned');
|
||||
$this->assertNull($doc->sub, 'Sub-document should have been null');
|
||||
}
|
||||
|
||||
public function testByFieldsSucceedsWhenAFieldIsNotRemoved(): void
|
||||
{
|
||||
RemoveFields::byFields(ThrowawayDb::TABLE, [Field::EQ('num_value', 17)], ['nada']);
|
||||
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||
}
|
||||
|
||||
public function testByFieldsSucceedsWhenNoDocumentIsMatched(): void
|
||||
{
|
||||
RemoveFields::byFields(ThrowawayDb::TABLE, [Field::NE('missing', 'nope')], ['value']);
|
||||
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||
}
|
||||
}
|
75
tests/integration/postgresql/ThrowawayDb.php
Normal file
75
tests/integration/postgresql/ThrowawayDb.php
Normal file
|
@ -0,0 +1,75 @@
|
|||
<?php declare(strict_types=1);
|
||||
|
||||
namespace Test\Integration\PostgreSQL;
|
||||
|
||||
use BitBadger\PDODocument\{AutoId, Configuration, Custom, Definition, Document, DocumentException, Mode};
|
||||
use Random\RandomException;
|
||||
use Test\Integration\{SubDocument, TestDocument};
|
||||
|
||||
/**
|
||||
* Utilities to create and destroy a throwaway PostgreSQL database to use for testing
|
||||
*/
|
||||
class ThrowawayDb
|
||||
{
|
||||
/** @var string The table used for document manipulation */
|
||||
public const TABLE = "test_table";
|
||||
|
||||
/**
|
||||
* Configure the document library for the given database (or the main PostgreSQL connection, if the database name
|
||||
* is not provided; this is used for creating and dropping databases)
|
||||
*
|
||||
* @param string|null $dbName The name of the database to configure (optional, defaults to env or "postgres")
|
||||
*/
|
||||
private static function configure(?string $dbName = null): void
|
||||
{
|
||||
Configuration::$pdoDSN = sprintf("pgsql:host=%s;dbname=%s", $_ENV['PDO_DOC_PGSQL_HOST'] ?? 'localhost',
|
||||
$dbName ?? $_ENV['PDO_DOC_PGSQL_DB'] ?? 'postgres');
|
||||
Configuration::$username = $_ENV['PDO_DOC_PGSQL_USER'] ?? 'postgres';
|
||||
Configuration::$password = $_ENV['PDO_DOC_PGSQL_PASS'] ?? 'postgres';
|
||||
Configuration::$mode = Mode::PgSQL;
|
||||
Configuration::resetPDO();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a throwaway PostgreSQL database
|
||||
*
|
||||
* @param bool $withData Whether to initialize this database with data (optional; defaults to `true`)
|
||||
* @return string The name of the database (use to pass to `destroy` function at end of test)
|
||||
* @throws DocumentException|RandomException If any is encountered
|
||||
*/
|
||||
public static function create(bool $withData = true): string
|
||||
{
|
||||
$dbName = 'throwaway_' . AutoId::generateRandom(10);
|
||||
self::configure();
|
||||
Custom::nonQuery("CREATE DATABASE $dbName WITH OWNER " . Configuration::$username, []);
|
||||
self::configure($dbName);
|
||||
|
||||
if ($withData) {
|
||||
Definition::ensureTable(self::TABLE);
|
||||
Document::insert(self::TABLE, new TestDocument('one', 'FIRST!', 0));
|
||||
Document::insert(self::TABLE, new TestDocument('two', 'another', 10, new SubDocument('green', 'blue')));
|
||||
Document::insert(self::TABLE, new TestDocument('three', '', 4));
|
||||
Document::insert(self::TABLE, new TestDocument('four', 'purple', 17, new SubDocument('green', 'red')));
|
||||
Document::insert(self::TABLE, new TestDocument('five', 'purple', 18));
|
||||
}
|
||||
|
||||
return $dbName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroy a throwaway PostgreSQL database
|
||||
*
|
||||
* @param string $dbName The name of the PostgreSQL database to be dropped
|
||||
* @throws DocumentException If any is encountered
|
||||
*/
|
||||
public static function destroy(string $dbName): void
|
||||
{
|
||||
self::configure();
|
||||
Custom::nonQuery("DROP DATABASE IF EXISTS $dbName WITH (FORCE)", []);
|
||||
Configuration::$pdoDSN = '';
|
||||
Configuration::$username = null;
|
||||
Configuration::$password = null;
|
||||
Configuration::$mode = null;
|
||||
Configuration::resetPDO();
|
||||
}
|
||||
}
|
|
@ -82,8 +82,6 @@ class FindTest extends TestCase
|
|||
{
|
||||
$docs = Find::byFields(ThrowawayDb::TABLE, [Field::GT('num_value', 100)], TestDocument::class);
|
||||
$this->assertNotNull($docs, 'There should have been a document list returned');
|
||||
$count = 0;
|
||||
foreach ($docs->items() as $ignored) $count++;
|
||||
$this->assertFalse($docs->hasItems(), 'There should have been no documents in the list');
|
||||
}
|
||||
|
||||
|
|
|
@ -44,7 +44,6 @@ class PatchTest extends TestCase
|
|||
$this->assertTrue(true, 'The above not throwing an exception is the test');
|
||||
}
|
||||
|
||||
|
||||
public function testByFieldsSucceedsWhenADocumentIsUpdated(): void
|
||||
{
|
||||
Patch::byFields(ThrowawayDb::TABLE, [Field::EQ('value', 'purple')], ['num_value' => 77]);
|
||||
|
|
|
@ -2,13 +2,9 @@
|
|||
|
||||
namespace Test\Integration\SQLite;
|
||||
|
||||
use BitBadger\PDODocument\Configuration;
|
||||
use BitBadger\PDODocument\Definition;
|
||||
use BitBadger\PDODocument\Document;
|
||||
use BitBadger\PDODocument\DocumentException;
|
||||
use BitBadger\PDODocument\Mode;
|
||||
use Test\Integration\SubDocument;
|
||||
use Test\Integration\TestDocument;
|
||||
use BitBadger\PDODocument\{AutoId, Configuration, Definition, Document, DocumentException, Mode};
|
||||
use Random\RandomException;
|
||||
use Test\Integration\{SubDocument, TestDocument};
|
||||
|
||||
/**
|
||||
* Utilities to create and destroy a throwaway SQLite database to use for testing
|
||||
|
@ -16,18 +12,18 @@ use Test\Integration\TestDocument;
|
|||
class ThrowawayDb
|
||||
{
|
||||
/** @var string The table used for document manipulation */
|
||||
public const string TABLE = "test_table";
|
||||
public const TABLE = "test_table";
|
||||
|
||||
/**
|
||||
* Create a throwaway SQLite database
|
||||
*
|
||||
* @param bool $withData Whether to initialize this database with data (optional; defaults to `true`)
|
||||
* @return string The name of the database (use to pass to `destroy` function at end of test)
|
||||
* @throws DocumentException If any is encountered
|
||||
* @throws DocumentException|RandomException If any is encountered
|
||||
*/
|
||||
public static function create(bool $withData = true): string
|
||||
{
|
||||
$fileName = sprintf('throwaway-%s-%d.db', date('His'), rand(10, 99));
|
||||
$fileName = sprintf('throwaway-%s.db', AutoId::generateRandom(10));
|
||||
Configuration::$pdoDSN = "sqlite:./$fileName";
|
||||
Configuration::$mode = Mode::SQLite;
|
||||
Configuration::resetPDO();
|
||||
|
@ -54,18 +50,4 @@ class ThrowawayDb
|
|||
Configuration::resetPDO();
|
||||
unlink("./$fileName");
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroy the given throwaway database and create another
|
||||
*
|
||||
* @param string $fileName The name of the database to be destroyed
|
||||
* @param bool $withData Whether to initialize the database with data (optional; defaults to `true`)
|
||||
* @return string The name of the new database
|
||||
* @throws DocumentException If any is encountered
|
||||
*/
|
||||
public static function exchange(string $fileName, bool $withData = true): string
|
||||
{
|
||||
self::destroy($fileName);
|
||||
return self::create($withData);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -221,7 +221,7 @@ class FieldTest extends TestCase
|
|||
try {
|
||||
$field = Field::LE('le_field', 18, '@it');
|
||||
$field->qualifier = 'q';
|
||||
$this->assertEquals("q.data->>'le_field' <= @it", $field->toWhere(),
|
||||
$this->assertEquals("(q.data->>'le_field')::numeric <= @it", $field->toWhere(),
|
||||
'WHERE fragment not generated correctly');
|
||||
} finally {
|
||||
Configuration::$mode = null;
|
||||
|
@ -248,7 +248,7 @@ class FieldTest extends TestCase
|
|||
Configuration::$mode = Mode::PgSQL;
|
||||
try {
|
||||
$field = Field::EQ('sub.foo.bar', 22, '@it');
|
||||
$this->assertEquals("data->>'sub.foo.bar' = @it", $field->toWhere(),
|
||||
$this->assertEquals("(data#>>'{sub,foo,bar}')::numeric = @it", $field->toWhere(),
|
||||
'WHERE fragment not generated correctly');
|
||||
} finally {
|
||||
Configuration::$mode = null;
|
||||
|
|
|
@ -51,7 +51,7 @@ class ParametersTest extends TestCase
|
|||
{
|
||||
try {
|
||||
Configuration::$mode = Mode::PgSQL;
|
||||
$this->assertEquals([':names' => "ARRAY['one','two','seven']"],
|
||||
$this->assertEquals([':names' => "{one,two,seven}"],
|
||||
Parameters::fieldNames(':names', ['one', 'two', 'seven']), 'Field name parameters not correct');
|
||||
} finally {
|
||||
Configuration::$mode = null;
|
||||
|
|
|
@ -49,7 +49,7 @@ class PatchTest extends TestCase
|
|||
{
|
||||
try {
|
||||
Configuration::$mode = Mode::PgSQL;
|
||||
$this->assertEquals("UPDATE that SET data = data || :data WHERE data->>'something' < :some",
|
||||
$this->assertEquals("UPDATE that SET data = data || :data WHERE (data->>'something')::numeric < :some",
|
||||
Patch::byFields('that', [Field::LT('something', 17, ':some')]),
|
||||
'Patch UPDATE statement is not correct');
|
||||
} finally {
|
||||
|
|
|
@ -17,8 +17,8 @@ class RemoveFieldsTest extends TestCase
|
|||
{
|
||||
try {
|
||||
Configuration::$mode = Mode::PgSQL;
|
||||
$this->assertEquals('UPDATE taco SET data = data - :names WHERE it = true',
|
||||
RemoveFields::update('taco', [':names' => "ARRAY['one','two']"], 'it = true'),
|
||||
$this->assertEquals('UPDATE taco SET data = data - :names::text[] WHERE it = true',
|
||||
RemoveFields::update('taco', [':names' => "{one,two}"], 'it = true'),
|
||||
'UPDATE statement not correct');
|
||||
} finally {
|
||||
Configuration::$mode = null;
|
||||
|
@ -50,7 +50,7 @@ class RemoveFieldsTest extends TestCase
|
|||
{
|
||||
try {
|
||||
Configuration::$mode = Mode::PgSQL;
|
||||
$this->assertEquals("UPDATE churro SET data = data - :bite WHERE data->>'id' = :id",
|
||||
$this->assertEquals("UPDATE churro SET data = data - :bite::text[] WHERE data->>'id' = :id",
|
||||
RemoveFields::byId('churro', Parameters::fieldNames(':bite', ['byte'])),
|
||||
'UPDATE statement not correct');
|
||||
} finally {
|
||||
|
@ -84,7 +84,7 @@ class RemoveFieldsTest extends TestCase
|
|||
{
|
||||
try {
|
||||
Configuration::$mode = Mode::PgSQL;
|
||||
$this->assertEquals("UPDATE enchilada SET data = data - :sauce WHERE data->>'cheese' = :queso",
|
||||
$this->assertEquals("UPDATE enchilada SET data = data - :sauce::text[] WHERE data->>'cheese' = :queso",
|
||||
RemoveFields::byFields('enchilada', [Field::EQ('cheese', 'jack', ':queso')],
|
||||
Parameters::fieldNames(':sauce', ['white'])),
|
||||
'UPDATE statement not correct');
|
||||
|
|
|
@ -90,8 +90,8 @@ class QueryTest extends TestCase
|
|||
Configuration::$mode = Mode::PgSQL;
|
||||
try {
|
||||
$this->assertEquals(
|
||||
"INSERT INTO test_tbl VALUES (:data || ('{\"id\":' "
|
||||
. "|| (SELECT COALESCE(MAX(data->>'id'), 0) + 1 FROM test_tbl) || '}'))",
|
||||
"INSERT INTO test_tbl VALUES (:data::jsonb || ('{\"id\":' "
|
||||
. "|| (SELECT COALESCE(MAX((data->>'id')::numeric), 0) + 1 FROM test_tbl) || '}')::jsonb)",
|
||||
Query::insert('test_tbl', AutoId::Number), 'INSERT statement not constructed correctly');
|
||||
} finally {
|
||||
Configuration::$mode = null;
|
||||
|
@ -118,7 +118,7 @@ class QueryTest extends TestCase
|
|||
Configuration::$mode = Mode::PgSQL;
|
||||
try {
|
||||
$query = Query::insert('test_tbl', AutoId::UUID);
|
||||
$this->assertStringStartsWith("INSERT INTO test_tbl VALUES (:data || '{\"id\":\"", $query,
|
||||
$this->assertStringStartsWith("INSERT INTO test_tbl VALUES (:data::jsonb || '{\"id\":\"", $query,
|
||||
'INSERT statement not constructed correctly');
|
||||
$this->assertStringEndsWith("\"}')", $query, 'INSERT statement not constructed correctly');
|
||||
} finally {
|
||||
|
@ -147,10 +147,10 @@ class QueryTest extends TestCase
|
|||
Configuration::$idStringLength = 8;
|
||||
try {
|
||||
$query = Query::insert('test_tbl', AutoId::RandomString);
|
||||
$this->assertStringStartsWith("INSERT INTO test_tbl VALUES (:data || '{\"id\":\"", $query,
|
||||
$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 || '{\"id\":\"", "\"}')"], '', $query);
|
||||
$id = str_replace(["INSERT INTO test_tbl VALUES (:data::jsonb || '{\"id\":\"", "\"}')"], '', $query);
|
||||
$this->assertEquals(8, strlen($id), "Generated ID [$id] should have been 8 characters long");
|
||||
} finally {
|
||||
Configuration::$mode = null;
|
||||
|
|
Loading…
Reference in New Issue
Block a user