Initial SQLite development (#1)

Reviewed-on: #1
This commit was merged in pull request #1.
This commit is contained in:
2024-06-08 23:58:45 +00:00
parent e91acee70f
commit f784f3e52c
66 changed files with 5509 additions and 2 deletions

67
src/Configuration.php Normal file
View File

@@ -0,0 +1,67 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument;
use PDO;
/**
* Common configuration for the document library
*/
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 string The data source name (DSN) of the connection string */
public static string $pdoDSN = '';
/** @var string|null The username to use to establish a data connection (use env PDO_DOC_USERNAME if possible) */
public static ?string $username = null;
/** @var string|null The password to use to establish a data connection (use env PDO_DOC_PASSWORD if possible) */
public static ?string $password = null;
/** @var array|null Options to use for connections (driver-specific) */
public static ?array $options = null;
/** @var Mode|null The mode in which the library is operating (filled after first connection if not configured) */
public static ?Mode $mode = null;
/** @var PDO|null The PDO instance to use for database commands */
private static ?PDO $_pdo = null;
/**
* Retrieve a new connection to the database
*
* @return PDO A new connection to the SQLite database with foreign key support enabled
* @throws DocumentException If this is called before a connection string is set
*/
public static function dbConn(): PDO
{
if (is_null(self::$_pdo)) {
if (empty(self::$pdoDSN)) {
throw new DocumentException('Please provide a data source name (DSN) before attempting data access');
}
self::$_pdo = new PDO(self::$pdoDSN, $_ENV['PDO_DOC_USERNAME'] ?? self::$username,
$_ENV['PDO_DOC_PASSWORD'] ?? self::$password, self::$options);
if (is_null(self::$mode)) {
$driver = self::$_pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
self::$mode = match ($driver) {
'pgsql' => Mode::PgSQL,
'sqlite' => Mode::SQLite,
default => throw new DocumentException(
"Unsupported driver $driver: this library currently supports PostgreSQL and SQLite")
};
}
}
return self::$_pdo;
}
public static function resetPDO(): void
{
self::$_pdo = null;
}
}

39
src/Count.php Normal file
View File

