Changes for beta10 (#5)

- Add In/InArray support
- Add ORDER BY support for `Find` functions
- Update dependencies
- Implement fixes identified via static analysis

Reviewed-on: #5
This commit was merged in pull request #5.
This commit is contained in:
2024-09-27 02:15:00 +00:00
parent 9e0e663811
commit d067f8983f
66 changed files with 1728 additions and 664 deletions

View File

@@ -34,7 +34,7 @@ class Configuration
/** @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) */
/** @var mixed[]|null Options to use for connections (driver-specific) */
public static ?array $options = null;
/** @var Option<Mode> The mode in which the library is operating */

View File

@@ -31,23 +31,23 @@ class Count
* 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 Field[] $fields The field comparison to match
* @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, ?FieldMatch $match = null): int
{
$namedFields = Parameters::nameFields($fields);
return Custom::scalar(Query\Count::byFields($tableName, $namedFields, $match),
Parameters::addFields($namedFields, []), new CountMapper());
Parameters::nameFields($fields);
return Custom::scalar(Query\Count::byFields($tableName, $fields, $match), Parameters::addFields($fields, []),
new CountMapper());
}
/**
* Count matching documents using a JSON containment query (`@>`; PostgreSQL only)
*
* @param string $tableName The name of the table in which documents should be counted
* @param array|object $criteria The criteria for the JSON containment query
* @param mixed[]|object $criteria The criteria for the JSON containment query
* @return int The number of documents matching the JSON containment query
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
*/

View File

@@ -23,7 +23,7 @@ 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
* @param array<string, mixed> $parameters The parameters for the query
* @return PDOStatement The result of executing the query
* @throws DocumentException If the query execution is unsuccessful
*/
@@ -67,7 +67,7 @@ class Custom
*
* @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 array<string, mixed> $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
@@ -82,7 +82,7 @@ class Custom
*
* @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 array<string, mixed> $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
@@ -97,7 +97,7 @@ class Custom
*
* @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 array<string, mixed> $parameters Parameters to use in executing the query
* @param Mapper<TDoc> $mapper Mapper to deserialize the result
* @return Option<TDoc> A `Some` instance if the item is found, `None` otherwise
* @throws DocumentException If any is encountered
@@ -116,7 +116,7 @@ class Custom
* 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
* @param array<string, mixed> $parameters Parameters to use in executing the query
* @throws DocumentException If any is encountered
*/
public static function nonQuery(string $query, array $parameters): void
@@ -133,7 +133,7 @@ class Custom
*
* @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 array<string, mixed> $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

View File

@@ -30,7 +30,7 @@ class Definition
*
* @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
* @param string[] $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

View File

@@ -29,22 +29,21 @@ class Delete
* 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 Field[] $fields The field comparison to match
* @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, ?FieldMatch $match = null): void
{
$namedFields = Parameters::nameFields($fields);
Custom::nonQuery(Query\Delete::byFields($tableName, $namedFields, $match),
Parameters::addFields($namedFields, []));
Parameters::nameFields($fields);
Custom::nonQuery(Query\Delete::byFields($tableName, $fields, $match), Parameters::addFields($fields, []));
}
/**
* Delete documents matching a JSON containment query (`@>`; PostgreSQL only)
*
* @param string $tableName The table from which documents should be deleted
* @param array|object $criteria The JSON containment query values
* @param mixed[]|object $criteria The JSON containment query values
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
*/
public static function byContains(string $tableName, array|object $criteria): void

View File

@@ -17,7 +17,7 @@ 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
* @param mixed[]|object $document The document to be inserted
* @throws DocumentException If any is encountered
*/
public static function insert(string $tableName, array|object $document): void
@@ -47,7 +47,7 @@ class 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
* @param mixed[]|object $document The document to be saved
* @throws DocumentException If any is encountered
*/
public static function save(string $tableName, array|object $document): void
@@ -60,7 +60,7 @@ class Document
*
* @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
* @param mixed[]|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

View File

