- Change multiple field matching to enum
- Implement auto-generated IDs

Reviewed-on: #2
This commit was merged in pull request #2.
This commit is contained in:
2024-06-11 11:07:56 +00:00
parent 1f1f06679f
commit 330e272187
26 changed files with 617 additions and 73 deletions

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) */
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 */
public static string $pdoDSN = '';
@@ -59,7 +67,9 @@ class Configuration
return self::$_pdo;
}
/**
* Clear the current PDO instance
*/
public static function resetPDO(): void
{
self::$_pdo = null;

View File

@@ -26,14 +26,14 @@ class Count
*
* @param string $tableName The name of the table in which documents should be counted
* @param array|Field[] $fields The field comparison to match
* @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
* @return int The count of documents matching the field comparison
* @throws DocumentException If one is encountered
*/
public static function byFields(string $tableName, array $fields, string $conjunction = 'AND'): int
public static function byFields(string $tableName, array $fields, ?FieldMatch $match = null): int
{
$namedFields = Parameters::nameFields($fields);
return Custom::scalar(Query\Count::byFields($tableName, $namedFields, $conjunction),
return Custom::scalar(Query\Count::byFields($tableName, $namedFields, $match),
Parameters::addFields($namedFields, []), new CountMapper());
}
}

View File

@@ -24,13 +24,13 @@ class Delete
*
* @param string $tableName The table from which documents should be deleted
* @param array|Field[] $fields The field comparison to match
* @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
* @throws DocumentException If any is encountered
*/
public static function byFields(string $tableName, array $fields, string $conjunction = 'AND'): void
public static function byFields(string $tableName, array $fields, ?FieldMatch $match = null): void
{
$namedFields = Parameters::nameFields($fields);
Custom::nonQuery(Query\Delete::byFields($tableName, $namedFields, $conjunction),
Custom::nonQuery(Query\Delete::byFields($tableName, $namedFields, $match),
Parameters::addFields($namedFields, []));
}
}

View File

@@ -16,7 +16,25 @@ class Document
*/
public static function insert(string $tableName, array|object $document): void
{
Custom::nonQuery(Query::insert($tableName), Parameters::json(':data', $document));
$doInsert = fn() => Custom::nonQuery(Query::insert($tableName), Parameters::json(':data', $document));
if (Configuration::$autoId == AutoId::None) {
$doInsert();
return;
}
$id = Configuration::$idField;
$idProvided =
(is_array( $document) && is_int( $document[$id]) && $document[$id] <> 0)
|| (is_array( $document) && is_string($document[$id]) && $document[$id] <> '')
|| (is_object($document) && is_int( $document->{$id}) && $document->{$id} <> 0)
|| (is_object($document) && is_string($document->{$id}) && $document->{$id} <> '');
if ($idProvided) {
$doInsert();
} else {
Custom::nonQuery(Query::insert($tableName, Configuration::$autoId), Parameters::json(':data', $document));
}
}
/**

View File

@@ -27,14 +27,14 @@ class Exists
*
* @param string $tableName The name of the table in which document existence should be determined
* @param Field[] $fields The field comparison to match
* @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
* @return bool True if any documents match the field comparison, false if not
* @throws DocumentException If any is encountered
*/
public static function byFields(string $tableName, array $fields, string $conjunction = 'AND'): bool
public static function byFields(string $tableName, array $fields, ?FieldMatch $match = null): bool
{
$namedFields = Parameters::nameFields($fields);
return Custom::scalar(Query\Exists::byFields($tableName, $namedFields, $conjunction),
return Custom::scalar(Query\Exists::byFields($tableName, $namedFields, $match),
Parameters::addFields($namedFields, []), new ExistsMapper());
}
}

28
src/FieldMatch.php Normal file
View File

@@ -0,0 +1,28 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument;
/**
* How multiple fields should be matched
*/
enum FieldMatch
{
/** Match all provided fields (`AND`) */
case All;
/** Match any provided fields (`OR`) */
case Any;
/**
* Get the SQL keyword for this enumeration value
*
* @return string The SQL keyword for this enumeration value
*/
public function toString(): string
{
return match ($this) {
FieldMatch::All => 'AND',
FieldMatch::Any => 'OR'
};
}
}

View File

@@ -45,15 +45,15 @@ class Find
* @param string $tableName The table from which documents should be retrieved
* @param array|Field[] $fields The field comparison to match
* @param class-string<TDoc> $className The name of the class to be retrieved
* @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
* @return DocumentList<TDoc> A list of documents matching the given field comparison
* @throws DocumentException If any is encountered
*/
public static function byFields(string $tableName, array $fields, string $className,
string $conjunction = 'AND'): DocumentList
?FieldMatch $match = null): DocumentList
{
$namedFields = Parameters::nameFields($fields);
return Custom::list(Query\Find::byFields($tableName, $namedFields, $conjunction),
return Custom::list(Query\Find::byFields($tableName, $namedFields, $match),
Parameters::addFields($namedFields, []), new DocumentMapper($className));
}
@@ -64,15 +64,15 @@ class Find
* @param string $tableName The table from which the document should be retrieved
* @param array|Field[] $fields The field comparison to match
* @param class-string<TDoc> $className The name of the class to be retrieved
* @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
* @return false|TDoc The first document if any matches are found, false otherwise
* @throws DocumentException If any is encountered
*/
public static function firstByFields(string $tableName, array $fields, string $className,
string $conjunction = 'AND'): mixed
?FieldMatch $match = null): mixed
{
$namedFields = Parameters::nameFields($fields);
return Custom::single(Query\Find::byFields($tableName, $namedFields, $conjunction),
return Custom::single(Query\Find::byFields($tableName, $namedFields, $match),
Parameters::addFields($namedFields, []), new DocumentMapper($className));
}
}

