Skip to content

Commit

Permalink
Fix Field to SQL convert when materialized field is available
Browse files Browse the repository at this point in the history
  • Loading branch information
mvorisek committed Dec 19, 2022
1 parent d4d144b commit 0f08d79
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/Model/AggregateModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Atk4\Data\Model;
use Atk4\Data\Persistence;
use Atk4\Data\Persistence\Sql\Expression;
use Atk4\Data\Persistence\Sql\MaterializedField;
use Atk4\Data\Persistence\Sql\Query;

/**
Expand Down Expand Up @@ -90,6 +91,11 @@ public function setGroupBy(array $fields, array $aggregateExpressions = [])

$seed['expr'] = $this->table->expr($seed['expr'], $exprArgs);

// convert base model fields to aliases, they are always already materialized as the base model is SQL inner table
foreach ($seed['expr']->args['custom'] as $argK => $argV) {
$seed['expr']->args['custom'][$argK] = new MaterializedField($this->table, $argV);
}

$this->addExpression($name, $seed);
}

Expand Down Expand Up @@ -160,7 +166,7 @@ protected function initQueryGrouping(Query $query): void
if ($field instanceof Expression) {
$expression = $field;
} else {
$expression = $this->table->getField($field)->shortName /* TODO shortName should be used by DSQL automatically when in GROUP BY, HAVING, ... */;
$expression = new MaterializedField($this->table, $this->table->getField($field)); /* TODO shortName should be used by DSQL automatically when in GROUP BY, HAVING, ... */;
}

$query->group($expression);
Expand Down
3 changes: 3 additions & 0 deletions src/Model/EntityFieldPair.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Atk4\Data\Model;

use Atk4\Core\WarnDynamicPropertyTrait;
use Atk4\Data\Field;
use Atk4\Data\Model;

Expand All @@ -13,6 +14,8 @@
*/
class EntityFieldPair
{
use WarnDynamicPropertyTrait;

/** @var TModel */
private $entity;
/** @var string */
Expand Down
30 changes: 30 additions & 0 deletions src/Persistence/Sql/MaterializedField.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

namespace Atk4\Data\Persistence\Sql;

use Atk4\Core\WarnDynamicPropertyTrait;
use Atk4\Data\Field;
use Atk4\Data\Model;
use Atk4\Data\Persistence\Sql\Expression;
use Atk4\Data\Persistence\Sql\Expressionable;

class MaterializedField implements Expressionable
{
use WarnDynamicPropertyTrait;

protected Field $field;

public function __construct(Model $context, Field $field)
{
$field->getOwner()->assertIsModel($context);

$this->field = $field;
}

public function getDsqlExpression(Expression $expression): Expression
{
return $expression->expr('{}', [$this->field->shortName]);
}
}

0 comments on commit 0f08d79

Please sign in to comment.