This commit is contained in:
Dave Mc Nicoll committed 2020-11-27 12:21:10 -05:00
commit f74d1907d9
21 files changed
+759 -555

No files matched your search

+151 -118
View File
@@ -7,7 +7,7 @@ use Ulmus\Common\EntityResolver;
class Repository
{
use EventTrait, Repository\ConditionTrait;
const DEFAULT_ALIAS = "this";
public ? ConnectionAdapter $adapter;
@@ -19,14 +19,14 @@ class Repository
public string $alias;
public string $entityClass;
public array $events = [];
public function __construct(string $entity, string $alias = self::DEFAULT_ALIAS, ConnectionAdapter $adapter = null) {
$this->entityClass = $entity;
$this->alias = $alias;
$this->entityResolver = Ulmus::resolveEntity($entity);
$this->adapter = $adapter ?? $this->entityResolver->databaseAdapter() ?? Ulmus::$defaultAdapter;
$this->adapter = $adapter ?? $this->entityResolver->databaseAdapter();
$this->queryBuilder = new QueryBuilder();
}
@@ -44,12 +44,12 @@ class Repository
{
return $this->where($field, $value)->loadOne();
}
public function loadFromPk($value, /* ? stringable */ $primaryKey = null) : ? object
{
return $primaryKey ? $this->loadOneFromField($primaryKey, $value) : $this->wherePrimaryKey($value)->loadOne();
}
public function loadAll() : EntityCollection
{
return $this->collectionFromQuery();
@@ -59,20 +59,20 @@ class Repository
{
return $this->where($field, $value)->collectionFromQuery();
}
public function count() : int
{
if ( null !== $select = $this->queryBuilder->getFragment(Query\Select::class) ) {
$this->queryBuilder->removeFragment($select);
}
if ( $this->queryBuilder->getFragment(Query\GroupBy::class) ) {
$this->select( "DISTINCT COUNT(*) OVER ()" );
}
else {
$this->select(Common\Sql::function("COUNT", "*"));
}
$this->selectSqlQuery();
$this->finalizeQuery();
@@ -80,13 +80,13 @@ class Repository
return Ulmus::runSelectQuery($this->queryBuilder, $this->adapter)->fetchColumn(0);
}
protected function deleteOne()
protected function deleteOne()
{
return $this->limit(1)->deleteSqlQuery()->runQuery();
}
protected function deleteAll()
{
protected function deleteAll()
{
return $this->deleteSqlQuery()->runQuery();
}
@@ -95,16 +95,16 @@ class Repository
if ( $value !== 0 && empty($value) ) {
throw new Exception\EntityPrimaryKeyUnknown("A primary key value has to be defined to delete an item.");
}
return (bool) $this->wherePrimaryKey($value)->deleteOne()->rowCount();
}
public function destroy(object $entity) : bool
{
if ( ! $this->matchEntity($entity) ) {
throw new \Exception("Your entity class `" . get_class($entity) . "` cannot match entity type of repository `{$this->entityClass}`");
}
$primaryKeyDefinition = Ulmus::resolveEntity($this->entityClass)->getPrimaryKeyField();
if ( $primaryKeyDefinition === null ) {
@@ -112,42 +112,41 @@ class Repository
}
else {
$pkField = key($primaryKeyDefinition);
return $this->deleteFromPk($entity->$pkField);
}
return false;
}
public function destroyAll(EntityCollection $collection) : void
public function destroyAll(EntityCollection $collection) : void
{
foreach($collection as $entity) {
$this->destroy($entity);
}
}
public function save(object $entity) : bool
{
{
if ( ! $this->matchEntity($entity) ) {
throw new \Exception("Your entity class `" . get_class($entity) . "` cannot match entity type of repository `{$this->entityClass}`");
}
$dataset = $entity->toArray();
$primaryKeyDefinition = Ulmus::resolveEntity($this->entityClass)->getPrimaryKeyField();
if ( ! $entity->isLoaded() ) {
$statement = $this->insertSqlQuery($dataset)->runQuery();
if ( ( 0 !== $statement->lastInsertId ) &&
( null !== $primaryKeyDefinition )) {
$pkField = key($primaryKeyDefinition);
$dataset[$pkField] = $statement->lastInsertId;
}
$entity->entityFillFromDataset($dataset, true);
return true;
}
else {
if ( $primaryKeyDefinition === null ) {
@@ -160,46 +159,52 @@ class Repository
$this->where($pkFieldName, $dataset[$pkFieldName]);
$update = $this->updateSqlQuery($diff)->runQuery();
$entity->entityFillFromDataset($dataset);
return $update ? (bool) $update->rowCount() : false;
}
}
return false;
}
public function saveAll(EntityCollection $collection) : void
public function saveAll(EntityCollection $collection) : void
{
foreach($collection as $entity) {
$this->save($entity);
}
}
public function truncate(? string $table = null, ? string $alias = null, ? string $schema = null) : self
{
$schema = $schema ?: $this->entityResolver->schemaName();
$this->queryBuilder->truncate($this->escapeTable($table ?: $this->entityResolver->tableName()), $alias ?: $this->alias, $this->escapeDatabase($this->adapter->adapter()->database), $schema ? $this->escapeSchema($schema) : null);
$this->queryBuilder->truncate($this->escapeTable($table ?: $this->entityResolver->tableName()), $alias ?: $this->alias, $this->escapedDatabase(), $schema ? $this->escapeSchema($schema) : null);
$this->finalizeQuery();
$result = Ulmus::runSelectQuery($this->queryBuilder, $this->adapter);
return $this;
}
public function createTable()
{
return $this->createSqlQuery()->runQuery();
}
public function generateDatasetDiff(object $entity) : array
{
return array_diff_assoc( array_change_key_case($entity->toArray()), array_change_key_case($entity->entityGetDataset(false, true)) );
}
public function yield() : \Generator
{
$class = $this->entityClass;
$this->selectSqlQuery();
$this->finalizeQuery();
foreach(Ulmus::iterateQueryBuilder($this->queryBuilder, $this->adapter) as $entityData) {
@@ -210,74 +215,73 @@ class Repository
public function select(/*array|Stringable*/ $fields) : self
{
$this->queryBuilder->select($fields);
return $this;
}
public function insert(array $fieldlist, string $table, string $alias, ? string $schema) : self
{
$this->queryBuilder->insert($fieldlist, $this->escapeTable($table), $alias, $schema);
$this->queryBuilder->insert($fieldlist, $this->escapeTable($table), $alias, $this->escapedDatabase(), $schema);
return $this;
}
public function values(array $dataset) : self
{
$this->queryBuilder->values($dataset);
return $this;
}
public function update(string $table, string $alias, ? string $schema) : self
{
$this->queryBuilder->update($this->escapeTable($table), $alias, $schema);
$this->queryBuilder->update($this->escapeTable($table), $alias, $this->escapedDatabase(), $schema);
return $this;
}
public function set(array $dataset) : self
{
$this->queryBuilder->set($dataset);
return $this;
}
public function delete() : self
{
$this->queryBuilder->delete($this->alias);
return $this;
}
public function from(string $table, ? string $alias, ? string $schema) : self
{
$this->queryBuilder->from($this->escapeTable($table), $alias, $this->escapeDatabase($this->adapter->adapter()->database), $schema ? $this->escapeSchema($schema) : null);
$this->queryBuilder->from($this->escapeTable($table), $alias, $this->escapedDatabase(), $schema ? $this->escapeSchema($schema) : null);
return $this;
}
public function join(string $type, $table, $field, $value, ? string $alias = null, ? callable $callback = null) : self
{
$join = $this->queryBuilder->withJoin($type, $this->escapeTable($table), $field, $value, false, $alias);
if ( $callback ) {
$callback($join);
}
return $this;
}
public function outerJoin(string $type, $table, $field, $value, ? string $alias = null, ? callable $callback = null) : self
{
$join = $this->queryBuilder->withJoin($type, $this->escapeTable($table), $field, $value, true, $alias);
if ( $callback ) {
$callback($join);
}
return $this;
}
public function match() : self
{
@@ -297,11 +301,11 @@ class Repository
{
}
public function groupBy($field) : self
{
$this->queryBuilder->groupBy($field);
return $this;
}
@@ -310,14 +314,14 @@ class Repository
foreach($groups as $field ) {
$this->groupBy($field);
}
return $this;
}
public function orderBy($field, ? string $direction = null) : self
{
$this->queryBuilder->orderBy($field, $direction);
return $this;
}
@@ -334,26 +338,24 @@ class Repository
foreach($orderList as $field => $direction) {
$this->orderBy($field, $direction);
}
return $this;
}
public function limit(int $value) : self
{
$this->queryBuilder->limit($value);
return $this;
}
public function offset(int $value) : self
{
$this->queryBuilder->offset($value);
return $this;
}
/* @TODO */
public function commit() : self
{
@@ -371,88 +373,83 @@ class Repository
if ( null === $primaryKeyField = Ulmus::resolveEntity($this->entityClass)->getPrimaryKeyField() ) {
throw new Exception\EntityPrimaryKeyUnknown("Entity has no field containing attributes 'primary_key'");
}
$pkField = key($primaryKeyField);
return $this->where($primaryKeyField[$pkField]->name ?? $pkField, $value);
}
public function withJoin(/*stringable|array*/ $fields) : self
public function withJoin(/*string|array*/ $fields) : self
{
$resolvedEntity = Ulmus::resolveEntity($this->entityClass);
if ( null === $this->queryBuilder->getFragment(Query\Select::class) ) {
$this->select("{$this->alias}.*");
}
foreach((array) $fields as $item) {
if ( null !== $join = $resolvedEntity->searchFieldAnnotation($item, new Annotation\Property\Join) ) {
if ( null !== $join = $this->entityResolver->searchFieldAnnotation($item, new Annotation\Property\Join) ) {
$alias = $join->alias ?? $item;
$entity = $join->entity ?? $resolvedEntity->properties[$item]['type'];
$entity = $join->entity ?? $this->entityResolver->properties[$item]['type'];
foreach($entity::resolveEntity()->fieldList(Common\EntityResolver::KEY_COLUMN_NAME, true) as $key => $field) {
$this->select("$alias.$key as {$alias}\${$field['name']}");
}
$key = is_string($join->key) ? $this->entityClass::field($join->key) : $join->key;
$foreignKey = is_string($join->foreignKey) ? $entity::field($join->foreignKey, $alias) : $join->foreignKey;
$this->join($join->type, $entity::resolveEntity()->tableName(), $key, $foreignKey, $alias);
}
else {
throw new \Exception("You referenced field `$item` which do not exist or do not contain a valid @Join annotation.");
}
}
return $this;
}
public function filterServerRequest(SearchRequest\SearchRequestInterface $searchRequest) : self
public function filterServerRequest(SearchRequest\SearchRequestInterface $searchRequest) : self
{
$likes = $searchRequest->likes();
$wheres = $searchRequest->wheres();
$groups = $searchRequest->groups();
$searchRequest->filter( $this )
->wheres($wheres, Query\Where::OPERATOR_EQUAL, Query\Where::CONDITION_AND)
->likes($likes, Query\Where::CONDITION_OR)
->groups($groups);
$searchRequest->count = $searchRequest->skipCount ? 0 : (clone $this)->count();
return $searchRequest
->filter($this)
->wheres($wheres, Query\Where::OPERATOR_EQUAL, Query\Where::CONDITION_AND)
->likes($likes, Query\Where::CONDITION_OR)
->groups($groups)
$searchRequest->count = $searchRequest->filter( clone $this )
->wheres($searchRequest->wheres(), Query\Where::OPERATOR_EQUAL, Query\Where::CONDITION_AND)
->likes($searchRequest->likes(), Query\Where::CONDITION_OR)
->groups($searchRequest->groups())
->count();
return $searchRequest->filter($this)
->wheres($searchRequest->wheres(), Query\Where::OPERATOR_EQUAL, Query\Where::CONDITION_AND)
->likes($searchRequest->likes(), Query\Where::CONDITION_OR)
->orders($searchRequest->orders())
->groups($searchRequest->groups())
->offset($searchRequest->offset())
->limit($searchRequest->limit());
}
public function collectionFromQuery(? string $entityClass = null) : EntityCollection
{
$class = $entityClass ?: $this->entityClass;
$entityCollection = $class::entityCollection();
$entityCollection = $this->instanciateEntityCollection();
$this->selectSqlQuery();
$this->finalizeQuery();
foreach(Ulmus::iterateQueryBuilder($this->queryBuilder, $this->adapter) as $entityData) {
$entityCollection->append( ( new $class() )->entityFillFromDataset($entityData) );
$entityCollection->append( ( new $class() )->resetVirtualProperties()->entityFillFromDataset($entityData) );
}
$this->eventExecute(Event\Repository\CollectionFromQueryInterface::class, $entityCollection);
$this->eventExecute(Event\RepositoryCollectionFromQueryInterface::class, $entityCollection);
return $entityCollection;
}
public function arrayFromQuery() : array
{
$this->selectSqlQuery();
$this->finalizeQuery();
return Ulmus::datasetQueryBuilder($this->queryBuilder, $this->adapter);
@@ -461,7 +458,7 @@ class Repository
public function runQuery() : ? \PDOStatement
{
$this->finalizeQuery();
return Ulmus::runQuery($this->queryBuilder, $this->adapter);
}
@@ -482,18 +479,18 @@ class Repository
return $this;
}
protected function updateSqlQuery(array $dataset) : self
{
if ( null === $this->queryBuilder->getFragment(Query\Update::class) ) {
$this->update($this->entityResolver->tableName(), $this->alias, $this->entityResolver->schemaName());
}
$this->set($dataset);
return $this;
}
protected function selectSqlQuery() : self
{
if ( null === $this->queryBuilder->getFragment(Query\Select::class) ) {
@@ -519,7 +516,22 @@ class Repository
return $this;
}
public function createSqlQuery() : self
{
if ( null === $this->queryBuilder->getFragment(Query\Create::class) ) {
$this->queryBuilder->create($this->entityResolver->fieldList(), $this->escapeTable($this->entityResolver->tableName()), $this->entityResolver->schemaName());
}
if ( null === $this->queryBuilder->getFragment(Query\Engine::class) ) {
if ( $engine = $this->entityResolver->tableAnnotation()->engine ?? $this->entityResolver->databaseAdapter()->adapter()->defaultEngine() ) {
$this->queryBuilder->engine($engine);
}
}
return $this;
}
protected function fromRow($row) : self
{
@@ -529,30 +541,51 @@ class Repository
{
}
public function getSqlQuery(bool $flush = true) : string
{
$result = $this->queryBuilder->render();
$flush and $this->queryBuilder->reset();
return $result;
}
public function instanciateEntityCollection(...$arguments) : EntityCollection
{
return $this->entityClass::entityCollection(...$arguments);
}
public function instanciateEntity() : object
{
return new $this->entityClass();
}
public function escapeTable(string $identifier) : string
{
return $this->adapter->adapter()->escapeIdentifier($identifier, Adapter\AdapterInterface::IDENTIFIER_TABLE);
}
public function escapeDatabase(string $identifier) : string
{
return $this->adapter->adapter()->escapeIdentifier($identifier, Adapter\AdapterInterface::IDENTIFIER_DATABASE);
}
public function escapedDatabase() : ? string
{
$name = $this->entityResolver->tableAnnotation()->database ?? $this->adapter->adapter()->database ?? null;
return $name ? static::escapeDatabase($name) : null;
}
public function escapeSchema(string $identifier) : string
{
return $this->adapter->adapter()->escapeIdentifier($identifier, Adapter\AdapterInterface::IDENTIFIER_SCHEMA);
}
protected function matchEntity(object $entity) {
return get_class($entity) === $this->entityClass;
}
protected function finalizeQuery() : void {}
}
}