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

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();
}
}