Add auto ID enum, modify insert queries

This commit is contained in:
2024-06-10 21:12:21 -04:00
parent 9729c50c00
commit c892689eb6
8 changed files with 243 additions and 15 deletions

View File

@@ -2,6 +2,8 @@
namespace BitBadger\PDODocument;
use Random\RandomException;
/**
* Query construction functions
*/
@@ -45,14 +47,38 @@ class Query
}
/**
* Query to insert a document
* Create an `INSERT` statement for a document
*
* @param string $tableName The name of the table into which a document should be inserted
* @return string The INSERT statement for the given table
* @param string $tableName The name of the table into which the document will be inserted
* @return string The `INSERT` statement to insert a document
* @throws DocumentException If the database mode is not set
*/
public static function insert(string $tableName): string
{
return "INSERT INTO $tableName VALUES (:data)";
try {
$id = Configuration::$idField;
$values = match (Configuration::$mode) {
Mode::SQLite => match (Configuration::$autoId) {
AutoId::None => ':data',
AutoId::Number => "json_set(:data, '$.$id', "
. "(SELECT coalesce(max(data->>'$id'), 0) + 1 FROM $tableName))",
AutoId::UUID => "json_set(:data, '$.$id', '" . AutoId::generateUUID() . "')",
AutoId::RandomString => "json_set(:data, '$.$id', '" . AutoId::generateRandom() ."')"
},
Mode::PgSQL => match (Configuration::$autoId) {
AutoId::None => ':data',
AutoId::Number => ":data || ('{\"$id\":' || "
. "(SELECT COALESCE(MAX(data->>'$id'), 0) + 1 FROM $tableName) || '}')",
AutoId::UUID => ":data || '{\"$id\":\"" . AutoId::generateUUID() . "\"}'",
AutoId::RandomString => ":data || '{\"$id\":\"" . AutoId::generateRandom() . "\"}'",
},
default =>
throw new DocumentException('Database mode not set; cannot generate auto-ID INSERT statement'),
};
return "INSERT INTO $tableName VALUES ($values)";
} catch (RandomException $ex) {
throw new DocumentException('Unable to generate ID: ' . $ex->getMessage(), previous: $ex);
}
}
/**
@@ -63,8 +89,8 @@ class Query
*/
public static function save(string $tableName): string
{
return self::insert($tableName)
. " ON CONFLICT ((data->>'" . Configuration::$idField . "')) DO UPDATE SET data = EXCLUDED.data";
$id = Configuration::$idField;
return "INSERT INTO $tableName VALUES (:data) ON CONFLICT ((data->>'$id')) DO UPDATE SET data = EXCLUDED.data";
}
/**