Add auto ID enum, modify insert queries

This commit is contained in:
Daniel J. Summers 2024-06-10 21:12:21 -04:00
parent 9729c50c00
commit c892689eb6
8 changed files with 243 additions and 15 deletions

View File

@ -17,7 +17,7 @@
"rss": "https://git.bitbadger.solutions/bit-badger/pdo-document.rss" "rss": "https://git.bitbadger.solutions/bit-badger/pdo-document.rss"
}, },
"require": { "require": {
"php": ">=8.1", "php": ">=8.2",
"netresearch/jsonmapper": "^4", "netresearch/jsonmapper": "^4",
"ext-pdo": "*" "ext-pdo": "*"
}, },

4
composer.lock generated
View File

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "f4563891566be8872ae85552261303bd", "content-hash": "20bf0d96304e429b431535d05ff4585a",
"packages": [ "packages": [
{ {
"name": "netresearch/jsonmapper", "name": "netresearch/jsonmapper",
@ -1697,7 +1697,7 @@
"prefer-stable": false, "prefer-stable": false,
"prefer-lowest": false, "prefer-lowest": false,
"platform": { "platform": {
"php": ">=8.1", "php": ">=8.2",
"ext-pdo": "*" "ext-pdo": "*"
}, },
"platform-dev": [], "platform-dev": [],

51
src/AutoId.php Normal file
View File

@ -0,0 +1,51 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument;
use Random\RandomException;
/**
* How automatic ID generation should be performed
*/
enum AutoId
{
/** Do not automatically generate IDs */
case None;
/** New documents with a 0 ID should receive max ID plus one */
case Number;
/** New documents with a blank ID should receive a v4 UUID (Universally Unique Identifier) */
case UUID;
/** New documents with a blank ID should receive a random string (set `Configuration::$idStringLength`) */
case RandomString;
/**
* Generate a v4 UUID
*
* @return string The v4 UUID
* @throws RandomException If an appropriate source of randomness cannot be found
*/
public static function generateUUID(): string
{
// hat tip: https://stackoverflow.com/a/15875555/276707
$bytes = random_bytes(16);
$bytes[6] = chr(ord($bytes[6]) & 0x0f | 0x40); // set version to 0100
$bytes[8] = chr(ord($bytes[8]) & 0x3f | 0x80); // set bits 6-7 to 10
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4));
}
/**
* Generate a random string ID
*
* @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
{
return bin2hex(random_bytes(Configuration::$idStringLength / 2));
}
}

View File

@ -12,6 +12,14 @@ class Configuration
/** @var string The name of the ID field used in the database (will be treated as the primary key) */ /** @var string The name of the ID field used in the database (will be treated as the primary key) */
public static string $idField = 'id'; public static string $idField = 'id';
/** @var AutoId The automatic ID generation process to use */
public static AutoId $autoId = AutoId::None;
/**
* @var int The number of characters a string generated by `AutoId::RandomString` will have (must be an even number)
*/
public static int $idStringLength = 16;
/** @var string The data source name (DSN) of the connection string */ /** @var string The data source name (DSN) of the connection string */
public static string $pdoDSN = ''; public static string $pdoDSN = '';
@ -59,7 +67,9 @@ class Configuration
return self::$_pdo; return self::$_pdo;
} }
/**
* Clear the current PDO instance
*/
public static function resetPDO(): void public static function resetPDO(): void
{ {
self::$_pdo = null; self::$_pdo = null;

View File

@ -2,6 +2,8 @@
namespace BitBadger\PDODocument; namespace BitBadger\PDODocument;
use BitBadger\PDODocument\Query\Insert;
/** /**
* Functions that apply at a whole document level * Functions that apply at a whole document level
*/ */

View File

@ -2,6 +2,8 @@
namespace BitBadger\PDODocument; namespace BitBadger\PDODocument;
use Random\RandomException;
/** /**
* Query construction functions * Query construction functions
*/ */
@ -45,14 +47,38 @@ class Query
} }
/** /**
* Query to insert a document * Create an `INSERT` statement for a document
* *
* @param string $tableName The name of the table into which a document should be inserted * @param string $tableName The name of the table into which the document will be inserted
* @return string The INSERT statement for the given table * @return string The `INSERT` statement to insert a document
* @throws DocumentException If the database mode is not set
*/ */
public static function insert(string $tableName): string public static function insert(string $tableName): string
{ {
return "INSERT INTO $tableName VALUES (:data)"; try {
$id = Configuration::$idField;
$values = match (Configuration::$mode) {
Mode::SQLite => match (Configuration::$autoId) {
AutoId::None => ':data',
AutoId::Number => "json_set(:data, '$.$id', "
. "(SELECT coalesce(max(data->>'$id'), 0) + 1 FROM $tableName))",
AutoId::UUID => "json_set(:data, '$.$id', '" . AutoId::generateUUID() . "')",
AutoId::RandomString => "json_set(:data, '$.$id', '" . AutoId::generateRandom() ."')"
},
Mode::PgSQL => match (Configuration::$autoId) {
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() . "\"}'",
},
default =>
throw new DocumentException('Database mode not set; cannot generate auto-ID INSERT statement'),
};
return "INSERT INTO $tableName VALUES ($values)";
} catch (RandomException $ex) {
throw new DocumentException('Unable to generate ID: ' . $ex->getMessage(), previous: $ex);
}
} }
/** /**
@ -63,8 +89,8 @@ class Query
*/ */
public static function save(string $tableName): string public static function save(string $tableName): string
{ {
return self::insert($tableName) $id = Configuration::$idField;
. " ON CONFLICT ((data->>'" . Configuration::$idField . "')) DO UPDATE SET data = EXCLUDED.data"; return "INSERT INTO $tableName VALUES (:data) ON CONFLICT ((data->>'$id')) DO UPDATE SET data = EXCLUDED.data";
} }
/** /**

View File

@ -2,7 +2,7 @@
namespace Test\Unit; namespace Test\Unit;
use BitBadger\PDODocument\{Configuration, DocumentException}; use BitBadger\PDODocument\{AutoId, Configuration, DocumentException};
use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
@ -29,6 +29,18 @@ class ConfigurationTest extends TestCase
} }
} }
#[TestDox('Auto ID default succeeds')]
public function testAutoIdDefaultSucceeds(): void
{
$this->assertEquals(AutoId::None, Configuration::$autoId, 'Auto ID should default to None');
}
#[TestDox('ID string length default succeeds')]
public function testIdStringLengthDefaultSucceeds(): void
{
$this->assertEquals(16, Configuration::$idStringLength, 'ID string length should default to 16');
}
#[TestDox("Db conn fails when no DSN specified")] #[TestDox("Db conn fails when no DSN specified")]
public function testDbConnFailsWhenNoDSNSpecified(): void public function testDbConnFailsWhenNoDSNSpecified(): void
{ {

View File

@ -2,7 +2,7 @@
namespace Test\Unit; namespace Test\Unit;
use BitBadger\PDODocument\{Configuration, Field, FieldMatch, Mode, Query}; use BitBadger\PDODocument\{AutoId, Configuration, DocumentException, Field, FieldMatch, Mode, Query};
use PHPUnit\Framework\Attributes\TestDox; use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
@ -60,10 +60,137 @@ class QueryTest extends TestCase
$this->assertEquals("data->>'id' = :di", Query::whereById(':di'), 'WHERE fragment not constructed correctly'); $this->assertEquals("data->>'id' = :di", Query::whereById(':di'), 'WHERE fragment not constructed correctly');
} }
public function testInsertSucceeds(): void #[TestDox('Insert succeeds with no auto-ID for PostgreSQL')]
public function testInsertSucceedsWithNoAutoIdForPostgreSQL(): void
{ {
$this->assertEquals('INSERT INTO my_table VALUES (:data)', Query::insert('my_table'), Configuration::$mode = Mode::PgSQL;
'INSERT statement not constructed correctly'); try {
$this->assertEquals('INSERT INTO test_tbl VALUES (:data)', Query::insert('test_tbl'),
'INSERT statement not constructed correctly');
} finally {
Configuration::$mode = null;
}
}
#[TestDox('Insert succeeds with no auto-ID for SQLite')]
public function testInsertSucceedsWithNoAutoIdForSQLite(): void
{
Configuration::$mode = Mode::SQLite;
try {
$this->assertEquals('INSERT INTO test_tbl VALUES (:data)', Query::insert('test_tbl'),
'INSERT statement not constructed correctly');
} finally {
Configuration::$mode = null;
}
}
#[TestDox('Insert succeeds with auto numeric ID for PostgreSQL')]
public function testInsertSucceedsWithAutoNumericIdForPostgreSQL(): void
{
Configuration::$mode = Mode::PgSQL;
Configuration::$autoId = AutoId::Number;
try {
$this->assertEquals(
"INSERT INTO test_tbl VALUES (:data || ('{\"id\":' "
. "|| (SELECT COALESCE(MAX(data->>'id'), 0) + 1 FROM test_tbl) || '}'))",
Query::insert('test_tbl'), 'INSERT statement not constructed correctly');
} finally {
Configuration::$mode = null;
Configuration::$autoId = AutoId::None;
}
}
#[TestDox('Insert succeeds with auto numeric ID for SQLite')]
public function testInsertSucceedsWithAutoNumericIdForSQLite(): void
{
Configuration::$mode = Mode::SQLite;
Configuration::$autoId = AutoId::Number;
try {
$this->assertEquals(
"INSERT INTO test_tbl VALUES (json_set(:data, '$.id', "
. "(SELECT coalesce(max(data->>'id'), 0) + 1 FROM test_tbl)))",
Query::insert('test_tbl'), 'INSERT statement not constructed correctly');
} finally {
Configuration::$mode = null;
Configuration::$autoId = AutoId::None;
}
}
#[TestDox('Insert succeeds with auto UUID for PostgreSQL')]
public function testInsertSucceedsWithAutoUuidForPostgreSQL(): void
{
Configuration::$mode = Mode::PgSQL;
Configuration::$autoId = AutoId::UUID;
try {
$query = Query::insert('test_tbl');
$this->assertStringStartsWith("INSERT INTO test_tbl VALUES (:data || '{\"id\":\"", $query,
'INSERT statement not constructed correctly');
$this->assertStringEndsWith("\"}')", $query, 'INSERT statement not constructed correctly');
} finally {
Configuration::$mode = null;
Configuration::$autoId = AutoId::None;
}
}
#[TestDox('Insert succeeds with auto UUID for SQLite')]
public function testInsertSucceedsWithAutoUuidForSQLite(): void
{
Configuration::$mode = Mode::SQLite;
Configuration::$autoId = AutoId::UUID;
try {
$query = Query::insert('test_tbl');
$this->assertStringStartsWith("INSERT INTO test_tbl VALUES (json_set(:data, '$.id', '", $query,
'INSERT statement not constructed correctly');
$this->assertStringEndsWith("'))", $query, 'INSERT statement not constructed correctly');
} finally {
Configuration::$mode = null;
Configuration::$autoId = AutoId::None;
}
}
#[TestDox('Insert succeeds with auto random string for PostgreSQL')]
public function testInsertSucceedsWithAutoRandomStringForPostgreSQL(): void
{
Configuration::$mode = Mode::PgSQL;
Configuration::$autoId = AutoId::RandomString;
Configuration::$idStringLength = 8;
try {
$query = Query::insert('test_tbl');
$this->assertStringStartsWith("INSERT INTO test_tbl VALUES (:data || '{\"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);
$this->assertEquals(8, strlen($id), "Generated ID [$id] should have been 8 characters long");
} finally {
Configuration::$mode = null;
Configuration::$autoId = AutoId::None;
Configuration::$idStringLength = 16;
}
}
#[TestDox('Insert succeeds with auto random string for SQLite')]
public function testInsertSucceedsWithAutoRandomStringForSQLite(): void
{
Configuration::$mode = Mode::SQLite;
Configuration::$autoId = AutoId::RandomString;
try {
$query = Query::insert('test_tbl');
$this->assertStringStartsWith("INSERT INTO test_tbl VALUES (json_set(:data, '$.id', '", $query,
'INSERT statement not constructed correctly');
$this->assertStringEndsWith("'))", $query, 'INSERT statement not constructed correctly');
$id = str_replace(["INSERT INTO test_tbl VALUES (json_set(:data, '$.id', '", "'))"], '', $query);
$this->assertEquals(16, strlen($id), "Generated ID [$id] should have been 16 characters long");
} finally {
Configuration::$mode = null;
Configuration::$autoId = AutoId::None;
}
}
public function testInsertFailsWhenModeNotSet(): void
{
$this->expectException(DocumentException::class);
Configuration::$mode = null;
Query::insert('kaboom');
} }
public function testSaveSucceeds(): void public function testSaveSucceeds(): void