View File

@@ -27,14 +27,14 @@ class Patch
* @param string $tableName The table in which documents should be patched
* @param array|Field[] $fields The field comparison to match
* @param array|object $patch The object with which the documents should be patched (will be JSON-encoded)
* @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
* @throws DocumentException If any is encountered
*/
public static function byFields(string $tableName, array $fields, array|object $patch,
string $conjunction = 'AND'): void
?FieldMatch $match = null): void
{
$namedFields = Parameters::nameFields($fields);
Custom::nonQuery(Query\Patch::byFields($tableName, $namedFields, $conjunction),
Custom::nonQuery(Query\Patch::byFields($tableName, $namedFields, $match),
Parameters::addFields($namedFields, Parameters::json(':data', $patch)));
}
}

View File

@@ -2,6 +2,8 @@
namespace BitBadger\PDODocument;
use Random\RandomException;
/**
* Query construction functions
*/
@@ -22,12 +24,14 @@ class Query
* Create a WHERE clause fragment to implement a comparison on fields in a JSON document
*
* @param Field[] $fields The field comparison to generate
* @param string $conjunction How to join multiple conditions (optional; defaults to AND)
* @param FieldMatch|null $match How to join multiple conditions (optional; defaults to All)
* @return string The WHERE clause fragment matching the given fields and parameter
* @throws DocumentException If the database mode has not been set
*/
public static function whereByFields(array $fields, string $conjunction = 'AND'): string
public static function whereByFields(array $fields, ?FieldMatch $match = null): string
{
return implode(" $conjunction ", array_map(fn($it) => $it->toWhere(), $fields));
return implode(' ' . ($match ?? FieldMatch::All)->toString() . ' ',
array_map(fn($it) => $it->toWhere(), $fields));
}
/**
@@ -35,6 +39,7 @@ class Query
*
* @param string $paramName The parameter name where the value of the ID will be provided (optional; default @id)
* @return string The WHERE clause fragment to match by ID
* @throws DocumentException If the database mode has not been set
*/
public static function whereById(string $paramName = ':id'): string
{
@@ -42,14 +47,39 @@ 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
* @return string The INSERT statement for the given table
* @param string $tableName The name of the table into which the document will be inserted
* @param AutoId|null $autoId The version of automatic ID query to generate (optional, defaults to None)
* @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, ?AutoId $autoId = null): string
{
return "INSERT INTO $tableName VALUES (:data)";
try {
$id = Configuration::$idField;
$values = match (Configuration::$mode) {
Mode::SQLite => match ($autoId ?? AutoId::None) {
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 ($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() . "\"}'",
},
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);
}
}
/**
@@ -60,8 +90,8 @@ class Query
*/
public static function save(string $tableName): string
{
return self::insert($tableName)
. " ON CONFLICT ((data->>'" . Configuration::$idField . "')) DO UPDATE SET data = EXCLUDED.data";
$id = Configuration::$idField;
return "INSERT INTO $tableName VALUES (:data) ON CONFLICT ((data->>'$id')) DO UPDATE SET data = EXCLUDED.data";
}
/**
@@ -69,6 +99,7 @@ class Query
*
* @param string $tableName The name of the table in which the document should be updated
* @return string The UPDATE query for the document
* @throws DocumentException If the database mode has not been set
*/
public static function update(string $tableName): string
{

View File

@@ -2,7 +2,7 @@
namespace BitBadger\PDODocument\Query;
use BitBadger\PDODocument\{Field, Query};
use BitBadger\PDODocument\{DocumentException, Field, FieldMatch, Query};
/**
* Queries for counting documents
@@ -25,11 +25,12 @@ class Count
*
* @param string $tableName The name of the table in which documents should be counted
* @param Field[] $fields The field comparison to match
* @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
* @param FieldMatch|null $match How to join multiple conditions (optional; defaults to All)
* @return string The query to count documents using a field comparison
* @throws DocumentException If the database mode has not been set
*/
public static function byFields(string $tableName, array $fields, string $conjunction = 'AND'): string
public static function byFields(string $tableName, array $fields, ?FieldMatch $match = null): string
{
return self::all($tableName) . ' WHERE ' . Query::whereByFields($fields, $conjunction);
return self::all($tableName) . ' WHERE ' . Query::whereByFields($fields, $match);
}
}

View File

@@ -2,7 +2,7 @@
namespace BitBadger\PDODocument\Query;
use BitBadger\PDODocument\{Field, Query};
use BitBadger\PDODocument\{DocumentException, Field, FieldMatch, Query};
/**
* Queries to delete documents
@@ -14,6 +14,7 @@ class Delete
*
* @param string $tableName The name of the table from which a document should be deleted
* @return string The DELETE statement to delete a document by its ID
* @throws DocumentException If the database mode has not been set
*/
public static function byId(string $tableName): string
{
@@ -25,11 +26,12 @@ class Delete
*
* @param string $tableName The name of the table from which documents should be deleted
* @param Field[] $fields The field comparison to match
* @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
* @return string The DELETE statement to delete documents via field comparison
* @throws DocumentException If the database mode has not been set
*/
public static function byFields(string $tableName, array $fields, string $conjunction = 'AND'): string
public static function byFields(string $tableName, array $fields, ?FieldMatch $match = null): string
{
return "DELETE FROM $tableName WHERE " . Query::whereByFields($fields, $conjunction);
return "DELETE FROM $tableName WHERE " . Query::whereByFields($fields, $match);
}
}

View File

@@ -2,7 +2,7 @@
namespace BitBadger\PDODocument\Query;
use BitBadger\PDODocument\{Field, Query};
use BitBadger\PDODocument\{DocumentException, Field, FieldMatch, Query};
/**
* Queries to determine document existence
@@ -26,6 +26,7 @@ class Exists
*
* @param string $tableName The name of the table in which document existence should be checked
* @return string The query to determine document existence by ID
* @throws DocumentException If the database mode has not been set
*/
public static function byId(string $tableName): string
{
@@ -37,11 +38,12 @@ class Exists
*
* @param string $tableName The name of the table in which document existence should be checked
* @param Field[] $fields The field comparison to match
* @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
* @return string The query to determine document existence by field comparison
* @throws DocumentException If the database mode has not been set
*/
public static function byFields(string $tableName, array $fields, string $conjunction = 'AND'): string
public static function byFields(string $tableName, array $fields, ?FieldMatch $match = null): string
{
return self::query($tableName, Query::whereByFields($fields, $conjunction));
return self::query($tableName, Query::whereByFields($fields, $match));
}
}

View File

@@ -2,7 +2,7 @@
namespace BitBadger\PDODocument\Query;
use BitBadger\PDODocument\{Field, Query};
use BitBadger\PDODocument\{DocumentException, Field, FieldMatch, Query};
/**
* Queries for retrieving documents
@@ -14,6 +14,7 @@ class Find
*
* @param string $tableName The name of the table from which a document should be retrieved
* @return string The SELECT statement to retrieve a document by its ID
* @throws DocumentException If the database mode has not been set
*/
public static function byId(string $tableName): string
{
@@ -25,11 +26,12 @@ class Find
*
* @param string $tableName The name of the table from which documents should be retrieved
* @param Field[] $fields The field comparison to match
* @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
* @return string The SELECT statement to retrieve documents by field comparison
* @throws DocumentException If the database mode has not been set
*/
public static function byFields(string $tableName, array $fields, string $conjunction = 'AND'): string
public static function byFields(string $tableName, array $fields, ?FieldMatch $match = null): string
{
return Query::selectFromTable($tableName) . ' WHERE ' . Query::whereByFields($fields, $conjunction);
return Query::selectFromTable($tableName) . ' WHERE ' . Query::whereByFields($fields, $match);
}
}

View File

@@ -2,7 +2,7 @@
namespace BitBadger\PDODocument\Query;
use BitBadger\PDODocument\{Configuration, DocumentException, Field, Mode, Query};
use BitBadger\PDODocument\{Configuration, DocumentException, Field, FieldMatch, Mode, Query};
/**
* Queries to perform partial updates on documents
@@ -44,12 +44,12 @@ class Patch
*
* @param string $tableName The name of the table in which documents should be patched
* @param array|Field[] $field The field comparison to match
* @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
* @return string The query to patch documents via field comparison
* @throws DocumentException If the database mode has not been set
*/
public static function byFields(string $tableName, array $field, string $conjunction = 'AND'): string
public static function byFields(string $tableName, array $field, ?FieldMatch $match = null): string
{
return self::update($tableName, Query::whereByFields($field, $conjunction));
return self::update($tableName, Query::whereByFields($field, $match));
}
}

