[CORE] Bump Database requirement to MariaDB 10.3+

This commit is contained in:
Diogo Cordeiro
2019-07-25 00:43:25 +01:00
parent 7044f0e2cf
commit f67a93eddc
62 changed files with 472 additions and 478 deletions

View File

@@ -55,7 +55,7 @@ abstract class Installer
public static $dbModules = array(
'mysql' => array(
'name' => 'MariaDB (or MySQL 5.5+)',
'name' => 'MariaDB 10.3+',
'check_module' => 'mysqli',
'scheme' => 'mysqli', // DSN prefix for PEAR::DB
),

View File

@@ -1,60 +1,51 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* StatusNet, the distributed open-source microblogging tool
* Database schema for MariaDB
*
* Database schema utilities
*
* PHP version 5
*
* LICENCE: This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @category Database
* @package StatusNet
* @author Evan Prodromou <evan@status.net>
* @copyright 2009 StatusNet, Inc.
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://status.net/
* @category Database
* @package GNUsocial
* @author Evan Prodromou <evan@status.net>
* @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
if (!defined('STATUSNET')) {
exit(1);
}
defined('GNUSOCIAL') || die();
/**
* Class representing the database schema
* Class representing the database schema for MariaDB
*
* A class representing the database schema. Can be used to
* manipulate the schema -- especially for plugins and upgrade
* utilities.
*
* @category Database
* @package StatusNet
* @author Evan Prodromou <evan@status.net>
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://status.net/
* @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class MysqlSchema extends Schema
{
static $_single = null;
protected $conn = null;
/**
* Main public entry point. Use this to get
* the singleton object.
*
* @param null $conn
* @return Schema the (single) Schema object
*/
@@ -74,13 +65,14 @@ class MysqlSchema extends Schema
*
* @param string $table Name of the table to get
*
* @return TableDef tabledef for that table.
* @return array of tabledef for that table.
* @throws PEAR_Exception
* @throws SchemaTableMissingException
*/
public function getTableDef($table)
{
$def = array();
$def = [];
$hasKeys = false;
// Pull column data from INFORMATION_SCHEMA
@@ -92,7 +84,7 @@ class MysqlSchema extends Schema
foreach ($columns as $row) {
$name = $row['COLUMN_NAME'];
$field = array();
$field = [];
// warning -- 'unsigned' attr on numbers isn't given in DATA_TYPE and friends.
// It is stuck in on COLUMN_TYPE though (eg 'bigint(20) unsigned')
@@ -119,7 +111,7 @@ class MysqlSchema extends Schema
if ($row['COLUMN_DEFAULT'] !== null) {
// Hack for timestamp cols
if ($type == 'timestamp' && $row['COLUMN_DEFAULT'] == 'CURRENT_TIMESTAMP') {
// skip
// skip because timestamp is numerical, but it accepts datetime strings as well
} else {
$field['default'] = $row['COLUMN_DEFAULT'];
if ($this->isNumericType($type)) {
@@ -144,11 +136,11 @@ class MysqlSchema extends Schema
// ^ ...... how to specify?
}
/* @fixme check against defaults?
if ($row['CHARACTER_SET_NAME'] !== null) {
// @fixme check against defaults?
//$def['charset'] = $row['CHARACTER_SET_NAME'];
//$def['collate'] = $row['COLLATION_NAME'];
}
$def['charset'] = $row['CHARACTER_SET_NAME'];
$def['collate'] = $row['COLLATION_NAME'];
}*/
$def['fields'][$name] = $field;
}
@@ -161,13 +153,14 @@ class MysqlSchema extends Schema
// Let's go old school and use SHOW INDEX :D
//
$keyInfo = $this->fetchIndexInfo($table);
$keys = array();
$keys = [];
$keyTypes = [];
foreach ($keyInfo as $row) {
$name = $row['Key_name'];
$column = $row['Column_name'];
if (!isset($keys[$name])) {
$keys[$name] = array();
$keys[$name] = [];
}
$keys[$name][] = $column;
@@ -199,8 +192,11 @@ class MysqlSchema extends Schema
* Pull the given table properties from INFORMATION_SCHEMA.
* Most of the good stuff is MySQL extensions.
*
* @param $table
* @param $props
* @return array
* @throws Exception if table info can't be looked up
* @throws PEAR_Exception
* @throws SchemaTableMissingException
*/
function getTableProperties($table, $props)
@@ -217,12 +213,15 @@ class MysqlSchema extends Schema
* Pull some INFORMATION.SCHEMA data for the given table.
*
* @param string $table
* @param $infoTable
* @param null $orderBy
* @return array of arrays
* @throws PEAR_Exception
*/
function fetchMetaInfo($table, $infoTable, $orderBy=null)
function fetchMetaInfo($table, $infoTable, $orderBy = null)
{
$query = "SELECT * FROM INFORMATION_SCHEMA.%s " .
"WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s'";
"WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s'";
$schema = $this->conn->dsn['database'];
$sql = sprintf($query, $infoTable, $schema, $table);
if ($orderBy) {
@@ -236,6 +235,7 @@ class MysqlSchema extends Schema
*
* @param string $table
* @return array of arrays
* @throws PEAR_Exception
*/
function fetchIndexInfo($table)
{
@@ -284,6 +284,9 @@ class MysqlSchema extends Schema
/**
* Get the unique index key name for a given column on this table
* @param $tableName
* @param $columnName
* @return string
*/
function _uniqueKey($tableName, $columnName)
{
@@ -292,6 +295,9 @@ class MysqlSchema extends Schema
/**
* Get the index key name for a given column on this table
* @param $tableName
* @param $columnName
* @return string
*/
function _key($tableName, $columnName)
{
@@ -314,7 +320,7 @@ class MysqlSchema extends Schema
* if they were indexes here.
*
* @param array $phrase
* @param <type> $keyName MySQL
* @param string $keyName MySQL
*/
function appendAlterDropUnique(array &$phrase, $keyName)
{
@@ -324,13 +330,17 @@ class MysqlSchema extends Schema
/**
* Throw some table metadata onto the ALTER TABLE if we have a mismatch
* in expected type, collation.
* @param array $phrase
* @param $tableName
* @param array $def
* @throws Exception
*/
function appendAlterExtras(array &$phrase, $tableName, array $def)
{
// Check for table properties: make sure we're using a sane
// engine type and charset/collation.
// @fixme make the default engine configurable?
$oldProps = $this->getTableProperties($tableName, array('ENGINE', 'TABLE_COLLATION'));
$oldProps = $this->getTableProperties($tableName, ['ENGINE', 'TABLE_COLLATION']);
$engine = $this->preferredEngine($def);
if (strtolower($oldProps['ENGINE']) != strtolower($engine)) {
$phrase[] = "ENGINE=$engine";
@@ -344,10 +354,12 @@ class MysqlSchema extends Schema
/**
* Is this column a string type?
* @param array $cd
* @return bool
*/
private function _isString(array $cd)
{
$strings = array('char', 'varchar', 'text');
$strings = ['char', 'varchar', 'text'];
return in_array(strtolower($cd['type']), $strings);
}
@@ -358,14 +370,14 @@ class MysqlSchema extends Schema
* Appropriate for use in CREATE TABLE or
* ALTER TABLE statements.
*
* @param ColumnDef $cd column to create
* @param array $cd column to create
*
* @return string correct SQL for that column
*/
function columnSql(array $cd)
{
$line = array();
$line = [];
$line[] = parent::columnSql($cd);
// This'll have been added from our transform of 'serial' type
@@ -383,9 +395,11 @@ class MysqlSchema extends Schema
function mapType($column)
{
$map = array('serial' => 'int',
'integer' => 'int',
'numeric' => 'decimal');
$map = [
'serial' => 'int',
'integer' => 'int',
'numeric' => 'decimal'
];
$type = $column['type'];
if (isset($map[$type])) {
@@ -395,10 +409,10 @@ class MysqlSchema extends Schema
if (!empty($column['size'])) {
$size = $column['size'];
if ($type == 'int' &&
in_array($size, array('tiny', 'small', 'medium', 'big'))) {
in_array($size, ['tiny', 'small', 'medium', 'big'])) {
$type = $size . $type;
} else if (in_array($type, array('blob', 'text')) &&
in_array($size, array('tiny', 'medium', 'long'))) {
} else if (in_array($type, ['blob', 'text']) &&
in_array($size, ['tiny', 'medium', 'long'])) {
$type = $size . $type;
}
}
@@ -409,7 +423,7 @@ class MysqlSchema extends Schema
function typeAndSize($column)
{
if ($column['type'] == 'enum') {
$vals = array_map(array($this, 'quote'), $column['enum']);
$vals = array_map([$this, 'quote'], $column['enum']);
return 'enum(' . implode(',', $vals) . ')';
} else if ($this->_isString($column)) {
$col = parent::typeAndSize($column);
@@ -433,6 +447,7 @@ class MysqlSchema extends Schema
* or type variants that we wouldn't get back from getTableDef().
*
* @param array $tableDef
* @return array
*/
function filterDef(array $tableDef)
{
@@ -443,26 +458,6 @@ class MysqlSchema extends Schema
$col['auto_increment'] = true;
}
// Avoid invalid date errors in MySQL 5.7+
if ($col['type'] == 'timestamp' && !isset($col['default'])
&& $version >= 50605) {
$col['default'] = 'CURRENT_TIMESTAMP';
}
if ($col['type'] == 'datetime') {
// Avoid invalid date errors in MySQL 5.7+
if (!isset($col['default']) && $version >= 50605) {
$col['default'] = 'CURRENT_TIMESTAMP';
}
// If we are using MySQL 5.5, convert datetime to timestamp if
// default value is CURRENT_TIMESTAMP. Not needed for MySQL 5.6+
// and MariaDB 10.0+
if (isset($col['default'])
&& $col['default'] == 'CURRENT_TIMESTAMP'
&& $version < 50605) {
$col['type'] = 'timestamp';
}
}
$col['type'] = $this->mapType($col);
unset($col['size']);
}

View File

@@ -1,52 +1,43 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* StatusNet, the distributed open-source microblogging tool
* Database schema for PostgreSQL
*
* Database schema utilities
*
* PHP version 5
*
* LICENCE: This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @category Database
* @package StatusNet
* @author Evan Prodromou <evan@status.net>
* @copyright 2009 StatusNet, Inc.
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://status.net/
* @category Database
* @package GNUsocial
* @author Evan Prodromou <evan@status.net>
* @author Brenda Wallace <shiny@cpan.org>
* @author Brion Vibber <brion@status.net>
* @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
if (!defined('STATUSNET')) {
exit(1);
}
defined('GNUSOCIAL') || die();
/**
* Class representing the database schema
* Class representing the database schema for PostgreSQL
*
* A class representing the database schema. Can be used to
* manipulate the schema -- especially for plugins and upgrade
* utilities.
*
* @category Database
* @package StatusNet
* @author Evan Prodromou <evan@status.net>
* @author Brenda Wallace <shiny@cpan.org>
* @author Brion Vibber <brion@status.net>
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://status.net/
* @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class PgsqlSchema extends Schema
{
@@ -59,11 +50,12 @@ class PgsqlSchema extends Schema
* @param string $table Name of the table to get
*
* @return array tabledef for that table.
* @throws SchemaTableMissingException
*/
public function getTableDef($table)
{
$def = array();
$def = [];
$hasKeys = false;
// Pull column data from INFORMATION_SCHEMA
@@ -73,15 +65,15 @@ class PgsqlSchema extends Schema
}
// We'll need to match up fields by ordinal reference
$orderedFields = array();
$orderedFields = [];
foreach ($columns as $row) {
$name = $row['column_name'];
$orderedFields[$row['ordinal_position']] = $name;
$field = array();
$field['type'] = $row['udt_name'];
$field = [];
$field['type'] = $type = $row['udt_name'];
if ($type == 'char' || $type == 'varchar') {
if ($row['character_maximum_length'] !== null) {
@@ -123,7 +115,7 @@ class PgsqlSchema extends Schema
// These are inconvenient arrays with partial references to the
// pg_att table, but since we've already fetched up the column
// info on the current table, we can look those up locally.
$cols = array();
$cols = [];
$colPositions = explode(' ', $row['indkey']);
foreach ($colPositions as $ord) {
if ($ord == 0) {
@@ -139,13 +131,13 @@ class PgsqlSchema extends Schema
// Pull constraint data from INFORMATION_SCHEMA:
// Primary key, unique keys, foreign keys
$keyColumns = $this->fetchMetaInfo($table, 'key_column_usage', 'constraint_name,ordinal_position');
$keys = array();
$keys = [];
foreach ($keyColumns as $row) {
$keyName = $row['constraint_name'];
$keyCol = $row['column_name'];
if (!isset($keys[$keyName])) {
$keys[$keyName] = array();
$keys[$keyName] = [];
}
$keys[$keyName][] = $keyCol;
}
@@ -157,7 +149,7 @@ class PgsqlSchema extends Schema
} else if (preg_match("/^{$table}_(.*)_fkey$/", $keyName, $matches)) {
$fkey = $this->getForeignKeyInfo($table, $keyName);
$colMap = array_combine($cols, $fkey['col_names']);
$def['foreign keys'][$keyName] = array($fkey['table_name'], $colMap);
$def['foreign keys'][$keyName] = [$fkey['table_name'], $colMap];
} else {
$def['unique keys'][$keyName] = $cols;
}
@@ -169,12 +161,15 @@ class PgsqlSchema extends Schema
* Pull some INFORMATION.SCHEMA data for the given table.
*
* @param string $table
* @param $infoTable
* @param null $orderBy
* @return array of arrays
* @throws PEAR_Exception
*/
function fetchMetaInfo($table, $infoTable, $orderBy=null)
function fetchMetaInfo($table, $infoTable, $orderBy = null)
{
$query = "SELECT * FROM information_schema.%s " .
"WHERE table_name='%s'";
"WHERE table_name='%s'";
$sql = sprintf($query, $infoTable, $table);
if ($orderBy) {
$sql .= ' ORDER BY ' . $orderBy;
@@ -186,36 +181,39 @@ class PgsqlSchema extends Schema
* Pull some PG-specific index info
* @param string $table
* @return array of arrays
* @throws PEAR_Exception
*/
function getIndexInfo($table)
{
$query = 'SELECT ' .
'(SELECT relname FROM pg_class WHERE oid=indexrelid) AS key_name, ' .
'* FROM pg_index ' .
'WHERE indrelid=(SELECT oid FROM pg_class WHERE relname=\'%s\') ' .
'AND indisprimary=\'f\' AND indisunique=\'f\' ' .
'ORDER BY indrelid, indexrelid';
'(SELECT relname FROM pg_class WHERE oid=indexrelid) AS key_name, ' .
'* FROM pg_index ' .
'WHERE indrelid=(SELECT oid FROM pg_class WHERE relname=\'%s\') ' .
'AND indisprimary=\'f\' AND indisunique=\'f\' ' .
'ORDER BY indrelid, indexrelid';
$sql = sprintf($query, $table);
return $this->fetchQueryData($sql);
}
/**
* Column names from the foreign table can be resolved with a call to getTableColumnNames()
* @param <type> $table
* @param string $table
* @param $constraint_name
* @return array array of rows with keys: fkey_name, table_name, table_id, col_names (array of strings)
* @throws PEAR_Exception
*/
function getForeignKeyInfo($table, $constraint_name)
{
// In a sane world, it'd be easier to query the column names directly.
// But it's pretty hard to work with arrays such as col_indexes in direct SQL here.
$query = 'SELECT ' .
'(SELECT relname FROM pg_class WHERE oid=confrelid) AS table_name, ' .
'confrelid AS table_id, ' .
'(SELECT indkey FROM pg_index WHERE indexrelid=conindid) AS col_indexes ' .
'FROM pg_constraint ' .
'WHERE conrelid=(SELECT oid FROM pg_class WHERE relname=\'%s\') ' .
'AND conname=\'%s\' ' .
'AND contype=\'f\'';
'(SELECT relname FROM pg_class WHERE oid=confrelid) AS table_name, ' .
'confrelid AS table_id, ' .
'(SELECT indkey FROM pg_index WHERE indexrelid=conindid) AS col_indexes ' .
'FROM pg_constraint ' .
'WHERE conrelid=(SELECT oid FROM pg_class WHERE relname=\'%s\') ' .
'AND conname=\'%s\' ' .
'AND contype=\'f\'';
$sql = sprintf($query, $table, $constraint_name);
$data = $this->fetchQueryData($sql);
if (count($data) < 1) {
@@ -223,10 +221,10 @@ class PgsqlSchema extends Schema
}
$row = $data[0];
return array(
return [
'table_name' => $row['table_name'],
'col_names' => $this->getTableColumnNames($row['table_id'], $row['col_indexes'])
);
];
}
/**
@@ -234,22 +232,23 @@ class PgsqlSchema extends Schema
* @param int $table_id
* @param array $col_indexes
* @return array of strings
* @throws PEAR_Exception
*/
function getTableColumnNames($table_id, $col_indexes)
{
$indexes = array_map('intval', explode(' ', $col_indexes));
$query = 'SELECT attnum AS col_index, attname AS col_name ' .
'FROM pg_attribute where attrelid=%d ' .
'AND attnum IN (%s)';
'FROM pg_attribute where attrelid=%d ' .
'AND attnum IN (%s)';
$sql = sprintf($query, $table_id, implode(',', $indexes));
$data = $this->fetchQueryData($sql);
$byId = array();
$byId = [];
foreach ($data as $row) {
$byId[$row['col_index']] = $row['col_name'];
}
$out = array();
$out = [];
foreach ($indexes as $id) {
$out[] = $byId[$id];
}
@@ -262,14 +261,15 @@ class PgsqlSchema extends Schema
*
* @return string postgres happy column type
*/
private function _columnTypeTranslation($type) {
$map = array(
'datetime' => 'timestamp',
);
if(!empty($map[$type])) {
return $map[$type];
}
return $type;
private function _columnTypeTranslation($type)
{
$map = [
'datetime' => 'timestamp',
];
if (!empty($map[$type])) {
return $map[$type];
}
return $type;
}
/**
@@ -286,7 +286,7 @@ class PgsqlSchema extends Schema
function columnSql(array $cd)
{
$line = array();
$line = [];
$line[] = parent::columnSql($cd);
/*
@@ -341,7 +341,6 @@ class PgsqlSchema extends Schema
* @param array $statements
* @param string $table
* @param string $name
* @param array $def
*/
function appendDropIndex(array &$statements, $table, $name)
{
@@ -361,10 +360,12 @@ class PgsqlSchema extends Schema
function mapType($column)
{
$map = array('serial' => 'bigserial', // FIXME: creates the wrong name for the sequence for some internal sequence-lookup function, so better fix this to do the real 'create sequence' dance.
'numeric' => 'decimal',
'datetime' => 'timestamp',
'blob' => 'bytea');
$map = [
'serial' => 'bigserial', // FIXME: creates the wrong name for the sequence for some internal sequence-lookup function, so better fix this to do the real 'create sequence' dance.
'numeric' => 'decimal',
'datetime' => 'timestamp',
'blob' => 'bytea'
];
$type = $column['type'];
if (isset($map[$type])) {
@@ -390,7 +391,7 @@ class PgsqlSchema extends Schema
function typeAndSize($column)
{
if ($column['type'] == 'enum') {
$vals = array_map(array($this, 'quote'), $column['enum']);
$vals = array_map([$this, 'quote'], $column['enum']);
return "text check ($name in " . implode(',', $vals) . ')';
} else {
return parent::typeAndSize($column);
@@ -405,6 +406,7 @@ class PgsqlSchema extends Schema
* or type variants that we wouldn't get back from getTableDef().
*
* @param array $tableDef
* @return array
*/
function filterDef(array $tableDef)
{
@@ -444,8 +446,7 @@ class PgsqlSchema extends Schema
function filterKeyDef(array $def)
{
// PostgreSQL doesn't like prefix lengths specified on keys...?
foreach ($def as $i => $item)
{
foreach ($def as $i => $item) {
if (is_array($item)) {
$def[$i] = $item[0];
}

View File

@@ -1,35 +1,31 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* StatusNet, the distributed open-source microblogging tool
* Database schema
*
* Database schema utilities
*
* PHP version 5
*
* LICENCE: This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @category Database
* @package StatusNet
* @author Evan Prodromou <evan@status.net>
* @copyright 2009 StatusNet, Inc.
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://status.net/
* @category Database
* @package GNUsocial
* @author Evan Prodromou <evan@status.net>
* @author Brion Vibber <brion@status.net>
* @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
if (!defined('STATUSNET')) {
exit(1);
}
defined('GNUSOCIAL') || die();
/**
* Class representing the database schema
@@ -38,14 +34,9 @@ if (!defined('STATUSNET')) {
* manipulate the schema -- especially for plugins and upgrade
* utilities.
*
* @category Database
* @package StatusNet
* @author Evan Prodromou <evan@status.net>
* @author Brion Vibber <brion@status.net>
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://status.net/
* @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class Schema
{
static $_static = null;
@@ -53,6 +44,7 @@ class Schema
/**
* Constructor. Only run once for singleton object.
* @param null $conn
*/
protected function __construct($conn = null)
@@ -72,6 +64,7 @@ class Schema
* Main public entry point. Use this to get
* the schema object.
*
* @param null $conn
* @return Schema the Schema object for the connection
*/
@@ -82,10 +75,10 @@ class Schema
} else {
$key = md5(serialize($conn->dsn));
}
$type = common_config('db', 'type');
if (empty(self::$_static[$key])) {
$schemaClass = ucfirst($type).'Schema';
$schemaClass = ucfirst($type) . 'Schema';
self::$_static[$key] = new $schemaClass($conn);
}
return self::$_static[$key];
@@ -96,7 +89,7 @@ class Schema
*
* Throws an exception if the table is not found.
*
* @param string $table name of the table
* @param string $table name of the table
* @param string $column name of the column
*
* @return ColumnDef definition of the column or null
@@ -121,10 +114,11 @@ class Schema
/**
* Creates a table with the given names and columns.
*
* @param string $tableName Name of the table
* @param array $def Table definition array listing fields and indexes.
* @param string $tableName Name of the table
* @param array $def Table definition array listing fields and indexes.
*
* @return boolean success flag
* @return bool success flag
* @throws PEAR_Exception
*/
public function createTable($tableName, $def)
@@ -137,16 +131,17 @@ class Schema
* Build a set of SQL statements to create a table with the given
* name and columns.
*
* @param string $name Name of the table
* @param array $def Table definition array
* @param string $name Name of the table
* @param array $def Table definition array
*
* @return boolean success flag
* @return array success flag
* @throws Exception
*/
public function buildCreateTable($name, $def)
{
$def = $this->validateDef($name, $def);
$def = $this->filterDef($def);
$sql = array();
$sql = [];
foreach ($def['fields'] as $col => $colDef) {
$this->appendColumnDef($sql, $col, $colDef);
@@ -171,10 +166,10 @@ class Schema
}
// Wrap the CREATE TABLE around the main body chunks...
$statements = array();
$statements = [];
$statements[] = $this->startCreateTable($name, $def) . "\n" .
implode($sql, ",\n") . "\n" .
$this->endCreateTable($name, $def);
implode($sql, ",\n") . "\n" .
$this->endCreateTable($name, $def);
// Multi-value indexes are advisory and for best portability
// should be created as separate statements.
@@ -197,11 +192,11 @@ class Schema
*
* @param string $name table name
* @param array $def table definition
* @param $string
* @return string
*/
function startCreateTable($name, array $def)
{
return 'CREATE TABLE ' . $this->quoteIdentifier($name) . ' (';
return 'CREATE TABLE ' . $this->quoteIdentifier($name) . ' (';
}
/**
@@ -260,6 +255,7 @@ class Schema
* @param array $sql
* @param string $name
* @param array $def
* @throws Exception
*/
function appendForeignKeyDef(array &$sql, $name, array $def)
{
@@ -270,11 +266,11 @@ class Schema
$srcCols = array_keys($map);
$refCols = array_values($map);
$sql[] = "CONSTRAINT $name FOREIGN KEY " .
$this->buildIndexList($srcCols) .
" REFERENCES " .
$this->quoteIdentifier($refTable) .
" " .
$this->buildIndexList($refCols);
$this->buildIndexList($srcCols) .
" REFERENCES " .
$this->quoteIdentifier($refTable) .
" " .
$this->buildIndexList($refCols);
}
/**
@@ -299,6 +295,7 @@ class Schema
* @param string $table
* @param string $name
* @param array $def
* @throws Exception
*/
function appendCreateFulltextIndex(array &$statements, $table, $name, array $def)
{
@@ -311,7 +308,6 @@ class Schema
* @param array $statements
* @param string $table
* @param string $name
* @param array $def
*/
function appendDropIndex(array &$statements, $table, $name)
{
@@ -321,7 +317,7 @@ class Schema
function buildIndexList(array $def)
{
// @fixme
return '(' . implode(',', array_map(array($this, 'buildIndexItem'), $def)) . ')';
return '(' . implode(',', array_map([$this, 'buildIndexItem'], $def)) . ')';
}
function buildIndexItem($def)
@@ -340,7 +336,8 @@ class Schema
*
* @param string $name Name of the table to drop
*
* @return boolean success flag
* @return bool success flag
* @throws PEAR_Exception
*/
public function dropTable($name)
@@ -365,28 +362,29 @@ class Schema
* Throws an exception on database error, esp. if the table
* does not exist.
*
* @param string $table Name of the table
* @param array $columnNames Name of columns to index
* @param string $name (Optional) name of the index
* @param string $table Name of the table
* @param array $columnNames Name of columns to index
* @param string $name (Optional) name of the index
*
* @return boolean success flag
* @return bool success flag
* @throws PEAR_Exception
*/
public function createIndex($table, $columnNames, $name=null)
public function createIndex($table, $columnNames, $name = null)
{
global $_PEAR;
if (!is_array($columnNames)) {
$columnNames = array($columnNames);
$columnNames = [$columnNames];
}
if (empty($name)) {
$name = "{$table}_".implode("_", $columnNames)."_idx";
$name = "{$table}_" . implode("_", $columnNames) . "_idx";
}
$res = $this->conn->query("ALTER TABLE $table ".
"ADD INDEX $name (".
implode(",", $columnNames).")");
$res = $this->conn->query("ALTER TABLE $table " .
"ADD INDEX $name (" .
implode(",", $columnNames) . ")");
if ($_PEAR->isError($res)) {
PEAR_ErrorToPEAR_Exception($res);
@@ -399,9 +397,10 @@ class Schema
* Drops a named index from a table.
*
* @param string $table name of the table the index is on.
* @param string $name name of the index
* @param string $name name of the index
*
* @return boolean success flag
* @return bool success flag
* @throws PEAR_Exception
*/
public function dropIndex($table, $name)
@@ -420,11 +419,12 @@ class Schema
/**
* Adds a column to a table
*
* @param string $table name of the table
* @param string $table name of the table
* @param ColumnDef $columndef Definition of the new
* column.
*
* @return boolean success flag
* @return bool success flag
* @throws PEAR_Exception
*/
public function addColumn($table, $columndef)
@@ -447,10 +447,11 @@ class Schema
*
* The name must match an existing column and table.
*
* @param string $table name of the table
* @param string $table name of the table
* @param ColumnDef $columndef new definition of the column.
*
* @return boolean success flag
* @return bool success flag
* @throws PEAR_Exception
*/
public function modifyColumn($table, $columndef)
@@ -458,7 +459,7 @@ class Schema
global $_PEAR;
$sql = "ALTER TABLE $table MODIFY COLUMN " .
$this->_columnSql($columndef);
$this->_columnSql($columndef);
$res = $this->conn->query($sql);
@@ -474,10 +475,11 @@ class Schema
*
* The name must match an existing column.
*
* @param string $table name of the table
* @param string $table name of the table
* @param string $columnName name of the column to drop
*
* @return boolean success flag
* @return bool success flag
* @throws PEAR_Exception
*/
public function dropColumn($table, $columnName)
@@ -504,9 +506,10 @@ class Schema
* alter the table to match the column definitions.
*
* @param string $tableName name of the table
* @param array $def Table definition array
* @param array $def Table definition array
*
* @return boolean success flag
* @return bool success flag
* @throws PEAR_Exception
*/
public function ensureTable($tableName, $def)
@@ -521,7 +524,8 @@ class Schema
*
* @fixme if multiple statements, wrap in a transaction?
* @param array $statements
* @return boolean success flag
* @return bool success flag
* @throws PEAR_Exception
*/
function runSqlSet(array $statements)
{
@@ -530,12 +534,12 @@ class Schema
$ok = true;
foreach ($statements as $sql) {
if (defined('DEBUG_INSTALLER')) {
echo "<tt>" . htmlspecialchars($sql) . "</tt><br/>\n";
echo "<code>" . htmlspecialchars($sql) . "</code><br/>\n";
}
$res = $this->conn->query($sql);
if ($_PEAR->isError($res)) {
common_debug('PEAR exception on query: '.$sql);
common_debug('PEAR exception on query: ' . $sql);
PEAR_ErrorToPEAR_Exception($res);
}
}
@@ -553,10 +557,9 @@ class Schema
* match the column definitions.
*
* @param string $tableName name of the table
* @param array $columns array of ColumnDef
* objects for the table
*
* @param array $def
* @return array of SQL statements
* @throws Exception
*/
function buildEnsureTable($tableName, array $def)
@@ -572,8 +575,8 @@ class Schema
$def = $this->validateDef($tableName, $def);
$def = $this->filterDef($def);
$statements = array();
$fields = $this->diffArrays($old, $def, 'fields', array($this, 'columnsEqual'));
$statements = [];
$fields = $this->diffArrays($old, $def, 'fields', [$this, 'columnsEqual']);
$uniques = $this->diffArrays($old, $def, 'unique keys');
$indexes = $this->diffArrays($old, $def, 'indexes');
$foreign = $this->diffArrays($old, $def, 'foreign keys');
@@ -592,7 +595,7 @@ class Schema
// For efficiency, we want this all in one
// query, instead of using our methods.
$phrase = array();
$phrase = [];
foreach ($foreign['del'] + $foreign['mod'] as $keyName) {
$this->appendAlterDropForeign($phrase, $keyName);
@@ -608,13 +611,13 @@ class Schema
foreach ($fields['add'] as $columnName) {
$this->appendAlterAddColumn($phrase, $columnName,
$def['fields'][$columnName]);
$def['fields'][$columnName]);
}
foreach ($fields['mod'] as $columnName) {
$this->appendAlterModifyColumn($phrase, $columnName,
$old['fields'][$columnName],
$def['fields'][$columnName]);
$old['fields'][$columnName],
$def['fields'][$columnName]);
}
foreach ($fields['del'] as $columnName) {
@@ -653,19 +656,19 @@ class Schema
return $statements;
}
function diffArrays($oldDef, $newDef, $section, $compareCallback=null)
function diffArrays($oldDef, $newDef, $section, $compareCallback = null)
{
$old = isset($oldDef[$section]) ? $oldDef[$section] : array();
$new = isset($newDef[$section]) ? $newDef[$section] : array();
$old = isset($oldDef[$section]) ? $oldDef[$section] : [];
$new = isset($newDef[$section]) ? $newDef[$section] : [];
$oldKeys = array_keys($old);
$newKeys = array_keys($new);
$toadd = array_diff($newKeys, $oldKeys);
$toadd = array_diff($newKeys, $oldKeys);
$todrop = array_diff($oldKeys, $newKeys);
$same = array_intersect($newKeys, $oldKeys);
$tomod = array();
$tokeep = array();
$same = array_intersect($newKeys, $oldKeys);
$tomod = [];
$tokeep = [];
// Find which fields have actually changed definition
// in a way that we need to tweak them for this DB type.
@@ -681,11 +684,13 @@ class Schema
}
$tomod[] = $name;
}
return array('add' => $toadd,
'del' => $todrop,
'mod' => $tomod,
'keep' => $tokeep,
'count' => count($toadd) + count($todrop) + count($tomod));
return [
'add' => $toadd,
'del' => $todrop,
'mod' => $tomod,
'keep' => $tokeep,
'count' => count($toadd) + count($todrop) + count($tomod)
];
}
/**
@@ -694,14 +699,14 @@ class Schema
*
* @param array $phrase
* @param string $columnName
* @param array $cd
* @param array $cd
*/
function appendAlterAddColumn(array &$phrase, $columnName, array $cd)
{
$phrase[] = 'ADD COLUMN ' .
$this->quoteIdentifier($columnName) .
' ' .
$this->columnSql($cd);
$this->quoteIdentifier($columnName) .
' ' .
$this->columnSql($cd);
}
/**
@@ -716,9 +721,9 @@ class Schema
function appendAlterModifyColumn(array &$phrase, $columnName, array $old, array $cd)
{
$phrase[] = 'MODIFY COLUMN ' .
$this->quoteIdentifier($columnName) .
' ' .
$this->columnSql($cd);
$this->quoteIdentifier($columnName) .
' ' .
$this->columnSql($cd);
}
/**
@@ -735,7 +740,7 @@ class Schema
function appendAlterAddUnique(array &$phrase, $keyName, array $def)
{
$sql = array();
$sql = [];
$sql[] = 'ADD';
$this->appendUniqueKeyDef($sql, $keyName, $def);
$phrase[] = implode(' ', $sql);
@@ -743,7 +748,7 @@ class Schema
function appendAlterAddForeign(array &$phrase, $keyName, array $def)
{
$sql = array();
$sql = [];
$sql[] = 'ADD';
$this->appendForeignKeyDef($sql, $keyName, $def);
$phrase[] = implode(' ', $sql);
@@ -751,7 +756,7 @@ class Schema
function appendAlterAddPrimary(array &$phrase, array $def)
{
$sql = array();
$sql = [];
$sql[] = 'ADD';
$this->appendPrimaryKeyDef($sql, $def);
$phrase[] = implode(' ', $sql);
@@ -809,7 +814,7 @@ class Schema
*
* @param array $a
* @param array $b
* @return boolean
* @return bool
*/
function columnsEqual(array $a, array $b)
{
@@ -827,7 +832,7 @@ class Schema
protected function _names($cds)
{
$names = array();
$names = [];
foreach ($cds as $cd) {
$names[] = $cd->name;
@@ -840,7 +845,7 @@ class Schema
* Get a ColumnDef from an array matching
* name.
*
* @param array $cds Array of ColumnDef objects
* @param array $cds Array of ColumnDef objects
* @param string $name Name of the column
*
* @return ColumnDef matching item or null if no match.
@@ -864,14 +869,14 @@ class Schema
* Appropriate for use in CREATE TABLE or
* ALTER TABLE statements.
*
* @param ColumnDef $cd column to create
* @param array $cd column to create
*
* @return string correct SQL for that column
*/
function columnSql(array $cd)
{
$line = array();
$line = [];
$line[] = $this->typeAndSize($cd);
if (isset($cd['default'])) {
@@ -902,7 +907,7 @@ class Schema
if (isset($column['size'])) {
$type = $column['size'] . $type;
}
$lengths = array();
$lengths = [];
if (isset($column['precision'])) {
$lengths[] = $column['precision'];
@@ -926,20 +931,20 @@ class Schema
* with plugins written for 0.9.x.
*
* @param string $tableName
* @param array $defs: array of ColumnDef objects
* @param array $defs : array of ColumnDef objects
* @return array
*/
protected function oldToNew($tableName, array $defs)
{
$table = array();
$prefixes = array(
$table = [];
$prefixes = [
'tiny',
'small',
'medium',
'big',
);
];
foreach ($defs as $cd) {
$column = array();
$column = [];
$column['type'] = $cd->type;
foreach ($prefixes as $prefix) {
if (substr($cd->type, 0, strlen($prefix)) == $prefix) {
@@ -969,19 +974,19 @@ class Schema
// If multiple columns are defined as primary key,
// we'll pile them on in sequence.
if (!isset($table['primary key'])) {
$table['primary key'] = array();
$table['primary key'] = [];
}
$table['primary key'][] = $cd->name;
} else if ($cd->key == 'MUL') {
// Individual multiple-value indexes are only per-column
// using the old ColumnDef syntax.
$idx = "{$tableName}_{$cd->name}_idx";
$table['indexes'][$idx] = array($cd->name);
$table['indexes'][$idx] = [$cd->name];
} else if ($cd->key == 'UNI') {
// Individual unique-value indexes are only per-column
// using the old ColumnDef syntax.
$idx = "{$tableName}_{$cd->name}_idx";
$table['unique keys'][$idx] = array($cd->name);
$table['unique keys'][$idx] = [$cd->name];
}
}
@@ -996,6 +1001,7 @@ class Schema
* or type variants that we wouldn't get back from getTableDef().
*
* @param array $tableDef
* @return array
*/
function filterDef(array $tableDef)
{
@@ -1008,7 +1014,7 @@ class Schema
* If necessary, converts from an old-style array of ColumnDef objects.
*
* @param string $tableName
* @param array $def: table definition array
* @param array $def : table definition array
* @return array validated table definition array
*
* @throws Exception on wildly invalid input
@@ -1030,7 +1036,7 @@ class Schema
function isNumericType($type)
{
$type = strtolower($type);
$known = array('int', 'serial', 'numeric');
$known = ['int', 'serial', 'numeric'];
return in_array($type, $known);
}
@@ -1039,6 +1045,7 @@ class Schema
*
* @param string $sql
* @return array of arrays
* @throws PEAR_Exception
*/
protected function fetchQueryData($sql)
{
@@ -1049,8 +1056,8 @@ class Schema
PEAR_ErrorToPEAR_Exception($res);
}
$out = array();
$row = array();
$out = [];
$row = [];
while ($res->fetchInto($row, DB_FETCHMODE_ASSOC)) {
$out[] = $row;
}