diff --git a/src/Mapping.php b/src/Mapping.php index 9227b8e..4b5b6ea 100644 --- a/src/Mapping.php +++ b/src/Mapping.php @@ -96,6 +96,51 @@ public function count(string $column = '*') return parent::count($column); } + /** + * Fetches all values for a single column. + * + * @param string $column + * @return array + */ + public function findAllByColumn($column) + { + if ($this->definition->getDeletionTimestamp()) { + $this->isNull($this->prefixTableNameTo($this->definition->getDeletionTimestamp())); + } + + return parent::findAllByColumn($column); + } + + /** + * Fetches a single column value from the first matching row. + * + * @param string $column + * @return mixed + */ + public function findOneColumn($column) + { + if ($this->definition->getDeletionTimestamp()) { + $this->isNull($this->prefixTableNameTo($this->definition->getDeletionTimestamp())); + } + + return parent::findOneColumn($column); + } + + /** + * Sums a column across all matching rows. + * + * @param string $column + * @return float + */ + public function sum(string $column) + { + if ($this->definition->getDeletionTimestamp()) { + $this->isNull($this->prefixTableNameTo($this->definition->getDeletionTimestamp())); + } + + return parent::sum($column); + } + /** * Maps the provided array into the database. * diff --git a/tests/MappingTest.php b/tests/MappingTest.php index b7d31dc..07252e5 100644 --- a/tests/MappingTest.php +++ b/tests/MappingTest.php @@ -192,6 +192,42 @@ public function testRemove() ); } + public function testFindAllByColumnExcludesSoftDeletedRecords() + { + $this->getMapping()->eq('id', 1)->remove(); + + $names = $this->getMapping()->findAllByColumn('name'); + + $this->assertCount(1, $names); + $this->assertNotContains('John Doe', $names); + $this->assertContains('Jane Doe', $names); + } + + public function testFindOneColumnExcludesSoftDeletedRecords() + { + $this->getMapping()->eq('id', 1)->remove(); + + $name = $this->getMapping()->eq('id', 1)->findOneColumn('name'); + + $this->assertFalse($name); + } + + public function testSumExcludesSoftDeletedRecords() + { + $this->db->execute('CREATE TABLE scores (id INTEGER PRIMARY KEY, customer_id INTEGER, points INTEGER, date_deleted TEXT)'); + $this->db->execute('INSERT INTO scores (id, customer_id, points) VALUES (1, 1, 100), (2, 2, 200)'); + + $score = (new Definition('scores')) + ->withColumns('id', 'customer_id', 'points') + ->withDeletionTimestamp('date_deleted'); + + $this->assertSame(300.0, (new Mapping($this->db, $score))->sum('points')); + + (new Mapping($this->db, $score))->eq('id', 1)->remove(); + + $this->assertSame(200.0, (new Mapping($this->db, $score))->sum('points')); + } + public function testReadOnlyInsert() { $customer = [