]> git.mxchange.org Git - friendica.git/blob - src/Util/Writer/DbaDefinitionSqlWriter.php
Fix: Pagination in search result works again
[friendica.git] / src / Util / Writer / DbaDefinitionSqlWriter.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Util\Writer;
23
24 use Exception;
25 use Friendica\App;
26 use Friendica\Database\Definition\DbaDefinition;
27
28 /**
29  * SQL writer utility for the database definition
30  */
31 class DbaDefinitionSqlWriter
32 {
33         /**
34          * Creates a complete SQL definition bases on a give DBA Definition class
35          *
36          * @param DbaDefinition $definition The DBA definition class
37          *
38          * @return string The SQL definition as a string
39          *
40          * @throws Exception in case of parameter failures
41          */
42         public static function create(DbaDefinition $definition): string
43         {
44                 $sqlString = "-- ------------------------------------------\n";
45                 $sqlString .= "-- " . App::PLATFORM . " " . App::VERSION . " (" . App::CODENAME . ")\n";
46                 $sqlString .= "-- DB_UPDATE_VERSION " . DB_UPDATE_VERSION . "\n";
47                 $sqlString .= "-- ------------------------------------------\n\n\n";
48
49                 foreach ($definition->getAll() as $tableName => $tableStructure) {
50                         $sqlString .= "--\n";
51                         $sqlString .= "-- TABLE $tableName\n";
52                         $sqlString .= "--\n";
53                         $sqlString .= static::createTable($tableName, $tableStructure);
54                 }
55
56                 return $sqlString;
57         }
58
59         /**
60          * Creates the SQL definition of one table
61          *
62          * @param string $tableName The table name
63          * @param array  $tableStructure The table structure
64          *
65          * @return string The SQL definition
66          *
67          * @throws Exception in cases of structure failures
68          */
69         public static function createTable(string $tableName, array $tableStructure): string
70         {
71                 $engine       = '';
72                 $comment      = '';
73                 $sql_rows     = [];
74                 $primary_keys = [];
75                 $foreign_keys = [];
76
77                 foreach ($tableStructure['fields'] as $fieldName => $field) {
78                         $sql_rows[] = '`' . static::escape($fieldName) . '` ' . self::fieldCommand($field);
79                         if (!empty($field['primary'])) {
80                                 $primary_keys[] = $fieldName;
81                         }
82                         if (!empty($field['foreign'])) {
83                                 $foreign_keys[$fieldName] = $field;
84                         }
85                 }
86
87                 if (!empty($tableStructure['indexes'])) {
88                         foreach ($tableStructure['indexes'] as $indexName => $fieldNames) {
89                                 $sql_index = self::createIndex($indexName, $fieldNames, '');
90                                 if (!is_null($sql_index)) {
91                                         $sql_rows[] = $sql_index;
92                                 }
93                         }
94                 }
95
96                 foreach ($foreign_keys as $fieldName => $parameters) {
97                         $sql_rows[] = self::foreignCommand($fieldName, $parameters);
98                 }
99
100                 if (isset($tableStructure['engine'])) {
101                         $engine = ' ENGINE=' . $tableStructure['engine'];
102                 }
103
104                 if (isset($tableStructure['comment'])) {
105                         $comment = " COMMENT='" . static::escape($tableStructure['comment']) . "'";
106                 }
107
108                 $sql = implode(",\n\t", $sql_rows);
109
110                 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", static::escape($tableName)) . $sql .
111                            "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
112                 return $sql . ";\n\n";
113         }
114
115         /**
116          * Standard escaping for SQL definitions
117          *
118          * @param string $sqlString the SQL string to escape
119          *
120          * @return string escaped SQL string
121          */
122         public static function escape(string $sqlString): string
123         {
124                 return str_replace("'", "\\'", $sqlString);
125         }
126
127         /**
128          * Creates the SQL definition to add a foreign key
129          *
130          * @param string $keyName    The foreign key name
131          * @param array  $parameters The given parameters of the foreign key
132          *
133          * @return string The SQL definition
134          */
135         public static function addForeignKey(string $keyName, array $parameters): string
136         {
137                 return sprintf("ADD %s", static::foreignCommand($keyName, $parameters));
138         }
139
140         /**
141          * Creates the SQL definition to drop a foreign key
142          *
143          * @param string $keyName The foreign key name
144          *
145          * @return string The SQL definition
146          */
147         public static function dropForeignKey(string $keyName): string
148         {
149                 return sprintf("DROP FOREIGN KEY `%s`", $keyName);
150         }
151
152         /**
153          * Creates the SQL definition to drop an index
154          *
155          * @param string $indexName The index name
156          *
157          * @return string The SQL definition
158          */
159         public static function dropIndex(string $indexName): string
160         {
161                 return sprintf("DROP INDEX `%s`", static::escape($indexName));
162         }
163
164         /**
165          * Creates the SQL definition to add a table field
166          *
167          * @param string $fieldName  The table field name
168          * @param array  $parameters The parameters of the table field
169          *
170          * @return string The SQL definition
171          */
172         public static function addTableField(string $fieldName, array $parameters): string
173         {
174                 return sprintf("ADD `%s` %s", static::escape($fieldName), static::fieldCommand($parameters));
175         }
176
177         /**
178          * Creates the SQL definition to modify a table field
179          *
180          * @param string $fieldName  The table field name
181          * @param array  $parameters The parameters to modify
182          *
183          * @return string The SQL definition
184          */
185         public static function modifyTableField(string $fieldName, array $parameters): string
186         {
187                 return sprintf("MODIFY `%s` %s", static::escape($fieldName), self::fieldCommand($parameters, false));
188         }
189
190         /**
191          * Returns SQL statement for field
192          *
193          * @param array   $parameters Parameters for SQL statement
194          * @param boolean $create Whether to include PRIMARY KEY statement (unused)
195          * @return string SQL statement part
196          */
197         public static function fieldCommand(array $parameters, bool $create = true): string
198         {
199                 $fieldstruct = $parameters['type'];
200
201                 if (isset($parameters['Collation'])) {
202                         $fieldstruct .= ' COLLATE ' . $parameters['Collation'];
203                 }
204
205                 if (isset($parameters['not null'])) {
206                         $fieldstruct .= ' NOT NULL';
207                 }
208
209                 if (isset($parameters['default'])) {
210                         if (strpos(strtolower($parameters['type']), 'int') !== false) {
211                                 $fieldstruct .= ' DEFAULT ' . $parameters['default'];
212                         } else {
213                                 $fieldstruct .= " DEFAULT '" . $parameters['default'] . "'";
214                         }
215                 }
216                 if (isset($parameters['extra'])) {
217                         $fieldstruct .= ' ' . $parameters['extra'];
218                 }
219
220                 if (isset($parameters['comment'])) {
221                         $fieldstruct .= " COMMENT '" . static::escape($parameters['comment']) . "'";
222                 }
223
224                 /*if (($parameters['primary'] != '') && $create)
225                         $fieldstruct .= ' PRIMARY KEY';*/
226
227                 return $fieldstruct;
228         }
229
230         /**
231          * Creates the SQL definition to create an index
232          *
233          * @param string $indexName  The index name
234          * @param array  $fieldNames The field names of this index
235          * @param string $method     The method to create the index (default is ADD)
236          *
237          * @return string The SQL definition
238          * @throws Exception in cases the parameter contains invalid content
239          */
240         public static function createIndex(string $indexName, array $fieldNames, string $method = 'ADD'): string
241         {
242                 $method = strtoupper(trim($method));
243                 if ($method != '' && $method != 'ADD') {
244                         throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
245                 }
246
247                 if (in_array($fieldNames[0], ['UNIQUE', 'FULLTEXT'])) {
248                         $index_type = array_shift($fieldNames);
249                         $method .= " " . $index_type;
250                 }
251
252                 $names = "";
253                 foreach ($fieldNames as $fieldName) {
254                         if ($names != '') {
255                                 $names .= ',';
256                         }
257
258                         if (preg_match('|(.+)\((\d+)\)|', $fieldName, $matches)) {
259                                 $names .= "`" . static::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
260                         } else {
261                                 $names .= "`" . static::escape($fieldName) . "`";
262                         }
263                 }
264
265                 if ($indexName == 'PRIMARY') {
266                         return sprintf("%s PRIMARY KEY(%s)", $method, $names);
267                 }
268
269
270                 return sprintf("%s INDEX `%s` (%s)", $method, static::escape($indexName), $names);
271         }
272
273         /**
274          * Creates the SQL definition for foreign keys
275          *
276          * @param string $foreignKeyName The foreign key name
277          * @param array  $parameters     The parameters of the foreign key
278          *
279          * @return string The SQL definition
280          */
281         public static function foreignCommand(string $foreignKeyName, array $parameters): string
282         {
283                 $foreign_table = array_keys($parameters['foreign'])[0];
284                 $foreign_field = array_values($parameters['foreign'])[0];
285
286                 $sql = "FOREIGN KEY (`" . $foreignKeyName . "`) REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
287
288                 if (!empty($parameters['foreign']['on update'])) {
289                         $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
290                 } else {
291                         $sql .= " ON UPDATE RESTRICT";
292                 }
293
294                 if (!empty($parameters['foreign']['on delete'])) {
295                         $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
296                 } else {
297                         $sql .= " ON DELETE CASCADE";
298                 }
299
300                 return $sql;
301         }
302 }