Skip to content

Commit

Permalink
Better queryBuilder, quoteIdentifier, updated docs. For 1.0.2 release
Browse files Browse the repository at this point in the history
  • Loading branch information
dmarkic committed Apr 23, 2024
1 parent eb4f080 commit f57d0e3
Show file tree
Hide file tree
Showing 27 changed files with 796 additions and 611 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# Changelog

## v1.0.2 (2024-04-23)

- QueryBuilder::quoteIdentifier()
- QueryBuilder fromArray is not longer static
- QueryBuilder\Query - removed static fromArray methods (except in Conditions)
- Updated docs

## v1.0.1 (2024-04-21)

- QueryBuilder::join() added
Expand Down
2 changes: 2 additions & 0 deletions docs/api/conditions.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ There are many predefined operators (methods) available:
- gte(): Greater than or equal `>=`
- isNull(): `IS NULL`
- isNotNull(): `IS NOT NULL`
- like(): `LIKE`
- notLike(): `NOT LIKE`

!!! note
More should be added (LIKE, NOT LIKE, IN, NOT IN, ...)
Expand Down
76 changes: 55 additions & 21 deletions docs/api/querybuilder.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,25 @@

Query builder is a heart of every DBAL. It strives to support any SQL query.

## SELECT query
## Queries

### SELECT query

Select query is started with issuing `select()` method.

```php
<?php
$queryBuilder->select('column as A', 'column AS B');
$queryBuilder->select('columnA', 'columnB');
```

SELECT queries are built from:

