3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Database;
25 use Friendica\Util\Writer\ViewDefinitionSqlWriter;
32 * @param bool $verbose Whether to show SQL statements
33 * @param bool $action Whether to execute SQL statements
36 public static function create(bool $verbose, bool $action)
38 // Delete previously used views that aren't used anymore
39 foreach (['post-view', 'post-thread-view'] as $view) {
40 if (self::isView($view)) {
41 $sql = sprintf("DROP VIEW IF EXISTS `%s`", DBA::escape($view));
42 if (!empty($sql) && $verbose) {
46 if (!empty($sql) && $action) {
52 $definition = DI::viewDefinition()->getAll();
54 foreach ($definition as $name => $structure) {
55 if (self::isView($name)) {
56 DBA::e(sprintf("DROP VIEW IF EXISTS `%s`", DBA::escape($name)));
57 } elseif (self::isTable($name)) {
58 DBA::e(sprintf("DROP TABLE IF EXISTS `%s`", DBA::escape($name)));
60 DBA::e(ViewDefinitionSqlWriter::createView($name, $structure));
65 * Check if the given table/view is a view
68 * @return boolean "true" if it's a view
70 private static function isView(string $view): bool
72 $status = DBA::selectFirst('INFORMATION_SCHEMA.TABLES', ['TABLE_TYPE'],
73 ['TABLE_SCHEMA' => DBA::databaseName(), 'TABLE_NAME' => $view]);
75 if (empty($status['TABLE_TYPE'])) {
79 return $status['TABLE_TYPE'] == 'VIEW';
83 * Check if the given table/view is a table
85 * @param string $table
86 * @return boolean "true" if it's a table
88 private static function isTable(string $table): bool
90 $status = DBA::selectFirst('INFORMATION_SCHEMA.TABLES', ['TABLE_TYPE'],
91 ['TABLE_SCHEMA' => DBA::databaseName(), 'TABLE_NAME' => $table]);
93 if (empty($status['TABLE_TYPE'])) {
97 return $status['TABLE_TYPE'] == 'BASE TABLE';