first version

This commit is contained in:
Bastian Allgeier
2019-01-13 23:17:34 +01:00
commit 01277f79f2
595 changed files with 82913 additions and 0 deletions

621
kirby/src/Database/Database.php Executable file
View File

@@ -0,0 +1,621 @@
<?php
namespace Kirby\Database;
use Exception;
use Kirby\Exception\InvalidArgumentException;
use Kirby\Toolkit\A;
use Kirby\Toolkit\Str;
use PDO;
use PDOStatement;
use Throwable;
/**
* A simple database class
*/
class Database
{
/**
* The number of affected rows for the last query
*
* @var int|null
*/
protected $affected;
/**
* Whitelist for column names
*
* @var array
*/
protected $columnWhitelist = [];
/**
* The established connection
*
* @var PDO|null
*/
protected $connection;
/**
* A global array of started connections
*
* @var array
*/
public static $connections = [];
/**
* Database name
*
* @var string
*/
protected $database;
/**
* @var string
*/
protected $dsn;
/**
* Set to true to throw exceptions on failed queries
*
* @var boolean
*/
protected $fail = false;
/**
* The connection id
*
* @var string
*/
protected $id;
/**
* The last error
*
* @var Exception|null
*/
protected $lastError;
/**
* The last insert id
*
* @var int|null
*/
protected $lastId;
/**
* The last query
*
* @var string
*/
protected $lastQuery;
/**
* The last result set
*
* @var mixed
*/
protected $lastResult;
/**
* Optional prefix for table names
*
* @var string
*/
protected $prefix;
/**
* The PDO query statement
*
* @var PDOStatement|null
*/
protected $statement;
/**
* Whitelists for table names
*
* @var array|null
*/
protected $tableWhitelist;
/**
* An array with all queries which are being made
*
* @var array
*/
protected $trace = [];
/**
* The database type (mysql, sqlite)
*
* @var string
*/
protected $type;
/**
* @var array
*/
public static $types = [];
/**
* Creates a new Database instance
*
* @param array $params
* @return void
*/
public function __construct(array $params = [])
{
$this->connect($params);
}
/**
* Returns one of the started instance
*
* @param string $id
* @return Database
*/
public static function instance(string $id = null): self
{
return $id === null ? A::last(static::$connections) : static::$connections[$id] ?? null;
}
/**
* Returns all started instances
*
* @return array
*/
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
* @return Database
*/
public function connect(array $params = null)
{
$defaults = [
'database' => null,
'type' => 'mysql',
'prefix' => null,
'user' => null,
'password' => null,
'id' => uniqid()
];
$options = array_merge($defaults, $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('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);
// store the connection
static::$connections[$this->id] = $this;
// return the connection
return $this->connection;
}
/**
* Returns the currently active connection
*
* @return Database|null
*/
public function connection()
{
return $this->connection;
}
/**
* Sets the exception mode for the next query
*
* @param boolean $fail
* @return Database
*/
public function fail(bool $fail = true)
{
$this->fail = $fail;
return $this;
}
/**
* Returns the used database type
*
* @return string
*/
public function type(): string
{
return $this->type;
}
/**
* Returns the used table name prefix
*
* @return string|null
*/
public function prefix(): ?string
{
return $this->prefix;
}
/**
* Escapes a value to be used for a safe query
* NOTE: Prepared statements using bound parameters are more secure and solid
*
* @param string $value
* @return string
*/
public function escape(string $value): string
{
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
*
* @param array $data
* @return array
*/
public function trace($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
*
* @return int|null
*/
public function affected(): ?int
{
return $this->affected;
}
/**
* Returns the last id if available
*
* @return int|null
*/
public function lastId(): ?int
{
return $this->lastId;
}
/**
* Returns the last query
*
* @return string|null
*/
public function lastQuery(): ?string
{
return $this->lastQuery;
}
/**
* Returns the last set of results
*
* @return mixed
*/
public function lastResult()
{
return $this->lastResult;
}
/**
* Returns the last db error
*
* @return Throwable
*/
public function lastError()
{
return $this->lastError;
}
/**
* Private method to execute database queries.
* This is used by the query() and execute() methods
*
* @param string $query
* @param array $bindings
* @return boolean
*/
protected function hit(string $query, array $bindings = []): bool
{
// try to prepare and execute the sql
try {
$this->statement = $this->connection->prepare($query);
$this->statement->execute($bindings);
$this->affected = $this->statement->rowCount();
$this->lastId = $this->connection->lastInsertId();
$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
]);
// reset some stuff
$this->fail = false;
// return true or false on success or failure
return $this->lastError === null;
}
/**
* Exectues a sql query, which is expected to return a set of results
*
* @param string $query
* @param array $bindings
* @param array $params
* @return mixed
*/
public function query(string $query, array $bindings = [], array $params = [])
{
$defaults = [
'flag' => null,
'method' => 'fetchAll',
'fetch' => 'Kirby\Toolkit\Obj',
'iterator' => 'Kirby\Toolkit\Collection',
];
$options = array_merge($defaults, $params);
if ($this->hit($query, $bindings) === false) {
return false;
}
// define the default flag for the fetch method
$flags = $options['fetch'] === 'array' ? PDO::FETCH_ASSOC : 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'] === 'array') {
$this->statement->setFetchMode($flags);
} else {
$this->statement->setFetchMode($flags, $options['fetch']);
}
// fetch that stuff
$results = $this->statement->{$options['method']}();
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
*
* @param string $query
* @param array $bindings
* @return boolean
*/
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
*
* @return Sql
*/
public function sql()
{
$className = static::$types[$this->type]['sql'] ?? 'Sql';
return new $className($this);
}
/**
* Sets the current table, which should be queried
*
* @param string $table
* @return Query Returns a Query object, which can be used to build a full query for that table
*/
public function table(string $table)
{
return new Query($this, $this->prefix() . $table);
}
/**
* Checks if a table exists in the current database
*
* @param string $table
* @return boolean
*/
public function validateTable(string $table): bool
{
if ($this->tableWhitelist === null) {
// Get the table whitelist from the database
$sql = $this->sql()->tables($this->database);
$results = $this->query($sql['query'], $sql['bindings']);
if ($results) {
$this->tableWhitelist = $results->pluck('name');
} else {
return false;
}
}
return in_array($table, $this->tableWhitelist) === true;
}
/**
* Checks if a column exists in a specified table
*
* @param string $table
* @param string $column
* @return boolean
*/
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;
}
/**
* Creates a new table
*
* @param string $table
* @param array $columns
* @return boolean
*/
public function createTable($table, $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;
}
}
return true;
}
/**
* Drops a table
*
* @param string $table
* @return boolean
*/
public function dropTable($table): bool
{
$sql = $this->sql()->dropTable($table);
return $this->execute($sql['query'], $sql['bindings']);
}
/**
* Magic way to start queries for tables by
* using a method named like the table.
* I.e. $db->users()->all()
*/
public function __call($method, $arguments = null)
{
return $this->table($method);
}
}
/**
* MySQL database connector
*/
Database::$types['mysql'] = [
'sql' => 'Kirby\Database\Sql\Mysql',
'dsn' => function (array $params) {
if (isset($params['host']) === false && isset($params['socket']) === false) {
throw new InvalidArgumentException('The mysql connection requires either a "host" or a "socket" parameter');
}
if (isset($params['database']) === false) {
throw new InvalidArgumentException('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'] ?? 'utf8');
return 'mysql:' . implode(';', $parts);
}
];
/**
* SQLite database connector
*/
Database::$types['sqlite'] = [
'sql' => 'Kirby\Database\Sql\Sqlite',
'dsn' => function (array $params) {
if (isset($params['database']) === false) {
throw new InvalidArgumentException('The sqlite connection requires a "database" parameter');
}
return 'sqlite:' . $params['database'];
}
];

