Add support, custom, and other queries

This commit is contained in:
2024-06-03 23:10:12 -04:00
parent 98bfceb7c9
commit b705130624
13 changed files with 576 additions and 8 deletions

View File

@@ -2,7 +2,10 @@
namespace BitBadger\PDODocument;
use BitBadger\PDODocument\Mapper\Mapper;
use Generator;
use PDO;
use PDOStatement;
/**
* A lazy iterator of results in a list; implementations will create new connections to the database and close/dispose
@@ -10,14 +13,16 @@ use Generator;
*
* @template TDoc The domain class for items returned by this list
*/
interface DocumentList
readonly class DocumentList
{
/**
* The items from the query result
* Constructor
*
* @return Generator<TDoc> The query results as a lazily-iterated generator
* @param PDO $pdo The database connection against which the query was opened
* @param PDOStatement $result The result of the query
* @param Mapper<TDoc> $mapper The mapper to deserialize JSON
*/
public function items(): Generator;
private function __construct(private PDO $pdo, private PDOStatement $result, private Mapper $mapper) { }
/**
* Construct a new document list
@@ -25,12 +30,28 @@ interface DocumentList
* @param string $query The query to run to retrieve results
* @param array $parameters An associative array of parameters for the query
* @param Mapper<TDoc> $mapper A mapper to deserialize JSON documents
* @return static The `DocumentList`-implementing instance
* @return static The document list instance
* @throws DocumentException If any is encountered
*/
public static function create(string $query, array $parameters, Mapper $mapper): static;
public static function create(string $query, array $parameters, Mapper $mapper): static
{
$pdo = Configuration::dbConn();
$stmt = Custom::runQuery($query, $parameters, $pdo);
if ($stmt->errorCode()) {
throw new DocumentException('Error retrieving data: ' . $stmt->errorCode());
}
return new static($pdo, $stmt, $mapper);
}
/**
* Clean up database connection resources
* The items from the query result
*
* @return Generator<TDoc> The items from the document list
*/
public function __destruct();
public function items(): Generator
{
if ($this->result) {
while ($row = $this->result->fetch(PDO::FETCH_ASSOC)) yield $this->mapper->map($row);
}
}
}