diff --git a/src/Query/Select.php b/src/Query/Select.php index aa2f3d8..4f7c01f 100644 --- a/src/Query/Select.php +++ b/src/Query/Select.php @@ -17,7 +17,7 @@ class Select extends Fragment { protected array $fields = []; const SQL_TOKEN = "SELECT"; - + public function set($fields) : self { $this->fields = is_array($fields) ? $fields : [ $fields ]; @@ -48,6 +48,7 @@ class Select extends Fragment { return $this->renderSegments([ ( $this->union ? 'UNION' : false ), static::SQL_TOKEN, + ( $this->distinct ? 'DISTINCT' : false ), ( $this->top ? sprintf('TOP (%s)', $this->top) : false ), implode(', ', $this->fields) ]); diff --git a/src/Repository.php b/src/Repository.php index 0e54639..05c0f31 100644 --- a/src/Repository.php +++ b/src/Repository.php @@ -63,9 +63,7 @@ class Repository public function count() : int { - if ( null !== $select = $this->queryBuilder->getFragment(Query\Select::class) ) { - $this->queryBuilder->removeFragment($select); - } + $this->removeQueryFragment($this->queryBuilder->getFragment(Query\Select::class)); if ( $this->queryBuilder->getFragment(Query\GroupBy::class) ) { $this->select( "DISTINCT COUNT(*) OVER ()" ); @@ -271,17 +269,22 @@ class Repository } } + public function removeQueryFragment(? Query\Fragment $fragment) : self + { + $fragment && $this->queryBuilder->removeFragment($fragment); + + return $this; + } + public function selectEntity(string $entity, string $alias, string $prependField = "") : self { - $prependField and ( $prependField .= "$" ); + $prependField and ($prependField .= "$"); - foreach($entity::resolveEntity()->fieldList(Common\EntityResolver::KEY_COLUMN_NAME, true) as $key => $field) { - if ( null === $entity::resolveEntity()->searchFieldAnnotation($field['name'], new RelationIgnore) ) { + foreach ($entity::resolveEntity()->fieldList(Common\EntityResolver::KEY_COLUMN_NAME, true) as $key => $field) { + if (null === $entity::resolveEntity()->searchFieldAnnotation($field['name'], new RelationIgnore)) { $this->select("$alias.$key as {$prependField}{$field['name']}"); } } - - return $this; } public function selectJsonEntity(string $entity, string $alias, bool $skipFrom = false) : self @@ -311,6 +314,14 @@ class Repository return $this; } + public function distinct(/*array|Stringable*/ $fields) : self + { + $this->queryBuilder->select($fields); + $this->queryBuilder->getFragment(Query\Select::class)->distinct = true; + + return $this; + } + public function insert(array $fieldlist, string $table, string $alias, ? string $schema) : self { $this->queryBuilder->insert($fieldlist, $this->escapeTable($table), $alias, $this->escapedDatabase(), $schema);