@@ -35,10 +35,12 @@ class DocumentList
*/
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;
if (!is_null($this->result)) {
if ($row = $this->result->fetch(PDO::FETCH_ASSOC)) {
$this->first = $this->mapper->map($row);
} else {
$this->result = null;
}
}
}
@@ -67,6 +69,11 @@ class DocumentList
$this->isConsumed = true;
return;
}
if (!$this->first) {
$this->isConsumed = true;
$this->result = null;
return;
}
yield $this->first;
while ($row = $this->result->fetch(PDO::FETCH_ASSOC)) {
yield $this->mapper->map($row);
@@ -133,14 +140,14 @@ class DocumentList
* 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 array<string, mixed> $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
* @return self<TDoc> The document list instance
* @throws DocumentException If any is encountered
*/
public static function create(string $query, array $parameters, Mapper $mapper): static
public static function create(string $query, array $parameters, Mapper $mapper): self
{
$stmt = &Custom::runQuery($query, $parameters);
return new static($stmt, $mapper);
return new self($stmt, $mapper);
}
}

View File

@@ -39,16 +39,16 @@ class Exists
*/
public static function byFields(string $tableName, array $fields, ?FieldMatch $match = null): bool
{
$namedFields = Parameters::nameFields($fields);
return Custom::scalar(Query\Exists::byFields($tableName, $namedFields, $match),
Parameters::addFields($namedFields, []), new ExistsMapper());
Parameters::nameFields($fields);
return Custom::scalar(Query\Exists::byFields($tableName, $fields, $match), Parameters::addFields($fields, []),
new ExistsMapper());
}
/**
* Determine if documents exist by a JSON containment query (`@>`; PostgreSQL only)
*
* @param string $tableName The name of the table in which document existence should be determined
* @param array|object $criteria The criteria for the JSON containment query
* @param mixed[]|object $criteria The criteria for the JSON containment query
* @return bool True if any documents match the JSON containment query, false if not
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
*/

View File

