3 * @copyright Copyright (C) 2020, Friendica
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\Core\Hook;
31 * view definition loaded from static/dbview.config.php
35 private static $definition = [];
38 * Loads the database structure definition from the static/dbview.config.php file.
39 * On first pass, defines DB_UPDATE_VERSION constant.
41 * @see static/dbview.config.php
42 * @param boolean $with_addons_structure Whether to tack on addons additional tables
43 * @param string $basePath The base path of this application
47 public static function definition($basePath = '', $with_addons_structure = true)
49 if (!self::$definition) {
50 if (empty($basePath)) {
51 $basePath = DI::app()->getBasePath();
54 $filename = $basePath . '/static/dbview.config.php';
56 if (!is_readable($filename)) {
57 throw new Exception('Missing database view config file static/dbview.config.php');
60 $definition = require $filename;
63 throw new Exception('Corrupted database view config file static/dbview.config.php');
66 self::$definition = $definition;
68 $definition = self::$definition;
71 if ($with_addons_structure) {
72 Hook::callAll('dbview_definition', $definition);
78 public static function create(bool $verbose, bool $action)
80 $definition = self::definition();
82 foreach ($definition as $name => $structure) {
83 self::createview($name, $structure, $verbose, $action);
87 public static function printStructure($basePath)
89 $database = self::definition($basePath, false);
91 foreach ($database AS $name => $structure) {
93 echo "-- VIEW $name\n";
95 self::createView($name, $structure, true, false);
101 private static function createview($name, $structure, $verbose, $action)
106 foreach ($structure["fields"] AS $fieldname => $origin) {
107 if (is_string($origin)) {
108 $sql_rows[] = $origin . " AS `" . DBA::escape($fieldname) . "`";
109 } elseif (is_array($origin) && (sizeof($origin) == 2)) {
110 $sql_rows[] = "`" . DBA::escape($origin[0]) . "`.`" . DBA::escape($origin[1]) . "` AS `" . DBA::escape($fieldname) . "`";
114 $sql = sprintf("DROP VIEW IF EXISTS `%s`", DBA::escape($name));
124 $sql = sprintf("CREATE VIEW `%s` AS SELECT \n\t", DBA::escape($name)) .
125 implode(",\n\t", $sql_rows) . "\n\t" . $structure['query'];