From dd6dc990d17faa661f0a2148d04c8426df5dcaa4 Mon Sep 17 00:00:00 2001 From: brendt Date: Sat, 14 Dec 2024 14:21:52 +0100 Subject: [PATCH] wip --- src/Tempest/Database/src/Query.php | 29 +++++++++++++++++------- tests/Integration/Database/QueryTest.php | 28 +++++++++++++++++++++++ 2 files changed, 49 insertions(+), 8 deletions(-) create mode 100644 tests/Integration/Database/QueryTest.php diff --git a/src/Tempest/Database/src/Query.php b/src/Tempest/Database/src/Query.php index 3fa63ab15..f39258182 100644 --- a/src/Tempest/Database/src/Query.php +++ b/src/Tempest/Database/src/Query.php @@ -14,25 +14,29 @@ public function __construct( ) { } - public function execute(): Id + public function execute(mixed ...$bindings): Id { + $this->bindings = [...$this->bindings, ...$bindings]; + $database = $this->getDatabase(); - $database->execute($this); + $query = $this->withBindings($bindings); + + $database->execute($query); - return isset($this->bindings['id']) - ? new Id($this->bindings['id']) + return isset($query->bindings['id']) + ? new Id($query->bindings['id']) : $database->getLastInsertId(); } - public function fetch(): array + public function fetch(mixed ...$bindings): array { - return $this->getDatabase()->fetch($this); + return $this->getDatabase()->fetch($this->withBindings($bindings)); } - public function fetchFirst(): ?array + public function fetchFirst(mixed ...$bindings): ?array { - return $this->getDatabase()->fetchFirst($this); + return $this->getDatabase()->fetchFirst($this->withBindings($bindings)); } public function getSql(): string @@ -47,6 +51,15 @@ public function append(string $append): self return $this; } + public function withBindings(array $bindings): self + { + $clone = clone $this; + + $clone->bindings = [...$clone->bindings, ...$bindings]; + + return $clone; + } + private function getDatabase(): Database { return get(Database::class); diff --git a/tests/Integration/Database/QueryTest.php b/tests/Integration/Database/QueryTest.php new file mode 100644 index 000000000..6c89577f4 --- /dev/null +++ b/tests/Integration/Database/QueryTest.php @@ -0,0 +1,28 @@ +migrate(CreateMigrationsTable::class, CreateAuthorTable::class); + + new Author(name: 'A')->save(); + new Author(name: 'B')->save(); + + $this->assertCount(1, new Query('SELECT * FROM authors WHERE name = ?')->fetch('A')); + $this->assertCount(1, new Query('SELECT * FROM authors WHERE name = :name')->fetch(name: 'A')); + $this->assertSame('A', new Query('SELECT * FROM authors WHERE name = ?')->fetchFirst('A')['name']); + $this->assertSame('A', new Query('SELECT * FROM authors WHERE name = :name')->fetchFirst(name: 'A')['name']); + + new Query('DELETE FROM authors WHERE name = :name')->execute(name: 'A'); + $this->assertCount(0, new Query('SELECT * FROM authors WHERE name = ?')->fetch('A')); + } +} \ No newline at end of file