262
kirby/src/Database/Db.php Executable file
View File

@@ -0,0 +1,262 @@
<?php
namespace Kirby\Database;
use InvalidArgumentException;
use Kirby\Toolkit\Config;
/**
* Database shortcuts
*/
class Db
{
const ERROR_UNKNOWN_METHOD = 0;
/**
* Query shortcuts
*
* @var array
*/
public static $queries = [];
/**
* The singleton Database object
*
* @var Database
*/
public static $connection = null;
/**
* (Re)connect the database
*
* @param array $params Pass [] to use the default params from the config
* @return Database
*/
public static function connect(array $params = null)
{
if ($params === null && static::$connection !== null) {
return static::$connection;
}
// try to connect with the default
// connection settings if no params are set
$params = $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', ''),
];
return static::$connection = new Database($params);
}
/**
* Returns the current database connection
*
* @return Database
*/
public static function connection()
{
return static::$connection;
}
/**
* Sets the current table, which should be queried
*
* @param string $table
* @return Query Returns a Query object, which can be used to build a full query for that table
*/
public static function table($table)
{
$db = static::connect();
return $db->table($table);
}
/**
* Executes a raw sql query which expects a set of results
*
* @param string $query
* @param array $bindings
* @param array $params
* @return mixed
*/
public static function query(string $query, array $bindings = [], array $params = [])
{
$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)
*
* @param string $query
* @param array $bindings
* @return mixed
*/
public static function execute(string $query, array $bindings = [])
{
$db = static::connect();
return $db->execute($query, $bindings);
}
/**
* Magic calls for other static db methods,
* which are redircted to the database class if available
*
* @param string $method
* @param mixed $arguments
* @return mixed
*/
public static function __callStatic($method, $arguments)
{
if (isset(static::$queries[$method])) {
return static::$queries[$method](...$arguments);
}
if (is_callable([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);
}
}
/**
* 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
* @param string $order
* @param int $offset
* @param int $limit
* @return mixed
*/
Db::$queries['select'] = function (string $table, $columns = '*', $where = null, string $order = null, int $offset = 0, int $limit = null) {
return Db::table($table)->select($columns)->where($where)->order($order)->offset($offset)->limit($limit)->all();
};
/**
* 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
* @param string $order
* @param int $offset
* @param int $limit
* @return mixed
*/
Db::$queries['first'] = Db::$queries['row'] = Db::$queries['one'] = function (string $table, $columns = '*', $where = null, string $order = null) {
return Db::table($table)->select($columns)->where($where)->order($order)->first();
};
/**
* 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
* @param string $order
* @param int $offset
* @param int $limit
* @return mixed
*/
Db::$queries['column'] = function (string $table, string $column, $where = null, string $order = null, int $offset = 0, int $limit = null) {
return Db::table($table)->where($where)->order($order)->offset($offset)->limit($limit)->column($column);
};
/**
* 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 boolean
*/
Db::$queries['insert'] = function (string $table, array $values) {
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
* @return boolean
*/
Db::$queries['update'] = function (string $table, array $values, $where = null) {
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
* @return boolean
*/
Db::$queries['delete'] = function (string $table, $where = null) {
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
* @return int
*/
Db::$queries['count'] = function (string $table, $where = null) {
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
* @return mixed
*/
Db::$queries['min'] = function (string $table, string $column, $where = null) {
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
* @return mixed
*/
Db::$queries['max'] = function (string $table, string $column, $where = null) {
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
* @return mixed
*/
Db::$queries['avg'] = function (string $table, string $column, $where = null) {
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
* @return mixed
*/
Db::$queries['sum'] = function (string $table, string $column, $where = null) {
return Db::table($table)->where($where)->sum($column);
};

1055
kirby/src/Database/Query.php Executable file

File diff suppressed because it is too large Load Diff

929
kirby/src/Database/Sql.php Executable file
View File

@@ -0,0 +1,929 @@
<?php
namespace Kirby\Database;
use Closure;
use Kirby\Exception\InvalidArgumentException;
use Kirby\Toolkit\A;
use Kirby\Toolkit\Str;
/**
* SQL Query builder
*/
class Sql
{
/**
* List of literals which should not be escaped in queries
*
* @var array
*/
public static $literals = ['NOW()', null];
/**
* The parent database connection
*
* @var Database
*/
public $database;
/**
* Constructor
*
* @param Database $database
*/
public function __construct($database)
{
$this->database = $database;
}
/**
* 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
*/
public function bindingName(string $label): string
{
// make sure that the binding name is valid to prevent injections
if (!preg_match('/^[a-z0-9_]+$/', $label)) {
$label = 'invalid';
}
return ':' . $label . '_' . Str::random(16);
}
/**
* Returns a list of columns for a specified table
* MySQL version
*
* @param string $table The 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->database,
$tableBinding => $table,
]
];
}
/**
* Optionl default value definition for the column
*
* @param array $column
* @return array
*/
public function columnDefault(array $column): array
{
if (isset($column['default']) === false) {
return [
'query' => null,
'bindings' => []
];
}
$binding = $this->bindingName($column['name'] . '_default');
return [
'query' => 'DEFAULT ' . $binding,
'bindings' => [
$binding = $column['default']
]
];
}
/**
* Returns a valid column name
*
* @param string $table
* @param string $column
* @param boolean $enforceQualified
* @return string|null
*/
public function columnName(string $table, string $column, bool $enforceQualified = false): ?string
{
list($table, $column) = $this->splitIdentifier($table, $column);
if ($this->validateColumn($table, $column) === true) {
return $this->combineIdentifier($table, $column, $enforceQualified !== true);
}
return null;
}
/**
* Abstracted column types to simplify table
* creation for multiple database drivers
*
* @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' => []
];
}
/**
* 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
* @return string
*/
public function combineIdentifier(string $table, string $column, bool $values = false): string
{
return $this->quoteIdentifier($table) . '.' . $this->quoteIdentifier($column);
}
/**
* Creates the create syntax for a single column
*
* @param string $table
* @param array $column
* @return array
*/
public function createColumn(string $table, array $column): array
{
// column type
if (isset($column['type']) === false) {
throw new InvalidArgumentException('No column type given for column ' . $column);
}
// 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)) {
throw new InvalidArgumentException('Unsupported column type: ' . $column['type']);
}
// null
if (A::get($column, 'null') === false) {
$null = 'NOT NULL';
} else {
$null = 'NULL';
}
// 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 (in_array($column['key'], ['PRIMARY KEY', 'INDEX']) === true) {
$key = $column['key'];
}
}
// default value
$columnDefault = $this->columnDefault($column);
$columnKey = $this->columnKey($column);
$query = trim(Str::template($template, [
'name' => $this->quoteIdentifier($column['name']),
'null' => $null,
'key' => $columnKey['query'],
'default' => $columnDefault['query'],
]));
$bindings = array_merge($columnKey['bindings'], $columnDefault['bindings']);
return [
'query' => $query,
'bindings' => $bindings,
'key' => $key
];
}
/**
* Creates a table with a simple scheme array for columns
* Default version for MySQL
*
* @param string $table The table name
* @param array $columns
* @return array
*/
public function createTable(string $table, array $columns = []): array
{
$output = [];
$keys = [];
$bindings = [];
foreach ($columns as $name => $column) {
$sql = $this->createColumn($table, $column);
$output[] = $sql['query'];
if ($sql['key']) {
$keys[$column['name']] = $sql['key'];
}
$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
];
}
/**
* 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
{
$defaults = [
'table' => '',
'where' => null,
'bindings' => []
];
$options = array_merge($defaults, $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
*
* @param string $table
* @return array
*/
public function dropTable(string $table): array
{
return [
'query' => 'DROP TABLE ' . $this->tableName($table),
'bindings' => []
];
}
/**
* Extends a given query and bindings
* by reference
*
* @param array $query
* @param array $bindings
* @param array $input
* @return void
*/
public function extend(&$query, array &$bindings = [], $input)
{
if (empty($input['query']) === false) {
$query[] = $input['query'];
$bindings = array_merge($bindings, $input['bindings']);
}
}
/**
* Creates the from syntax
*
* @param string $table
* @return array
*/
public function from(string $table): array
{
return [
'query' => 'FROM ' . $this->tableName($table),
'bindings' => []
];
}
/**
* Creates the group by syntax
*
* @param string $group
* @return array
*/
public function group(string $group = null): array
{
if (empty($group) === true) {
return [
'query' => null,
'bindings' => []
];
}
return [
'query' => 'GROUP BY ' . $group,
'bindings' => []
];
}
/**
* Creates the having syntax
*
* @param string $having
* @return array
*/
public function having(string $having = null): array
{
if (empty($having) === true) {
return [
'query' => null,
'bindings' => []
];
}
return [
'query' => 'HAVING ' . $having,
'bindings' => []
];
}
/**
* Creates an insert query
*
* @param array $params
* @return array
*/
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
*
* @param string $table
* @param string $type
* @param string $on
* @return array
*/
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) === false) {
throw new InvalidArgumentException('Invalid join type ' . $type);
}
return [
'query' => $type . ' ' . $this->tableName($table) . ' ON ' . $on,
'bindings' => [],
];
}
/**
* Create the syntax for multiple joins
*
* @params array $joins
* @return array
*/
public function joins(array $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
*
* @param integer $offset
* @param integer|null $limit
* @return array
*/
public function limit(int $offset = 0, int $limit = null): array
{
// no need to add it to the query
if ($offset === 0 && $limit === null) {
return [
'query' => null,
'bindings' => []
];
}
$limit = $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
*
* @param string $order
* @return array
*/
public function order(string $order = null): array
{
if (empty($order) === true) {
return [
'query' => null,
'bindings' => []
];
}
return [
'query' => 'ORDER BY ' . $order,
'bindings' => []
];
}
/**
* Converts a query array into a final string
*
* @param array $query
* @param string $separator
* @return string
*/
public function query(array $query, string $separator = ' ')
{
return implode($separator, array_filter($query));
}
/**
* Quotes an identifier (table *or* column)
* Default version for MySQL
*
* @param $identifier string
* @return string
*/
public function quoteIdentifier(string $identifier): string
{
// * is special
if ($identifier === '*') {
return $identifier;
}
// replace every backtick with two backticks
$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
{
$defaults = [
'table' => '',
'columns' => '*',
'join' => null,
'distinct' => false,
'where' => null,
'group' => null,
'having' => null,
'order' => null,
'offset' => 0,
'limit' => null,
'bindings' => []
];
$options = array_merge($defaults, $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
*
* @param string $table
* @param array|string|null $columns
* @return string
*/
public function selected($table, $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) {
list($table, $columnPart) = $this->splitIdentifier($table, $column);
if ($this->validateColumn($table, $columnPart) === true) {
$result[] = $this->combineIdentifier($table, $columnPart);
}
}
return implode(', ', $result);
} else {
return $columns;
}
}
/**
* Splits a (qualified) identifier into table and column
*
* @param $table string Default table if the identifier is not qualified
* @param $identifier string
* @return array
*/
public function splitIdentifier($table, $identifier): array
{
// split by dot, but only outside of quotes
$parts = preg_split('/(?:`[^`]*`|"[^"]*")(*SKIP)(*F)|\./', $identifier);
switch (count($parts)) {
// non-qualified identifier
case 1:
return array($table, $this->unquoteIdentifier($parts[0]));
// qualified identifier
case 2:
return array($this->unquoteIdentifier($parts[0]), $this->unquoteIdentifier($parts[1]));
// every other number is an error
default:
throw new InvalidArgumentException('Invalid identifier ' . $identifier);
}
}
/**
* Returns a list of tables for a specified database
* MySQL version
*
* @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->database
]
];
}
/**
* Validates and quotes a table name
*
* @param string $table
* @return string
*/
public function tableName(string $table): string
{
// validate table
if ($this->database->validateTable($table) === false) {
throw new InvalidArgumentException('Invalid table ' . $table);
}
return $this->quoteIdentifier($table);
}
/**
* Unquotes an identifier (table *or* column)
*
* @param $identifier string
* @return string
*/
public function unquoteIdentifier(string $identifier): string
{
// remove quotes around the identifier
if (in_array(Str::substr($identifier, 0, 1), ['"', '`']) === true) {
$identifier = Str::substr($identifier, 1);
}
if (in_array(Str::substr($identifier, -1), ['"', '`']) === true) {
$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.
* @return array
*/
public function update(array $params = []): array
{
$defaults = [
'table' => null,
'values' => null,
'where' => null,
'bindings' => []
];
$options = array_merge($defaults, $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
*
* @param string $table
* @param string $column
* @return boolean
*/
public function validateColumn(string $table, string $column): bool
{
if ($this->database->validateColumn($table, $column) === false) {
throw new InvalidArgumentException('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 boolean $set If true builds a set list of values for update clauses
* @param boolean $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);
} else {
return $this->valueList($table, $values, $separator, $enforceQualified);
}
}
/**
* Creates a list of fields and values
*
* @param string $table
* @param string|array $values
* @param string $separator
* @param bool $enforceQualified
* @param array
*/
public function valueList(string $table, $values, string $separator = ',', bool $enforceQualified = false): array
{
$fields = [];
$query = [];
$bindings = [];
foreach ($values as $key => $value) {
$fields[] = $this->columnName($table, $key, $enforceQualified);
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
*
* @param string $table
* @param string|array $values
* @param string $separator
* @param bool $enforceQualified
* @param array
*/
public function valueSet(string $table, $values, string $separator = ',', bool $enforceQualified = false): array
{
$query = [];
$bindings = [];
foreach ($values as $column => $value) {
$key = $this->columnName($table, $column, $enforceQualified);
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
];
}
/**
* @param string|array|null $where
* @param array $bindings
* @return array
*/
public function where($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,12 @@
<?php
namespace Kirby\Database\Sql;
use Kirby\Database\Sql;
/**
* Mysql query builder
*/
class Mysql extends Sql
{
}

120
kirby/src/Database/Sql/Sqlite.php Executable file
View File

@@ -0,0 +1,120 @@
<?php
namespace Kirby\Database\Sql;
use Kirby\Database\Sql;
/**
* Sqlite query builder
*/
class Sqlite extends Sql
{
/**
* Returns a list of columns for a specified table
* SQLite version
*
* @param string $table The table name
* @return string
*/
public function columns(string $table): array
{
return [
'query' => 'PRAGMA table_info(' . $this->tableName($table) . ')',
'bindings' => [],
];
}
/**
* 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
*
* @return array
*/
public function columnTypes(): array
{
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 }}'
];
}
/**
* 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
* @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) {
return $this->quoteIdentifier($column);
}
return $this->quoteIdentifier($table) . '.' . $this->quoteIdentifier($column);
}
/**
* Quotes an identifier (table *or* column)
*
* @param $identifier string
* @return string
*/
public function quoteIdentifier(string $identifier): string
{
// * is special
if ($identifier === '*') {
return $identifier;
}
// replace every quote with two quotes
$identifier = str_replace('"', '""', $identifier);
// wrap in quotes
return '"' . $identifier . '"';
}
/**
* Returns a list of tables of the database
* SQLite version
*
* @param string $database The database name
* @return string
*/
public function tables(): array
{
return [
'query' => 'SELECT name FROM sqlite_master WHERE type = "table"',
'bindings' => []
];
}
}