This commit is contained in:
Bastian Allgeier
2020-07-07 12:40:13 +02:00
parent 5f025ac2c2
commit f79d2e960c
176 changed files with 10532 additions and 5343 deletions

View File

@@ -2,6 +2,7 @@
namespace Kirby\Database;
use Closure;
use Exception;
use Kirby\Exception\InvalidArgumentException;
use Kirby\Toolkit\A;
@@ -230,7 +231,7 @@ class Database
}
/**
* Sets the exception mode for the next query
* Sets the exception mode
*
* @param bool $fail
* @return \Kirby\Database\Database
@@ -369,7 +370,7 @@ class Database
$this->statement->execute($bindings);
$this->affected = $this->statement->rowCount();
$this->lastId = $this->connection->lastInsertId();
$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
@@ -395,9 +396,6 @@ class Database
'error' => $this->lastError
]);
// reset some stuff
$this->fail = false;
// return true or false on success or failure
return $this->lastError === null;
}
@@ -426,7 +424,11 @@ class Database
}
// define the default flag for the fetch method
$flags = $options['fetch'] === 'array' ? PDO::FETCH_ASSOC : PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE;
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) {
@@ -434,7 +436,7 @@ class Database
}
// set the fetch mode
if ($options['fetch'] === 'array') {
if ($options['fetch'] instanceof Closure || $options['fetch'] === 'array') {
$this->statement->setFetchMode($flags);
} else {
$this->statement->setFetchMode($flags, $options['fetch']);
@@ -443,6 +445,13 @@ class Database
// fetch that stuff
$results = $this->statement->{$options['method']}();
// apply the fetch closure to all results if given
if ($options['fetch'] instanceof Closure) {
foreach ($results as $key => $result) {
$results[$key] = $options['fetch']($result, $key);
}
}
if ($options['iterator'] === 'array') {
return $this->lastResult = $results;
}
@@ -559,6 +568,11 @@ class Database
}
}
// update cache
if (in_array($table, $this->tableWhitelist) !== true) {
$this->tableWhitelist[] = $table;
}
return true;
}
@@ -571,7 +585,17 @@ class Database
public function dropTable($table): bool
{
$sql = $this->sql()->dropTable($table);
return $this->execute($sql['query'], $sql['bindings']);
if ($this->execute($sql['query'], $sql['bindings']) !== true) {
return false;
}
// update cache
$key = array_search($this->tableWhitelist, $table);
if ($key !== false) {
unset($this->tableWhitelist[$key]);
}
return true;
}
/**

View File

@@ -2,7 +2,7 @@
namespace Kirby\Database;
use InvalidArgumentException;
use Kirby\Exception\InvalidArgumentException;
use Kirby\Toolkit\Config;
/**
@@ -16,8 +16,6 @@ use Kirby\Toolkit\Config;
*/
class Db
{
const ERROR_UNKNOWN_METHOD = 0;
/**
* Query shortcuts
*
@@ -35,10 +33,11 @@ class Db
/**
* (Re)connect the database
*
* @param array $params Pass [] to use the default params from the config
* @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 $params = null)
public static function connect(?array $params = null)
{
if ($params === null && static::$connection !== null) {
return static::$connection;
@@ -46,14 +45,15 @@ class Db
// try to connect with the default
// connection settings if no params are set
$params = $params ?? [
$defaults = [
'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', ''),
'prefix' => Config::get('db.prefix', '')
];
$params = $params ?? $defaults;
return static::$connection = new Database($params);
}
@@ -61,7 +61,7 @@ class Db
/**
* Returns the current database connection
*
* @return \Kirby\Database\Database
* @return \Kirby\Database\Database|null
*/
public static function connection()
{
@@ -69,7 +69,7 @@ class Db
}
/**
* Sets the current table, which should be queried. Returns a
* Sets the current table which should be queried. Returns a
* Query object, which can be used to build a full query for
* that table.
*
@@ -83,7 +83,7 @@ class Db
}
/**
* Executes a raw sql query which expects a set of results
* Executes a raw SQL query which expects a set of results
*
* @param string $query
* @param array $bindings
@@ -97,21 +97,22 @@ class Db
}
/**
* Executes a raw sql query which expects no set of results (i.e. update, insert, delete)
* Executes a raw SQL query which expects no set of results (i.e. update, insert, delete)
*
* @param string $query
* @param array $bindings
* @return mixed
* @return bool
*/
public static function execute(string $query, array $bindings = [])
public static function execute(string $query, array $bindings = []): bool
{
$db = static::connect();
return $db->execute($query, $bindings);
}
/**
* Magic calls for other static db methods,
* which are redircted to the database class if available
* Magic calls for other static Db methods are
* redirected to either a predefined query or
* the respective method of the Database object
*
* @param string $method
* @param mixed $arguments
@@ -123,20 +124,21 @@ class Db
return static::$queries[$method](...$arguments);
}
if (is_callable([static::$connection, $method]) === true) {
if (static::$connection !== null && method_exists(static::$connection, $method) === true) {
return call_user_func_array([static::$connection, $method], $arguments);
}
throw new InvalidArgumentException('Invalid static Db method: ' . $method, static::ERROR_UNKNOWN_METHOD);
throw new InvalidArgumentException('Invalid static Db method: ' . $method);
}
}
/**
* Shortcut for select clauses
* Shortcut for SELECT clauses
* @codeCoverageIgnore
*
* @param string $table The name of the table, which should be queried
* @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 mixed $where The WHERE clause; can be a string or an array
* @param string $order
* @param int $offset
* @param int $limit
@@ -148,10 +150,11 @@ Db::$queries['select'] = function (string $table, $columns = '*', $where = null,
/**
* Shortcut for selecting a single row in a table
* @codeCoverageIgnore
*
* @param string $table The name of the table, which should be queried
* @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 mixed $where The WHERE clause; can be a string or an array
* @param string $order
* @param int $offset
* @param int $limit
@@ -163,10 +166,11 @@ Db::$queries['first'] = Db::$queries['row'] = Db::$queries['one'] = function (st
/**
* Returns only values from a single column
* @codeCoverageIgnore
*
* @param string $table The name of the table, which should be queried
* @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 mixed $where The WHERE clause; can be a string or an array
* @param string $order
* @param int $offset
* @param int $limit
@@ -178,93 +182,101 @@ Db::$queries['column'] = function (string $table, string $column, $where = null,
/**
* Shortcut for inserting a new row into a table
* @codeCoverageIgnore
*
* @param string $table The name of the table, which should be queried
* @param array $values An array of values, which should be inserted
* @return bool
* @param string $table The name of the table which should be queried
* @param array $values An array of values which should be inserted
* @return int ID of the inserted row
*/
Db::$queries['insert'] = function (string $table, array $values) {
Db::$queries['insert'] = function (string $table, array $values): int {
return Db::table($table)->insert($values);
};
/**
* Shortcut for updating a row in a table
* @codeCoverageIgnore
*
* @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
* @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) {
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
* @codeCoverageIgnore
*
* @param string $table The name of the table, which should be queried
* @param mixed $where An optional where clause
* @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) {
Db::$queries['delete'] = function (string $table, $where = null): bool {
return Db::table($table)->where($where)->delete();
};
/**
* Shortcut for counting rows in a table
* @codeCoverageIgnore
*
* @param string $table The name of the table, which should be queried
* @param mixed $where An optional where clause
* @param string $table The name of the table which should be queried
* @param mixed $where An optional WHERE clause
* @return int
*/
Db::$queries['count'] = function (string $table, $where = null) {
Db::$queries['count'] = function (string $table, $where = null): int {
return Db::table($table)->where($where)->count();
};
/**
* Shortcut for calculating the minimum value in a column
* @codeCoverageIgnore
*
* @param string $table The name of the table, which should be queried
* @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 mixed
* @param mixed $where An optional WHERE clause
* @return float
*/
Db::$queries['min'] = function (string $table, string $column, $where = null) {
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
* @codeCoverageIgnore
*
* @param string $table The name of the table, which should be queried
* @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 mixed
* @param mixed $where An optional WHERE clause
* @return float
*/
Db::$queries['max'] = function (string $table, string $column, $where = null) {
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
* @codeCoverageIgnore
*
* @param string $table The name of the table, which should be queried
* @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 mixed
* @param mixed $where An optional WHERE clause
* @return float
*/
Db::$queries['avg'] = function (string $table, string $column, $where = null) {
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
* @codeCoverageIgnore
*
* @param string $table The name of the table, which should be queried
* @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 mixed
* @param mixed $where An optional WHERE clause
* @return float
*/
Db::$queries['sum'] = function (string $table, string $column, $where = null) {
Db::$queries['sum'] = function (string $table, string $column, $where = null): float {
return Db::table($table)->where($where)->sum($column);
};

View File

@@ -30,8 +30,9 @@ class Query
/**
* The object which should be fetched for each row
* or function to call for each row
*
* @var string
* @var string|\Closure
*/
protected $fetch = 'Kirby\Toolkit\Obj';
@@ -219,13 +220,14 @@ class Query
}
/**
* Sets the object class, which should be fetched
* Set this to array to get a simple array instead of an object
* 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
*
* @param string $fetch
* @param string|\Closure $fetch
* @return \Kirby\Database\Query
*/
public function fetch(string $fetch)
public function fetch($fetch)
{
$this->fetch = $fetch;
return $this;
@@ -559,55 +561,55 @@ class Query
/**
* Builds a count query
*
* @return \Kirby\Database\Query
* @return int
*/
public function count()
public function count(): int
{
return $this->aggregate('COUNT');
return (int)$this->aggregate('COUNT');
}
/**
* Builds a max query
*
* @param string $column
* @return \Kirby\Database\Query
* @return float
*/
public function max(string $column)
public function max(string $column): float
{
return $this->aggregate('MAX', $column);
return (float)$this->aggregate('MAX', $column);
}
/**
* Builds a min query
*
* @param string $column
* @return \Kirby\Database\Query
* @return float
*/
public function min(string $column)
public function min(string $column): float
{
return $this->aggregate('MIN', $column);
return (float)$this->aggregate('MIN', $column);
}
/**
* Builds a sum query
*
* @param string $column
* @return \Kirby\Database\Query
* @return float
*/
public function sum(string $column)
public function sum(string $column): float
{
return $this->aggregate('SUM', $column);
return (float)$this->aggregate('SUM', $column);
}
/**
* Builds an average query
*
* @param string $column
* @return \Kirby\Database\Query
* @return float
*/
public function avg(string $column)
public function avg(string $column): float
{
return $this->aggregate('AVG', $column);
return (float)$this->aggregate('AVG', $column);
}
/**
@@ -812,10 +814,16 @@ class Query
*/
public function column($column)
{
$sql = $this->database->sql();
$primaryKey = $sql->combineIdentifier($this->table, $this->primaryKeyName);
// 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();
$primaryKey = $sql->combineIdentifier($this->table, $this->primaryKeyName);
$results = $this->query($this->select([$column])->order($primaryKey . ' ASC')->build('select'), [
$this->order($primaryKey . ' ASC');
}
$results = $this->query($this->select([$column])->build('select'), [
'iterator' => 'array',
'fetch' => 'array',
]);

View File

@@ -15,7 +15,7 @@ use Kirby\Toolkit\Str;
* @copyright Bastian Allgeier GmbH
* @license https://opensource.org/licenses/MIT
*/
class Sql
abstract class Sql
{
/**
* List of literals which should not be escaped in queries
@@ -27,12 +27,21 @@ class Sql
/**
* The parent database connection
*
* @var Database
* @var \Kirby\Database\Database
*/
public $database;
protected $database;
/**
* List of used bindings; used to avoid
* duplicate binding names
*
* @var array
*/
protected $bindings = [];
/**
* Constructor
* @codeCoverageIgnore
*
* @param \Kirby\Database\Database $database
*/
@@ -44,51 +53,45 @@ class Sql
/**
* Returns a randomly generated binding name
*
* @param string $label String that contains lowercase letters and numbers to use as a readable identifier
* @param string $prefix
* @return string
* @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 valid to prevent injections
if (!preg_match('/^[a-z0-9_]+$/', $label)) {
// 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';
}
return ':' . $label . '_' . Str::random(16);
// generate random bindings until the name is unique
do {
$binding = ':' . $label . '_' . Str::random(8, 'alphaNum');
} while (in_array($binding, $this->bindings) === true);
// cache the generated binding name for future invocations
$this->bindings[] = $binding;
return $binding;
}
/**
* Returns a list of columns for a specified table
* MySQL version
* Returns a query to list the columns of a specified table;
* the query needs to return rows with a column `name`
*
* @param string $table The table name
* @param string $table Table name
* @return array
*/
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,
]
];
}
abstract public function columns(string $table): array;
/**
* Optionl default value definition for the column
* Returns a query snippet for a column default value
*
* @param array $column
* @return array
* @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(array $column): array
public function columnDefault(string $name, array $column): array
{
if (isset($column['default']) === false) {
return [
@@ -97,74 +100,63 @@ class Sql
];
}
$binding = $this->bindingName($column['name'] . '_default');
$binding = $this->bindingName($name . '_default');
return [
'query' => 'DEFAULT ' . $binding,
'bindings' => [
$binding = $column['default']
$binding => $column['default']
]
];
}
/**
* Returns a valid column name
* Returns the cleaned identifier based on the table and column name
*
* @param string $table
* @param string $column
* @param bool $enforceQualified
* @return string|null
* @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
{
// ensure we have clean $table and $column values without qualified identifiers
list($table, $column) = $this->splitIdentifier($table, $column);
if ($this->validateColumn($table, $column) === true) {
// 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
*
* @return array
*/
public function columnTypes(): array
{
return [
'id' => '{{ name }} INT(11) UNSIGNED NOT NULL AUTO_INCREMENT',
'varchar' => '{{ name }} varchar(255) {{ null }} {{ default }}',
'text' => '{{ name }} TEXT',
'int' => '{{ name }} INT(11) UNSIGNED {{ null }} {{ default }}',
'timestamp' => '{{ name }} TIMESTAMP {{ null }} {{ default }}'
];
}
/**
* Optional key definition for the column.
*
* @param array $column
* @return array
*/
public function columnKey(array $column): array
{
return [
'query' => null,
'bindings' => []
'id' => '{{ name }} INT(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY',
'varchar' => '{{ name }} varchar(255) {{ null }} {{ default }} {{ unique }}',
'text' => '{{ name }} TEXT {{ unique }}',
'int' => '{{ name }} INT(11) UNSIGNED {{ null }} {{ default }} {{ unique }}',
'timestamp' => '{{ name }} TIMESTAMP {{ null }} {{ default }} {{ unique }}'
];
}
/**
* Combines an identifier (table and column)
* Default version for MySQL
*
* @param $table string
* @param $column string
* @param $values boolean Whether the identifier is going to be used for a values clause
* Only relevant for SQLite
* @param $values boolean 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
@@ -173,33 +165,29 @@ class Sql
}
/**
* Creates the create syntax for a single column
* Creates the CREATE TABLE syntax for a single column
*
* @param string $table
* @param array $column
* @return array
* @param string $name Column name
* @param array $column Column definition array; valid keys:
* - `type` (required): Column template to use
* - `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
*/
public function createColumn(string $table, array $column): array
public function createColumn(string $name, array $column): array
{
// column type
if (isset($column['type']) === false) {
throw new InvalidArgumentException('No column type given for column ' . $column);
throw new InvalidArgumentException('No column type given for column ' . $name);
}
// column name
if (isset($column['name']) === false) {
throw new InvalidArgumentException('No column name given');
}
if ($column['type'] === 'id') {
$column['key'] = 'PRIMARY';
}
if (!$template = ($this->columnTypes()[$column['type']] ?? null)) {
$template = $this->columnTypes()[$column['type']] ?? null;
if (!$template) {
throw new InvalidArgumentException('Unsupported column type: ' . $column['type']);
}
// null
// null option
if (A::get($column, 'null') === false) {
$null = 'NOT NULL';
} else {
@@ -207,85 +195,124 @@ class Sql
}
// indexes/keys
$key = false;
if (isset($column['key']) === true) {
$column['key'] = strtoupper($column['key']);
// backwards compatibility
if ($column['key'] === 'PRIMARY') {
$column['key'] = 'PRIMARY KEY';
if (is_string($column['key']) === true) {
$column['key'] = strtolower($column['key']);
} elseif ($column['key'] === true) {
$column['key'] = $name . '_index';
}
}
if (in_array($column['key'], ['PRIMARY KEY', 'INDEX']) === true) {
$key = $column['key'];
// 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($column);
$columnKey = $this->columnKey($column);
$columnDefault = $this->columnDefault($name, $column);
$query = trim(Str::template($template, [
'name' => $this->quoteIdentifier($column['name']),
'name' => $this->quoteIdentifier($name),
'null' => $null,
'key' => $columnKey['query'],
'default' => $columnDefault['query'],
]));
$bindings = array_merge($columnKey['bindings'], $columnDefault['bindings']);
'unique' => $uniqueColumn
], ''));
return [
'query' => $query,
'bindings' => $bindings,
'key' => $key
'bindings' => $columnDefault['bindings'],
'key' => $column['key'] ?? null,
'unique' => $uniqueKey
];
}
/**
* Creates a table with a simple scheme array for columns
* Default version for MySQL
* Creates the inner query for the columns in a CREATE TABLE query
*
* @param string $table The table name
* @param array $columns
* @return array
* @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 createTable(string $table, array $columns = []): array
public function createTableInner(array $columns): array
{
$output = [];
$keys = [];
$query = [];
$bindings = [];
$keys = [];
$unique = [];
foreach ($columns as $name => $column) {
$sql = $this->createColumn($table, $column);
$sql = $this->createColumn($name, $column);
$output[] = $sql['query'];
// collect query and bindings
$query[] = $sql['query'];
$bindings += $sql['bindings'];
if ($sql['key']) {
$keys[$column['name']] = $sql['key'];
// 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;
}
}
$bindings = array_merge($bindings, $sql['bindings']);
}
// combine columns
$inner = implode(',' . PHP_EOL, $output);
// add keys
foreach ($keys as $name => $key) {
$inner .= ',' . PHP_EOL . $key . ' (' . $this->quoteIdentifier($name) . ')';
}
return [
'query' => 'CREATE TABLE ' . $this->quoteIdentifier($table) . ' (' . PHP_EOL . $inner . PHP_EOL . ')',
'bindings' => $bindings
'query' => implode(',' . PHP_EOL, $query),
'bindings' => $bindings,
'keys' => $keys,
'unique' => $unique
];
}
/**
* Builds a delete clause
* Creates a CREATE TABLE query
*
* @param array $params List of parameters for the delete clause. See defaults for more info.
* @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(function ($name) {
return $this->quoteIdentifier($name);
}, $columns));
if ($key === 'primary') {
$key = 'PRIMARY KEY';
} else {
$unique = isset($inner['unique'][$key]) === true ? '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.
* @return array
*/
public function delete(array $params = []): array
@@ -546,19 +573,18 @@ class Sql
/**
* Quotes an identifier (table *or* column)
* Default version for MySQL
*
* @param $identifier string
* @return string
*/
public function quoteIdentifier(string $identifier): string
{
// * is special
// * is special, don't quote that
if ($identifier === '*') {
return $identifier;
}
// replace every backtick with two backticks
// escape backticks inside the identifier name
$identifier = str_replace('`', '``', $identifier);
// wrap in backticks
@@ -688,22 +714,12 @@ class Sql
}
/**
* Returns a list of tables for a specified database
* MySQL version
* 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
{
$binding = $this->bindingName('database');
return [
'query' => 'SELECT TABLE_NAME AS name FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ' . $binding,
'bindings' => [
$binding => $this->database->name()
]
];
}
abstract public function tables(): array;
/**
* Validates and quotes a table name
@@ -781,10 +797,12 @@ class Sql
* @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
{
if ($this->database->validateColumn($table, $column) === false) {
if ($this->database->validateColumn($table, $column) !== true) {
throw new InvalidArgumentException('Invalid column ' . $column);
}

View File

@@ -5,7 +5,7 @@ namespace Kirby\Database\Sql;
use Kirby\Database\Sql;
/**
* Mysql query builder
* MySQL query builder
*
* @package Kirby Database
* @author Bastian Allgeier <bastian@getkirby.com>
@@ -15,4 +15,45 @@ use Kirby\Database\Sql;
*/
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
* @return array
*/
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`
*
* @return array
*/
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

@@ -5,7 +5,7 @@ namespace Kirby\Database\Sql;
use Kirby\Database\Sql;
/**
* Sqlite query builder
* SQLite query builder
*
* @package Kirby Database
* @author Bastian Allgeier <bastian@getkirby.com>
@@ -16,11 +16,11 @@ use Kirby\Database\Sql;
class Sqlite extends Sql
{
/**
* Returns a list of columns for a specified table
* SQLite version
* Returns a query to list the columns of a specified table;
* the query needs to return rows with a column `name`
*
* @param string $table The table name
* @return string
* @param string $table Table name
* @return array
*/
public function columns(string $table): array
{
@@ -30,30 +30,10 @@ class Sqlite extends Sql
];
}
/**
* Optional key definition for the column.
*
* @param array $column
* @return array
*/
public function columnKey(array $column): array
{
if (isset($column['key']) === false || $column['key'] === 'INDEX') {
return [
'query' => null,
'bindings' => []
];
}
return [
'query' => $column['key'],
'bindings' => []
];
}
/**
* Abstracted column types to simplify table
* creation for multiple database drivers
* @codeCoverageIgnore
*
* @return array
*/
@@ -61,33 +41,72 @@ class Sqlite extends Sql
{
return [
'id' => '{{ name }} INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE',
'varchar' => '{{ name }} TEXT {{ null }} {{ key }} {{ default }}',
'text' => '{{ name }} TEXT {{ null }} {{ key }} {{ default }}',
'int' => '{{ name }} INTEGER {{ null }} {{ key }} {{ default }}',
'timestamp' => '{{ name }} INTEGER {{ null }} {{ key }} {{ default }}'
'varchar' => '{{ name }} TEXT {{ null }} {{ default }} {{ unique }}',
'text' => '{{ name }} TEXT {{ null }} {{ default }} {{ unique }}',
'int' => '{{ name }} INTEGER {{ null }} {{ default }} {{ unique }}',
'timestamp' => '{{ name }} INTEGER {{ null }} {{ default }} {{ unique }}'
];
}
/**
* Combines an identifier (table and column)
* SQLite version
*
* @param $table string
* @param $column string
* @param $values boolean Whether the identifier is going to be used for a values clause
* Only relevant for SQLite
* @param $values boolean 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
{
// SQLite doesn't support qualified column names for VALUES clauses
if ($values) {
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);
// add keys
$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(function ($name) {
return $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]) === true ? '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 (empty($keys) === false) {
$query .= ';' . PHP_EOL . implode(';' . PHP_EOL, $keys);
}
return [
'query' => $query,
'bindings' => $inner['bindings']
];
}
/**
* Quotes an identifier (table *or* column)
*
@@ -101,7 +120,7 @@ class Sqlite extends Sql
return $identifier;
}
// replace every quote with two quotes
// escape quotes inside the identifier name
$identifier = str_replace('"', '""', $identifier);
// wrap in quotes
@@ -109,10 +128,9 @@ class Sqlite extends Sql
}
/**
* Returns a list of tables of the database
* SQLite version
* Returns a query to list the tables of the current database;
* the query needs to return rows with a column `name`
*
* @param string $database The database name
* @return string
*/
public function tables(): array