Upgrade to 3.8.3

This commit is contained in:
Bastian Allgeier
2022-12-06 15:37:13 +01:00
parent f9e812cb0c
commit 8381ccb96c
69 changed files with 752 additions and 966 deletions

View File

@@ -3,10 +3,12 @@
namespace Kirby\Database;
use Closure;
use Exception;
use Kirby\Exception\InvalidArgumentException;
use Kirby\Toolkit\A;
use Kirby\Toolkit\Str;
use PDO;
use PDOStatement;
use Throwable;
/**
@@ -22,131 +24,90 @@ class Database
{
/**
* The number of affected rows for the last query
*
* @var int|null
*/
protected $affected;
protected int|null $affected = null;
/**
* Whitelist for column names
*
* @var array
*/
protected $columnWhitelist = [];
protected array $columnWhitelist = [];
/**
* The established connection
*
* @var \PDO|null
*/
protected $connection;
protected PDO|null $connection = null;
/**
* A global array of started connections
*
* @var array
*/
public static $connections = [];
public static array $connections = [];
/**
* Database name
*
* @var string
*/
protected $database;
protected string $database;
/**
* @var string
*/
protected $dsn;
protected string $dsn;
/**
* Set to true to throw exceptions on failed queries
*
* @var bool
*/
protected $fail = false;
protected bool $fail = false;
/**
* The connection id
*
* @var string
*/
protected $id;
protected string $id;
/**
* The last error
*
* @var \Exception|null
*/
protected $lastError;
protected Exception|null $lastError = null;
/**
* The last insert id
*
* @var int|null
*/
protected $lastId;
protected int|null $lastId = null;
/**
* The last query
*
* @var string
*/
protected $lastQuery;
protected string $lastQuery;
/**
* The last result set
*
* @var mixed
*/
protected $lastResult;
/**
* Optional prefix for table names
*
* @var string
*/
protected $prefix;
protected string|null $prefix = null;
/**
* The PDO query statement
*
* @var \PDOStatement|null
*/
protected $statement;
protected PDOStatement|null $statement = null;
/**
* List of existing tables in the database
*
* @var array|null
*/
protected $tables;
protected array|null $tables = null;
/**
* An array with all queries which are being made
*
* @var array
*/
protected $trace = [];
protected array $trace = [];
/**
* The database type (mysql, sqlite)
*
* @var string
*/
protected $type;
protected string $type;
/**
* @var array
*/
public static $types = [];
public static array $types = [];
/**
* Creates a new Database instance
*
* @param array $params
* @return void
*/
public function __construct(array $params = [])
{
@@ -155,19 +116,18 @@ class Database
/**
* Returns one of the started instances
*
* @param string|null $id
* @return static|null
*/
public static function instance(string $id = null)
public static function instance(string|null $id = null): static|null
{
return $id === null ? A::last(static::$connections) : static::$connections[$id] ?? null;
if ($id === null) {
return A::last(static::$connections);
}
return static::$connections[$id] ?? null;
}
/**
* Returns all started instances
*
* @return array
*/
public static function instances(): array
{
@@ -178,10 +138,9 @@ class Database
* Connects to a database
*
* @param array|null $params This can either be a config key or an array of parameters for the connection
* @return \PDO|null
* @throws \Kirby\Exception\InvalidArgumentException
*/
public function connect(array $params = null)
public function connect(array|null $params = null): PDO|null
{
$defaults = [
'database' => null,
@@ -227,10 +186,8 @@ class Database
/**
* Returns the currently active connection
*
* @return \PDO|null
*/
public function connection(): ?PDO
public function connection(): PDO|null
{
return $this->connection;
}
@@ -238,10 +195,9 @@ class Database
/**
* Sets the exception mode
*
* @param bool $fail
* @return \Kirby\Database\Database
* @return $this
*/
public function fail(bool $fail = true)
public function fail(bool $fail = true): static
{
$this->fail = $fail;
return $this;
@@ -249,8 +205,6 @@ class Database
/**
* Returns the used database type
*
* @return string
*/
public function type(): string
{
@@ -259,8 +213,6 @@ class Database
/**
* Returns the used table name prefix
*
* @return string|null
*/
public function prefix(): string|null
{
@@ -270,9 +222,6 @@ class Database
/**
* Escapes a value to be used for a safe query
* NOTE: Prepared statements using bound parameters are more secure and solid
*
* @param string $value
* @return string
*/
public function escape(string $value): string
{
@@ -280,12 +229,10 @@ class Database
}
/**
* Adds a value to the db trace and also returns the entire trace if nothing is specified
*
* @param array|null $data
* @return array
* Adds a value to the db trace and also
* returns the entire trace if nothing is specified
*/
public function trace(array $data = null): array
public function trace(array|null $data = null): array
{
// return the full trace
if ($data === null) {
@@ -300,8 +247,6 @@ class Database
/**
* Returns the number of affected rows for the last query
*
* @return int|null
*/
public function affected(): int|null
{
@@ -310,8 +255,6 @@ class Database
/**
* Returns the last id if available
*
* @return int|null
*/
public function lastId(): int|null
{
@@ -320,8 +263,6 @@ class Database
/**
* Returns the last query
*
* @return string|null
*/
public function lastQuery(): string|null
{
@@ -330,8 +271,6 @@ class Database
/**
* Returns the last set of results
*
* @return mixed
*/
public function lastResult()
{
@@ -340,18 +279,14 @@ class Database
/**
* Returns the last db error
*
* @return \Throwable
*/
public function lastError()
public function lastError(): Throwable
{
return $this->lastError;
}
/**
* Returns the name of the database
*
* @return string|null
*/
public function name(): string|null
{
@@ -361,10 +296,6 @@ class Database
/**
* Private method to execute database queries.
* This is used by the query() and execute() methods
*
* @param string $query
* @param array $bindings
* @return bool
*/
protected function hit(string $query, array $bindings = []): bool
{
@@ -405,11 +336,6 @@ class Database
/**
* Executes a sql query, which is expected to return a set of results
*
* @param string $query
* @param array $bindings
* @param array $params
* @return mixed
*/
public function query(string $query, array $bindings = [], array $params = [])
{
@@ -466,11 +392,8 @@ class Database
}
/**
* Executes a sql query, which is expected to not return a set of results
*
* @param string $query
* @param array $bindings
* @return bool
* Executes a sql query, which is expected
* to not return a set of results
*/
public function execute(string $query, array $bindings = []): bool
{
@@ -480,10 +403,8 @@ class Database
/**
* Returns the correct Sql generator instance
* for the type of database
*
* @return \Kirby\Database\Sql
*/
public function sql()
public function sql(): Sql
{
$className = static::$types[$this->type]['sql'] ?? 'Sql';
return new $className($this);
@@ -493,20 +414,14 @@ class Database
* Sets the current table, which should be queried. Returns a
* Query object, which can be used to build a full query
* for that table
*
* @param string $table
* @return \Kirby\Database\Query
*/
public function table(string $table)
public function table(string $table): Query
{
return new Query($this, $this->prefix() . $table);
}
/**
* Checks if a table exists in the current database
*
* @param string $table
* @return bool
*/
public function validateTable(string $table): bool
{
@@ -527,10 +442,6 @@ class Database
/**
* Checks if a column exists in a specified table
*
* @param string $table
* @param string $column
* @return bool
*/
public function validateColumn(string $table, string $column): bool
{
@@ -556,12 +467,8 @@ class Database
/**
* Creates a new table
*
* @param string $table
* @param array $columns
* @return bool
*/
public function createTable($table, $columns = []): bool
public function createTable(string $table, array $columns = []): bool
{
$sql = $this->sql()->createTable($table, $columns);
$queries = Str::split($sql['query'], ';');
@@ -584,9 +491,6 @@ class Database
/**
* Drops a table
*
* @param string $table
* @return bool
*/
public function dropTable(string $table): bool
{
@@ -608,12 +512,8 @@ class Database
* Magic way to start queries for tables by
* using a method named like the table.
* I.e. $db->users()->all()
*
* @param mixed $method
* @param mixed $arguments
* @return \Kirby\Database\Query
*/
public function __call($method, $arguments = null)
public function __call(string $method, mixed $arguments = null): Query
{
return $this->table($method);
}
@@ -624,7 +524,7 @@ class Database
*/
Database::$types['mysql'] = [
'sql' => 'Kirby\Database\Sql\Mysql',
'dsn' => function (array $params) {
'dsn' => function (array $params): string {
if (isset($params['host']) === false && isset($params['socket']) === false) {
throw new InvalidArgumentException('The mysql connection requires either a "host" or a "socket" parameter');
}
@@ -662,7 +562,7 @@ Database::$types['mysql'] = [
*/
Database::$types['sqlite'] = [
'sql' => 'Kirby\Database\Sql\Sqlite',
'dsn' => function (array $params) {
'dsn' => function (array $params): string {
if (isset($params['database']) === false) {
throw new InvalidArgumentException('The sqlite connection requires a "database" parameter');
}

View File

@@ -18,26 +18,21 @@ class Db
{
/**
* Query shortcuts
*
* @var array
*/
public static $queries = [];
public static array $queries = [];
/**
* The singleton Database object
*
* @var \Kirby\Database\Database
*/
public static $connection = null;
public static Database|null $connection = null;
/**
* (Re)connect the database
*
* @param array|null $params Pass `[]` to use the default params from the config,
* don't pass any argument to get the current connection
* @return \Kirby\Database\Database
*/
public static function connect(array|null $params = null)
public static function connect(array|null $params = null): Database
{
if ($params === null && static::$connection !== null) {
return static::$connection;
@@ -60,10 +55,8 @@ class Db
/**
* Returns the current database connection
*
* @return \Kirby\Database\Database|null
*/
public static function connection()
public static function connection(): Database|null
{
return static::$connection;
}
@@ -72,11 +65,8 @@ class Db
* Sets the current table which should be queried. Returns a
* Query object, which can be used to build a full query for
* that table.
*
* @param string $table
* @return \Kirby\Database\Query
*/
public static function table(string $table)
public static function table(string $table): Query
{
$db = static::connect();
return $db->table($table);
@@ -84,11 +74,6 @@ class Db
/**
* Executes a raw SQL query which expects a set of results
*
* @param string $query
* @param array $bindings
* @param array $params
* @return mixed
*/
public static function query(string $query, array $bindings = [], array $params = [])
{
@@ -97,11 +82,8 @@ class Db
}
/**
* Executes a raw SQL query which expects no set of results (i.e. update, insert, delete)
*
* @param string $query
* @param array $bindings
* @return bool
* Executes a raw SQL query which expects
* no set of results (i.e. update, insert, delete)
*/
public static function execute(string $query, array $bindings = []): bool
{
@@ -114,9 +96,6 @@ class Db
* redirected to either a predefined query or
* the respective method of the Database object
*
* @param string $method
* @param mixed $arguments
* @return mixed
* @throws \Kirby\Exception\InvalidArgumentException
*/
public static function __callStatic(string $method, $arguments)
@@ -125,7 +104,10 @@ class Db
return (static::$queries[$method])(...$arguments);
}
if (static::$connection !== null && method_exists(static::$connection, $method) === true) {
if (
static::$connection !== null &&
method_exists(static::$connection, $method) === true
) {
return call_user_func_array([static::$connection, $method], $arguments);
}
@@ -141,13 +123,22 @@ class Db
* @param string $table The name of the table which should be queried
* @param mixed $columns Either a string with columns or an array of column names
* @param mixed $where The WHERE clause; can be a string or an array
* @param string $order
* @param int $offset
* @param int $limit
* @return mixed
*/
Db::$queries['select'] = function (string $table, $columns = '*', $where = null, string $order = null, int $offset = 0, int $limit = null) {
return Db::table($table)->select($columns)->where($where)->order($order)->offset($offset)->limit($limit)->all();
Db::$queries['select'] = function (
string $table,
$columns = '*',
$where = null,
string|null $order = null,
int $offset = 0,
int|null $limit = null
) {
return Db::table($table)
->select($columns)
->where($where)
->order($order)
->offset($offset)
->limit($limit)
->all();
};
/**
@@ -156,13 +147,18 @@ Db::$queries['select'] = function (string $table, $columns = '*', $where = null,
* @param string $table The name of the table which should be queried
* @param mixed $columns Either a string with columns or an array of column names
* @param mixed $where The WHERE clause; can be a string or an array
* @param string $order
* @param int $offset
* @param int $limit
* @return mixed
*/
Db::$queries['first'] = Db::$queries['row'] = Db::$queries['one'] = function (string $table, $columns = '*', $where = null, string $order = null) {
return Db::table($table)->select($columns)->where($where)->order($order)->first();
Db::$queries['first'] = Db::$queries['row'] = Db::$queries['one'] = function (
string $table,
$columns = '*',
$where = null,
string|null $order = null
) {
return Db::table($table)
->select($columns)
->where($where)
->order($order)
->first();
};
/**
@@ -171,13 +167,21 @@ Db::$queries['first'] = Db::$queries['row'] = Db::$queries['one'] = function (st
* @param string $table The name of the table which should be queried
* @param string $column The name of the column to select from
* @param mixed $where The WHERE clause; can be a string or an array
* @param string $order
* @param int $offset
* @param int $limit
* @return mixed
*/
Db::$queries['column'] = function (string $table, string $column, $where = null, string $order = null, int $offset = 0, int $limit = null) {
return Db::table($table)->where($where)->order($order)->offset($offset)->limit($limit)->column($column);
Db::$queries['column'] = function (
string $table,
string $column,
$where = null,
string|null $order = null,
int $offset = 0,
int|null $limit = null
) {
return Db::table($table)
->where($where)
->order($order)
->offset($offset)
->limit($limit)
->column($column);
};
/**
@@ -197,9 +201,12 @@ Db::$queries['insert'] = function (string $table, array $values) {
* @param string $table The name of the table which should be queried
* @param array $values An array of values which should be inserted
* @param mixed $where An optional WHERE clause
* @return bool
*/
Db::$queries['update'] = function (string $table, array $values, $where = null): bool {
Db::$queries['update'] = function (
string $table,
array $values,
$where = null
): bool {
return Db::table($table)->where($where)->update($values);
};
@@ -208,7 +215,6 @@ Db::$queries['update'] = function (string $table, array $values, $where = null):
*
* @param string $table The name of the table which should be queried
* @param mixed $where An optional WHERE clause
* @return bool
*/
Db::$queries['delete'] = function (string $table, $where = null): bool {
return Db::table($table)->where($where)->delete();
@@ -231,9 +237,12 @@ Db::$queries['count'] = function (string $table, $where = null): int {
* @param string $table The name of the table which should be queried
* @param string $column The name of the column of which the minimum should be calculated
* @param mixed $where An optional WHERE clause
* @return float
*/
Db::$queries['min'] = function (string $table, string $column, $where = null): float {
Db::$queries['min'] = function (
string $table,
string $column,
$where = null
): float {
return Db::table($table)->where($where)->min($column);
};
@@ -243,9 +252,12 @@ Db::$queries['min'] = function (string $table, string $column, $where = null): f
* @param string $table The name of the table which should be queried
* @param string $column The name of the column of which the maximum should be calculated
* @param mixed $where An optional WHERE clause
* @return float
*/
Db::$queries['max'] = function (string $table, string $column, $where = null): float {
Db::$queries['max'] = function (
string $table,
string $column,
$where = null
): float {
return Db::table($table)->where($where)->max($column);
};
@@ -255,9 +267,12 @@ Db::$queries['max'] = function (string $table, string $column, $where = null): f
* @param string $table The name of the table which should be queried
* @param string $column The name of the column of which the average should be calculated
* @param mixed $where An optional WHERE clause
* @return float
*/
Db::$queries['avg'] = function (string $table, string $column, $where = null): float {
Db::$queries['avg'] = function (
string $table,
string $column,
$where = null
): float {
return Db::table($table)->where($where)->avg($column);
};
@@ -267,9 +282,12 @@ Db::$queries['avg'] = function (string $table, string $column, $where = null): f
* @param string $table The name of the table which should be queried
* @param string $column The name of the column of which the sum should be calculated
* @param mixed $where An optional WHERE clause
* @return float
*/
Db::$queries['sum'] = function (string $table, string $column, $where = null): float {
Db::$queries['sum'] = function (
string $table,
string $column,
$where = null
): float {
return Db::table($table)->where($where)->sum($column);
};

View File

@@ -2,8 +2,10 @@
namespace Kirby\Database;
use Closure;
use InvalidArgumentException;
use Kirby\Toolkit\A;
use Kirby\Toolkit\Collection;
use Kirby\Toolkit\Obj;
use Kirby\Toolkit\Pagination;
use Kirby\Toolkit\Str;
@@ -23,130 +25,94 @@ class Query
/**
* Parent Database object
*
* @var \Kirby\Database\Database
*/
protected $database = null;
protected Database|null $database = null;
/**
* The object which should be fetched for each row
* or function to call for each row
*
* @var string|\Closure
*/
protected $fetch = 'Kirby\Toolkit\Obj';
protected string|Closure $fetch = Obj::class;
/**
* The iterator class, which should be used for result sets
*
* @var string
*/
protected $iterator = 'Kirby\Toolkit\Collection';
protected string $iterator = Collection::class;
/**
* An array of bindings for the final query
*
* @var array
*/
protected $bindings = [];
protected array $bindings = [];
/**
* The table name
*
* @var string
*/
protected $table;
protected string $table;
/**
* The name of the primary key column
*
* @var string
*/
protected $primaryKeyName = 'id';
protected string $primaryKeyName = 'id';
/**
* An array with additional join parameters
*
* @var array
*/
protected $join;
protected array|null $join = null;
/**
* A list of columns, which should be selected
*
* @var array|string
*/
protected $select;
protected array|string|null $select = null;
/**
* Boolean for distinct select clauses
*
* @var bool
*/
protected $distinct;
protected bool|null $distinct = null;
/**
* Boolean for if exceptions should be thrown on failing queries
*
* @var bool
*/
protected $fail = false;
protected bool $fail = false;
/**
* A list of values for update and insert clauses
*
* @var array
*/
protected $values;
protected array|null $values = null;
/**
* WHERE clause
*
* @var mixed
*/
protected $where;
protected $where = null;
/**
* GROUP BY clause
*
* @var mixed
*/
protected $group;
protected string|null $group = null;
/**
* HAVING clause
*
* @var mixed
*/
protected $having;
protected $having = null;
/**
* ORDER BY clause
*
* @var mixed
*/
protected $order;
protected $order = null;
/**
* The offset, which should be applied to the select query
*
* @var int
*/
protected $offset = 0;
protected int $offset = 0;
/**
* The limit, which should be applied to the select query
*
* @var int
*/
protected $limit;
protected int|null $limit = null;
/**
* Boolean to enable query debugging
*
* @var bool
*/
protected $debug = false;
protected bool $debug = false;
/**
* Constructor
@@ -163,7 +129,7 @@ class Query
/**
* Reset the query class after each db hit
*/
protected function reset()
protected function reset(): void
{
$this->bindings = [];
$this->join = null;
@@ -185,10 +151,9 @@ class Query
* If enabled, the query will return an array with all important info about
* the query instead of actually executing the query and returning results
*
* @param bool $debug
* @return \Kirby\Database\Query
* @return $this
*/
public function debug(bool $debug = true)
public function debug(bool $debug = true): static
{
$this->debug = $debug;
return $this;
@@ -197,10 +162,9 @@ class Query
/**
* Enables distinct select clauses.
*
* @param bool $distinct
* @return \Kirby\Database\Query
* @return $this
*/
public function distinct(bool $distinct = true)
public function distinct(bool $distinct = true): static
{
$this->distinct = $distinct;
return $this;
@@ -210,10 +174,9 @@ class Query
* Enables failing queries.
* If enabled queries will no longer fail silently but throw an exception
*
* @param bool $fail
* @return \Kirby\Database\Query
* @return $this
*/
public function fail(bool $fail = true)
public function fail(bool $fail = true): static
{
$this->fail = $fail;
return $this;
@@ -224,10 +187,9 @@ class Query
* set this to `'array'` to get a simple array instead of an object;
* pass a function that receives the `$data` and the `$key` to generate arbitrary data structures
*
* @param string|\Closure $fetch
* @return \Kirby\Database\Query
* @return $this
*/
public function fetch($fetch)
public function fetch(string|Closure $fetch): static
{
$this->fetch = $fetch;
return $this;
@@ -237,10 +199,9 @@ class Query
* Sets the iterator class, which should be used for multiple results
* Set this to array to get a simple array instead of an iterator object
*
* @param string $iterator
* @return \Kirby\Database\Query
* @return $this
*/
public function iterator(string $iterator)
public function iterator(string $iterator): static
{
$this->iterator = $iterator;
return $this;
@@ -249,11 +210,10 @@ class Query
/**
* Sets the name of the table, which should be queried
*
* @param string $table
* @return \Kirby\Database\Query
* @return $this
* @throws \Kirby\Exception\InvalidArgumentException if the table does not exist
*/
public function table(string $table)
public function table(string $table): static
{
if ($this->database->validateTable($table) === false) {
throw new InvalidArgumentException('Invalid table: ' . $table);
@@ -266,10 +226,9 @@ class Query
/**
* Sets the name of the primary key column
*
* @param string $primaryKeyName
* @return \Kirby\Database\Query
* @return $this
*/
public function primaryKeyName(string $primaryKeyName)
public function primaryKeyName(string $primaryKeyName): static
{
$this->primaryKeyName = $primaryKeyName;
return $this;
@@ -279,10 +238,10 @@ class Query
* Sets the columns, which should be selected from the table
* By default all columns will be selected
*
* @param mixed $select Pass either a string of columns or an array
* @return \Kirby\Database\Query
* @param array|string|null $select Pass either a string of columns or an array
* @return $this
*/
public function select($select)
public function select(array|string|null $select): static
{
$this->select = $select;
return $this;
@@ -296,7 +255,7 @@ class Query
* @param string $type The join type. Uses an inner join by default
* @return $this
*/
public function join(string $table, string $on, string $type = 'JOIN')
public function join(string $table, string $on, string $type = 'JOIN'): static
{
$join = [
'table' => $table,
@@ -313,11 +272,11 @@ class Query
*
* @param string $table Name of the table, which should be joined
* @param string $on The on clause for this join
* @return \Kirby\Database\Query
* @return $this
*/
public function leftJoin(string $table, string $on)
public function leftJoin(string $table, string $on): static
{
return $this->join($table, $on, 'left');
return $this->join($table, $on, 'left join');
}
/**
@@ -325,11 +284,11 @@ class Query
*
* @param string $table Name of the table, which should be joined
* @param string $on The on clause for this join
* @return \Kirby\Database\Query
* @return $this
*/
public function rightJoin(string $table, string $on)
public function rightJoin(string $table, string $on): static
{
return $this->join($table, $on, 'right');
return $this->join($table, $on, 'right join');
}
/**
@@ -337,9 +296,9 @@ class Query
*
* @param string $table Name of the table, which should be joined
* @param string $on The on clause for this join
* @return \Kirby\Database\Query
* @return $this
*/
public function innerJoin($table, $on)
public function innerJoin($table, $on): static
{
return $this->join($table, $on, 'inner join');
}
@@ -348,9 +307,9 @@ class Query
* Sets the values which should be used for the update or insert clause
*
* @param mixed $values Can either be a string or an array of values
* @return \Kirby\Database\Query
* @return $this
*/
public function values($values = [])
public function values($values = []): static
{
if ($values !== null) {
$this->values = $values;
@@ -360,12 +319,13 @@ class Query
/**
* Attaches additional bindings to the query.
* Also can be used as getter for all attached bindings by not passing an argument.
* Also can be used as getter for all attached bindings
* by not passing an argument.
*
* @param mixed $bindings Array of bindings or null to use this method as getter
* @return array|\Kirby\Database\Query
* @return array|$this
* @psalm-return ($bindings is array ? $this : array)
*/
public function bindings(array $bindings = null)
public function bindings(array|null $bindings = null): array|static
{
if (is_array($bindings) === true) {
$this->bindings = array_merge($this->bindings, $bindings);
@@ -386,10 +346,9 @@ class Query
* ->where('username like ?', 'myuser') (args: 2)
* ->where('username', 'like', 'myuser'); (args: 3)
*
* @param mixed ...$args
* @return \Kirby\Database\Query
* @return $this
*/
public function where(...$args)
public function where(...$args): static
{
$this->where = $this->filterQuery($args, $this->where);
return $this;
@@ -399,10 +358,9 @@ class Query
* Shortcut to attach a where clause with an OR operator.
* Check out the where() method docs for additional info.
*
* @param mixed ...$args
* @return \Kirby\Database\Query
* @return $this
*/
public function orWhere(...$args)
public function orWhere(...$args): static
{
$this->where = $this->filterQuery($args, $this->where, 'OR');
return $this;
@@ -412,10 +370,9 @@ class Query
* Shortcut to attach a where clause with an AND operator.
* Check out the where() method docs for additional info.
*
* @param mixed ...$args
* @return \Kirby\Database\Query
* @return $this
*/
public function andWhere(...$args)
public function andWhere(...$args): static
{
$this->where = $this->filterQuery($args, $this->where, 'AND');
return $this;
@@ -424,10 +381,9 @@ class Query
/**
* Attaches a group by clause
*
* @param string|null $group
* @return \Kirby\Database\Query
* @return $this
*/
public function group(string $group = null)
public function group(string|null $group = null): static
{
$this->group = $group;
return $this;
@@ -444,10 +400,9 @@ class Query
* ->having('username like ?', 'myuser') (args: 2)
* ->having('username', 'like', 'myuser'); (args: 3)
*
* @param mixed ...$args
* @return \Kirby\Database\Query
* @return $this
*/
public function having(...$args)
public function having(...$args): static
{
$this->having = $this->filterQuery($args, $this->having);
return $this;
@@ -457,7 +412,7 @@ class Query
* Attaches an order clause
*
* @param string|null $order
* @return \Kirby\Database\Query
* @return $this
*/
public function order(string $order = null)
{
@@ -468,10 +423,9 @@ class Query
/**
* Sets the offset for select clauses
*
* @param int|null $offset
* @return \Kirby\Database\Query
* @return $this
*/
public function offset(int $offset = null)
public function offset(int $offset): static
{
$this->offset = $offset;
return $this;
@@ -480,10 +434,9 @@ class Query
/**
* Sets the limit for select clauses
*
* @param int|null $limit
* @return \Kirby\Database\Query
* @return $this
*/
public function limit(int $limit = null)
public function limit(int|null $limit = null): static
{
$this->limit = $limit;
return $this;
@@ -496,7 +449,7 @@ class Query
* @param string $type (select, update, insert)
* @return array The final query
*/
public function build(string $type)
public function build(string $type): array
{
$sql = $this->database->sql();
@@ -536,8 +489,6 @@ class Query
/**
* Builds a count query
*
* @return int
*/
public function count(): int
{
@@ -546,9 +497,6 @@ class Query
/**
* Builds a max query
*
* @param string $column
* @return float
*/
public function max(string $column): float
{
@@ -557,9 +505,6 @@ class Query
/**
* Builds a min query
*
* @param string $column
* @return float
*/
public function min(string $column): float
{
@@ -568,9 +513,6 @@ class Query
/**
* Builds a sum query
*
* @param string $column
* @return float
*/
public function sum(string $column): float
{
@@ -579,9 +521,6 @@ class Query
/**
* Builds an average query
*
* @param string $column
* @return float
*/
public function avg(string $column): float
{
@@ -592,12 +531,9 @@ class Query
* Builds an aggregation query.
* This is used by all the aggregation methods above
*
* @param string $method
* @param string $column
* @param int $default An optional default value, which should be returned if the query fails
* @return mixed
*/
public function aggregate(string $method, string $column = '*', $default = 0)
public function aggregate(string $method, string $column = '*', int $default = 0)
{
// reset the sorting to avoid counting issues
$this->order = null;
@@ -609,13 +545,13 @@ class Query
}
$fetch = $this->fetch;
$row = $this->select($method . '(' . $column . ') as aggregation')->fetch('Obj')->first();
$row = $this->select($method . '(' . $column . ') as aggregation')->fetch(Obj::class)->first();
if ($this->debug === true) {
return $row;
}
$result = $row ? $row->get('aggregation') : $default;
$result = $row?->get('aggregation') ?? $default;
$this->fetch($fetch);
@@ -624,12 +560,8 @@ class Query
/**
* Used as an internal shortcut for firing a db query
*
* @param string|array $sql
* @param array $params
* @return mixed
*/
protected function query($sql, array $params = [])
protected function query(string|array $sql, array $params = [])
{
if (is_string($sql) === true) {
$sql = [
@@ -659,12 +591,8 @@ class Query
/**
* Used as an internal shortcut for executing a db query
*
* @param string|array $sql
* @param array $params
* @return mixed
*/
protected function execute($sql, array $params = [])
protected function execute(string|array $sql, array $params = [])
{
if (is_string($sql) === true) {
$sql = [
@@ -694,10 +622,8 @@ class Query
/**
* Selects only one row from a table
*
* @return object
*/
public function first()
public function first(): object|array|false
{
return $this->query($this->offset(0)->limit(1)->build('select'), [
'fetch' => $this->fetch,
@@ -708,20 +634,16 @@ class Query
/**
* Selects only one row from a table
*
* @return object
*/
public function row()
public function row(): object|array|false
{
return $this->first();
}
/**
* Selects only one row from a table
*
* @return object
*/
public function one()
public function one(): object|array|false
{
return $this->first();
}
@@ -729,11 +651,10 @@ class Query
/**
* Automatically adds pagination to a query
*
* @param int $page
* @param int $limit The number of rows, which should be returned for each page
* @return object Collection iterator with attached pagination object
*/
public function page(int $page, int $limit)
public function page(int $page, int $limit): object
{
// clone this to create a counter query
$counter = clone $this;
@@ -775,8 +696,6 @@ class Query
/**
* Returns all matching rows from a table
*
* @return mixed
*/
public function all()
{
@@ -788,9 +707,6 @@ class Query
/**
* Returns only values from a single column
*
* @param string $column
* @return mixed
*/
public function column(string $column)
{
@@ -825,10 +741,6 @@ class Query
/**
* Find a single row by column and value
*
* @param string $column
* @param mixed $value
* @return mixed
*/
public function findBy(string $column, $value)
{
@@ -837,9 +749,6 @@ class Query
/**
* Find a single row by its primary key
*
* @param mixed $id
* @return mixed
*/
public function find($id)
{
@@ -868,9 +777,8 @@ class Query
*
* @param mixed $values You can pass values here or set them with ->values() before
* @param mixed $where You can pass a where clause here or set it with ->where() before
* @return bool
*/
public function update($values = null, $where = null)
public function update($values = null, $where = null): bool
{
return $this->execute($this->values($values)->where($where)->build('update'));
}
@@ -879,19 +787,14 @@ class Query
* Fires a delete query
*
* @param mixed $where You can pass a where clause here or set it with ->where() before
* @return bool
*/
public function delete($where = null)
public function delete($where = null): bool
{
return $this->execute($this->where($where)->build('delete'));
}
/**
* Enables magic queries like findByUsername or findByEmail
*
* @param string $method
* @param array $arguments
* @return mixed
*/
public function __call(string $method, array $arguments = [])
{
@@ -907,7 +810,6 @@ class Query
*
* @param array $args Arguments, see where() description
* @param mixed $current Current value (like $this->where)
* @return string
*/
protected function filterQuery(array $args, $current, string $mode = 'AND')
{

View File

@@ -19,33 +19,25 @@ abstract class Sql
{
/**
* List of literals which should not be escaped in queries
*
* @var array
*/
public static $literals = ['NOW()', null];
public static array $literals = ['NOW()', null];
/**
* The parent database connection
*
* @var \Kirby\Database\Database
*/
protected $database;
protected Database $database;
/**
* List of used bindings; used to avoid
* duplicate binding names
*
* @var array
*/
protected $bindings = [];
protected array $bindings = [];
/**
* Constructor
* @codeCoverageIgnore
*
* @param \Kirby\Database\Database $database
*/
public function __construct($database)
public function __construct(Database $database)
{
$this->database = $database;
}
@@ -80,7 +72,6 @@ abstract class Sql
* the query needs to return rows with a column `name`
*
* @param string $table Table name
* @return array
*/
abstract public function columns(string $table): array;
@@ -136,8 +127,6 @@ abstract class Sql
* Abstracted column types to simplify table
* creation for multiple database drivers
* @codeCoverageIgnore
*
* @return array
*/
public function columnTypes(): array
{
@@ -154,11 +143,8 @@ abstract class Sql
/**
* Combines an identifier (table and column)
*
* @param $table string
* @param $column string
* @param $values bool Whether the identifier is going to be used for a VALUES clause;
* only relevant for SQLite
* @return string
*/
public function combineIdentifier(string $table, string $column, bool $values = false): string
{
@@ -316,7 +302,6 @@ abstract class Sql
* Builds a DELETE clause
*
* @param array $params List of parameters for the DELETE clause. See defaults for more info.
* @return array
*/
public function delete(array $params = []): array
{
@@ -344,9 +329,6 @@ abstract class Sql
/**
* Creates the sql for dropping a single table
*
* @param string $table
* @return array
*/
public function dropTable(string $table): array
{
@@ -359,13 +341,8 @@ abstract class Sql
/**
* Extends a given query and bindings
* by reference
*
* @param array $query
* @param array $bindings
* @param array $input
* @return void
*/
public function extend(&$query, array &$bindings, $input)
public function extend(array &$query, array &$bindings, array $input): void
{
if (empty($input['query']) === false) {
$query[] = $input['query'];
@@ -375,9 +352,6 @@ abstract class Sql
/**
* Creates the from syntax
*
* @param string $table
* @return array
*/
public function from(string $table): array
{
@@ -389,51 +363,36 @@ abstract class Sql
/**
* Creates the group by syntax
*
* @param string $group
* @return array
*/
public function group(string $group = null): array
public function group(string|null $group = null): array
{
if (empty($group) === true) {
return [
'query' => null,
'bindings' => []
];
if (empty($group) === false) {
$query = 'GROUP BY ' . $group;
}
return [
'query' => 'GROUP BY ' . $group,
'query' => $query ?? null,
'bindings' => []
];
}
/**
* Creates the having syntax
*
* @param string|null $having
* @return array
*/
public function having(string $having = null): array
public function having(string|null $having = null): array
{
if (empty($having) === true) {
return [
'query' => null,
'bindings' => []
];
if (empty($having) === false) {
$query = 'HAVING ' . $having;
}
return [
'query' => 'HAVING ' . $having,
'query' => $query ?? null,
'bindings' => []
];
}
/**
* Creates an insert query
*
* @param array $params
* @return array
*/
public function insert(array $params = []): array
{
@@ -454,10 +413,6 @@ abstract class Sql
/**
* Creates a join query
*
* @param string $table
* @param string $type
* @param string $on
* @return array
* @throws \Kirby\Exception\InvalidArgumentException if an invalid join type is given
*/
public function join(string $type, string $table, string $on): array
@@ -492,11 +447,8 @@ abstract class Sql
/**
* Create the syntax for multiple joins
*
* @param array|null $joins
* @return array
*/
public function joins(array $joins = null): array
public function joins(array|null $joins = null): array
{
$query = [];
$bindings = [];
@@ -513,12 +465,8 @@ abstract class Sql
/**
* Creates a limit and offset query instruction
*
* @param int $offset
* @param int|null $limit
* @return array
*/
public function limit(int $offset = 0, int $limit = null): array
public function limit(int $offset = 0, int|null $limit = null): array
{
// no need to add it to the query
if ($offset === 0 && $limit === null) {
@@ -544,42 +492,29 @@ abstract class Sql
/**
* Creates the order by syntax
*
* @param string $order
* @return array
*/
public function order(string $order = null): array
public function order(string|null $order = null): array
{
if (empty($order) === true) {
return [
'query' => null,
'bindings' => []
];
if (empty($order) === false) {
$query = 'ORDER BY ' . $order;
}
return [
'query' => 'ORDER BY ' . $order,
'query' => $query ?? null,
'bindings' => []
];
}
/**
* Converts a query array into a final string
*
* @param array $query
* @param string $separator
* @return string
*/
public function query(array $query, string $separator = ' ')
public function query(array $query, string $separator = ' '): string
{
return implode($separator, array_filter($query));
}
/**
* Quotes an identifier (table *or* column)
*
* @param $identifier string
* @return string
*/
public function quoteIdentifier(string $identifier): string
{
@@ -658,12 +593,8 @@ abstract class Sql
/**
* Creates a columns definition from string or array
*
* @param string $table
* @param array|string|null $columns
* @return string
*/
public function selected($table, $columns = null): string
public function selected(string $table, array|string|null $columns = null): string
{
// all columns
if (empty($columns) === true) {
@@ -692,12 +623,10 @@ abstract class Sql
/**
* Splits a (qualified) identifier into table and column
*
* @param $table string Default table if the identifier is not qualified
* @param $identifier string
* @return array
* @param string $table Default table if the identifier is not qualified
* @throws \Kirby\Exception\InvalidArgumentException if an invalid identifier is given
*/
public function splitIdentifier($table, $identifier): array
public function splitIdentifier(string $table, string $identifier): array
{
// split by dot, but only outside of quotes
$parts = preg_split('/(?:`[^`]*`|"[^"]*")(*SKIP)(*F)|\./', $identifier);
@@ -720,16 +649,12 @@ abstract class Sql
/**
* Returns a query to list the tables of the current database;
* the query needs to return rows with a column `name`
*
* @return array
*/
abstract public function tables(): array;
/**
* Validates and quotes a table name
*
* @param string $table
* @return string
* @throws \Kirby\Exception\InvalidArgumentException if an invalid table name is given
*/
public function tableName(string $table): string
@@ -744,9 +669,6 @@ abstract class Sql
/**
* Unquotes an identifier (table *or* column)
*
* @param $identifier string
* @return string
*/
public function unquoteIdentifier(string $identifier): string
{
@@ -767,7 +689,6 @@ abstract class Sql
* Builds an update clause
*
* @param array $params List of parameters for the update clause. See defaults for more info.
* @return array
*/
public function update(array $params = []): array
{
@@ -799,9 +720,6 @@ abstract class Sql
/**
* Validates a given column name in a table
*
* @param string $table
* @param string $column
* @return bool
* @throws \Kirby\Exception\InvalidArgumentException If the column is invalid
*/
public function validateColumn(string $table, string $column): bool
@@ -822,8 +740,13 @@ abstract class Sql
* @param bool $set If true builds a set list of values for update clauses
* @param bool $enforceQualified Always use fully qualified column names
*/
public function values(string $table, $values, string $separator = ', ', bool $set = true, bool $enforceQualified = false): array
{
public function values(
string $table,
$values,
string $separator = ', ',
bool $set = true,
bool $enforceQualified = false
): array {
if (is_array($values) === false) {
return [
'query' => $values,
@@ -840,15 +763,13 @@ abstract class Sql
/**
* Creates a list of fields and values
*
* @param string $table
* @param string|array $values
* @param string $separator
* @param bool $enforceQualified
* @param array
*/
public function valueList(string $table, $values, string $separator = ',', bool $enforceQualified = false): array
{
public function valueList(
string $table,
string|array $values,
string $separator = ',',
bool $enforceQualified = false
): array {
$fields = [];
$query = [];
$bindings = [];
@@ -886,16 +807,13 @@ abstract class Sql
/**
* Creates a set of values
*
* @param string $table
* @param string|array $values
* @param string $separator
* @param bool $enforceQualified
* @param array
* @return array
*/
public function valueSet(string $table, $values, string $separator = ',', bool $enforceQualified = false): array
{
public function valueSet(
string $table,
string|array $values,
string $separator = ',',
bool $enforceQualified = false
): array {
$query = [];
$bindings = [];
@@ -928,12 +846,7 @@ abstract class Sql
];
}
/**
* @param string|array|null $where
* @param array $bindings
* @return array
*/
public function where($where, array $bindings = []): array
public function where(string|array|null $where, array $bindings = []): array
{
if (empty($where) === true) {
return [

View File

@@ -20,7 +20,6 @@ class Mysql extends Sql
* the query needs to return rows with a column `name`
*
* @param string $table Table name
* @return array
*/
public function columns(string $table): array
{
@@ -42,8 +41,6 @@ class Mysql extends Sql
/**
* Returns a query to list the tables of the current database;
* the query needs to return rows with a column `name`
*
* @return array
*/
public function tables(): array
{

View File

@@ -20,7 +20,6 @@ class Sqlite extends Sql
* the query needs to return rows with a column `name`
*
* @param string $table Table name
* @return array
*/
public function columns(string $table): array
{
@@ -34,8 +33,6 @@ class Sqlite extends Sql
* Abstracted column types to simplify table
* creation for multiple database drivers
* @codeCoverageIgnore
*
* @return array
*/
public function columnTypes(): array
{
@@ -52,11 +49,9 @@ class Sqlite extends Sql
/**
* Combines an identifier (table and column)
*
* @param $table string
* @param $column string
* @param $values bool Whether the identifier is going to be used for a VALUES clause;
* only relevant for SQLite
* @return string
* @param bool $values Whether the identifier is going to be
* used for a VALUES clause; only relevant
* for SQLite
*/
public function combineIdentifier(string $table, string $column, bool $values = false): string
{
@@ -111,9 +106,6 @@ class Sqlite extends Sql
/**
* Quotes an identifier (table *or* column)
*
* @param $identifier string
* @return string
*/
public function quoteIdentifier(string $identifier): string
{
@@ -132,8 +124,6 @@ class Sqlite extends Sql
/**
* Returns a query to list the tables of the current database;
* the query needs to return rows with a column `name`
*
* @return string
*/
public function tables(): array
{