View File

@@ -2,7 +2,7 @@
namespace BitBadger\PDODocument\Query;
use BitBadger\PDODocument\{Configuration, DocumentException, Field, Mode, Query};
use BitBadger\PDODocument\{Configuration, DocumentException, Field, FieldMatch, Mode, Query};
/**
* Queries to remove fields from documents
@@ -54,13 +54,13 @@ class RemoveFields
* @param string $tableName The name of the table in which documents should be manipulated
* @param array|Field[] $fields The field comparison to match
* @param array $parameters The parameter list for the query
* @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
* @return string The UPDATE statement to remove fields from documents via field comparison
* @throws DocumentException If the database mode has not been set
*/
public static function byFields(string $tableName, array $fields, array $parameters,
string $conjunction = 'AND'): string
?FieldMatch $match = null): string
{
return self::update($tableName, $parameters, Query::whereByFields($fields, $conjunction));
return self::update($tableName, $parameters, Query::whereByFields($fields, $match));
}
}

View File

@@ -28,15 +28,15 @@ class RemoveFields
* @param string $tableName The table in which documents should have fields removed
* @param array|Field[] $fields The field comparison to match
* @param array|string[] $fieldNames The names of the fields to be removed
* @param string $conjunction How to handle multiple conditions (optional; defaults to `AND`)
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
* @throws DocumentException If any is encountered
*/
public static function byFields(string $tableName, array $fields, array $fieldNames,
string $conjunction = 'AND'): void
?FieldMatch $match = null): void
{
$nameParams = Parameters::fieldNames(':name', $fieldNames);
$namedFields = Parameters::nameFields($fields);
Custom::nonQuery(Query\RemoveFields::byFields($tableName, $namedFields, $nameParams, $conjunction),
Custom::nonQuery(Query\RemoveFields::byFields($tableName, $namedFields, $nameParams, $match),
Parameters::addFields($namedFields, $nameParams));
}
}