@@ -27,31 +27,67 @@ class 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 function __construct(public string $fieldName = '', public Op $op = Op::Equal, 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
* @param array<string, mixed> $existing The existing parameters
* @return array<string, mixed> The given parameter array with this field's name and value(s) appended
*/
public function appendParameter(array $existing): array
{
switch ($this->op) {
case Op::EX:
case Op::NEX:
case Op::Exists:
case Op::NotExists:
break;
case Op::BT:
case Op::Between:
$existing["{$this->paramName}min"] = $this->value[0];
$existing["{$this->paramName}max"] = $this->value[1];
break;
case Op::In:
for ($idx = 0; $idx < count($this->value); $idx++) {
$existing["{$this->paramName}_$idx"] = $this->value[$idx];
}
break;
case Op::InArray:
$mkString = Configuration::mode("Append parameters for InArray condition") === Mode::PgSQL;
$values = $this->value['values'];
for ($idx = 0; $idx < count($values); $idx++) {
$existing["{$this->paramName}_$idx"] = $mkString ? "$values[$idx]" : $values[$idx];
}
break;
default:
$existing[$this->paramName] = $this->value;
}
return $existing;
}
/**
* Derive the path for this field
*
* @param bool $asJSON Whether the field should be treated as JSON in the query (optional, default false)
* @return string The path for this field
* @throws Exception If the database mode has not been set
*/
public function path(bool $asJSON = false): string
{
$extra = $asJSON ? '' : '>';
if (str_contains($this->fieldName, '.')) {
$mode = Configuration::mode('determine field path');
if ($mode === Mode::PgSQL) {
return "data#>$extra'{" . implode(',', explode('.', $this->fieldName)) . "}'";
}
if ($mode === Mode::SQLite) {
$parts = explode('.', $this->fieldName);
$last = array_pop($parts);
return "data->'" . implode("'->'", $parts) . "'->$extra'$last'";
}
}
return "data->$extra'$this->fieldName'";
}
/**
* Get the WHERE clause fragment for this parameter
*
@@ -60,26 +96,41 @@ class Field
*/
public function toWhere(): string
{
$mode = Configuration::mode('make field WHERE clause');
$fieldName = (empty($this->qualifier) ? '' : "$this->qualifier.") . 'data' . match (true) {
!str_contains($this->fieldName, '.') => "->>'$this->fieldName'",
$mode === Mode::PgSQL => "#>>'{" . implode(',', explode('.', $this->fieldName)) . "}'",
$mode === Mode::SQLite => "->>'" . implode("'->>'", explode('.', $this->fieldName)) . "'",
};
$fieldPath = match ($mode) {
$mode = Configuration::mode('make field WHERE clause');
$fieldName = (empty($this->qualifier) ? '' : "$this->qualifier.") . $this->path($this->op === Op::InArray);
$fieldPath = match ($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,
$this->op === Op::Between,
$this->op === Op::In => 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",
Op::Exists,
Op::NotExists => '',
Op::Between => " {$this->paramName}min AND {$this->paramName}max",
Op::In => ' (' . $this->inParameterNames() . ')',
Op::InArray => $mode === Mode::PgSQL ? ' ARRAY[' . $this->inParameterNames() . ']' : '',
default => " $this->paramName",
};
return $fieldPath . ' ' . $this->op->toSQL() . $criteria;
return $mode === Mode::SQLite && $this->op === Op::InArray
? "EXISTS (SELECT 1 FROM json_each({$this->value['table']}.data, '\$.$this->fieldName') WHERE value IN ("
. $this->inParameterNames() . '))'
: $fieldPath . ' ' . $this->op->toSQL() . $criteria;
}
/**
* Create parameter names for an IN clause
*
* @return string A comma-delimited string of parameter names
*/
private function inParameterNames(): string
{
$values = $this->op === Op::In ? $this->value : $this->value['values'];
return implode(', ',
array_map(fn($value, $key) => "{$this->paramName}_$key", $values, range(0, count($values) - 1)));
}
/**
@@ -88,11 +139,24 @@ class Field
* @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
* @return self The field with the requested criterion
*/
public static function EQ(string $fieldName, mixed $value, string $paramName = ''): static
public static function equal(string $fieldName, mixed $value, string $paramName = ''): self
{
return new static($fieldName, Op::EQ, $value, $paramName);
return new self($fieldName, Op::Equal, $value, $paramName);
}
/**
* Create an equals (=) field criterion _(alias for `Field.equal`)_
*
* @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 self The field with the requested criterion
*/
public static function EQ(string $fieldName, mixed $value, string $paramName = ''): self
{
return self::equal($fieldName, $value, $paramName);
}
/**
@@ -101,11 +165,24 @@ class Field
* @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
* @return self The field with the requested criterion
*/
public static function GT(string $fieldName, mixed $value, string $paramName = ''): static
public static function greater(string $fieldName, mixed $value, string $paramName = ''): self
{
return new static($fieldName, Op::GT, $value, $paramName);
return new self($fieldName, Op::Greater, $value, $paramName);
}
/**
* Create a greater than (>) field criterion _(alias for `Field.greater`)_
*
* @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 self The field with the requested criterion
*/
public static function GT(string $fieldName, mixed $value, string $paramName = ''): self
{
return self::greater($fieldName, $value, $paramName);
}
/**
@@ -114,11 +191,24 @@ class Field
* @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
* @return self The field with the requested criterion
*/
public static function GE(string $fieldName, mixed $value, string $paramName = ''): static
public static function greaterOrEqual(string $fieldName, mixed $value, string $paramName = ''): self
{
return new static($fieldName, Op::GE, $value, $paramName);
return new self($fieldName, Op::GreaterOrEqual, $value, $paramName);
}
/**
* Create a greater than or equal to (>=) field criterion _(alias for `Field.greaterOrEqual`)_
*
* @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 self The field with the requested criterion
*/
public static function GE(string $fieldName, mixed $value, string $paramName = ''): self
{
return self::greaterOrEqual($fieldName, $value, $paramName);
}
/**
@@ -127,11 +217,24 @@ class Field
* @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
* @return self The field with the requested criterion
*/
public static function LT(string $fieldName, mixed $value, string $paramName = ''): static
public static function less(string $fieldName, mixed $value, string $paramName = ''): self
{
return new static($fieldName, Op::LT, $value, $paramName);
return new self($fieldName, Op::Less, $value, $paramName);
}
/**
* Create a less than (<) field criterion _(alias for `Field.less`)_
*
* @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 self The field with the requested criterion
*/
public static function LT(string $fieldName, mixed $value, string $paramName = ''): self
{
return self::less($fieldName, $value, $paramName);
}
/**
@@ -140,11 +243,24 @@ class Field
* @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
* @return self The field with the requested criterion
*/
public static function LE(string $fieldName, mixed $value, string $paramName = ''): static
public static function lessOrEqual(string $fieldName, mixed $value, string $paramName = ''): self
{
return new static($fieldName, Op::LE, $value, $paramName);
return new self($fieldName, Op::LessOrEqual, $value, $paramName);
}
/**
* Create a less than or equal to (<=) field criterion _(alias for `Field.lessOrEqual`)_
*
* @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 self The field with the requested criterion
*/
public static function LE(string $fieldName, mixed $value, string $paramName = ''): self
{
return self::lessOrEqual($fieldName, $value, $paramName);
}
/**
@@ -153,11 +269,24 @@ class Field
* @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
* @return self The field with the requested criterion
*/
public static function NE(string $fieldName, mixed $value, string $paramName = ''): static
public static function notEqual(string $fieldName, mixed $value, string $paramName = ''): self
{
return new static($fieldName, Op::NE, $value, $paramName);
return new self($fieldName, Op::NotEqual, $value, $paramName);
}
/**
* Create a not equals (<>) field criterion _(alias for `Field.notEqual`)_
*
* @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 self The field with the requested criterion
*/
public static function NE(string $fieldName, mixed $value, string $paramName = ''): self
{
return self::notEqual($fieldName, $value, $paramName);
}
/**
@@ -167,32 +296,109 @@ class Field
* @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
* @return self The field with the requested criterion
*/
public static function BT(string $fieldName, mixed $minValue, mixed $maxValue, string $paramName = ''): static
public static function between(string $fieldName, mixed $minValue, mixed $maxValue, string $paramName = ''): self
{
return new static($fieldName, Op::BT, [$minValue, $maxValue], $paramName);
return new self($fieldName, Op::Between, [$minValue, $maxValue], $paramName);
}
/**
* Create a BETWEEN field criterion _(alias for `Field.between`)_
*
* @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 self The field with the requested criterion
*/
public static function BT(string $fieldName, mixed $minValue, mixed $maxValue, string $paramName = ''): self
{
return self::between($fieldName, $minValue, $maxValue, $paramName);
}
/**
* Create an IN field criterion
*
* @param string $fieldName The name of the field against which the values will be compared
* @param mixed[] $values The potential matching values for the field
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
* @return self The field with the requested criterion
*/
public static function in(string $fieldName, array $values, string $paramName = ''): self
{
return new self($fieldName, Op::In, $values, $paramName);
}
/**
* Create an IN ARRAY field criterion
*
* @param string $fieldName The name of the field against which the values will be compared
* @param string $tableName The table name where this field is located
* @param mixed[] $values The potential matching values for the field
* @param string $paramName The name of the parameter to which this should be bound (optional; generated if blank)
* @return self The field with the requested criterion
*/
public static function inArray(string $fieldName, string $tableName, array $values, string $paramName = ''): self
{
return new self($fieldName, Op::InArray, ['table' => $tableName, 'values' => $values], $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
* @return self The field with the requested criterion
*/
public static function EX(string $fieldName): static
public static function exists(string $fieldName): self
{
return new static($fieldName, Op::EX, '', '');
return new self($fieldName, Op::Exists, '', '');
}
/**
* Create an exists (IS NOT NULL) field criterion _(alias for `Field.exists`)_
*
* @param string $fieldName The name of the field for which existence will be checked
* @return self The field with the requested criterion
*/
public static function EX(string $fieldName): self
{
return self::exists($fieldName);
}
/**
* 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
* @return self The field with the requested criterion
*/
public static function NEX(string $fieldName): static
public static function notExists(string $fieldName): self
{
return new static($fieldName, Op::NEX, '', '');
return new self($fieldName, Op::NotExists, '', '');
}
/**
* Create a not exists (IS NULL) field criterion _(alias for `Field.notExists`)_
*
* @param string $fieldName The name of the field for which non-existence will be checked
* @return self The field with the requested criterion
*/
public static function NEX(string $fieldName): self
{
return self::notExists($fieldName);
}
/**
* Create a named fields (used for creating fields for ORDER BY clauses)
*
* Prepend the field name with 'n:' to treat the field as a number; prepend the field name with 'i:' to perform
* a case-insensitive ordering.
*
* @param string $name The name of the field, plus any direction for the ordering
* @return self
*/
public static function named(string $name): self
{
return new self($name, Op::Equal, '', '');
}
}

View File

@@ -22,12 +22,14 @@ class Find
* @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
* @param Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
* @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
public static function all(string $tableName, string $className, array $orderBy = []): DocumentList
{
return Custom::list(Query::selectFromTable($tableName), [], new DocumentMapper($className));
return Custom::list(Query::selectFromTable($tableName) . Query::orderBy($orderBy), [],
new DocumentMapper($className));
}
/**
@@ -51,18 +53,19 @@ class Find
*
* @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 Field[] $fields The field comparison to match
* @param class-string<TDoc> $className The name of the class to be retrieved
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
* @param Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
* @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,
?FieldMatch $match = null): DocumentList
?FieldMatch $match = null, array $orderBy = []): DocumentList
{
$namedFields = Parameters::nameFields($fields);
return Custom::list(Query\Find::byFields($tableName, $namedFields, $match),
Parameters::addFields($namedFields, []), new DocumentMapper($className));
Parameters::nameFields($fields);
return Custom::list(Query\Find::byFields($tableName, $fields, $match) . Query::orderBy($orderBy),
Parameters::addFields($fields, []), new DocumentMapper($className));
}
/**
@@ -70,15 +73,17 @@ class Find
*
* @template TDoc The type of document to be retrieved
* @param string $tableName The name of the table from which documents should be retrieved
* @param array|object $criteria The criteria for the JSON containment query
* @param mixed[]|object $criteria The criteria for the JSON containment query
* @param class-string<TDoc> $className The name of the class to be retrieved
* @param Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
* @return DocumentList<TDoc> A list of documents matching the JSON containment query
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
*/
public static function byContains(string $tableName, array|object $criteria, string $className): DocumentList
public static function byContains(string $tableName, array|object $criteria, string $className,
array $orderBy = []): DocumentList
{
return Custom::list(Query\Find::byContains($tableName), Parameters::json(':criteria', $criteria),
new DocumentMapper($className));
return Custom::list(Query\Find::byContains($tableName) . Query::orderBy($orderBy),
Parameters::json(':criteria', $criteria), new DocumentMapper($className));
}
/**
@@ -88,12 +93,15 @@ class Find
* @param string $tableName The name of the table from which documents should be retrieved
* @param string $path The JSON Path match string
* @param class-string<TDoc> $className The name of the class to be retrieved
* @param Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
* @return DocumentList<TDoc> A list of documents matching the JSON Path
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
*/
public static function byJsonPath(string $tableName, string $path, string $className): DocumentList
public static function byJsonPath(string $tableName, string $path, string $className,
array $orderBy = []): DocumentList
{
return Custom::list(Query\Find::byJsonPath($tableName), [':path' => $path], new DocumentMapper($className));
return Custom::list(Query\Find::byJsonPath($tableName) . Query::orderBy($orderBy), [':path' => $path],
new DocumentMapper($className));
}
/**
@@ -101,18 +109,19 @@ class Find
*
* @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 Field[] $fields The field comparison to match
* @param class-string<TDoc> $className The name of the class to be retrieved
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
* @param Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
* @return Option<TDoc> A `Some` instance with the first document if any matches are found, `None` otherwise
* @throws DocumentException If any is encountered
*/
public static function firstByFields(string $tableName, array $fields, string $className,
?FieldMatch $match = null): Option
?FieldMatch $match = null, array $orderBy = []): Option
{
$namedFields = Parameters::nameFields($fields);
return Custom::single(Query\Find::byFields($tableName, $namedFields, $match),
Parameters::addFields($namedFields, []), new DocumentMapper($className));
Parameters::nameFields($fields);
return Custom::single(Query\Find::byFields($tableName, $fields, $match) . Query::orderBy($orderBy),
Parameters::addFields($fields, []), new DocumentMapper($className));
}
/**
@@ -120,15 +129,17 @@ class Find
*
* @template TDoc The type of document to be retrieved
* @param string $tableName The name of the table from which documents should be retrieved
* @param array|object $criteria The criteria for the JSON containment query
* @param mixed[]|object $criteria The criteria for the JSON containment query
* @param class-string<TDoc> $className The name of the class to be retrieved
* @param Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
* @return Option<TDoc> A `Some` instance with the first document if any matches are found, `None` otherwise
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
*/
public static function firstByContains(string $tableName, array|object $criteria, string $className): Option
public static function firstByContains(string $tableName, array|object $criteria, string $className,
array $orderBy = []): Option
{
return Custom::single(Query\Find::byContains($tableName), Parameters::json(':criteria', $criteria),
new DocumentMapper($className));
return Custom::single(Query\Find::byContains($tableName) . Query::orderBy($orderBy),
Parameters::json(':criteria', $criteria), new DocumentMapper($className));
}
/**
@@ -138,11 +149,14 @@ class Find
* @param string $tableName The name of the table from which documents should be retrieved
* @param string $path The JSON Path match string
* @param class-string<TDoc> $className The name of the class to be retrieved
* @param Field[] $orderBy Fields by which the results should be ordered (optional, default no ordering)
* @return Option<TDoc> A `Some` instance with the first document if any matches are found, `None` otherwise
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
*/
public static function firstByJsonPath(string $tableName, string $path, string $className): Option
public static function firstByJsonPath(string $tableName, string $path, string $className,
array $orderBy = []): Option
{
return Custom::single(Query\Find::byJsonPath($tableName), [':path' => $path], new DocumentMapper($className));
return Custom::single(Query\Find::byJsonPath($tableName) . Query::orderBy($orderBy), [':path' => $path],
new DocumentMapper($className));
}
}

View File

@@ -10,10 +10,15 @@ namespace BitBadger\PDODocument\Mapper;
/**
* A mapper that returns the associative array from the database
*
* @implements Mapper<array<string|int, mixed>>
*/
class ArrayMapper implements Mapper
{
/** @inheritDoc */
/**
* @inheritDoc
* @return array<string|int, mixed> The array given as the parameter
*/
public function map(array $result): array
{
return $result;

View File

@@ -10,6 +10,8 @@ namespace BitBadger\PDODocument\Mapper;
/**
* A mapper that returns the integer value of the first item in the results
*
* @implements Mapper<int>
*/
class CountMapper implements Mapper
{

View File

@@ -31,7 +31,7 @@ class DocumentMapper implements Mapper
/**
* Map a result to a domain class instance
*
* @param array $result An associative array representing a single database result
* @param array<string|int, mixed> $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
*/

View File

@@ -13,6 +13,8 @@ use Exception;
/**
* Map an EXISTS result to a boolean value
*
* @implements Mapper<bool>
*/
class ExistsMapper implements Mapper
{

View File

@@ -18,7 +18,7 @@ interface Mapper
/**
* Map a result to the specified type
*
* @param array $result An associative array representing a single database result
* @param array<string|int, mixed> $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

@@ -9,28 +9,32 @@ declare(strict_types=1);
namespace BitBadger\PDODocument;
/**
* The types of logical operations allowed for JSON fields
* The types of comparison operators allowed for JSON fields
*/
enum Op
{
/** Equals (=) */
case EQ;
case Equal;
/** Greater Than (>) */
case GT;
case Greater;
/** Greater Than or Equal To (>=) */
case GE;
case GreaterOrEqual;
/** Less Than (<) */
case LT;
case Less;
/** Less Than or Equal To (<=) */
case LE;
case LessOrEqual;
/** Not Equal to (<>) */
case NE;
case NotEqual;
/** Between (BETWEEN) */
case BT;
case Between;
/** In (IN) */
case In;
/** In Array (PostgreSQL - ?|, SQLite - EXISTS / json_each / IN) */
case InArray;
/** Exists (IS NOT NULL) */
case EX;
case Exists;
/** Does Not Exist (IS NULL) */
case NEX;
case NotExists;
/**
* Get the SQL representation of this operator
@@ -40,15 +44,17 @@ enum Op
public function toSQL(): 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",
Op::Equal => "=",
Op::Greater => ">",
Op::GreaterOrEqual => ">=",
Op::Less => "<",
Op::LessOrEqual => "<=",
Op::NotEqual => "<>",
Op::Between => "BETWEEN",
Op::In => "IN",
Op::InArray => "??|", // The actual operator is ?|, but needs to be escaped by doubling
Op::Exists => "IS NOT NULL",
Op::NotExists => "IS NULL",
};
}
}

View File

@@ -19,19 +19,19 @@ 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
* @return array<string, mixed> 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"];
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
* @param mixed[]|object $document The value that should be passed as a JSON string
* @return array<string, string> An associative array with the named parameter/value pair
*/
public static function json(string $name, object|array $document): array
{
@@ -59,23 +59,21 @@ class Parameters
/**
* Fill in parameter names for any fields missing one
*
* @param Field[] $fields The fields for the query
* @return Field[] The fields, all with non-blank parameter names
* @param Field[] $fields The fields for the query (entries with no names will be modified)
*/
public static function nameFields(array $fields): array
public static function nameFields(array &$fields): void
{
array_walk($fields, function (Field $field, int $idx) {
if (empty($field->paramName)) $field->paramName =":field$idx";
});
return $fields;
}
/**
* Add field parameters to the given set of parameters
*
* @param 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
* @param array<string, mixed> $parameters An associative array of parameters to which the fields should be added
* @return array<string, mixed> An associative array of parameter names and values with the fields added
*/
public static function addFields(array $fields, array $parameters): array
{
@@ -87,7 +85,7 @@ class Parameters
*
* @param string $paramName The name of the parameter for the field names
* @param string[] $fieldNames The names of the fields for the parameter
* @return array An associative array of parameter/value pairs for the field names
* @return array<string, string> An associative array of parameter/value pairs for the field names
* @throws Exception If the database mode has not been set
*/
public static function fieldNames(string $paramName, array $fieldNames): array

View File

@@ -18,7 +18,7 @@ class Patch
*
* @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)
* @param mixed[]|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
@@ -31,25 +31,25 @@ class 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 Field[] $fields The field comparison to match
* @param mixed[]|object $patch The object with which the documents should be patched (will be JSON-encoded)
* @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,
?FieldMatch $match = null): void
{
$namedFields = Parameters::nameFields($fields);
Custom::nonQuery(Query\Patch::byFields($tableName, $namedFields, $match),
Parameters::addFields($namedFields, Parameters::json(':data', $patch)));
Parameters::nameFields($fields);
Custom::nonQuery(Query\Patch::byFields($tableName, $fields, $match),
Parameters::addFields($fields, Parameters::json(':data', $patch)));
}
/**
* Patch documents using a JSON containment query (`@>`; PostgreSQL only)
*
* @param string $tableName The table in which documents should be patched
* @param array|object $criteria The JSON containment query values to match
* @param array|object $patch The object with which the documents should be patched (will be JSON-encoded)
* @param mixed[]|object $criteria The JSON containment query values to match
* @param mixed[]|object $patch The object with which the documents should be patched (will be JSON-encoded)
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
*/
public static function byContains(string $tableName, array|object $criteria, array|object $patch): void
@@ -63,7 +63,7 @@ class Patch
*
* @param string $tableName The table in which documents should be patched
* @param string $path The JSON Path match string
* @param array|object $patch The object with which the documents should be patched (will be JSON-encoded)
* @param mixed[]|object $patch The object with which the documents should be patched (will be JSON-encoded)
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
*/
public static function byJsonPath(string $tableName, string $path, array|object $patch): void

View File

@@ -51,7 +51,7 @@ class Query
*/
public static function whereById(string $paramName = ':id', mixed $docId = null): string
{
return self::whereByFields([Field::EQ(Configuration::$idField, $docId ?? '', $paramName)]);
return self::whereByFields([Field::equal(Configuration::$idField, $docId ?? '', $paramName)]);
}
/**
@@ -142,4 +142,46 @@ class Query
{
return "UPDATE $tableName SET data = :data WHERE " . self::whereById();
}
/**
* Create an `ORDER BY` clause ('n:' treats field as number, 'i:' does case-insensitive ordering)
*
* @param Field[] $fields The fields, named for the field plus directions (ex. 'field DESC NULLS FIRST')
* @return string The ORDER BY clause with the given fields
* @throws Exception If the database mode has not been set
*/
public static function orderBy(array $fields): string
{
if (empty($fields)) return "";
$mode = Configuration::mode('render ORDER BY clause');
$sqlFields = array_map(function (Field $it) use ($mode) {
if (str_contains($it->fieldName, ' ')) {
$parts = explode(' ', $it->fieldName);
$it->fieldName = array_shift($parts);
$direction = ' ' . implode(' ', $parts);
} else {
$direction = '';
}
if (str_starts_with($it->fieldName, 'n:')) {
$it->fieldName = substr($it->fieldName, 2);
$value = match ($mode) {
Mode::PgSQL => '(' . $it->path() . ')::numeric',
Mode::SQLite => $it->path()
};
} elseif (str_starts_with($it->fieldName, 'i:')) {
$it->fieldName = substr($it->fieldName, 2);
$value = match ($mode) {
Mode::PgSQL => 'LOWER(' . $it->path() . ')',
Mode::SQLite => $it->path() . ' COLLATE NOCASE'
};
} else {
$value = $it->path();
}
return $value . $direction;
}, $fields);
return ' ORDER BY ' . implode(', ', $sqlFields);
}
}

View File

@@ -49,7 +49,7 @@ class Definition
*
* @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')
* @param string[] $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

View File

@@ -24,7 +24,7 @@ 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 array<string, mixed> $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 Exception If the database mode has not been set
@@ -43,7 +43,7 @@ class RemoveFields
* 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
* @param array<string, mixed> $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
@@ -57,8 +57,8 @@ class RemoveFields
* 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 Field[] $fields The field comparison to match
* @param array<string, mixed> $parameters The parameter list for the query
* @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
@@ -73,7 +73,7 @@ class RemoveFields
* Query to remove fields from documents via a JSON containment query (PostgreSQL only)
*
* @param string $tableName The name of the table in which documents should be manipulated
* @param array $parameters The parameter list for the query
* @param array<string, mixed> $parameters The parameter list for the query
* @return string The UPDATE statement to remove fields from documents via a JSON containment query
* @throws DocumentException If the database mode is not PostgreSQL
*/
@@ -86,7 +86,7 @@ class RemoveFields
* Query to remove fields from documents via a JSON Path match query (PostgreSQL only)
*
* @param string $tableName The name of the table in which documents should be manipulated
* @param array $parameters The parameter list for the query
* @param array<string, mixed> $parameters The parameter list for the query
* @return string The UPDATE statement to remove fields from documents via a JSON Path match
* @throws DocumentException
*/

View File

@@ -18,7 +18,7 @@ class RemoveFields
*
* @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
* @param 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
@@ -32,8 +32,8 @@ class RemoveFields
* 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 Field[] $fields The field comparison to match
* @param string[] $fieldNames The names of the fields to be removed
* @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All)
* @throws DocumentException If any is encountered
*/
@@ -41,17 +41,17 @@ class RemoveFields
?FieldMatch $match = null): void
{
$nameParams = Parameters::fieldNames(':name', $fieldNames);
$namedFields = Parameters::nameFields($fields);
Custom::nonQuery(Query\RemoveFields::byFields($tableName, $namedFields, $nameParams, $match),
Parameters::addFields($namedFields, $nameParams));
Parameters::nameFields($fields);
Custom::nonQuery(Query\RemoveFields::byFields($tableName, $fields, $nameParams, $match),
Parameters::addFields($fields, $nameParams));
}
/**
* Remove fields from documents via a JSON containment query (`@>`; PostgreSQL only)
*
* @param string $tableName The table in which documents should have fields removed
* @param array|object $criteria The JSON containment query values
* @param array|string[] $fieldNames The names of the fields to be removed
* @param mixed[]|object $criteria The JSON containment query values
* @param string[] $fieldNames The names of the fields to be removed
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
*/
public static function byContains(string $tableName, array|object $criteria, array $fieldNames): void
@@ -66,7 +66,7 @@ class RemoveFields
*
* @param string $tableName The table in which documents should have fields removed
* @param string $path The JSON Path match string
* @param array|string[] $fieldNames The names of the fields to be removed
* @param string[] $fieldNames The names of the fields to be removed
* @throws DocumentException If the database mode is not PostgreSQL, or if an error occurs
*/
public static function byJsonPath(string $tableName, string $path, array $fieldNames): void