initial commit

This commit is contained in:
isUnknown 2026-01-13 10:21:41 +01:00
commit 5210d78d7d
969 changed files with 223828 additions and 0 deletions

View file

@ -0,0 +1,613 @@
<?php
namespace Kirby\Database;
use Closure;
use Kirby\Database\Sql\Mysql;
use Kirby\Database\Sql\Sqlite;
use Kirby\Exception\InvalidArgumentException;
use Kirby\Toolkit\A;
use Kirby\Toolkit\Collection;
use Kirby\Toolkit\Obj;
use Kirby\Toolkit\Str;
use PDO;
use PDOStatement;
use Throwable;
/**
* A simple database class
*
* @package Kirby Database
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://opensource.org/licenses/MIT
*/
class Database
{
/**
* The number of affected rows for the last query
*/
protected int|null $affected = null;
/**
* Whitelist for column names
*/
protected array $columnWhitelist = [];
/**
* The established connection
*/
protected PDO|null $connection = null;
/**
* A global array of started connections
*/
public static array $connections = [];
/**
* Database name
*/
protected string $database;
protected string $dsn;
/**
* Set to true to throw exceptions on failed queries
*/
protected bool $fail = false;
/**
* The connection id
*/
protected string $id;
/**
* The last error
*/
protected Throwable|null $lastError = null;
/**
* The last insert id
*/
protected int|null $lastId = null;
/**
* The last query
*/
protected string $lastQuery;
/**
* The last result set
*/
protected mixed $lastResult;
/**
* Optional prefix for table names
*/
protected string|null $prefix = null;
/**
* The PDO query statement
*/
protected PDOStatement|null $statement = null;
/**
* List of existing tables in the database
*/
protected array|null $tables = null;
/**
* An array with all queries which are being made
*/
protected array $trace = [];
/**
* The database type (mysql, sqlite)
*/
protected string $type;
public static array $types = [];
/**
* Creates a new Database instance
*/
public function __construct(array $params = [])
{
$this->connect($params);
}
/**
* Returns one of the started instances
*/
public static function instance(string|null $id = null): static|null
{
if ($id === null) {
return A::last(static::$connections);
}
return static::$connections[$id] ?? null;
}
/**
* Returns all started instances
*/
public static function instances(): array
{
return static::$connections;
}
/**
* Connects to a database
*
* @param array|null $params This can either be a config key or an array of parameters for the connection
* @throws \Kirby\Exception\InvalidArgumentException
*/
public function connect(array|null $params = null): PDO|null
{
$options = [
'database' => null,
'type' => 'mysql',
'prefix' => null,
'user' => null,
'password' => null,
'id' => uniqid(),
...$params
];
// store the database information
$this->database = $options['database'];
$this->type = $options['type'];
$this->prefix = $options['prefix'];
$this->id = $options['id'];
if (isset(static::$types[$this->type]) === false) {
throw new InvalidArgumentException(
message: 'Invalid database type: ' . $this->type
);
}
// fetch the dsn and store it
$this->dsn = (static::$types[$this->type]['dsn'])($options);
// try to connect
$this->connection = new PDO($this->dsn, $options['user'], $options['password']);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
// TODO: behavior without this attribute would be preferrable
// (actual types instead of all strings) but would be a breaking change
if ($this->type === 'sqlite') {
$this->connection->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, true);
}
// store the connection
static::$connections[$this->id] = $this;
// return the connection
return $this->connection;
}
/**
* Returns the currently active connection
*/
public function connection(): PDO|null
{
return $this->connection;
}
/**
* Sets the exception mode
*
* @return $this
*/
public function fail(bool $fail = true): static
{
$this->fail = $fail;
return $this;
}
/**
* Returns the used database type
*/
public function type(): string
{
return $this->type;
}
/**
* Returns the used table name prefix
*/
public function prefix(): string|null
{
return $this->prefix;
}
/**
* Escapes a value to be used for a safe query
* NOTE: Prepared statements using bound parameters are more secure and solid
*/
public function escape(string $value): string
{
return substr($this->connection()->quote($value), 1, -1);
}
/**
* Adds a value to the db trace and also
* returns the entire trace if nothing is specified
*/
public function trace(array|null $data = null): array
{
// return the full trace
if ($data === null) {
return $this->trace;
}
// add a new entry to the trace
$this->trace[] = $data;
return $this->trace;
}
/**
* Returns the number of affected rows for the last query
*/
public function affected(): int|null
{
return $this->affected;
}
/**
* Returns the last id if available
*/
public function lastId(): int|null
{
return $this->lastId;
}
/**
* Returns the last query
*/
public function lastQuery(): string|null
{
return $this->lastQuery;
}
/**
* Returns the last set of results
*/
public function lastResult()
{
return $this->lastResult;
}
/**
* Returns the last db error
*/
public function lastError(): Throwable|null
{
return $this->lastError;
}
/**
* Returns the name of the database
*/
public function name(): string|null
{
return $this->database;
}
/**
* Private method to execute database queries.
* This is used by the query() and execute() methods
*/
protected function hit(string $query, array $bindings = []): bool
{
// try to prepare and execute the sql
try {
$this->statement = $this->connection->prepare($query);
// bind parameters to statement
foreach ($bindings as $parameter => $value) {
// positional parameters start at 1
if (is_int($parameter)) {
$parameter++;
}
$type = match (gettype($value)) {
'integer' => PDO::PARAM_INT,
'boolean' => PDO::PARAM_BOOL,
'NULL' => PDO::PARAM_NULL,
default => PDO::PARAM_STR
};
$this->statement->bindValue($parameter, $value, $type);
}
$this->statement->execute();
$this->affected = $this->statement->rowCount();
$this->lastId = Str::startsWith($query, 'insert ', true) ? $this->connection->lastInsertId() : null;
$this->lastError = null;
// store the final sql to add it to the trace later
$this->lastQuery = $this->statement->queryString;
} catch (Throwable $e) {
// store the error
$this->affected = 0;
$this->lastError = $e;
$this->lastId = null;
$this->lastQuery = $query;
// only throw the extension if failing is allowed
if ($this->fail === true) {
throw $e;
}
}
// add a new entry to the singleton trace array
$this->trace([
'query' => $this->lastQuery,
'bindings' => $bindings,
'error' => $this->lastError
]);
// return true or false on success or failure
return $this->lastError === null;
}
/**
* Executes a sql query, which is expected to return a set of results
*/
public function query(
string $query,
array $bindings = [],
array $params = []
) {
$options = [
'flag' => null,
'method' => 'fetchAll',
'fetch' => Obj::class,
'iterator' => Collection::class,
...$params
];
if ($this->hit($query, $bindings) === false) {
return false;
}
// define the default flag for the fetch method
if (
$options['fetch'] instanceof Closure ||
$options['fetch'] === 'array'
) {
$flags = PDO::FETCH_ASSOC;
} else {
$flags = PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE;
}
// add optional flags
if (empty($options['flag']) === false) {
$flags |= $options['flag'];
}
// set the fetch mode
if (
$options['fetch'] instanceof Closure ||
$options['fetch'] === 'array'
) {
$this->statement->setFetchMode($flags);
} else {
$this->statement->setFetchMode($flags, $options['fetch']);
}
// fetch that stuff
$results = $this->statement->{$options['method']}();
// apply the fetch closure to all results if given
if ($options['fetch'] instanceof Closure) {
if ($options['method'] === 'fetchAll') {
// fetching multiple records
foreach ($results as $key => $result) {
$results[$key] = $options['fetch']($result, $key);
}
} elseif ($options['method'] === 'fetch' && $results !== false) {
// fetching a single record
$results = $options['fetch']($results, null);
}
}
if ($options['iterator'] === 'array') {
return $this->lastResult = $results;
}
return $this->lastResult = new $options['iterator']($results);
}
/**
* Executes a sql query, which is expected
* to not return a set of results
*/
public function execute(string $query, array $bindings = []): bool
{
return $this->lastResult = $this->hit($query, $bindings);
}
/**
* Returns the correct Sql generator instance
* for the type of database
*/
public function sql(): Sql
{
$className = static::$types[$this->type]['sql'] ?? 'Sql';
return new $className($this);
}
/**
* Sets the current table, which should be queried. Returns a
* Query object, which can be used to build a full query
* for that table
*/
public function table(string $table): Query
{
return new Query($this, $this->prefix() . $table);
}
/**
* Checks if a table exists in the current database
*/
public function validateTable(string $table): bool
{
if ($this->tables === null) {
// Get the list of tables from the database
$sql = $this->sql()->tables();
$results = $this->query($sql['query'], $sql['bindings']);
if ($results) {
$this->tables = $results->pluck('name');
} else {
return false;
}
}
return in_array($table, $this->tables, true) === true;
}
/**
* Checks if a column exists in a specified table
*/
public function validateColumn(string $table, string $column): bool
{
if (isset($this->columnWhitelist[$table]) === false) {
if ($this->validateTable($table) === false) {
$this->columnWhitelist[$table] = [];
return false;
}
// Get the column whitelist from the database
$sql = $this->sql()->columns($table);
$results = $this->query($sql['query'], $sql['bindings']);
if ($results) {
$this->columnWhitelist[$table] = $results->pluck('name');
} else {
return false;
}
}
return in_array($column, $this->columnWhitelist[$table], true) === true;
}
/**
* Creates a new table
*/
public function createTable(string $table, array $columns = []): bool
{
$sql = $this->sql()->createTable($table, $columns);
$queries = Str::split($sql['query'], ';');
foreach ($queries as $query) {
$query = trim($query);
if ($this->execute($query, $sql['bindings']) === false) {
return false;
}
}
// update cache
if (in_array($table, $this->tables ?? [], true) !== true) {
$this->tables[] = $table;
}
return true;
}
/**
* Drops a table
*/
public function dropTable(string $table): bool
{
$sql = $this->sql()->dropTable($table);
if ($this->execute($sql['query'], $sql['bindings']) !== true) {
return false;
}
// update cache
$key = array_search($table, $this->tables ?? []);
if ($key !== false) {
unset($this->tables[$key]);
}
return true;
}
/**
* Magic way to start queries for tables by
* using a method named like the table.
* I.e. $db->users()->all()
*/
public function __call(string $method, mixed $arguments = null): Query
{
return $this->table($method);
}
}
/**
* MySQL database connector
*/
Database::$types['mysql'] = [
'sql' => Mysql::class,
'dsn' => function (array $params): string {
if (
isset($params['host']) === false &&
isset($params['socket']) === false
) {
throw new InvalidArgumentException(
message: 'The mysql connection requires either a "host" or a "socket" parameter'
);
}
if (isset($params['database']) === false) {
throw new InvalidArgumentException(
message: 'The mysql connection requires a "database" parameter'
);
}
$parts = [];
if (empty($params['host']) === false) {
$parts[] = 'host=' . $params['host'];
}
if (empty($params['port']) === false) {
$parts[] = 'port=' . $params['port'];
}
if (empty($params['socket']) === false) {
$parts[] = 'unix_socket=' . $params['socket'];
}
if (empty($params['database']) === false) {
$parts[] = 'dbname=' . $params['database'];
}
$parts[] = 'charset=' . ($params['charset'] ?? 'utf8mb4');
return 'mysql:' . implode(';', $parts);
}
];
/**
* SQLite database connector
*/
Database::$types['sqlite'] = [
'sql' => Sqlite::class,
'dsn' => function (array $params): string {
if (isset($params['database']) === false) {
throw new InvalidArgumentException(
message: 'The sqlite connection requires a "database" parameter'
);
}
return 'sqlite:' . $params['database'];
}
];

