Initial SQLite development (#1)
Reviewed-on: #1
This commit was merged in pull request #1.
This commit is contained in:
55
src/Query/Patch.php
Normal file
55
src/Query/Patch.php
Normal 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));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user