@@ -0,0 +1,39 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument;
use BitBadger\PDODocument\Mapper\CountMapper;
/**
* Functions to count documents
*/
class Count
{
/**
* Count all documents in a table
*
* @param string $tableName The name of the table in which documents should be counted
* @return int The count of documents in the table
* @throws DocumentException If one is encountered
*/
public static function all(string $tableName): int
{
return Custom::scalar(Query\Count::all($tableName), [], new CountMapper());
}
/**
* Count matching documents using a comparison on JSON fields
*
* @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`)
* @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
{
$namedFields = Parameters::nameFields($fields);
return Custom::scalar(Query\Count::byFields($tableName, $namedFields, $conjunction),
Parameters::addFields($namedFields, []), new CountMapper());
}
}

143
src/Custom.php Normal file
View File

@@ -0,0 +1,143 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument;
use BitBadger\PDODocument\Mapper\Mapper;
use PDO;
use PDOException;
use PDOStatement;
/**
* Functions to execute custom queries
*/
class Custom
{
/**
* Prepare a query for execution and run it
*
* @param string $query The query to be run
* @param array $parameters The parameters for the query
* @return PDOStatement The result of executing the query
* @throws DocumentException If the query execution is unsuccessful
*/
public static function &runQuery(string $query, array $parameters): PDOStatement
{
$debug = defined('PDO_DOC_DEBUG_SQL');
try {
$stmt = Configuration::dbConn()->prepare($query);
} catch (PDOException $ex) {
$keyword = explode(' ', $query, 2)[0];
throw new DocumentException(
sprintf("Error executing %s statement: [%s] %s", $keyword, Configuration::dbConn()->errorCode(),
Configuration::dbConn()->errorInfo()[2]),
previous: $ex);
}
foreach ($parameters as $key => $value) {
if ($debug) echo "<pre>Binding $value to $key\n</pre>";
$dataType = match (true) {
is_bool($value) => PDO::PARAM_BOOL,
is_int($value) => PDO::PARAM_INT,
is_null($value) => PDO::PARAM_NULL,
default => PDO::PARAM_STR
};
$stmt->bindValue($key, $value, $dataType);
}
if ($debug) echo '<pre>SQL: ' . $stmt->queryString . '</pre>';
try {
if ($stmt->execute()) return $stmt;
} catch (PDOException $ex) {
$keyword = explode(' ', $query, 2)[0];
throw new DocumentException(
sprintf("Error executing %s statement: [%s] %s", $keyword, $stmt->errorCode(), $stmt->errorInfo()[2]),
previous: $ex);
}
$keyword = explode(' ', $query, 2)[0];
throw new DocumentException("Error executing $keyword statement: " . $stmt->errorCode());
}
/**
* Execute a query that returns a list of results (lazy)
*
* @template TDoc The domain type of the document to retrieve
* @param string $query The query to be executed
* @param array $parameters Parameters to use in executing the query
* @param Mapper<TDoc> $mapper Mapper to deserialize the result
* @return DocumentList<TDoc> The items matching the query
* @throws DocumentException If any is encountered
*/
public static function list(string $query, array $parameters, Mapper $mapper): DocumentList
{
return DocumentList::create($query, $parameters, $mapper);
}
/**
* Execute a query that returns an array of results (eager)
*
* @template TDoc The domain type of the document to retrieve
* @param string $query The query to be executed
* @param array $parameters Parameters to use in executing the query
* @param Mapper<TDoc> $mapper Mapper to deserialize the result
* @return TDoc[] The items matching the query
* @throws DocumentException If any is encountered
*/
public static function array(string $query, array $parameters, Mapper $mapper): array
{
return iterator_to_array(self::list($query, $parameters, $mapper)->items());
}
/**
* Execute a query that returns one or no results (returns false if not found)
*
* @template TDoc The domain type of the document to retrieve
* @param string $query The query to be executed (will have "LIMIT 1" appended)
* @param array $parameters Parameters to use in executing the query
* @param Mapper<TDoc> $mapper Mapper to deserialize the result
* @return false|TDoc The item if it is found, false if not
* @throws DocumentException If any is encountered
*/
public static function single(string $query, array $parameters, Mapper $mapper): mixed
{
try {
$stmt = &self::runQuery("$query LIMIT 1", $parameters);
return ($first = $stmt->fetch(PDO::FETCH_ASSOC)) ? $mapper->map($first) : false;
} finally {
$stmt = null;
}
}
/**
* Execute a query that does not return a value
*
* @param string $query The query to execute
* @param array $parameters Parameters to use in executing the query
* @throws DocumentException If any is encountered
*/
public static function nonQuery(string $query, array $parameters): void
{
try {
$stmt = &self::runQuery($query, $parameters);
} finally {
$stmt = null;
}
}
/**
* Execute a query that returns a scalar value
*
* @template T The scalar type to return
* @param string $query The query to retrieve the value
* @param array $parameters Parameters to use in executing the query
* @param Mapper<T> $mapper The mapper to obtain the result
* @return mixed|false|T The scalar value if found, false if not
* @throws DocumentException If any is encountered
*/
public static function scalar(string $query, array $parameters, Mapper $mapper): mixed
{
try {
$stmt = &self::runQuery($query, $parameters);
return ($first = $stmt->fetch(PDO::FETCH_NUM)) ? $mapper->map($first) : false;
} finally {
$stmt = null;
}
}
}

34
src/Definition.php Normal file
View File

@@ -0,0 +1,34 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument;
/**
* Functions to create tables and indexes
*/
class Definition
{
/**
* Ensure a document table exists
*
* @param string $name The name of the table to be created if it does not exist
* @throws DocumentException If any is encountered
*/
public static function ensureTable(string $name): void
{
Custom::nonQuery(Query\Definition::ensureTable($name), []);
Custom::nonQuery(Query\Definition::ensureKey($name), []);
}
/**
* Ensure a field index exists on a document table
*
* @param string $tableName The name of the table which should be indexed
* @param string $indexName The name of the index
* @param array $fields Fields which should be a part of this index
* @throws DocumentException If any is encountered
*/
public static function ensureFieldIndex(string $tableName, string $indexName, array $fields): void
{
Custom::nonQuery(Query\Definition::ensureIndexOn($tableName, $indexName, $fields), []);
}
}

36
src/Delete.php Normal file
View File

@@ -0,0 +1,36 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument;
/**
* Functions to delete documents
*/
class Delete
{
/**
* Delete a document by its ID
*
* @param string $tableName The table from which the document should be deleted
* @param mixed $docId The ID of the document to be deleted
* @throws DocumentException If any is encountered
*/
public static function byId(string $tableName, mixed $docId): void
{
Custom::nonQuery(Query\Delete::byId($tableName), Parameters::id($docId));
}
/**
* Delete documents by matching a comparison on JSON fields
*
* @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`)
* @throws DocumentException If any is encountered
*/
public static function byFields(string $tableName, array $fields, string $conjunction = 'AND'): void
{
$namedFields = Parameters::nameFields($fields);
Custom::nonQuery(Query\Delete::byFields($tableName, $namedFields, $conjunction),
Parameters::addFields($namedFields, []));
}
}

47
src/Document.php Normal file
View File

@@ -0,0 +1,47 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument;
/**
* Functions that apply at a whole document level
*/
class Document
{
/**
* Insert a new document
*
* @param string $tableName The name of the table into which the document should be inserted
* @param array|object $document The document to be inserted
* @throws DocumentException If any is encountered
*/
public static function insert(string $tableName, array|object $document): void
{
Custom::nonQuery(Query::insert($tableName), Parameters::json(':data', $document));
}
/**
* Save a document, inserting it if it does not exist and updating it if it does (AKA "upsert")
*
* @param string $tableName The name of the table to which the document should be saved
* @param array|object $document The document to be saved
* @throws DocumentException If any is encountered
*/
public static function save(string $tableName, array|object $document): void
{
Custom::nonQuery(Query::save($tableName), Parameters::json(':data', $document));
}
/**
* Update (replace) an entire document by its ID
*
* @param string $tableName The table in which the document should be updated
* @param mixed $docId The ID of the document to be updated
* @param array|object $document The document to be updated
* @throws DocumentException If any is encountered
*/
public static function update(string $tableName, mixed $docId, array|object $document): void
{
Custom::nonQuery(Query::update($tableName),
array_merge(Parameters::id($docId), Parameters::json(':data', $document)));
}
}

30
src/DocumentException.php Normal file
View File

@@ -0,0 +1,30 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument;
use Exception;
use Throwable;
/**
* Exceptions occurring during document processing
*/
class DocumentException extends Exception
{
/**
* Constructor
*
* @param string $message A message for the exception
* @param int $code The code for the exception (optional; defaults to 0)
* @param Throwable|null $previous The previous exception (optional; defaults to `null`)
*/
public function __construct(string $message, int $code = 0, ?Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
}
public function __toString(): string
{
$codeStr = $this->code == 0 ? '' : "[$this->code] ";
return __CLASS__ . ": $codeStr$this->message\n";
}
}

83
src/DocumentList.php Normal file
View File

@@ -0,0 +1,83 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument;
use BitBadger\PDODocument\Mapper\Mapper;
use Generator;
use PDO;
use PDOStatement;
/**
* A lazy iterator of results in a list; implementations will create new connections to the database and close/dispose
* them as required once the results have been exhausted.
*
* @template TDoc The domain class for items returned by this list
*/
class DocumentList
{
/** @var TDoc|null $_first The first item from the results */
private mixed $_first = null;
/**
* Constructor
*
* @param PDOStatement|null $result The result of the query
* @param Mapper<TDoc> $mapper The mapper to deserialize JSON
*/
private function __construct(private ?PDOStatement &$result, private readonly Mapper $mapper)
{
if ($row = $this->result->fetch(PDO::FETCH_ASSOC)) {
$this->_first = $this->mapper->map($row);
} else {
$this->result = null;
}
}
/**
* Construct a new document list
*
* @param string $query The query to run to retrieve results
* @param array $parameters An associative array of parameters for the query
* @param Mapper<TDoc> $mapper A mapper to deserialize JSON documents
* @return static The document list instance
* @throws DocumentException If any is encountered
*/
public static function create(string $query, array $parameters, Mapper $mapper): static
{
$stmt = &Custom::runQuery($query, $parameters);
return new static($stmt, $mapper);
}
/**
* The items from the query result
*
* @return Generator<TDoc> The items from the document list
*/
public function items(): Generator
{
if (!$this->result) return;
yield $this->_first;
while ($row = $this->result->fetch(PDO::FETCH_ASSOC)) {
yield $this->mapper->map($row);
}
$this->result = null;
}
/**
* Does this list have items remaining?
*
* @return bool True if there are items still to be retrieved from the list, false if not
*/
public function hasItems(): bool
{
return !is_null($this->result);
}
/**
* Ensure the statement is destroyed if the generator is not exhausted
*/
public function __destruct()
{
if (!is_null($this->result)) $this->result = null;
}
}

40
src/Exists.php Normal file
View File

@@ -0,0 +1,40 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument;
use BitBadger\PDODocument\Mapper\ExistsMapper;
/**
* Functions to determine if documents exist
*/
class Exists
{
/**
* Determine if a document exists for the given ID
*
* @param string $tableName The name of the table in which document existence should be determined
* @param mixed $docId The ID of the document whose existence should be determined
* @return bool True if the document exists, false if not
* @throws DocumentException If any is encountered
*/
public static function byId(string $tableName, mixed $docId): bool
{
return Custom::scalar(Query\Exists::byId($tableName), Parameters::id($docId), new ExistsMapper());
}
/**
* Determine if a document exists using a comparison on JSON fields
*
* @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`)
* @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
{
$namedFields = Parameters::nameFields($fields);
return Custom::scalar(Query\Exists::byFields($tableName, $namedFields, $conjunction),
Parameters::addFields($namedFields, []), new ExistsMapper());
}
}

188
src/Field.php Normal file
View File

@@ -0,0 +1,188 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument;
/**
* Criteria for a field WHERE clause
*/
class Field
{
/**
* Constructor
*
* NOTE: Use static construction methods rather than using this directly; different properties are required
* depending on the operation being performed. This is only public so it can be tested.
*
* @param string $fieldName The name of the field
* @param Op $op The operation by which the field will be compared
* @param mixed $value The value of the field
* @param string $paramName The name of the parameter to which this should be bound
* @param string $qualifier A table qualifier for the `data` column
*/
public function __construct(public string $fieldName = '', public Op $op = Op::EQ, public mixed $value = '',
public string $paramName = '', public string $qualifier = '') { }
/**
* Append the parameter name and value to the given associative array
*
* @param array $existing The existing parameters
* @return array The given parameter array with this field's name and value appended
*/
public function appendParameter(array $existing): array
{
switch ($this->op) {
case Op::EX:
case Op::NEX:
break;
case Op::BT:
$existing["{$this->paramName}min"] = $this->value[0];
$existing["{$this->paramName}max"] = $this->value[1];
break;
default:
$existing[$this->paramName] = $this->value;
}
return $existing;
}
/**
* Get the WHERE clause fragment for this parameter
*
* @return string The WHERE clause fragment for this parameter
* @throws DocumentException If the database mode has not been set
*/
public function toWhere(): string
{
$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;
}
/**
* Create an equals (=) field criterion
*
* @param string $fieldName The name of the field against which the value will be compared
* @param mixed $value The value for which equality will be checked
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
* @return static The field with the requested criterion
*/
public static function EQ(string $fieldName, mixed $value, string $paramName = ''): static
{
return new static($fieldName, Op::EQ, $value, $paramName);
}
/**
* Create a greater than (>) field criterion
*
* @param string $fieldName The name of the field against which the value will be compared
* @param mixed $value The value for the greater than comparison
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
* @return static The field with the requested criterion
*/
public static function GT(string $fieldName, mixed $value, string $paramName = ''): static
{
return new static($fieldName, Op::GT, $value, $paramName);
}
/**
* Create a greater than or equal to (>=) field criterion
*
* @param string $fieldName The name of the field against which the value will be compared
* @param mixed $value The value for the greater than or equal to comparison
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
* @return static The field with the requested criterion
*/
public static function GE(string $fieldName, mixed $value, string $paramName = ''): static
{
return new static($fieldName, Op::GE, $value, $paramName);
}
/**
* Create a less than (<) field criterion
*
* @param string $fieldName The name of the field against which the value will be compared
* @param mixed $value The value for the less than comparison
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
* @return static The field with the requested criterion
*/
public static function LT(string $fieldName, mixed $value, string $paramName = ''): static
{
return new static($fieldName, Op::LT, $value, $paramName);
}
/**
* Create a less than or equal to (<=) field criterion
*
* @param string $fieldName The name of the field against which the value will be compared
* @param mixed $value The value for the less than or equal to comparison
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
* @return static The field with the requested criterion
*/
public static function LE(string $fieldName, mixed $value, string $paramName = ''): static
{
return new static($fieldName, Op::LE, $value, $paramName);
}
/**
* Create a not equals (<>) field criterion
*
* @param string $fieldName The name of the field against which the value will be compared
* @param mixed $value The value for the not equals comparison
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
* @return static The field with the requested criterion
*/
public static function NE(string $fieldName, mixed $value, string $paramName = ''): static
{
return new static($fieldName, Op::NE, $value, $paramName);
}
/**
* Create a BETWEEN field criterion
*
* @param string $fieldName The name of the field against which the value will be compared
* @param mixed $minValue The lower value for range
* @param mixed $maxValue The upper value for the range
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
* @return static The field with the requested criterion
*/
public static function BT(string $fieldName, mixed $minValue, mixed $maxValue, string $paramName = ''): static
{
return new static($fieldName, Op::BT, [$minValue, $maxValue], $paramName);
}
/**
* Create an exists (IS NOT NULL) field criterion
*
* @param string $fieldName The name of the field for which existence will be checked
* @return static The field with the requested criterion
*/
public static function EX(string $fieldName): static
{
return new static($fieldName, Op::EX, '', '');
}
/**
* Create a not exists (IS NULL) field criterion
*
* @param string $fieldName The name of the field for which non-existence will be checked
* @return static The field with the requested criterion
*/
public static function NEX(string $fieldName): static
{
return new static($fieldName, Op::NEX, '', '');
}
}

78
src/Find.php Normal file
View File

@@ -0,0 +1,78 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument;
use BitBadger\PDODocument\Mapper\DocumentMapper;
/**
* Functions to find documents
*/
class Find
{
/**
* Retrieve all documents in the given table
*
* @template TDoc The type of document to be retrieved
* @param string $tableName The table from which documents should be retrieved
* @param class-string<TDoc> $className The name of the class to be retrieved
* @return DocumentList<TDoc> A list of all documents from the table
* @throws DocumentException If any is encountered
*/
public static function all(string $tableName, string $className): DocumentList
{
return Custom::list(Query::selectFromTable($tableName), [], new DocumentMapper($className));
}
/**
* Retrieve a document by its ID (returns false if not found)
*
* @template TDoc The type of document to be retrieved
* @param string $tableName The table from which the document should be retrieved
* @param mixed $docId The ID of the document to retrieve
* @param class-string<TDoc> $className The name of the class to be retrieved
* @return false|TDoc The document if it exists, false if not
* @throws DocumentException If any is encountered
*/
public static function byId(string $tableName, mixed $docId, string $className): mixed
{
return Custom::single(Query\Find::byId($tableName), Parameters::id($docId), new DocumentMapper($className));
}
/**
* Retrieve documents via a comparison on JSON fields
*
* @template TDoc The type of document to be retrieved
* @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`)
* @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
{
$namedFields = Parameters::nameFields($fields);
return Custom::list(Query\Find::byFields($tableName, $namedFields, $conjunction),
Parameters::addFields($namedFields, []), new DocumentMapper($className));
}
/**
* Retrieve documents via a comparison on JSON fields, returning only the first result
*
* @template TDoc The type of document to be retrieved
* @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`)
* @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
{
$namedFields = Parameters::nameFields($fields);
return Custom::single(Query\Find::byFields($tableName, $namedFields, $conjunction),
Parameters::addFields($namedFields, []), new DocumentMapper($className));
}
}

View File

@@ -0,0 +1,17 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument\Mapper;
/**
* A mapper that returns the associative array from the database
*/
class ArrayMapper implements Mapper
{
/**
* @inheritDoc
*/
public function map(array $result): array
{
return $result;
}
}

View File

@@ -0,0 +1,17 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument\Mapper;
/**
* A mapper that returns the integer value of the first item in the results
*/
class CountMapper implements Mapper
{
/**
* @inheritDoc
*/
public function map(array $result): int
{
return (int) $result[0];
}
}

View File

@@ -0,0 +1,44 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument\Mapper;
use BitBadger\PDODocument\DocumentException;
use JsonMapper;
use JsonMapper_Exception;
/**
* Map domain class instances from JSON documents
*
* @template TDoc The type of document returned by this mapper
* @implements Mapper<TDoc> Provide a mapping from JSON
*/
class DocumentMapper implements Mapper
{
/**
* Constructor
*
* @param class-string<TDoc> $className The type of class to be returned by this mapping
* @param string $fieldName The name of the field (optional; defaults to `data`)
*/
public function __construct(public string $className, public string $fieldName = 'data') { }
/**
* Map a result to a domain class instance
*
* @param array $result An associative array representing a single database result
* @return TDoc The document, deserialized from its JSON representation
* @throws DocumentException If the JSON cannot be deserialized
*/
public function map(array $result): mixed
{
try {
$json = json_decode($result[$this->fieldName]);
if (is_null($json)) {
throw new DocumentException("Could not map document for $this->className: " . json_last_error_msg());
}
return (new JsonMapper())->map($json, $this->className);
} catch (JsonMapper_Exception $ex) {
throw new DocumentException("Could not map document for $this->className", previous: $ex);
}
}
}

View File

@@ -0,0 +1,24 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument\Mapper;
use BitBadger\PDODocument\{Configuration, DocumentException, Mode};
/**
* Map an EXISTS result to a boolean value
*/
class ExistsMapper implements Mapper
{
/**
* @inheritDoc
* @throws DocumentException If the database mode has not been set
*/
public function map(array $result): bool
{
return match (Configuration::$mode) {
Mode::PgSQL => (bool)$result[0],
Mode::SQLite => (int)$result[0] > 0,
default => throw new DocumentException('Database mode not set; cannot map existence result'),
};
}
}

19
src/Mapper/Mapper.php Normal file
View File

@@ -0,0 +1,19 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument\Mapper;
/**
* Map an associative array of results to a domain class
*
* @template T The type of document retrieved by this mapper
*/
interface Mapper
{
/**
* Map a result to the specified type
*
* @param array $result An associative array representing a single database result
* @return T The item mapped from the given result
*/
public function map(array $result): mixed;
}

View File

@@ -0,0 +1,30 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument\Mapper;
/**
* Map a string result from the
*
* @implements Mapper<string>
*/
class StringMapper implements Mapper
{
/**
* Constructor
*
* @param string $fieldName The name of the field to be retrieved as a string
*/
public function __construct(public string $fieldName) { }
/**
* @inheritDoc
*/
public function map(array $result): ?string
{
return match (false) {
key_exists($this->fieldName, $result) => null,
is_string($result[$this->fieldName]) => "{$result[$this->fieldName]}",
default => $result[$this->fieldName]
};
}
}

15
src/Mode.php Normal file
View File

@@ -0,0 +1,15 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument;
/**
* The mode for queries generated by the library
*/
enum Mode
{
/** Storing documents in a PostgreSQL database */
case PgSQL;
/** Storing documents in a SQLite database */
case SQLite;
}

48
src/Op.php Normal file
View File

@@ -0,0 +1,48 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument;
/**
* The types of logical operations allowed for JSON fields
*/
enum Op
{
/** Equals (=) */
case EQ;
/** Greater Than (>) */
case GT;
/** Greater Than or Equal To (>=) */
case GE;
/** Less Than (<) */
case LT;
/** Less Than or Equal To (<=) */
case LE;
/** Not Equal to (<>) */
case NE;
/** Between (BETWEEN) */
case BT;
/** Exists (IS NOT NULL) */
case EX;
/** Does Not Exist (IS NULL) */
case NEX;
/**
* Get the string representation of this operator
*
* @return string The operator to use in SQL statements
*/
public function toString(): string
{
return match ($this) {
Op::EQ => "=",
Op::GT => ">",
Op::GE => ">=",
Op::LT => "<",
Op::LE => "<=",
Op::NE => "<>",
Op::BT => "BETWEEN",
Op::EX => "IS NOT NULL",
Op::NEX => "IS NULL"
};
}
}

81
src/Parameters.php Normal file
View File

@@ -0,0 +1,81 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument;
/**
* Functions to create parameters for queries
*/
class Parameters
{
/**
* Create an ID parameter (name ":id", key will be treated as a string)
*
* @param mixed $key The key representing the ID of the document
* @return array|string[] An associative array with an "@id" parameter/value pair
*/
public static function id(mixed $key): array
{
return [':id' => is_int($key) || is_string($key) ? $key : "$key"];
}
/**
* Create a parameter with a JSON value
*
* @param string $name The name of the JSON parameter
* @param object|array $document The value that should be passed as a JSON string
* @return array An associative array with the named parameter/value pair
*/
public static function json(string $name, object|array $document): array
{
return [$name => json_encode($document, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)];
}
/**
* Fill in parameter names for any fields missing one
*
* @param array|Field[] $fields The fields for the query
* @return array|Field[] The fields, all with non-blank parameter names
*/
public static function nameFields(array $fields): array
{
for ($idx = 0; $idx < sizeof($fields); $idx++) {
if ($fields[$idx]->paramName == '') $fields[$idx]->paramName = ":field$idx";
}
return $fields;
}
/**
* Add field parameters to the given set of parameters
*
* @param array|Field[] $fields The fields being compared in the query
* @param array $parameters An associative array of parameters to which the fields should be added
* @return array An associative array of parameter names and values with the fields added
*/
public static function addFields(array $fields, array $parameters): array
{
return array_reduce($fields, fn($carry, $item) => $item->appendParameter($carry), $parameters);
}
/**
* Create JSON field name parameters for the given field names to the given parameter
*
* @param string $paramName The name of the parameter for the field names
* @param array|string[] $fieldNames The names of the fields for the parameter
* @return array An associative array of parameter/value pairs for the field names
* @throws DocumentException If the database mode has not been set
*/
public static function fieldNames(string $paramName, array $fieldNames): array
{
switch (Configuration::$mode) {
case Mode::PgSQL:
return [$paramName => "ARRAY['" . implode("','", $fieldNames) . "']"];
case Mode::SQLite:
$it = [];
$idx = 0;
foreach ($fieldNames as $field) $it[$paramName . $idx++] = "$.$field";
return $it;
default:
throw new DocumentException('Database mode not set; cannot generate field name parameters');
}
}
}

40
src/Patch.php Normal file
View File

@@ -0,0 +1,40 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument;
/**
* Functions to patch (partially update) documents
*/
class Patch
{
/**
* Patch a document by its ID
*
* @param string $tableName The table in which the document should be patched
* @param mixed $docId The ID of the document to be patched
* @param array|object $patch The object with which the document should be patched (will be JSON-encoded)
* @throws DocumentException If any is encountered (database mode must be set)
*/
public static function byId(string $tableName, mixed $docId, array|object $patch): void
{
Custom::nonQuery(Query\Patch::byId($tableName),
array_merge(Parameters::id($docId), Parameters::json(':data', $patch)));
}
/**
* Patch documents using a comparison on JSON fields
*
* @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`)
* @throws DocumentException If any is encountered
*/
public static function byFields(string $tableName, array $fields, array|object $patch,
string $conjunction = 'AND'): void
{
$namedFields = Parameters::nameFields($fields);
Custom::nonQuery(Query\Patch::byFields($tableName, $namedFields, $conjunction),
Parameters::addFields($namedFields, Parameters::json(':data', $patch)));
}
}

77
src/Query.php Normal file
View File

@@ -0,0 +1,77 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument;
/**
* Query construction functions
*/
class Query
{
/**
* Create a SELECT clause to retrieve the document data from the given table
*
* @param string $tableName The name of the table from which document data should be retrieved
* @return string The SELECT clause to retrieve a document from the given table
*/
public static function selectFromTable(string $tableName): string
{
return "SELECT data FROM $tableName";
}
/**
* 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)
* @return string The WHERE clause fragment matching the given fields and parameter
*/
public static function whereByFields(array $fields, string $conjunction = 'AND'): string
{
return implode(" $conjunction ", array_map(fn($it) => $it->toWhere(), $fields));
}
/**
* 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)
* @return string The WHERE clause fragment to match by ID
*/
public static function whereById(string $paramName = ':id'): string
{
return self::whereByFields([Field::EQ(Configuration::$idField, 0, $paramName)]);
}
/**
* Query to insert 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
*/
public static function insert(string $tableName): string
{
return "INSERT INTO $tableName VALUES (:data)";
}
/**
* Query to save a document, inserting it if it does not exist and updating it if it does (AKA "upsert")
*
* @param string $tableName The name of the table into which a document should be saved
* @return string The INSERT...ON CONFLICT query for the document
*/
public static function save(string $tableName): string
{
return self::insert($tableName)
. " ON CONFLICT ((data->>'" . Configuration::$idField . "')) DO UPDATE SET data = EXCLUDED.data";
}
/**
* Query to update a document
*
* @param string $tableName The name of the table in which the document should be updated
* @return string The UPDATE query for the document
*/
public static function update(string $tableName): string
{
return "UPDATE $tableName SET data = :data WHERE " . self::whereById();
}
}

35
src/Query/Count.php Normal file
View File

@@ -0,0 +1,35 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument\Query;
use BitBadger\PDODocument\{Field, Query};
/**
* Queries for counting documents
*/
class Count
{
/**
* Query to count all documents in a table
*
* @param string $tableName The name of the table in which documents should be counted
* @return string The query to count all documents in a table
*/
public static function all(string $tableName): string
{
return "SELECT COUNT(*) FROM $tableName";
}
/**
* Query to count matching documents using a text comparison on JSON fields
*
* @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`)
* @return string The query to count documents using a field comparison
*/
public static function byFields(string $tableName, array $fields, string $conjunction = 'AND'): string
{
return self::all($tableName) . ' WHERE ' . Query::whereByFields($fields, $conjunction);
}
}

71
src/Query/Definition.php Normal file
View File

@@ -0,0 +1,71 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument\Query;
use BitBadger\PDODocument\{Configuration, DocumentException, Mode};
/**
* Queries to define tables and indexes
*/
class Definition
{
/**
* SQL statement to create a document table
*
* @param string $name The name of the table (including schema, if applicable)
* @return string The CREATE TABLE statement for the document table
* @throws DocumentException If the database mode has not been set
*/
public static function ensureTable(string $name): string
{
$dataType = match (Configuration::$mode) {
Mode::PgSQL => 'JSONB',
Mode::SQLite => 'TEXT',
default => throw new DocumentException('Database mode not set; cannot make create table statement')
};
return "CREATE TABLE IF NOT EXISTS $name (data $dataType NOT NULL)";
}
/**
* Split a schema and table name
*
* @param string $tableName The name of the table, possibly including the schema
* @return array|string[] An array with the schema at index 0 and the table name at index 1
*/
private static function splitSchemaAndTable(string $tableName): array
{
$parts = explode('.', $tableName);
return sizeof($parts) == 1 ? ["", $tableName] : [$parts[0], $parts[1]];
}
/**
* SQL statement to create an index on one or more fields in a JSON document
*
* @param string $tableName The name of the table which should be indexed
* @param string $indexName The name of the index to create
* @param array $fields An array of fields to be indexed; may contain direction (ex. 'salary DESC')
* @return string The CREATE INDEX statement to ensure the index exists
*/
public static function ensureIndexOn(string $tableName, string $indexName, array $fields): string
{
[, $tbl] = self::splitSchemaAndTable($tableName);
$jsonFields = implode(', ', array_map(function (string $field) {
$parts = explode(' ', $field);
$fieldName = sizeof($parts) == 1 ? $field : $parts[0];
$direction = sizeof($parts) < 2 ? "" : " $parts[1]";
return "(data->>'$fieldName')$direction";
}, $fields));
return "CREATE INDEX IF NOT EXISTS idx_{$tbl}_$indexName ON $tableName ($jsonFields)";
}
/**
* SQL statement to create a key index for a document table
*
* @param string $tableName The name of the table whose key should be ensured
* @return string The CREATE INDEX statement to ensure the key index exists
*/
public static function ensureKey(string $tableName): string
{
return str_replace('INDEX', 'UNIQUE INDEX', self::ensureIndexOn($tableName, 'key', [Configuration::$idField]));
}
}

35
src/Query/Delete.php Normal file
View File

@@ -0,0 +1,35 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument\Query;
use BitBadger\PDODocument\{Field, Query};
/**
* Queries to delete documents
*/
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
* @return string The DELETE statement to delete a document by its ID
*/
public static function byId(string $tableName): string
{
return "DELETE FROM $tableName WHERE " . Query::whereById();
}
/**
* Query to delete documents using a comparison on JSON fields
*
* @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`)
* @return string The DELETE statement to delete documents via field comparison
*/
public static function byFields(string $tableName, array $fields, string $conjunction = 'AND'): string
{
return "DELETE FROM $tableName WHERE " . Query::whereByFields($fields, $conjunction);
}
}

47
src/Query/Exists.php Normal file
View File

@@ -0,0 +1,47 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument\Query;
use BitBadger\PDODocument\{Field, Query};
/**
* Queries to determine document existence
*/
class Exists
{
/**
* The shell of a query for an existence check
*
* @param string $tableName The name of the table in which existence should be checked
* @param string $whereClause The conditions for which existence should be checked
* @return string The query to determine existence of documents
*/
public static function query(string $tableName, string $whereClause): string
{
return "SELECT EXISTS (SELECT 1 FROM $tableName WHERE $whereClause)";
}
/**
* 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
* @return string The query to determine document existence by ID
*/
public static function byId(string $tableName): string
{
return self::query($tableName, Query::whereById());
}
/**
* Query to determine if documents exist using a comparison on JSON fields
*
* @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`)
* @return string The query to determine document existence by field comparison
*/
public static function byFields(string $tableName, array $fields, string $conjunction = 'AND'): string
{
return self::query($tableName, Query::whereByFields($fields, $conjunction));
}
}

35
src/Query/Find.php Normal file
View File

@@ -0,0 +1,35 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument\Query;
use BitBadger\PDODocument\{Field, Query};
/**
* Queries for retrieving documents
*/
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
* @return string The SELECT statement to retrieve a document by its ID
*/
public static function byId(string $tableName): string
{
return Query::selectFromTable($tableName) . ' WHERE ' . Query::whereById();
}
/**
* Query to retrieve documents using a comparison on JSON fields
*
* @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`)
* @return string The SELECT statement to retrieve documents by field comparison
*/
public static function byFields(string $tableName, array $fields, string $conjunction = 'AND'): string
{
return Query::selectFromTable($tableName) . ' WHERE ' . Query::whereByFields($fields, $conjunction);
}
}

55
src/Query/Patch.php Normal file
View File

@@ -0,0 +1,55 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument\Query;
use BitBadger\PDODocument\{Configuration, DocumentException, Field, Mode, Query};
/**
* Queries to perform partial updates on documents
*/
class Patch
{
/**
* Create an UPDATE statement to patch documents
*
* @param string $tableName The name of the table in which documents should be patched
* @param string $whereClause The body of the WHERE clause to use in the UPDATE statement
* @return string The UPDATE statement to perform the patch
* @throws DocumentException If the database mode has not been set
*/
public static function update(string $tableName, string $whereClause): string
{
$setValue = match (Configuration::$mode) {
Mode::PgSQL => 'data || :data',
Mode::SQLite => 'json_patch(data, json(:data))',
default => throw new DocumentException('Database mode not set; cannot make patch statement')
};
return "UPDATE $tableName SET data = $setValue WHERE $whereClause";
}
/**
* 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
* @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
{
return self::update($tableName, Query::whereById());
}
/**
* Query to patch (partially update) a document via a comparison on a JSON field
*
* @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`)
* @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
{
return self::update($tableName, Query::whereByFields($field, $conjunction));
}
}

View File

@@ -0,0 +1,66 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument\Query;
use BitBadger\PDODocument\{Configuration, DocumentException, Field, Mode, Query};
/**
* Queries to remove fields from documents
*
* _NOTE: When using these queries to build custom functions, be aware that different databases use significantly
* different syntax. The `$parameters` passed to these functions should be run through `Parameters::fieldNames`
* function to generate them appropriately for the database currently being targeted._
*/
class RemoveFields
{
/**
* Create an UPDATE statement to remove fields from a JSON document
*
* @param string $tableName The name of the table in which documents should be manipulated
* @param array $parameters The parameter list for the query
* @param string $whereClause The body of the WHERE clause for the update
* @return string The UPDATE statement to remove fields from a JSON document
* @throws DocumentException If the database mode has not been set
*/
public static function update(string $tableName, array $parameters, string $whereClause): string
{
switch (Configuration::$mode) {
case Mode::PgSQL:
return "UPDATE $tableName SET data = data - " . array_keys($parameters)[0] . " WHERE $whereClause";
case Mode::SQLite:
$paramNames = implode(', ', array_keys($parameters));
return "UPDATE $tableName SET data = json_remove(data, $paramNames) WHERE $whereClause";
default:
throw new DocumentException('Database mode not set; cannot generate field removal query');
}
}
/**
* Query to remove fields from a document by the document's ID
*
* @param string $tableName The name of the table in which the document should be manipulated
* @param array $parameters The parameter list for the query
* @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
{
return self::update($tableName, $parameters, Query::whereById());
}
/**
* Query to remove fields from documents via a comparison on JSON fields within the document
*
* @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`)
* @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
{
return self::update($tableName, $parameters, Query::whereByFields($fields, $conjunction));
}
}

42
src/RemoveFields.php Normal file
View File

@@ -0,0 +1,42 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument;
/**
* Functions to remove fields from documents
*/
class RemoveFields
{
/**
* Remove fields from a document by the document's ID
*
* @param string $tableName The table in which the document should have fields removed
* @param mixed $docId The ID of the document from which fields should be removed
* @param array|string[] $fieldNames The names of the fields to be removed
* @throws DocumentException If any is encountered
*/
public static function byId(string $tableName, mixed $docId, array $fieldNames): void
{
$nameParams = Parameters::fieldNames(':name', $fieldNames);
Custom::nonQuery(Query\RemoveFields::byId($tableName, $nameParams),
array_merge(Parameters::id($docId), $nameParams));
}
/**
* Remove fields from documents via a comparison on a JSON field in the document
*
* @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`)
* @throws DocumentException If any is encountered
*/
public static function byFields(string $tableName, array $fields, array $fieldNames,
string $conjunction = 'AND'): void
{
$nameParams = Parameters::fieldNames(':name', $fieldNames);
$namedFields = Parameters::nameFields($fields);
Custom::nonQuery(Query\RemoveFields::byFields($tableName, $namedFields, $nameParams, $conjunction),
Parameters::addFields($namedFields, $nameParams));
}
}