296
kirby/src/Database/Db.php Normal file
View file

@ -0,0 +1,296 @@
<?php
namespace Kirby\Database;
use Kirby\Exception\InvalidArgumentException;
use Kirby\Toolkit\Config;
/**
* Database shortcuts
*
* @package Kirby Database
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://opensource.org/licenses/MIT
*/
class Db
{
/**
* Query shortcuts
*/
public static array $queries = [];
/**
* The singleton Database object
*/
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
*/
public static function connect(array|null $params = null): Database
{
if ($params === null && static::$connection !== null) {
return static::$connection;
}
// try to connect with the default
// connection settings if no params are set
$params ??= [
'type' => Config::get('db.type', 'mysql'),
'host' => Config::get('db.host', 'localhost'),
'user' => Config::get('db.user', 'root'),
'password' => Config::get('db.password', ''),
'database' => Config::get('db.database', ''),
'prefix' => Config::get('db.prefix', ''),
'port' => Config::get('db.port', ''),
'charset' => Config::get('db.charset')
];
return static::$connection = new Database($params);
}
/**
* Returns the current database connection
*/
public static function connection(): Database|null
{
return static::$connection;
}
/**
* Sets the current table which should be queried. Returns a
* Query object, which can be used to build a full query for
* that table.
*/
public static function table(string $table): Query
{
$db = static::connect();
return $db->table($table);
}
/**
* Executes a raw SQL query which expects a set of results
*/
public static function query(string $query, array $bindings = [], array $params = [])
{
$db = static::connect();
return $db->query($query, $bindings, $params);
}
/**
* 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
{
$db = static::connect();
return $db->execute($query, $bindings);
}
/**
* Magic calls for other static Db methods are
* redirected to either a predefined query or
* the respective method of the Database object
*
* @throws \Kirby\Exception\InvalidArgumentException
*/
public static function __callStatic(string $method, $arguments)
{
if (isset(static::$queries[$method])) {
return (static::$queries[$method])(...$arguments);
}
if (
static::$connection !== null &&
method_exists(static::$connection, $method) === true
) {
return call_user_func_array([static::$connection, $method], $arguments);
}
throw new InvalidArgumentException(
message: 'Invalid static Db method: ' . $method
);
}
}
// @codeCoverageIgnoreStart
/**
* Shortcut for SELECT clauses
*
* @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
*/
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();
};
/**
* Shortcut for selecting a single row in a table
*
* @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
*/
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();
};
/**
* Returns only values from a single column
*
* @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
*/
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);
};
/**
* Shortcut for inserting a new row into a table
*
* @param string $table The name of the table which should be queried
* @param array $values An array of values which should be inserted
* @return mixed Returns the last inserted id on success or false
*/
Db::$queries['insert'] = function (string $table, array $values): mixed {
return Db::table($table)->insert($values);
};
/**
* Shortcut for updating a row in a table
*
* @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
*/
Db::$queries['update'] = function (
string $table,
array $values,
$where = null
): bool {
return Db::table($table)->where($where)->update($values);
};
/**
* Shortcut for deleting rows in a table
*
* @param string $table The name of the table which should be queried
* @param mixed $where An optional WHERE clause
*/
Db::$queries['delete'] = function (string $table, $where = null): bool {
return Db::table($table)->where($where)->delete();
};
/**
* Shortcut for counting rows in a table
*
* @param string $table The name of the table which should be queried
* @param mixed $where An optional WHERE clause
*/
Db::$queries['count'] = function (string $table, mixed $where = null): int {
return Db::table($table)->where($where)->count();
};
/**
* Shortcut for calculating the minimum value in a column
*
* @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
*/
Db::$queries['min'] = function (
string $table,
string $column,
$where = null
): float {
return Db::table($table)->where($where)->min($column);
};
/**
* Shortcut for calculating the maximum value in a column
*
* @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
*/
Db::$queries['max'] = function (
string $table,
string $column,
$where = null
): float {
return Db::table($table)->where($where)->max($column);
};
/**
* Shortcut for calculating the average value in a column
*
* @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
*/
Db::$queries['avg'] = function (
string $table,
string $column,
$where = null
): float {
return Db::table($table)->where($where)->avg($column);
};
/**
* Shortcut for calculating the sum of all values in a column
*
* @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
*/
Db::$queries['sum'] = function (
string $table,
string $column,
$where = null
): float {
return Db::table($table)->where($where)->sum($column);
};
// @codeCoverageIgnoreEnd

