diff --git a/src/QueryBuilder.php b/src/QueryBuilder.php index b1632f2..349ac6d 100644 --- a/src/QueryBuilder.php +++ b/src/QueryBuilder.php @@ -14,7 +14,7 @@ class QueryBuilder protected ?int $offset; protected string $raw_query; - public function __construct($table, $pk) + public function __construct($table, $pk = "id") { $this->table = $table; $this->pk = $pk; @@ -83,6 +83,12 @@ class QueryBuilder return $this; } + public function whereRaw(string $raw) + { + $this->wheres[] = $raw; + return $this; + } + public function find($id): mixed { $this->reset(); @@ -153,12 +159,24 @@ class QueryBuilder $ret->setQuery(""); $ret->setData([]); + if (count($this->columns) == 0) { + $this->columns("*"); + } + $columns = implode(",", $this->columns); $where = ""; foreach ($this->wheres as $expression) { - $sw = $expression->raw(); - $ret->addData($expression->getValue()); - if ($where != "") { + $sw = ""; + if ($expression instanceof Expression) { + $sw = $expression->raw(); + $ret->addData($expression->getValue()); + } + if ($expression instanceof string) { + if (trim($expression) !== "") { + $sw = "(" . $expression . ")"; + } + } + if ($where != "" && $sw != "") { $where .= " AND "; } $where .= $sw; diff --git a/tests/DbTest.php b/tests/DbTest.php index 90762eb..fa26128 100644 --- a/tests/DbTest.php +++ b/tests/DbTest.php @@ -23,7 +23,7 @@ test("insert row",function () { }); test("querybuilder", function() { - $qb = new QueryBuilder("test","id"); + $qb = new QueryBuilder("test"); $row = $qb->find(1); expect($row)->toBeObject(); @@ -41,6 +41,16 @@ test("querybuilder", function() { expect($rows)->toBeArray(); expect(count($rows))->toBe(0); + + $qb->reset(); + $rows = $qb->whereRaw("id = 1")->columns("*")->get(); + expect($rows)->toBeArray(); + expect(count($rows))->toBe(1); + + $qb->reset(); + $rows = $qb->whereRaw("id = 1")->get(); + expect($rows)->toBeArray(); + expect(count($rows))->toBe(1); }); test("update row", function() {