Skip to content

Commit

Permalink
make query builder marcoable
Browse files Browse the repository at this point in the history
  • Loading branch information
norbybaru committed Oct 19, 2023
1 parent 6d3ec31 commit 97cead8
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/Builder/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
use Closure;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\Macroable;
use NorbyBaru\AwsTimestream\Concerns\BuildersConcern;
use NorbyBaru\AwsTimestream\Contract\QueryBuilderContract;

abstract class Builder implements QueryBuilderContract
{
use BuildersConcern;
use BuildersConcern;
Use Macroable;

protected string $database = '';
protected string $table = '';
Expand Down
31 changes: 31 additions & 0 deletions tests/Unit/QueryBuilderUnitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,29 @@

namespace NorbyBaru\AwsTimestream\Tests\Unit;

use Illuminate\Support\Carbon;
use NorbyBaru\AwsTimestream\Builder\Builder;
use NorbyBaru\AwsTimestream\Builder\TimestreamQueryBuilder;
use NorbyBaru\AwsTimestream\Tests\TestCase;
use NorbyBaru\AwsTimestream\TimestreamBuilder;

class QueryBuilderUnitTest extends TestCase
{
protected function setUp(): void
{
TimestreamQueryBuilder::macro(
"whereDateBetween",
fn ($from, $to) => $this->whereBetween('date', [$from, $to])
);

TimestreamQueryBuilder::macro(
"whereHoursAgo",
fn (string $column, int $hours, string $operator = '=') => $this->whereAgo($column, "{$hours}h", $operator)
);

parent::setUp();
}

public function test_it_can_return_query_builder()
{
$this->assertInstanceOf(Builder::class, TimestreamBuilder::query());
Expand Down Expand Up @@ -74,6 +90,21 @@ public function test_it_can_build_where_in_query()
$this->validateSql("WHERE state IN ('open','draft','published')", $query);
}

public function test_it_should_build_query_from_marco()
{
$dateFrom = Carbon::now()->yesterday()->toDateString();
$dateTo = Carbon::now()->toDateString();
$query = TimestreamBuilder::query()
->whereIn('state', ['open', 'draft', 'published'])
->whereDateBetween($dateFrom, $dateTo)
->whereHoursAgo('time', 72);

$this->validateSql(
"WHERE state IN ('open','draft','published') AND date BETWEEN {$dateFrom} and {$dateTo} AND time = ago(72h)",
$query
);
}

private function validateSql(string $expected, TimestreamQueryBuilder $builder)
{
$this->assertEquals($expected, trim($builder->getSql()));
Expand Down

0 comments on commit 97cead8

Please sign in to comment.