- [SELECT](#select-query) expression
- [FROM](#from-clause) expression
- [SELECT](#select-query) clause
- [FROM](#from-clause) clause
- [JOIN](#join-clause) clause
- [WHERE](#where) [conditions](conditions.md)
- [ORDER BY](#order-by) expression
- [LIMIT](#limit) expression
- [ORDER BY](#order-by) clause
- [LIMIT](#limit) clause

**Example**

Expand All @@ -26,6 +29,7 @@ SELECT queries are built from:
$queryBuilder
->select('column')
->from('table')
->join('another', 'table.another_id = another.id', 'another')
->where($queryBuilder->condition('column', '=', '?'))
->orderBy('column', 'ASC')
->limit(1)
Expand All @@ -35,7 +39,7 @@ $queryBuilder
!!! note
See [Conditions](conditions.md) on how to construct `WHERE` conditions.

## UPDATE query
### UPDATE query

Update query is started by issuing `update()` method.

Expand All @@ -47,10 +51,11 @@ $queryBuilder->update('table', 'alias');
UPDATE queries are built from:

- [FROM](#from-clause) table to update
- [SET](#set) expression
- [WHERE](#where) [conditions](conditions.md)
- [ORDER BY](#order-by) expression
- [LIMIT](#limit) expression
- [JOIN](#join-clause) clause
- [SET](#valuesset-clause) clause
- [WHERE](#where-clause) [conditions](conditions.md)
- [ORDER BY](#order-by) clause
- [LIMIT](#limit) clause

**Example**

Expand All @@ -62,13 +67,13 @@ $queryBuilder
'columnA' => 'valueA',
'columnB' => 'valueB'
])
->where($queryBuilder->condition('column', '=', '?'))
->orderBy('column', 'ASC')
->where($queryBuilder->condition('columnC', '=', '?'))
->orderBy('columnD', 'ASC')
->limit(1)
->setParameters('condition');
```

## INSERT query
### INSERT query

Insert query is started by issuing `insert()` method.

Expand All @@ -80,8 +85,8 @@ $queryBuilder->insert('table', 'alias');
INSERT queries are built from:

- [INTO](#into-clause) table to insert into
- [COLUMNS](#values) columns definition
- [VALUES](#values) values
- [COLUMNS](#valuesset-clause) clause
- [VALUES](#valuesset-clause) clause

**Example**

Expand All @@ -95,7 +100,7 @@ $queryBuilder
]);
```

## DELETE query
### DELETE query

Delete query is started by issuing `delete()` method.

Expand All @@ -107,7 +112,7 @@ $queryBuilder->delete('table', 'alias');
DELETE queries are built from:

- [FROM](#from-clause) table to delete from
- [WHERE](#where) [conditions](conditions.md)
- [WHERE](#where-clause) [conditions](conditions.md)
- [ORDER BY](#order-by) expressions
- [LIMIT](#limit) expressions

Expand All @@ -123,7 +128,9 @@ $queryBuilder
->setParameters('condition');
```

## FROM clause
## Clauses

### FROM clause

```php
<?php
Expand All @@ -132,7 +139,7 @@ public function from(string|QueryBuilderInterface $from, string $as = null): sta

`FROM` clause defines a table or `subquery` (another `QueryBuilder` for SELECT statements).

## INTO clause
### INTO clause

```php
<?php
Expand All @@ -141,7 +148,23 @@ public function into(string $from, string $as = null): static;

`INTO` clause defines a table for [INSERT](#insert-query) queries. It's an alias for [FROM](#from-clause), but it supports only table names and alias.

## VALUES
### JOIN clause

`JOIN` clause is used to combine rows from tables based on related columns.

```php
<?php
// inner join
public function join(string $table, string $on, string $alias = null, JoinType $type = JoinType::INNER): static;
// left join
public function leftJoin(string $table, string $on, string $alias = null): static;
// right join
public function rightJoin(string $table, string $on, string $alias = null): static;
// full join
public function fullJoin(string $table, string $on, string $alias = null): static;
```

### VALUES/SET clause

Values are an associative array of column, value for [INSERT](#insert-query) or [UPDATE](#update-query) queries.

Expand All @@ -150,4 +173,15 @@ Values are an associative array of column, value for [INSERT](#insert-query) or
public function values(array $values): static;
public function value(string $column, mixed $value): static; // add single value
public function set(array $values): static; // alias for values
```

### WHERE clause

`WHERE` clause is used to filter records. Where clauses are built using [conditions](conditions.md).

```php
<?php
public function where(Condition|ConditionGroup|callable $condition): static; // single where
public function andWhere(Condition|ConditionGroup|callable $condition): static; // add AND where
public function orWhere(Condition|ConditionGroup|callable $condition): static; // add OR where
```
35 changes: 35 additions & 0 deletions docs/api/result.md
Original file line number Diff line number Diff line change
@@ -1 +1,36 @@
# Result

Every query executed will return `Blrf\Dbal\Result` object.

```php
<?php
class Result {
public readonly array $rows = [];
public readonly ?int $insertId = null;
public readonly int $affectedRows = 0;
public readonly int $warningCount = 0;
}
```

## $rows

`SELECT` queries will return result with `$rows` array.

### Iterator

Result implements [Iterator](https://www.php.net/iterator) so you can also use Result object as an array:

```php
<?php
foreach ($result as $row) {
echo " - my awesome row: " . print_r($row, true) . "\n";
}
```

## $insertId

`INSERT` queries with sequence/autoincrement/... table keys will return last insert id.

## $affectedRows

`UPDATE` or `DELETE` queries will report affected rows.
6 changes: 5 additions & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,8 @@ Currently these drivers are directly supported:

- MySql: using [ReactPHP Mysql](https://github.com/friends-of-reactphp/mysql/)

See [Config](api/config.md) on how to use the drivers.
See [Config](api/config.md) on how to use the drivers.

## Query builder

See [Query builder](api/querybuilder.md) on how to construct and run queries.
4 changes: 4 additions & 0 deletions docs/quickstart/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ $config->create()->then(
)->then(
function (Blrf\Dbal\Result $result) {
print_r($result->rows);
// or you can iterate result rows directly
foreach ($result as $row) {
print_r($row);
}
}
);
```
Expand Down
4 changes: 4 additions & 0 deletions examples/select.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,9 @@ function (Blrf\Dbal\Connection $db) {
)->then(
function (Blrf\Dbal\Result $result) {
print_r($result->rows);
// or
foreach ($result as $row) {
print_r($row);
}
}
);
23 changes: 23 additions & 0 deletions examples/update.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

require __DIR__ . '/../vendor/autoload.php';
$config = new Blrf\Dbal\Config('mysql://user:pass@localhost/bookstore');

$config->create()->then(
function (Blrf\Dbal\Connection $db) {
// start query builder
$qb = $db->query()
->update('book')
->values(['title' => 'Moby Dick: ' . time()]); // automatically added to parameters
$qb->where($qb->condition('book_id'))
->addParameter([11089]) // we add parameter
->limit(1);
echo "sql: " . $qb->getSql() . "\n";
// sql: UPDATE book SET title = ? WHERE book_id = ? LIMIT 1
return $qb->execute();
}
)->then(
function (Blrf\Dbal\Result $result) {
print_r($result);
}
);
38 changes: 38 additions & 0 deletions examples/updateJoin.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

require __DIR__ . '/../vendor/autoload.php';
$config = new Blrf\Dbal\Config('mysql://user:pass@localhost/bookstore');

$config->create()->then(
function (Blrf\Dbal\Connection $db) {
// start query builder
$qb = $db->query()
->update('address')
->join(
'customer_address',
'customer_address.address_id = address.address_id'
)
->join(
'address_status',
'address_status.status_id = customer_address.status_id'
)
->values(['address.street_name' => 'Inactive: ' . time()]) // parameter is added
->where(
fn($cb) => $cb->and(
$cb->eq('address_status.address_status'),
$cb->eq('customer_address.customer_id')
)
)
->addParameter('Inactive', 3);
echo "sql: " . $qb->getSql() . "\n";
// sql: UPDATE address INNER JOIN customer_address ON customer_address.address_id = address.address_id
// INNER JOIN address_status ON address_status.status_id = customer_address.status_id
// SET address.street_name = ?
// WHERE (address_status.address_status = ? AND customer_address.customer_id = ?)
return $qb->execute();
}
)->then(
function (Blrf\Dbal\Result $result) {
print_r($result);
}
);
23 changes: 18 additions & 5 deletions src/Query/Condition.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,18 @@

/**
* Single condition for WHERE or HAVING
*
* @phpstan-type ConditionToArray array{
* expression: string,
* operator: string,
* value: mixed
* }
*
* @phpstan-type ConditionFromArray array{
* expression: string,
* operator: string,
* value: mixed
* }
*/
class Condition implements Stringable
{
Expand All @@ -17,10 +29,6 @@ class Condition implements Stringable
'is null', 'is not null'
];

/**
* Value will be null if operator is in noValueOperators
*/
public readonly ?string $value;
/**
* Create condition from array
*
Expand Down Expand Up @@ -71,6 +79,11 @@ public static function fromArray(array $data): static|ConditionGroup
return new static($expression, $operator, $value);
}

/**
* Value will be null if operator is in noValueOperators
*/
public readonly ?string $value;

final public function __construct(
public readonly string $expression,
public readonly string $operator = '=',
Expand All @@ -87,7 +100,7 @@ public function __toString(): string
return $this->expression . ' ' . $this->operator . ($this->value === null ? '' : ' ' . $this->value);
}

/** @return array{expression:string, operator:string, value:string|null} */
/** @return ConditionToArray */
public function toArray(): array
{
return [
Expand Down
Loading

0 comments on commit f57d0e3

Please sign in to comment.