Add classes and tests from common project

This commit is contained in:
2024-06-03 19:46:39 -04:00
parent e91acee70f
commit 1164dc7cc5
32 changed files with 3175 additions and 0 deletions

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

@@ -0,0 +1,66 @@
<?php declare(strict_types=1);
namespace BitBadger\PDODocument\Query;
use BitBadger\PDODocument\Configuration;
/**
* 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)
* @param string $dataType The data type used for the document column
* @return string The CREATE TABLE statement for the document table
*/
public static function ensureTableFor(string $name, string $dataType): string
{
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()]));
}
}