* @license MIT */ declare(strict_types=1); namespace BitBadger\PDODocument\Query; use BitBadger\PDODocument\{DocumentException, Field, FieldMatch, Query}; /** * Queries to determine document existence */ class Exists { /** * The shell of a query for an existence check * * @param string $tableName The name of the table in which existence should be checked * @param string $whereClause The conditions for which existence should be checked * @return string The query to determine existence of documents */ public static function query(string $tableName, string $whereClause): string { return "SELECT EXISTS (SELECT 1 FROM $tableName WHERE $whereClause)"; } /** * Query to determine if a document exists for the given ID * * @param string $tableName The name of the table in which document existence should be checked * @param mixed $docId The ID of the document whose existence should be checked (optional; string ID assumed) * @return string The query to determine document existence by ID * @throws DocumentException If the database mode has not been set */ public static function byId(string $tableName, mixed $docId = null): string { return self::query($tableName, Query::whereById(docId: $docId)); } /** * Query to determine if documents exist using a comparison on JSON fields * * @param string $tableName The name of the table in which document existence should be checked * @param Field[] $fields The field comparison to match * @param FieldMatch|null $match How to handle multiple conditions (optional; defaults to All) * @return string The query to determine document existence by field comparison * @throws DocumentException If the database mode has not been set */ public static function byFields(string $tableName, array $fields, ?FieldMatch $match = null): string { return self::query($tableName, Query::whereByFields($fields, $match)); } /** * Query to determine if documents exist using a JSON containment query (PostgreSQL only) * * @param string $tableName The name of the table in which document existence should be checked * @return string The query to determine document existence by a JSON containment query * @throws DocumentException If the database mode is not PostgreSQL */ public static function byContains(string $tableName): string { return self::query($tableName, Query::whereDataContains()); } /** * Query to determine if documents exist using a JSON Path match query (PostgreSQL only) * * @param string $tableName The name of the table in which document existence should be checked * @return string The query to determine document existence by a JSON Path match * @throws DocumentException If the database mode is not PostgreSQL */ public static function byJsonPath(string $tableName): string { return self::query($tableName, Query::whereJsonPathMatches()); } }