View file

@ -0,0 +1,972 @@
<?php
namespace Kirby\Database;
use Closure;
use InvalidArgumentException;
use Kirby\Toolkit\Collection;
use Kirby\Toolkit\Obj;
use Kirby\Toolkit\Pagination;
use Kirby\Toolkit\Str;
/**
* The query builder is used by the Database class
* to build SQL queries with a fluent API
*
* @package Kirby Database
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://opensource.org/licenses/MIT
*/
class Query
{
public const ERROR_INVALID_QUERY_METHOD = 0;
/**
* The object which should be fetched for each row
* or function to call for each row
*/
protected string|Closure $fetch = Obj::class;
/**
* The iterator class, which should be used for result sets
*/
protected string $iterator = Collection::class;
/**
* An array of bindings for the final query
*/
protected array $bindings = [];
/**
* The name of the primary key column
*/
protected string $primaryKeyName = 'id';
/**
* An array with additional join parameters
*/
protected array|null $join = null;
/**
* A list of columns, which should be selected
*/
protected array|string|null $select = null;
/**
* Boolean for distinct select clauses
*/
protected bool|null $distinct = null;
/**
* Boolean for if exceptions should be thrown on failing queries
*/
protected bool $fail = false;
/**
* A list of values for update and insert clauses
*/
protected array|null $values = null;
/**
* WHERE clause
*/
protected string|null $where = null;
/**
* GROUP BY clause
*/
protected string|null $group = null;
/**
* HAVING clause
*/
protected string|null $having = null;
/**
* ORDER BY clause
*/
protected string|null $order = null;
/**
* The offset, which should be applied to the select query
*/
protected int $offset = 0;
/**
* The limit, which should be applied to the select query
*/
protected int|null $limit = null;
/**
* Boolean to enable query debugging
*/
protected bool $debug = false;
/**
* @param string $table name of the table, which should be queried
*/
public function __construct(
protected Database $database,
protected string $table
) {
$this->table($table);
}
/**
* Reset the query class after each db hit
*/
protected function reset(): void
{
$this->bindings = [];
$this->join = null;
$this->select = null;
$this->distinct = null;
$this->fail = false;
$this->values = null;
$this->where = null;
$this->group = null;
$this->having = null;
$this->order = null;
$this->offset = 0;
$this->limit = null;
$this->debug = false;
}
/**
* Enables query debugging.
* If enabled, the query will return an array with all important info about
* the query instead of actually executing the query and returning results
*
* @return $this
*/
public function debug(bool $debug = true): static
{
$this->debug = $debug;
return $this;
}
/**
* Enables distinct select clauses.
*
* @return $this
*/
public function distinct(bool $distinct = true): static
{
$this->distinct = $distinct;
return $this;
}
/**
* Enables failing queries.
* If enabled queries will no longer fail silently but throw an exception
*
* @return $this
*/
public function fail(bool $fail = true): static
{
$this->fail = $fail;
return $this;
}
/**
* Sets the object class, which should be fetched;
* 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
*
* @return $this
*/
public function fetch(string|callable|Closure $fetch): static
{
if (is_callable($fetch) === true) {
$fetch = Closure::fromCallable($fetch);
}
$this->fetch = $fetch;
return $this;
}
/**
* 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
*
* @return $this
*/
public function iterator(string $iterator): static
{
$this->iterator = $iterator;
return $this;
}
/**
* Sets the name of the table, which should be queried
*
* @return $this
* @throws \Kirby\Exception\InvalidArgumentException if the table does not exist
*/
public function table(string $table): static
{
if ($this->database->validateTable($table) === false) {
throw new InvalidArgumentException(
message: 'Invalid table: ' . $table
);
}
$this->table = $table;
return $this;
}
/**
* Sets the name of the primary key column
*
* @return $this
*/
public function primaryKeyName(string $primaryKeyName): static
{
$this->primaryKeyName = $primaryKeyName;
return $this;
}
/**
* Sets the columns, which should be selected from the table
* By default all columns will be selected
*
* @param array|string|null $select Pass either a string of columns or an array
* @return $this
*/
public function select(array|string|null $select): static
{
$this->select = $select;
return $this;
}
/**
* Adds a new join clause to the query
*
* @param string $table Name of the table, which should be joined
* @param string $on The on clause for this join
* @param string $type The join type. Uses an inner join by default
* @return $this
*/
public function join(
string $table,
string $on,
string $type = 'JOIN'
): static {
$join = [
'table' => $table,
'on' => $on,
'type' => $type
];
$this->join[] = $join;
return $this;
}
/**
* Shortcut for creating a left join clause
*
* @param string $table Name of the table, which should be joined
* @param string $on The on clause for this join
* @return $this
*/
public function leftJoin(string $table, string $on): static
{
return $this->join($table, $on, 'left join');
}
/**
* Shortcut for creating a right join clause
*
* @param string $table Name of the table, which should be joined
* @param string $on The on clause for this join
* @return $this
*/
public function rightJoin(string $table, string $on): static
{
return $this->join($table, $on, 'right join');
}
/**
* Shortcut for creating an inner join clause
*
* @param string $table Name of the table, which should be joined
* @param string $on The on clause for this join
* @return $this
*/
public function innerJoin($table, $on): static
{
return $this->join($table, $on, 'inner join');
}
/**
* 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 $this
*/
public function values($values = []): static
{
if ($values !== null) {
$this->values = $values;
}
return $this;
}
/**
* Attaches additional bindings to the query.
* Also can be used as getter for all attached bindings
* by not passing an argument.
*
* @return array|$this
* @psalm-return ($bindings is array ? $this : array)
*/
public function bindings(array|null $bindings = null): array|static
{
if (is_array($bindings) === true) {
$this->bindings = [...$this->bindings, ...$bindings];
return $this;
}
return $this->bindings;
}
/**
* Attaches an additional where clause
*
* All available ways to add where clauses
*
* ->where('username like "myuser"'); (args: 1)
* ->where(['username' => 'myuser']); (args: 1)
* ->where(function($where) { $where->where('id', '=', 1) }) (args: 1)
* ->where('username like ?', 'myuser') (args: 2)
* ->where('username', 'like', 'myuser'); (args: 3)
*
* @return $this
*/
public function where(...$args): static
{
$this->where = $this->filterQuery($args, $this->where);
return $this;
}
/**
* Shortcut to attach a where clause with an OR operator.
* Check out the where() method docs for additional info.
*
* @return $this
*/
public function orWhere(...$args): static
{
$this->where = $this->filterQuery($args, $this->where, 'OR');
return $this;
}
/**
* Shortcut to attach a where clause with an AND operator.
* Check out the where() method docs for additional info.
*
* @return $this
*/
public function andWhere(...$args): static
{
$this->where = $this->filterQuery($args, $this->where, 'AND');
return $this;
}
/**
* Attaches a group by clause
*
* @return $this
*/
public function group(string|null $group = null): static
{
$this->group = $group;
return $this;
}
/**
* Attaches an additional having clause
*
* All available ways to add having clauses
*
* ->having('username like "myuser"'); (args: 1)
* ->having(['username' => 'myuser']); (args: 1)
* ->having(function($having) { $having->having('id', '=', 1) }) (args: 1)
* ->having('username like ?', 'myuser') (args: 2)
* ->having('username', 'like', 'myuser'); (args: 3)
*
* @return $this
*/
public function having(...$args): static
{
$this->having = $this->filterQuery($args, $this->having);
return $this;
}
/**
* Attaches an order clause
*
* @return $this
*/
public function order(string|null $order = null)
{
$this->order = $order;
return $this;
}
/**
* Sets the offset for select clauses
*
* @return $this
*/
public function offset(int $offset): static
{
$this->offset = $offset;
return $this;
}
/**
* Sets the limit for select clauses
*
* @return $this
*/
public function limit(int|null $limit = null): static
{
$this->limit = $limit;
return $this;
}
/**
* Builds the different types of SQL queries
* This uses the SQL class to build stuff.
*
* @param string $type (select, update, insert)
* @return array The final query
*/
public function build(string $type): array
{
$sql = $this->database->sql();
return match ($type) {
'select' => $sql->select([
'table' => $this->table,
'columns' => $this->select,
'join' => $this->join,
'distinct' => $this->distinct,
'where' => $this->where,
'group' => $this->group,
'having' => $this->having,
'order' => $this->order,
'offset' => $this->offset,
'limit' => $this->limit,
'bindings' => $this->bindings
]),
'update' => $sql->update([
'table' => $this->table,
'where' => $this->where,
'values' => $this->values,
'bindings' => $this->bindings
]),
'insert' => $sql->insert([
'table' => $this->table,
'values' => $this->values,
'bindings' => $this->bindings
]),
'delete' => $sql->delete([
'table' => $this->table,
'where' => $this->where,
'bindings' => $this->bindings
]),
default => null
};
}
/**
* Builds a count query
*/
public function count(): int
{
return (int)$this->aggregate('COUNT');
}
/**
* Builds a max query
*/
public function max(string $column): float
{
return (float)$this->aggregate('MAX', $column);
}
/**
* Builds a min query
*/
public function min(string $column): float
{
return (float)$this->aggregate('MIN', $column);
}
/**
* Builds a sum query
*/
public function sum(string $column): float
{
return (float)$this->aggregate('SUM', $column);
}
/**
* Builds an average query
*/
public function avg(string $column): float
{
return (float)$this->aggregate('AVG', $column);
}
/**
* Builds an aggregation query.
* This is used by all the aggregation methods above
*
* @param int $default An optional default value, which should be returned if the query fails
*/
public function aggregate(
string $method,
string $column = '*',
int $default = 0
) {
// reset the sorting to avoid counting issues
$this->order = null;
// validate column
if ($column !== '*') {
$sql = $this->database->sql();
$column = $sql->columnName($this->table, $column);
}
$fetch = $this->fetch;
$row = $this->select($method . '(' . $column . ') as aggregation')->fetch(Obj::class)->first();
if ($this->debug === true) {
return $row;
}
$result = $row?->get('aggregation') ?? $default;
$this->fetch($fetch);
return $result;
}
/**
* Used as an internal shortcut for firing a db query
*/
protected function query(string|array $sql, array $params = [])
{
if (is_string($sql) === true) {
$sql = [
'query' => $sql,
'bindings' => $this->bindings()
];
}
if ($this->debug) {
return [
'query' => $sql['query'],
'bindings' => $this->bindings(),
'options' => $params
];
}
if ($this->fail) {
$this->database->fail();
}
$result = $this->database->query(
$sql['query'],
$sql['bindings'],
$params
);
$this->reset();
return $result;
}
/**
* Used as an internal shortcut for executing a db query
*/
protected function execute(string|array $sql, array $params = [])
{
if (is_string($sql) === true) {
$sql = [
'query' => $sql,
'bindings' => $this->bindings()
];
}
if ($this->debug === true) {
return [
'query' => $sql['query'],
'bindings' => $sql['bindings'],
'options' => $params
];
}
if ($this->fail) {
$this->database->fail();
}
$result = $this->database->execute($sql['query'], $sql['bindings']);
$this->reset();
return $result;
}
/**
* Selects only one row from a table
*/
public function first(): mixed
{
return $this->query($this->offset(0)->limit(1)->build('select'), [
'fetch' => $this->fetch,
'iterator' => 'array',
'method' => 'fetch',
]);
}
/**
* Selects only one row from a table
*/
public function row(): mixed
{
return $this->first();
}
/**
* Selects only one row from a table
*/
public function one(): mixed
{
return $this->first();
}
/**
* Automatically adds pagination to a query
*
* @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): object
{
// clone this to create a counter query
$counter = clone $this;
// count the total number of rows for this query
$count = $counter->debug(false)->count();
// pagination
$pagination = new Pagination([
'limit' => $limit,
'page' => $page,
'total' => $count,
]);
// apply it to the dataset and retrieve all rows. make sure to use Collection as the iterator to be able to attach the pagination object
$iterator = $this->iterator;
$collection = $this
->offset($pagination->offset())
->limit($pagination->limit())
->iterator(Collection::class)
->all();
$this->iterator($iterator);
// return debug information if debug mode is active
if ($this->debug) {
$collection['totalcount'] = $count;
return $collection;
}
// store all pagination vars in a separate object
if ($collection) {
$collection->paginate($pagination);
}
// return the limited collection
return $collection;
}
/**
* Returns all matching rows from a table
*/
public function all()
{
return $this->query($this->build('select'), [
'fetch' => $this->fetch,
'iterator' => $this->iterator,
]);
}
/**
* Returns only values from a single column
*/
public function column(string $column)
{
// if there isn't already an explicit order, order by the primary key
// instead of the column that was requested (which would be implied otherwise)
if ($this->order === null) {
$sql = $this->database->sql();
$key = $sql->combineIdentifier($this->table, $this->primaryKeyName);
$this->order($key . ' ASC');
}
$results = $this->query($this->select([$column])->build('select'), [
'iterator' => 'array',
'fetch' => 'array',
]);
if ($this->debug === true) {
return $results;
}
$results = array_column($results, $column);
if ($this->iterator === 'array') {
return $results;
}
$iterator = $this->iterator;
return new $iterator($results);
}
/**
* Find a single row by column and value
*/
public function findBy(string $column, $value)
{
return $this->where([$column => $value])->first();
}
/**
* Find a single row by its primary key
*/
public function find($id)
{
return $this->findBy($this->primaryKeyName, $id);
}
/**
* Fires an insert query
*
* @param mixed $values You can pass values here or set them with ->values() before
* @return mixed Returns the last inserted id on success or false.
*/
public function insert($values = null)
{
$query = $this->execute(
$this->values($values)->build('insert')
);
if ($this->debug === true) {
return $query;
}
return $query ? $this->database->lastId() : false;
}
/**
* Fires an update 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
*/
public function update($values = null, $where = null): bool
{
return $this->execute(
$this->values($values)->where($where)->build('update')
);
}
/**
* Fires a delete query
*
* @param mixed $where You can pass a where clause here or set it with ->where() before
*/
public function delete($where = null): bool
{
return $this->execute(
$this->where($where)->build('delete')
);
}
/**
* Enables magic queries like findByUsername or findByEmail
*/
public function __call(string $method, array $arguments = [])
{
if (preg_match('!^findBy([a-z]+)!i', $method, $match)) {
$column = Str::lower($match[1]);
return $this->findBy($column, $arguments[0]);
}
throw new InvalidArgumentException(
message: 'Invalid query method: ' . $method,
code: static::ERROR_INVALID_QUERY_METHOD
);
}
/**
* Builder for where and having clauses
*
* @param array $args Arguments, see where() description
* @param mixed $current Current value (like $this->where)
*/
protected function filterQuery(
array $args,
$current,
string $mode = 'AND'
) {
$result = '';
switch (count($args)) {
case 1:
if ($args[0] === null) {
return $current;
}
// ->where('username like "myuser"');
if (is_string($args[0]) === true) {
// simply add the entire string to the where clause
// escaping or using bindings has to be done
// before calling this method
$result = $args[0];
// ->where(['username' => 'myuser']);
} elseif (is_array($args[0]) === true) {
// simple array mode (AND operator)
$sql = $this->database->sql()->values($this->table, $args[0], ' AND ', true, true);
$result = $sql['query'];
$this->bindings($sql['bindings']);
} elseif (is_callable($args[0]) === true) {
$query = clone $this;
// since the callback uses its own where condition
// it is necessary to clear/reset the cloned where condition
$query->where = null;
call_user_func($args[0], $query);
// copy over the bindings from the nested query
$this->bindings = [...$this->bindings, ...$query->bindings];
$result = '(' . $query->where . ')';
}
break;
case 2:
// ->where('username like :username', ['username' => 'myuser'])
if (
is_string($args[0]) === true &&
is_array($args[1]) === true
) {
// prepared where clause
$result = $args[0];
// store the bindings
$this->bindings($args[1]);
// ->where('username like ?', 'myuser')
} elseif (
is_string($args[0]) === true &&
is_scalar($args[1]) === true
) {
// prepared where clause
$result = $args[0];
// store the bindings
$this->bindings([$args[1]]);
}
break;
case 3:
// ->where('username', 'like', 'myuser');
if (
is_string($args[0]) === true &&
is_string($args[1]) === true
) {
// validate column
$sql = $this->database->sql();
$key = $sql->columnName($this->table, $args[0]);
// ->where('username', 'in', ['myuser', 'myotheruser']);
// ->where('quantity', 'between', [10, 50]);
$predicate = trim(strtoupper($args[1]));
if (is_array($args[2]) === true) {
if (in_array($predicate, ['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], true) === false) {
throw new InvalidArgumentException(
message: 'Invalid predicate ' . $predicate
);
}
// build a list of bound values
$values = [];
$bindings = [];
foreach ($args[2] as $value) {
$valueBinding = $sql->bindingName('value');
$bindings[$valueBinding] = $value;
$values[] = $valueBinding;
}
// add that to the where clause in parenthesis or seperated by AND
$values = match ($predicate) {
'IN',
'NOT IN' => '(' . implode(', ', $values) . ')',
'BETWEEN',
'NOT BETWEEN' => $values[0] . ' AND ' . $values[1]
};
$result = $key . ' ' . $predicate . ' ' . $values;
// ->where('username', 'like', 'myuser');
} else {
$predicates = [
'=', '>=', '>', '<=', '<', '<>', '!=', '<=>',
'IS', 'IS NOT',
'LIKE', 'NOT LIKE',
'SOUNDS LIKE',
'REGEXP', 'NOT REGEXP'
];
if (in_array($predicate, $predicates, true) === false) {
throw new InvalidArgumentException(
message: 'Invalid predicate/operator ' . $predicate
);
}
$valueBinding = $sql->bindingName('value');
$bindings[$valueBinding] = $args[2];
$result = $key . ' ' . $predicate . ' ' . $valueBinding;
}
$this->bindings($bindings);
}
break;
}
// attach the where clause
if (empty($current) === false) {
return $current . ' ' . $mode . ' ' . $result;
}
return $result;
}
}

962
kirby/src/Database/Sql.php Normal file
View file

@ -0,0 +1,962 @@
<?php
namespace Kirby\Database;
use Kirby\Exception\InvalidArgumentException;
use Kirby\Toolkit\A;
use Kirby\Toolkit\Str;
/**
* SQL Query builder
*
* @package Kirby Database
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://opensource.org/licenses/MIT
*/
abstract class Sql
{
/**
* List of literals which should not be escaped in queries
*/
public static array $literals = ['NOW()', null];
/**
* List of used bindings; used to avoid
* duplicate binding names
*/
protected array $bindings = [];
/**
* Constructor
* @codeCoverageIgnore
*/
public function __construct(
protected Database $database
) {
}
/**
* Returns a randomly generated binding name
*
* @param string $label String that only contains alphanumeric chars and
* underscores to use as a human-readable identifier
* @return string Binding name that is guaranteed to be unique for this connection
*/
public function bindingName(string $label): string
{
// make sure that the binding name is safe to prevent injections;
// otherwise use a generic label
if (!$label || preg_match('/^[a-zA-Z0-9_]+$/', $label) !== 1) {
$label = 'invalid';
}
// generate random bindings until the name is unique
do {
$binding = ':' . $label . '_' . Str::random(8, 'alphaNum');
} while (in_array($binding, $this->bindings, true) === true);
// cache the generated binding name for future invocations
$this->bindings[] = $binding;
return $binding;
}
/**
* Returns a query to list the columns of a specified table;
* the query needs to return rows with a column `name`
*
* @param string $table Table name
*/
abstract public function columns(string $table): array;
/**
* Returns a query snippet for a column default value
*
* @param string $name Column name
* @param array $column Column definition array with an optional `default` key
* @return array Array with a `query` string and a `bindings` array
*/
public function columnDefault(string $name, array $column): array
{
if (isset($column['default']) === false) {
return [
'query' => null,
'bindings' => []
];
}
$binding = $this->bindingName($name . '_default');
return [
'query' => 'DEFAULT ' . $binding,
'bindings' => [
$binding => $column['default']
]
];
}
/**
* Returns the cleaned identifier based on the table and column name
*
* @param string $table Table name
* @param string $column Column name
* @param bool $enforceQualified If true, a qualified identifier is returned in all cases
* @return string|null Identifier or null if the table or column is invalid
*/
public function columnName(
string $table,
string $column,
bool $enforceQualified = false
): string|null {
// ensure we have clean $table and $column values
// without qualified identifiers
[$table, $column] = $this->splitIdentifier($table, $column);
// combine the identifiers again
if ($this->database->validateColumn($table, $column) === true) {
return $this->combineIdentifier(
$table,
$column,
$enforceQualified !== true
);
}
// the table or column does not exist
return null;
}
/**
* Abstracted column types to simplify table
* creation for multiple database drivers
* @codeCoverageIgnore
*/
public function columnTypes(): array
{
return [
'id' => '{{ name }} INT(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY',
'varchar' => '{{ name }} varchar({{ size }}) {{ null }} {{ default }} {{ unique }}',
'text' => '{{ name }} TEXT {{ unique }}',
'int' => '{{ name }} INT(11) {{ unsigned }} {{ null }} {{ default }} {{ unique }}',
'timestamp' => '{{ name }} TIMESTAMP {{ null }} {{ default }} {{ unique }}',
'bool' => '{{ name }} TINYINT(1) {{ null }} {{ default }} {{ unique }}',
'float' => '{{ name }} DOUBLE {{ null }} {{ default }} {{ unique }}',
'decimal' => '{{ name }} DECIMAL({{ precision }}, {{ decimalPlaces }}) {{ null }} {{ default }} {{ unique }}'
];
}
/**
* Combines an identifier (table and column)
*
* @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 {
return $this->quoteIdentifier($table) . '.' . $this->quoteIdentifier($column);
}
/**
* Creates the CREATE TABLE syntax for a single column
*
* @param string $name Column name
* @param array $column Column definition array; valid keys:
* - `type` (required): Column template to use
* - `unsigned`: Whether an int column is signed or unsigned (boolean)
* - `size`: The size of varchar (int)
* - `precision`: The precision of a decimal type
* - `decimalPlaces`: The number of decimal places for a decimal type
* - `null`: Whether the column may be NULL (boolean)
* - `key`: Index this column is part of; special values `'primary'` for PRIMARY KEY and `true` for automatic naming
* - `unique`: Whether the index (or if not set the column itself) has a UNIQUE constraint
* - `default`: Default value of this column
* @return array Array with `query` and `key` strings, a `unique` boolean and a `bindings` array
* @throws \Kirby\Exception\InvalidArgumentException if no column type is given or the column type is not supported.
*/
public function createColumn(string $name, array $column): array
{
// column type
if (isset($column['type']) === false) {
throw new InvalidArgumentException(
message: 'No column type given for column ' . $name
);
}
$template = $this->columnTypes()[$column['type']] ?? null;
if (!$template) {
throw new InvalidArgumentException(
message: 'Unsupported column type: ' . $column['type']
);
}
// null option
if (A::get($column, 'null') === false) {
$null = 'NOT NULL';
} else {
$null = 'NULL';
}
// indexes/keys
if (isset($column['key']) === true) {
if (is_string($column['key']) === true) {
$column['key'] = strtolower($column['key']);
} elseif ($column['key'] === true) {
$column['key'] = $name . '_index';
}
}
// unsigned (defaults to true for backwards compatibility)
if (
isset($column['unsigned']) === true &&
$column['unsigned'] === false
) {
$unsigned = '';
} else {
$unsigned = 'UNSIGNED';
}
// unique
$uniqueKey = false;
$uniqueColumn = null;
if (
isset($column['unique']) === true &&
$column['unique'] === true
) {
if (isset($column['key']) === true) {
// this column is part of an index, make that unique
$uniqueKey = true;
} else {
// make the column itself unique
$uniqueColumn = 'UNIQUE';
}
}
// default value
$columnDefault = $this->columnDefault($name, $column);
$query = trim(Str::template($template, [
'name' => $this->quoteIdentifier($name),
'unsigned' => $unsigned,
'size' => $column['size'] ?? 255,
'precision' => $column['precision'] ?? 14,
'decimalPlaces' => $column['decimalPlaces'] ?? 4,
'null' => $null,
'default' => $columnDefault['query'],
'unique' => $uniqueColumn
], ['fallback' => '']));
return [
'query' => $query,
'bindings' => $columnDefault['bindings'],
'key' => $column['key'] ?? null,
'unique' => $uniqueKey
];
}
/**
* Creates the inner query for the columns in a CREATE TABLE query
*
* @param array $columns Array of column definition arrays, see `Kirby\Database\Sql::createColumn()`
* @return array Array with a `query` string and `bindings`, `keys` and `unique` arrays
*/
public function createTableInner(array $columns): array
{
$query = [];
$bindings = [];
$keys = [];
$unique = [];
foreach ($columns as $name => $column) {
$sql = $this->createColumn($name, $column);
// collect query and bindings
$query[] = $sql['query'];
$bindings += $sql['bindings'];
// make a list of keys per key name
if ($sql['key'] !== null) {
if (isset($keys[$sql['key']]) !== true) {
$keys[$sql['key']] = [];
}
$keys[$sql['key']][] = $name;
if ($sql['unique'] === true) {
$unique[$sql['key']] = true;
}
}
}
return [
'query' => implode(',' . PHP_EOL, $query),
'bindings' => $bindings,
'keys' => $keys,
'unique' => $unique
];
}
/**
* Creates a CREATE TABLE query
*
* @param string $table Table name
* @param array $columns Array of column definition arrays, see `Kirby\Database\Sql::createColumn()`
* @return array Array with a `query` string and a `bindings` array
*/
public function createTable(string $table, array $columns = []): array
{
$inner = $this->createTableInner($columns);
// add keys
foreach ($inner['keys'] as $key => $columns) {
// quote each column name and make a list string out of the column names
$columns = implode(', ', array_map(
fn ($name) => $this->quoteIdentifier($name),
$columns
));
if ($key === 'primary') {
$key = 'PRIMARY KEY';
} else {
$unique = isset($inner['unique'][$key]) ? 'UNIQUE ' : '';
$key = $unique . 'INDEX ' . $this->quoteIdentifier($key);
}
$inner['query'] .= ',' . PHP_EOL . $key . ' (' . $columns . ')';
}
return [
'query' => 'CREATE TABLE ' . $this->quoteIdentifier($table) . ' (' . PHP_EOL . $inner['query'] . PHP_EOL . ')',
'bindings' => $inner['bindings']
];
}
/**
* Builds a DELETE clause
*
* @param array $params List of parameters for the DELETE clause. See defaults for more info.
*/
public function delete(array $params = []): array
{
$options = [
'table' => '',
'where' => null,
'bindings' => [],
...$params
];
$bindings = $options['bindings'];
$query = ['DELETE'];
// from
$this->extend($query, $bindings, $this->from($options['table']));
// where
$this->extend($query, $bindings, $this->where($options['where']));
return [
'query' => $this->query($query),
'bindings' => $bindings
];
}
/**
* Creates the sql for dropping a single table
*/
public function dropTable(string $table): array
{
return [
'query' => 'DROP TABLE ' . $this->tableName($table),
'bindings' => []
];
}
/**
* Extends a given query and bindings
* by reference
*/
public function extend(
array &$query,
array &$bindings,
array $input
): void {
if (empty($input['query']) === false) {
$query[] = $input['query'];
$bindings = [...$bindings, ...$input['bindings']];
}
}
/**
* Creates the from syntax
*/
public function from(string $table): array
{
return [
'query' => 'FROM ' . $this->tableName($table),
'bindings' => []
];
}
/**
* Creates the group by syntax
*/
public function group(string|null $group = null): array
{
if (empty($group) === false) {
$query = 'GROUP BY ' . $group;
}
return [
'query' => $query ?? null,
'bindings' => []
];
}
/**
* Creates the having syntax
*/
public function having(string|null $having = null): array
{
if (empty($having) === false) {
$query = 'HAVING ' . $having;
}
return [
'query' => $query ?? null,
'bindings' => []
];
}
/**
* Creates an insert query
*/
public function insert(array $params = []): array
{
$table = $params['table'] ?? null;
$values = $params['values'] ?? null;
$bindings = $params['bindings'];
$query = ['INSERT INTO ' . $this->tableName($table)];
// add the values
$this->extend(
$query,
$bindings,
$this->values($table, $values, ', ', false)
);
return [
'query' => $this->query($query),
'bindings' => $bindings
];
}
/**
* Creates a join query
*
* @throws \Kirby\Exception\InvalidArgumentException if an invalid join type is given
*/
public function join(string $type, string $table, string $on): array
{
$types = [
'JOIN',
'INNER JOIN',
'OUTER JOIN',
'LEFT OUTER JOIN',
'LEFT JOIN',
'RIGHT OUTER JOIN',
'RIGHT JOIN',
'FULL OUTER JOIN',
'FULL JOIN',
'NATURAL JOIN',
'CROSS JOIN',
'SELF JOIN'
];
$type = strtoupper(trim($type));
// validate join type
if (in_array($type, $types, true) === false) {
throw new InvalidArgumentException(
message: 'Invalid join type ' . $type
);
}
return [
'query' => $type . ' ' . $this->tableName($table) . ' ON ' . $on,
'bindings' => [],
];
}
/**
* Create the syntax for multiple joins
*/
public function joins(array|null $joins = null): array
{
$query = [];
$bindings = [];
foreach ((array)$joins as $join) {
$this->extend(
$query,
$bindings,
$this->join(
$join['type'] ?? 'JOIN',
$join['table'] ?? null,
$join['on'] ?? null
)
);
}
return [
'query' => implode(' ', array_filter($query)),
'bindings' => [],
];
}
/**
* Creates a limit and offset query instruction
*/
public function limit(int $offset = 0, int|null $limit = null): array
{
// no need to add it to the query
if ($offset === 0 && $limit === null) {
return [
'query' => null,
'bindings' => []
];
}
$limit ??= '18446744073709551615';
$offsetBinding = $this->bindingName('offset');
$limitBinding = $this->bindingName('limit');
return [
'query' => 'LIMIT ' . $offsetBinding . ', ' . $limitBinding,
'bindings' => [
$limitBinding => $limit,
$offsetBinding => $offset,
]
];
}
/**
* Creates the order by syntax
*/
public function order(string|null $order = null): array
{
if (empty($order) === false) {
$query = 'ORDER BY ' . $order;
}
return [
'query' => $query ?? null,
'bindings' => []
];
}
/**
* Converts a query array into a final string
*/
public function query(array $query, string $separator = ' '): string
{
return implode($separator, array_filter($query));
}
/**
* Quotes an identifier (table *or* column)
*/
public function quoteIdentifier(string $identifier): string
{
// * is special, don't quote that
if ($identifier === '*') {
return $identifier;
}
// escape backticks inside the identifier name
$identifier = str_replace('`', '``', $identifier);
// wrap in backticks
return '`' . $identifier . '`';
}
/**
* Builds a select clause
*
* @param array $params List of parameters for the select clause. Check out the defaults for more info.
* @return array An array with the query and the bindings
*/
public function select(array $params = []): array
{
$options = [
'table' => '',
'columns' => '*',
'join' => null,
'distinct' => false,
'where' => null,
'group' => null,
'having' => null,
'order' => null,
'offset' => 0,
'limit' => null,
'bindings' => [],
...$params
];
$bindings = $options['bindings'];
$query = ['SELECT'];
// select distinct values
if ($options['distinct'] === true) {
$query[] = 'DISTINCT';
}
// columns
$query[] = $this->selected($options['table'], $options['columns']);
// from
$this->extend($query, $bindings, $this->from($options['table']));
// joins
$this->extend($query, $bindings, $this->joins($options['join']));
// where
$this->extend($query, $bindings, $this->where($options['where']));
// group
$this->extend($query, $bindings, $this->group($options['group']));
// having
$this->extend($query, $bindings, $this->having($options['having']));
// order
$this->extend($query, $bindings, $this->order($options['order']));
// offset and limit
$this->extend($query, $bindings, $this->limit($options['offset'], $options['limit']));
return [
'query' => $this->query($query),
'bindings' => $bindings
];
}
/**
* Creates a columns definition from string or array
*/
public function selected(string $table, array|string|null $columns = null): string
{
// all columns
if (empty($columns) === true) {
return '*';
}
// array of columns
if (is_array($columns) === true) {
// validate columns
$result = [];
foreach ($columns as $column) {
[$table, $columnPart] = $this->splitIdentifier($table, $column);
if ($this->validateColumn($table, $columnPart) === true) {
$result[] = $this->combineIdentifier($table, $columnPart);
}
}
return implode(', ', $result);
}
return $columns;
}
/**
* Splits a (qualified) identifier into table and column
*
* @param string $table Default table if the identifier is not qualified
* @throws \Kirby\Exception\InvalidArgumentException if an invalid identifier is given
*/
public function splitIdentifier(string $table, string $identifier): array
{
// split by dot, but only outside of quotes
$parts = preg_split('/(?:`[^`]*`|"[^"]*")(*SKIP)(*F)|\./', $identifier);
return match (count($parts)) {
// non-qualified identifier
1 => [$table, $this->unquoteIdentifier($parts[0])],
// qualified identifier
2 => [
$this->unquoteIdentifier($parts[0]),
$this->unquoteIdentifier($parts[1])
],
// every other number is an error
default => throw new InvalidArgumentException(
message: 'Invalid identifier ' . $identifier
)
};
}
/**
* Returns a query to list the tables of the current database;
* the query needs to return rows with a column `name`
*/
abstract public function tables(): array;
/**
* Validates and quotes a table name
*
* @throws \Kirby\Exception\InvalidArgumentException if an invalid table name is given
*/
public function tableName(string $table): string
{
// validate table
if ($this->database->validateTable($table) === false) {
throw new InvalidArgumentException(
message: 'Invalid table ' . $table
);
}
return $this->quoteIdentifier($table);
}
/**
* Unquotes an identifier (table *or* column)
*/
public function unquoteIdentifier(string $identifier): string
{
// remove quotes around the identifier
if (
str_starts_with($identifier, '"') ||
str_starts_with($identifier, '`')
) {
$identifier = Str::substr($identifier, 1);
}
if (
str_ends_with($identifier, '"') ||
str_ends_with($identifier, '`')
) {
$identifier = Str::substr($identifier, 0, -1);
}
// unescape duplicated quotes
return str_replace(['""', '``'], ['"', '`'], $identifier);
}
/**
* Builds an update clause
*
* @param array $params List of parameters for the update clause. See defaults for more info.
*/
public function update(array $params = []): array
{
$options = [
'table' => null,
'values' => null,
'where' => null,
'bindings' => [],
...$params
];
$bindings = $options['bindings'];
// start the query
$query = ['UPDATE ' . $this->tableName($options['table']) . ' SET'];
// add the values
$this->extend(
$query,
$bindings,
$this->values($options['table'], $options['values'])
);
// add the where clause
$this->extend(
$query,
$bindings,
$this->where($options['where'])
);
return [
'query' => $this->query($query),
'bindings' => $bindings
];
}
/**
* Validates a given column name in a table
*
* @throws \Kirby\Exception\InvalidArgumentException If the column is invalid
*/
public function validateColumn(string $table, string $column): bool
{
if ($this->database->validateColumn($table, $column) !== true) {
throw new InvalidArgumentException(
message: 'Invalid column ' . $column
);
}
return true;
}
/**
* Builds a safe list of values for insert, select or update queries
*
* @param string $table Table name
* @param mixed $values A value string or array of values
* @param string $separator A separator which should be used to join values
* @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 {
if (is_array($values) === false) {
return [
'query' => $values,
'bindings' => []
];
}
if ($set === true) {
return $this->valueSet(
$table,
$values,
$separator,
$enforceQualified
);
}
return $this->valueList(
$table,
$values,
$separator,
$enforceQualified
);
}
/**
* Creates a list of fields and values
*/
public function valueList(
string $table,
string|array $values,
string $separator = ',',
bool $enforceQualified = false
): array {
$fields = [];
$query = [];
$bindings = [];
foreach ($values as $column => $value) {
$key = $this->columnName($table, $column, $enforceQualified);
if ($key === null) {
continue;
}
$fields[] = $key;
if (in_array($value, static::$literals, true) === true) {
$query[] = $value ?: 'null';
continue;
}
if (is_array($value) === true) {
$value = json_encode($value);
}
// add the binding
$bindings[$bindingName = $this->bindingName('value')] = $value;
// create the query
$query[] = $bindingName;
}
return [
'query' => '(' . implode($separator, $fields) . ') VALUES (' . implode($separator, $query) . ')',
'bindings' => $bindings
];
}
/**
* Creates a set of values
*/
public function valueSet(
string $table,
string|array $values,
string $separator = ',',
bool $enforceQualified = false
): array {
$query = [];
$bindings = [];
foreach ($values as $column => $value) {
$key = $this->columnName($table, $column, $enforceQualified);
if ($key === null) {
continue;
}
if (in_array($value, static::$literals, true) === true) {
$query[] = $key . ' = ' . ($value ?: 'null');
continue;
}
if (is_array($value) === true) {
$value = json_encode($value);
}
// add the binding
$bindings[$bindingName = $this->bindingName('value')] = $value;
// create the query
$query[] = $key . ' = ' . $bindingName;
}
return [
'query' => implode($separator, $query),
'bindings' => $bindings
];
}
public function where(string|array|null $where, array $bindings = []): array
{
if (empty($where) === true) {
return [
'query' => null,
'bindings' => [],
];
}
if (is_string($where) === true) {
return [
'query' => 'WHERE ' . $where,
'bindings' => $bindings
];
}
$query = [];
foreach ($where as $key => $value) {
$binding = $this->bindingName('where_' . $key);
$bindings[$binding] = $value;
$query[] = $key . ' = ' . $binding;
}
return [
'query' => 'WHERE ' . implode(' AND ', $query),
'bindings' => $bindings
];
}
}

View file

@ -0,0 +1,56 @@
<?php
namespace Kirby\Database\Sql;
use Kirby\Database\Sql;
/**
* MySQL query builder
*
* @package Kirby Database
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://opensource.org/licenses/MIT
*/
class Mysql extends Sql
{
/**
* Returns a query to list the columns of a specified table;
* the query needs to return rows with a column `name`
*
* @param string $table Table name
*/
public function columns(string $table): array
{
$databaseBinding = $this->bindingName('database');
$tableBinding = $this->bindingName('table');
$query = 'SELECT COLUMN_NAME AS name FROM INFORMATION_SCHEMA.COLUMNS ';
$query .= 'WHERE TABLE_SCHEMA = ' . $databaseBinding . ' AND TABLE_NAME = ' . $tableBinding;
return [
'query' => $query,
'bindings' => [
$databaseBinding => $this->database->name(),
$tableBinding => $table,
]
];
}
/**
* Returns a query to list the tables of the current database;
* the query needs to return rows with a column `name`
*/
public function tables(): array
{
$binding = $this->bindingName('database');
return [
'query' => 'SELECT TABLE_NAME AS name FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ' . $binding,
'bindings' => [
$binding => $this->database->name()
]
];
}
}

View file

@ -0,0 +1,144 @@
<?php
namespace Kirby\Database\Sql;
use Kirby\Database\Sql;
/**
* SQLite query builder
*
* @package Kirby Database
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://opensource.org/licenses/MIT
*/
class Sqlite extends Sql
{
/**
* Returns a query to list the columns of a specified table;
* the query needs to return rows with a column `name`
*
* @param string $table Table name
*/
public function columns(string $table): array
{
return [
'query' => 'PRAGMA table_info(' . $this->tableName($table) . ')',
'bindings' => [],
];
}
/**
* Abstracted column types to simplify table
* creation for multiple database drivers
* @codeCoverageIgnore
*/
public function columnTypes(): array
{
return [
'id' => '{{ name }} INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE',
'varchar' => '{{ name }} TEXT {{ null }} {{ default }} {{ unique }}',
'text' => '{{ name }} TEXT {{ null }} {{ default }} {{ unique }}',
'int' => '{{ name }} INTEGER {{ null }} {{ default }} {{ unique }}',
'timestamp' => '{{ name }} INTEGER {{ null }} {{ default }} {{ unique }}',
'bool' => '{{ name }} INTEGER {{ null }} {{ default }} {{ unique }}',
'float' => '{{ name }} REAL {{ null }} {{ default }} {{ unique }}',
'decimal' => '{{ name }} REAL {{ null }} {{ default }} {{ unique }}'
];
}
/**
* Combines an identifier (table and column)
*
* @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 {
// SQLite doesn't support qualified column names for VALUES clauses
if ($values === true) {
return $this->quoteIdentifier($column);
}
return $this->quoteIdentifier($table) . '.' . $this->quoteIdentifier($column);
}
/**
* Creates a CREATE TABLE query
*
* @param string $table Table name
* @param array $columns Array of column definition arrays, see `Kirby\Database\Sql::createColumn()`
* @return array Array with a `query` string and a `bindings` array
*/
public function createTable(
string $table,
array $columns = []
): array {
$inner = $this->createTableInner($columns);
$keys = [];
// add keys
foreach ($inner['keys'] as $key => $columns) {
// quote each column name and
// make a list string out of the column names
$columns = implode(', ', array_map(
fn ($name) => $this->quoteIdentifier($name),
$columns
));
if ($key === 'primary') {
$inner['query'] .= ',' . PHP_EOL . 'PRIMARY KEY (' . $columns . ')';
} else {
// SQLite only supports index creation
// using a separate CREATE INDEX query
$unique = isset($inner['unique'][$key]) ? 'UNIQUE ' : '';
$keys[] = 'CREATE ' . $unique . 'INDEX ' . $this->quoteIdentifier($table . '_index_' . $key) . ' ON ' . $this->quoteIdentifier($table) . ' (' . $columns . ')';
}
}
$query = 'CREATE TABLE ' . $this->quoteIdentifier($table) . ' (' . PHP_EOL . $inner['query'] . PHP_EOL . ')';
if ($keys !== []) {
$query .= ';' . PHP_EOL . implode(';' . PHP_EOL, $keys);
}
return [
'query' => $query,
'bindings' => $inner['bindings']
];
}
/**
* Quotes an identifier (table *or* column)
*/
public function quoteIdentifier(string $identifier): string
{
// * is special
if ($identifier === '*') {
return $identifier;
}
// escape quotes inside the identifier name
$identifier = str_replace('"', '""', $identifier);
// wrap in quotes
return '"' . $identifier . '"';
}
/**
* Returns a query to list the tables of the current database;
* the query needs to return rows with a column `name`
*/
public function tables(): array
{
return [
'query' => 'SELECT name FROM sqlite_master WHERE type = \'table\' OR type = \'view\'',
'bindings' => []
];
}
}