Passed
Pull Request — release-2.1 (#7424)
by Jeremy
05:01
created

smf_db_list_indexes()   C

Complexity

Conditions 12
Paths 92

Size

Total Lines 56
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 12
eloc 29
c 1
b 0
f 0
nc 92
nop 3
dl 0
loc 56
rs 6.9666

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * This file contains database functionality specifically designed for packages (mods) to utilize.
5
 *
6
 * Simple Machines Forum (SMF)
7
 *
8
 * @package SMF
9
 * @author Simple Machines https://www.simplemachines.org
10
 * @copyright 2022 Simple Machines and individual contributors
11
 * @license https://www.simplemachines.org/about/smf/license.php BSD
12
 *
13
 * @version 2.1.0
14
 */
15
16
if (!defined('SMF'))
17
	die('No direct access...');
18
19
/**
20
 * Add the file functions to the $smcFunc array.
21
 */
22
function db_packages_init()
23
{
24
	global $smcFunc, $reservedTables, $db_package_log, $db_prefix;
25
26
	if (!isset($smcFunc['db_create_table']) || $smcFunc['db_create_table'] != 'smf_db_create_table')
27
	{
28
		$smcFunc += array(
29
			'db_add_column' => 'smf_db_add_column',
30
			'db_add_index' => 'smf_db_add_index',
31
			'db_calculate_type' => 'smf_db_calculate_type',
32
			'db_change_column' => 'smf_db_change_column',
33
			'db_create_table' => 'smf_db_create_table',
34
			'db_drop_table' => 'smf_db_drop_table',
35
			'db_table_structure' => 'smf_db_table_structure',
36
			'db_list_columns' => 'smf_db_list_columns',
37
			'db_list_indexes' => 'smf_db_list_indexes',
38
			'db_remove_column' => 'smf_db_remove_column',
39
			'db_remove_index' => 'smf_db_remove_index',
40
		);
41
		$db_package_log = array();
42
	}
43
44
	// We setup an array of SMF tables we can't do auto-remove on - in case a mod writer cocks it up!
45
	$reservedTables = array(
46
		'admin_info_files', 'approval_queue', 'attachments',
47
		'background_tasks', 'ban_groups', 'ban_items', 'board_permissions',
48
		'board_permissions_view', 'boards', 'calendar', 'calendar_holidays',
49
		'categories', 'custom_fields', 'group_moderators', 'log_actions',
50
		'log_activity', 'log_banned', 'log_boards', 'log_comments',
51
		'log_digest', 'log_errors', 'log_floodcontrol', 'log_group_requests',
52
		'log_mark_read', 'log_member_notices', 'log_notify', 'log_online',
53
		'log_packages', 'log_polls', 'log_reported', 'log_reported_comments',
54
		'log_scheduled_tasks', 'log_search_messages', 'log_search_results',
55
		'log_search_subjects', 'log_search_topics', 'log_spider_hits',
56
		'log_spider_stats', 'log_subscribed', 'log_topics', 'mail_queue',
57
		'member_logins', 'membergroups', 'members', 'mentions',
58
		'message_icons', 'messages', 'moderator_groups', 'moderators',
59
		'package_servers', 'permission_profiles', 'permissions',
60
		'personal_messages', 'pm_labeled_messages', 'pm_labels',
61
		'pm_recipients', 'pm_rules', 'poll_choices', 'polls', 'qanda',
62
		'scheduled_tasks', 'sessions', 'settings', 'smiley_files', 'smileys',
63
		'spiders', 'subscriptions', 'themes', 'topics', 'user_alerts',
64
		'user_alerts_prefs', 'user_drafts', 'user_likes',
65
	);
66
	foreach ($reservedTables as $k => $table_name)
67
		$reservedTables[$k] = strtolower($db_prefix . $table_name);
68
69
	// We in turn may need the extra stuff.
70
	db_extend('extra');
71
}
72
73
/**
74
 * This function can be used to create a table without worrying about schema
75
 *  compatibilities across supported database systems.
76
 *  - If the table exists will, by default, do nothing.
77
 *  - Builds table with columns as passed to it - at least one column must be sent.
78
 *  The columns array should have one sub-array for each column - these sub arrays contain:
79
 *  	'name' = Column name
80
 *  	'type' = Type of column - values from (smallint, mediumint, int, text, varchar, char, tinytext, mediumtext, largetext)
81
 *  	'size' => Size of column (If applicable) - for example 255 for a large varchar, 10 for an int etc.
82
 *  		If not set SMF will pick a size.
83
 *  	- 'default' = Default value - do not set if no default required.
84
 *  	- 'not_null' => Can it be null (true or false) - if not set default will be false.
85
 *  	- 'auto' => Set to true to make it an auto incrementing column. Set to a numerical value to set from what
86
 *  		 it should begin counting.
87
 *  - Adds indexes as specified within indexes parameter. Each index should be a member of $indexes. Values are:
88
 *  	- 'name' => Index name (If left empty SMF will generate).
89
 *  	- 'type' => Type of index. Choose from 'primary', 'unique' or 'index'. If not set will default to 'index'.
90
 *  	- 'columns' => Array containing columns that form part of key - in the order the index is to be created.
91
 *  - parameters: (None yet)
92
 *  - if_exists values:
93
 *  	- 'ignore' will do nothing if the table exists. (And will return true)
94
 *  	- 'overwrite' will drop any existing table of the same name.
95
 *  	- 'error' will return false if the table already exists.
96
 *  	- 'update' will update the table if the table already exists (no change of ai field and only colums with the same name keep the data)
97
 *
98
 * @param string $table_name The name of the table to create
99
 * @param array $columns An array of column info in the specified format
100
 * @param array $indexes An array of index info in the specified format
101
 * @param array $parameters Currently not used
102
 * @param string $if_exists What to do if the table exists.
103
 * @param string $error
104
 */
105
function smf_db_create_table($table_name, $columns, $indexes = array(), $parameters = array(), $if_exists = 'ignore', $error = 'fatal')
106
{
107
	global $reservedTables, $smcFunc, $db_package_log, $db_prefix, $db_name;
108
109
	$db_trans = false;
110
	$old_table_exists = false;
111
112
	// Strip out the table name, we might not need it in some cases
113
	$real_prefix = preg_match('~^("?)(.+?)\\1\\.(.*?)$~', $db_prefix, $match) === 1 ? $match[3] : $db_prefix;
114
	$database = !empty($match[2]) ? $match[2] : $db_name;
115
116
	// With or without the database name, the fullname looks like this.
117
	$full_table_name = str_replace('{db_prefix}', $real_prefix, $table_name);
118
	$short_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
119
120
	// First - no way do we touch SMF tables.
121
	if (in_array(strtolower($short_table_name), $reservedTables))
122
		return false;
123
124
	// Log that we'll want to remove this on uninstall.
125
	$db_package_log[] = array('remove_table', $short_table_name);
126
127
	// This... my friends... is a function in a half - let's start by checking if the table exists!
128
	$tables = $smcFunc['db_list_tables']($database);
129
	if (in_array($full_table_name, $tables))
130
	{
131
		// This is a sad day... drop the table? If not, return false (error) by default.
132
		if ($if_exists == 'overwrite')
133
			$smcFunc['db_drop_table']($table_name);
134
		elseif ($if_exists == 'update')
135
		{
136
			$smcFunc['db_drop_table']($table_name . '_old');
137
			$smcFunc['db_transaction']('begin');
138
			$db_trans = true;
139
			$smcFunc['db_query']('', '
140
				ALTER TABLE ' . $short_table_name . ' RENAME TO ' . $short_table_name . '_old',
141
				array(
142
					'security_override' => true,
143
				)
144
			);
145
			$old_table_exists = true;
146
		}
147
		else
148
			return $if_exists == 'ignore';
149
	}
150
151
	// If we've got this far - good news - no table exists. We can build our own!
152
	if (!$db_trans)
153
		$smcFunc['db_transaction']('begin');
154
	$table_query = 'CREATE TABLE ' . $short_table_name . "\n" . '(';
155
	foreach ($columns as $column)
156
	{
157
		$column = array_change_key_case($column);
158
159
		// If we have an auto increment do it!
160
		if (!empty($column['auto']))
161
		{
162
			if (!$old_table_exists)
163
				$smcFunc['db_query']('', '
164
					DROP SEQUENCE IF EXISTS ' . $short_table_name . '_seq',
165
					array(
166
						'security_override' => true,
167
					)
168
				);
169
170
			if (!$old_table_exists)
171
				$smcFunc['db_query']('', '
172
					CREATE SEQUENCE ' . $short_table_name . '_seq',
173
					array(
174
						'security_override' => true,
175
					)
176
				);
177
			$default = 'default nextval(\'' . $short_table_name . '_seq\')';
178
		}
179
		elseif (isset($column['default']) && $column['default'] !== null)
180
			$default = 'default \'' . $smcFunc['db_escape_string']($column['default']) . '\'';
181
		else
182
			$default = '';
183
184
		// Sort out the size...
185
		$column['size'] = isset($column['size']) && is_numeric($column['size']) ? $column['size'] : null;
186
		list ($type, $size) = $smcFunc['db_calculate_type']($column['type'], $column['size']);
187
		if ($size !== null)
188
			$type = $type . '(' . $size . ')';
189
190
		// backward compatibility
191
		if (isset($column['null']) && !isset($column['not_null']))
192
			$column['not_null'] = !$column['null'];
193
194
		// Now just put it together!
195
		$table_query .= "\n\t\"" . $column['name'] . '" ' . $type . ' ' . (!empty($column['not_null']) ? 'NOT NULL' : '') . ' ' . $default . ',';
196
	}
197
198
	// Loop through the indexes a sec...
199
	$index_queries = array();
200
	foreach ($indexes as $index)
201
	{
202
		// MySQL you can do a "column_name (length)", postgresql does not allow this.  Strip it.
203
		foreach ($index['columns'] as &$c)
204
			$c = preg_replace('~\s+(\(\d+\))~', '', $c);
205
206
		$idx_columns = implode(',', $index['columns']);
207
208
		// Primary goes in the table...
209
		if (isset($index['type']) && $index['type'] == 'primary')
210
			$table_query .= "\n\t" . 'PRIMARY KEY (' . implode(',', $index['columns']) . '),';
211
		else
212
		{
213
			if (empty($index['name']))
214
				$index['name'] = trim(implode('_', preg_replace('~(\(\d+\))~', '', $index['columns'])));
215
216
			$index_queries[] = 'CREATE ' . (isset($index['type']) && $index['type'] == 'unique' ? 'UNIQUE' : '') . ' INDEX ' . $short_table_name . '_' . $index['name'] . ' ON ' . $short_table_name . ' (' . $idx_columns . ')';
217
		}
218
	}
219
220
	// No trailing commas!
221
	if (substr($table_query, -1) == ',')
222
		$table_query = substr($table_query, 0, -1);
223
224
	$table_query .= ')';
225
226
	// Create the table!
227
	$smcFunc['db_query']('', $table_query,
228
		array(
229
			'security_override' => true,
230
		)
231
	);
232
233
	// Fill the old data
234
	if ($old_table_exists)
235
	{
236
		$same_col = array();
237
238
		$request = $smcFunc['db_query']('', '
239
			SELECT count(*), column_name
240
			FROM information_schema.columns
241
			WHERE table_name in ({string:table1},{string:table2}) AND table_schema = {string:schema}
242
			GROUP BY column_name
243
			HAVING count(*) > 1',
244
			array(
245
				'table1' => $short_table_name,
246
				'table2' => $short_table_name . '_old',
247
				'schema' => 'public',
248
			)
249
		);
250
251
		while ($row = $smcFunc['db_fetch_assoc']($request))
252
		{
253
			$same_col[] = $row['column_name'];
254
		}
255
256
		$smcFunc['db_query']('', '
257
			INSERT INTO ' . $short_table_name . '('
258
			. implode(',', $same_col) .
259
			')
260
			SELECT ' . implode(',', $same_col) . '
261
			FROM ' . $short_table_name . '_old',
262
			array()
263
		);
264
	}
265
266
	// And the indexes...
267
	foreach ($index_queries as $query)
268
		$smcFunc['db_query']('', $query,
269
			array(
270
				'security_override' => true,
271
			)
272
		);
273
274
	// Go, go power rangers!
275
	$smcFunc['db_transaction']('commit');
276
277
	if ($old_table_exists)
278
		$smcFunc['db_drop_table']($table_name . '_old');
279
280
	return true;
281
}
282
283
/**
284
 * Drop a table and its associated sequences.
285
 *
286
 * @param string $table_name The name of the table to drop
287
 * @param array $parameters Not used at the moment
288
 * @param string $error
289
 * @return boolean Whether or not the operation was successful
290
 */
291
function smf_db_drop_table($table_name, $parameters = array(), $error = 'fatal')
292
{
293
	global $reservedTables, $smcFunc, $db_prefix, $db_name;
294
295
	// After stripping away the database name, this is what's left.
296
	$real_prefix = preg_match('~^("?)(.+?)\\1\\.(.*?)$~', $db_prefix, $match) === 1 ? $match[3] : $db_prefix;
297
	$database = !empty($match[2]) ? $match[2] : $db_name;
298
299
	// Get some aliases.
300
	$full_table_name = str_replace('{db_prefix}', $real_prefix, $table_name);
301
	$short_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
302
303
	// God no - dropping one of these = bad.
304
	if (in_array(strtolower($table_name), $reservedTables))
305
		return false;
306
307
	// Does it exist?
308
	$tables = $smcFunc['db_list_tables']($database);
309
	if (in_array($full_table_name, $tables))
310
	{
311
		// We can then drop the table.
312
		$smcFunc['db_transaction']('begin');
313
314
		// the table
315
		$table_query = 'DROP TABLE ' . $short_table_name;
316
317
		// and the assosciated sequence, if any
318
		$sequence_query = 'DROP SEQUENCE IF EXISTS ' . $short_table_name . '_seq';
319
320
		// drop them
321
		$smcFunc['db_query']('',
322
			$table_query,
323
			array(
324
				'security_override' => true,
325
			)
326
		);
327
		$smcFunc['db_query']('',
328
			$sequence_query,
329
			array(
330
				'security_override' => true,
331
			)
332
		);
333
334
		$smcFunc['db_transaction']('commit');
335
336
		return true;
337
	}
338
339
	// Otherwise do 'nout.
340
	return false;
341
}
342
343
/**
344
 * This function adds a column.
345
 *
346
 * @param string $table_name The name of the table to add the column to
347
 * @param array $column_info An array of column info (see {@link smf_db_create_table()})
348
 * @param array $parameters Not used?
349
 * @param string $if_exists What to do if the column exists. If 'update', column is updated.
350
 * @param string $error
351
 * @return boolean Whether or not the operation was successful
352
 */
353
function smf_db_add_column($table_name, $column_info, $parameters = array(), $if_exists = 'update', $error = 'fatal')
354
{
355
	global $smcFunc, $db_package_log, $db_prefix;
356
357
	$short_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
358
	$column_info = array_change_key_case($column_info);
359
360
	// Log that we will want to uninstall this!
361
	$db_package_log[] = array('remove_column', $short_table_name, $column_info['name']);
362
363
	// Does it exist - if so don't add it again!
364
	$columns = $smcFunc['db_list_columns']($table_name, false);
365
	foreach ($columns as $column)
366
		if ($column == $column_info['name'])
367
		{
368
			// If we're going to overwrite then use change column.
369
			if ($if_exists == 'update')
370
				return $smcFunc['db_change_column']($table_name, $column_info['name'], $column_info);
371
			else
372
				return false;
373
		}
374
375
	// Get the specifics...
376
	$column_info['size'] = isset($column_info['size']) && is_numeric($column_info['size']) ? $column_info['size'] : null;
377
	list ($type, $size) = $smcFunc['db_calculate_type']($column_info['type'], $column_info['size']);
378
	if ($size !== null)
379
		$type = $type . '(' . $size . ')';
380
381
	// Now add the thing!
382
	$query = '
383
		ALTER TABLE ' . $short_table_name . '
384
		ADD COLUMN ' . $column_info['name'] . ' ' . $type;
385
	$smcFunc['db_query']('', $query,
386
		array(
387
			'security_override' => true,
388
		)
389
	);
390
391
	// If there's more attributes they need to be done via a change on PostgreSQL.
392
	unset($column_info['type'], $column_info['size']);
393
394
	if (count($column_info) != 1)
395
		return $smcFunc['db_change_column']($table_name, $column_info['name'], $column_info);
396
	else
397
		return true;
398
}
399
400
/**
401
 * Removes a column.
402
 *
403
 * @param string $table_name The name of the table to drop the column from
404
 * @param string $column_name The name of the column to drop
405
 * @param array $parameters Not used?
406
 * @param string $error
407
 * @return boolean Whether or not the operation was successful
408
 */
409
function smf_db_remove_column($table_name, $column_name, $parameters = array(), $error = 'fatal')
410
{
411
	global $smcFunc, $db_prefix;
412
413
	$short_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
414
415
	// Does it exist?
416
	$columns = $smcFunc['db_list_columns']($table_name, true);
417
418
	foreach ($columns as $column)
419
		if (strtolower($column['name']) == strtolower($column_name))
420
		{
421
			// If there is an auto we need remove it!
422
			if ($column['auto'])
423
				$smcFunc['db_query']('', '
424
					DROP SEQUENCE IF EXISTS ' . $short_table_name . '_seq',
425
					array(
426
						'security_override' => true,
427
					)
428
				);
429
430
			$smcFunc['db_query']('', '
431
				ALTER TABLE ' . $short_table_name . '
432
				DROP COLUMN ' . $column_name,
433
				array(
434
					'security_override' => true,
435
				)
436
			);
437
438
			return true;
439
		}
440
441
	// If here we didn't have to work - joy!
442
	return false;
443
}
444
445
/**
446
 * Change a column.
447
 *
448
 * @param string $table_name The name of the table this column is in
449
 * @param string $old_column The name of the column we want to change
450
 * @param array $column_info An array of info about the "new" column definition (see {@link smf_db_create_table()})
451
 * @return bool
452
 */
453
function smf_db_change_column($table_name, $old_column, $column_info)
454
{
455
	global $smcFunc, $db_prefix;
456
457
	$short_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
458
	$column_info = array_change_key_case($column_info);
459
460
	// backward compatibility
461
	if (isset($column_info['null']) && !isset($column_info['not_null']))
462
		$column_info['not_null'] = !$column_info['null'];
463
464
	// Check it does exist!
465
	$columns = $smcFunc['db_list_columns']($table_name, true);
466
	$old_info = null;
467
	foreach ($columns as $column)
468
		if ($column['name'] == $old_column)
469
			$old_info = $column;
470
471
	// Nothing?
472
	if ($old_info == null)
473
		return false;
474
475
	// Now we check each bit individually and ALTER as required.
476
	if (isset($column_info['name']) && $column_info['name'] != $old_column)
477
	{
478
		$smcFunc['db_query']('', '
479
			ALTER TABLE ' . $short_table_name . '
480
			RENAME COLUMN ' . $old_column . ' TO ' . $column_info['name'],
481
			array(
482
				'security_override' => true,
483
			)
484
		);
485
	}
486
	// Different default?
487
	if (array_key_exists('default', $column_info) && $column_info['default'] != $old_info['default'])
488
	{
489
		// Fix the default.
490
		$default = '';
491
		if (array_key_exists('default', $column_info) && is_null($column_info['default']))
492
			$default = 'NULL';
493
		elseif (isset($column_info['default']) && is_numeric($column_info['default']))
494
			$default = strpos($column_info['default'], '.') ? floatval($column_info['default']) : intval($column_info['default']);
495
		else
496
			$default = '\'' . $smcFunc['db_escape_string']($column_info['default']) . '\'';
497
498
		$action = $default === '' ? 'DROP DEFAULT' : 'SET DEFAULT ' . $default;
499
		$smcFunc['db_query']('', '
500
			ALTER TABLE ' . $short_table_name . '
501
			ALTER COLUMN ' . $column_info['name'] . ' ' . $action,
502
			array(
503
				'security_override' => true,
504
			)
505
		);
506
	}
507
508
	// Is it null - or otherwise?
509
	if (isset($column_info['not_null']) && $column_info['not_null'] != $old_info['not_null'])
510
	{
511
		$action = $column_info['not_null'] ? 'SET' : 'DROP';
512
		$smcFunc['db_transaction']('begin');
513
		if ($column_info['not_null'])
514
		{
515
			// We have to set it to something if we are making it NOT NULL. And we must comply with the current column format.
516
			$setTo = isset($column_info['default']) ? $column_info['default'] : (strpos($old_info['type'], 'int') !== false ? 0 : '');
517
			$smcFunc['db_query']('', '
518
				UPDATE ' . $short_table_name . '
519
				SET ' . $column_info['name'] . ' = \'' . $setTo . '\'
520
				WHERE ' . $column_info['name'] . ' IS NULL',
521
				array(
522
					'security_override' => true,
523
				)
524
			);
525
		}
526
		$smcFunc['db_query']('', '
527
			ALTER TABLE ' . $short_table_name . '
528
			ALTER COLUMN ' . $column_info['name'] . ' ' . $action . ' NOT NULL',
529
			array(
530
				'security_override' => true,
531
			)
532
		);
533
		$smcFunc['db_transaction']('commit');
534
	}
535
	// What about a change in type?
536
	if (isset($column_info['type']) && ($column_info['type'] != $old_info['type'] || (isset($column_info['size']) && $column_info['size'] != $old_info['size'])))
537
	{
538
		$column_info['size'] = isset($column_info['size']) && is_numeric($column_info['size']) ? $column_info['size'] : null;
539
		list ($type, $size) = $smcFunc['db_calculate_type']($column_info['type'], $column_info['size']);
540
		if ($size !== null)
541
			$type = $type . '(' . $size . ')';
542
543
		// The alter is a pain.
544
		$smcFunc['db_transaction']('begin');
545
		$smcFunc['db_query']('', '
546
			ALTER TABLE ' . $short_table_name . '
547
			ADD COLUMN ' . $column_info['name'] . '_tempxx ' . $type,
548
			array(
549
				'security_override' => true,
550
			)
551
		);
552
		$smcFunc['db_query']('', '
553
			UPDATE ' . $short_table_name . '
554
			SET ' . $column_info['name'] . '_tempxx = CAST(' . $column_info['name'] . ' AS ' . $type . ')',
555
			array(
556
				'security_override' => true,
557
			)
558
		);
559
		$smcFunc['db_query']('', '
560
			ALTER TABLE ' . $short_table_name . '
561
			DROP COLUMN ' . $column_info['name'],
562
			array(
563
				'security_override' => true,
564
			)
565
		);
566
		$smcFunc['db_query']('', '
567
			ALTER TABLE ' . $short_table_name . '
568
			RENAME COLUMN ' . $column_info['name'] . '_tempxx TO ' . $column_info['name'],
569
			array(
570
				'security_override' => true,
571
			)
572
		);
573
		$smcFunc['db_transaction']('commit');
574
	}
575
	// Finally - auto increment?!
576
	if (isset($column_info['auto']) && $column_info['auto'] != $old_info['auto'])
577
	{
578
		// Are we removing an old one?
579
		if ($old_info['auto'])
580
		{
581
			// Alter the table first - then drop the sequence.
582
			$smcFunc['db_query']('', '
583
				ALTER TABLE ' . $short_table_name . '
584
				ALTER COLUMN ' . $column_info['name'] . ' SET DEFAULT \'0\'',
585
				array(
586
					'security_override' => true,
587
				)
588
			);
589
			$smcFunc['db_query']('', '
590
				DROP SEQUENCE IF EXISTS ' . $short_table_name . '_seq',
591
				array(
592
					'security_override' => true,
593
				)
594
			);
595
		}
596
		// Otherwise add it!
597
		else
598
		{
599
			$smcFunc['db_query']('', '
600
				DROP SEQUENCE IF EXISTS ' . $short_table_name . '_seq',
601
				array(
602
					'security_override' => true,
603
				)
604
			);
605
606
			$smcFunc['db_query']('', '
607
				CREATE SEQUENCE ' . $short_table_name . '_seq',
608
				array(
609
					'security_override' => true,
610
				)
611
			);
612
			$smcFunc['db_query']('', '
613
				ALTER TABLE ' . $short_table_name . '
614
				ALTER COLUMN ' . $column_info['name'] . ' SET DEFAULT nextval(\'' . $short_table_name . '_seq\')',
615
				array(
616
					'security_override' => true,
617
				)
618
			);
619
		}
620
	}
621
622
	return true;
623
}
624
625
/**
626
 * Add an index.
627
 *
628
 * @param string $table_name The name of the table to add the index to
629
 * @param array $index_info An array of index info (see {@link smf_db_create_table()})
630
 * @param array $parameters Not used?
631
 * @param string $if_exists What to do if the index exists. If 'update', the definition will be updated.
632
 * @param string $error
633
 * @return boolean Whether or not the operation was successful
634
 */
635
function smf_db_add_index($table_name, $index_info, $parameters = array(), $if_exists = 'update', $error = 'fatal')
636
{
637
	global $smcFunc, $db_package_log, $db_prefix;
638
639
	$parsed_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
640
	$real_table_name = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $parsed_table_name, $match) === 1 ? $match[3] : $parsed_table_name;
641
642
	// No columns = no index.
643
	if (empty($index_info['columns']))
644
		return false;
645
646
	// MySQL you can do a "column_name (length)", postgresql does not allow this.  Strip it.
647
	foreach ($index_info['columns'] as &$c)
648
		$c = preg_replace('~\s+(\(\d+\))~', '', $c);
649
650
	$columns = implode(',', $index_info['columns']);
651
652
	// No name - make it up!
653
	if (empty($index_info['name']))
654
	{
655
		// No need for primary.
656
		if (isset($index_info['type']) && $index_info['type'] == 'primary')
657
			$index_info['name'] = '';
658
		else
659
			$index_info['name'] = trim(implode('_', preg_replace('~(\(\d+\))~', '', $index_info['columns'])));
660
	}
661
	else
662
		$index_info['name'] = $index_info['name'];
663
664
	// Log that we are going to want to remove this!
665
	$db_package_log[] = array('remove_index', $parsed_table_name, $index_info['name']);
666
667
	// Let's get all our indexes.
668
	$indexes = $smcFunc['db_list_indexes']($table_name, true);
669
670
	// Do we already have it?
671
	foreach ($indexes as $index)
672
	{
673
		if ($index['name'] == $index_info['name'] || ($index['type'] == 'primary' && isset($index_info['type']) && $index_info['type'] == 'primary'))
674
		{
675
			// If we want to overwrite simply remove the current one then continue.
676
			if ($if_exists != 'update' || $index['type'] == 'primary')
677
				return false;
678
			else
679
				$smcFunc['db_remove_index']($table_name, $index_info['name']);
680
		}
681
	}
682
683
	// If we're here we know we don't have the index - so just add it.
684
	if (!empty($index_info['type']) && $index_info['type'] == 'primary')
685
	{
686
		$smcFunc['db_query']('', '
687
			ALTER TABLE ' . $real_table_name . '
688
			ADD PRIMARY KEY (' . $columns . ')',
689
			array(
690
				'security_override' => true,
691
			)
692
		);
693
	}
694
	else
695
	{
696
		$smcFunc['db_query']('', '
697
			CREATE ' . (isset($index_info['type']) && $index_info['type'] == 'unique' ? 'UNIQUE' : '') . ' INDEX ' . $real_table_name . '_' . $index_info['name'] . ' ON ' . $real_table_name . ' (' . $columns . ')',
698
			array(
699
				'security_override' => true,
700
			)
701
		);
702
	}
703
}
704
705
/**
706
 * Remove an index.
707
 *
708
 * @param string $table_name The name of the table to remove the index from
709
 * @param string $index_name The name of the index to remove
710
 * @param array $parameters Not used?
711
 * @param string $error
712
 * @return boolean Whether or not the operation was successful
713
 */
714
function smf_db_remove_index($table_name, $index_name, $parameters = array(), $error = 'fatal')
715
{
716
	global $smcFunc, $db_prefix;
717
718
	$parsed_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
719
	$real_table_name = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $parsed_table_name, $match) === 1 ? $match[3] : $parsed_table_name;
720
721
	// Better exist!
722
	$indexes = $smcFunc['db_list_indexes']($table_name, true);
723
724
	// Do not add the table name to the index if it is arleady there.
725
	if ($index_name != 'primary' && strpos($index_name, $real_table_name) !== false)
726
		$index_name = str_replace($real_table_name . '_', '', $index_name);
727
728
	foreach ($indexes as $index)
729
	{
730
		// If the name is primary we want the primary key!
731
		if ($index['type'] == 'primary' && $index_name == 'primary')
732
		{
733
			// Dropping primary key is odd...
734
			$smcFunc['db_query']('', '
735
				ALTER TABLE ' . $real_table_name . '
736
				DROP CONSTRAINT ' . $index['name'],
737
				array(
738
					'security_override' => true,
739
				)
740
			);
741
742
			return true;
743
		}
744
745
		if ($index['name'] == $index_name)
746
		{
747
			// Drop the bugger...
748
			$smcFunc['db_query']('', '
749
				DROP INDEX ' . $real_table_name . '_' . $index_name,
750
				array(
751
					'security_override' => true,
752
				)
753
			);
754
755
			return true;
756
		}
757
	}
758
759
	// Not to be found ;(
760
	return false;
761
}
762
763
/**
764
 * Get the schema formatted name for a type.
765
 *
766
 * @param string $type_name The data type (int, varchar, smallint, etc.)
767
 * @param int $type_size The size (8, 255, etc.)
768
 * @param boolean $reverse If true, returns specific types for a generic type
769
 * @return array An array containing the appropriate type and size for this DB type
770
 */
771
function smf_db_calculate_type($type_name, $type_size = null, $reverse = false)
772
{
773
	// Let's be sure it's lowercase MySQL likes both, others no.
774
	$type_name = strtolower($type_name);
775
	// Generic => Specific.
776
	if (!$reverse)
777
	{
778
		$types = array(
779
			'varchar' => 'character varying',
780
			'char' => 'character',
781
			'mediumint' => 'int',
782
			'tinyint' => 'smallint',
783
			'tinytext' => 'character varying',
784
			'mediumtext' => 'text',
785
			'largetext' => 'text',
786
			'inet' => 'inet',
787
			'time' => 'time without time zone',
788
			'datetime' => 'timestamp without time zone',
789
			'timestamp' => 'timestamp without time zone',
790
		);
791
	}
792
	else
793
	{
794
		$types = array(
795
			'character varying' => 'varchar',
796
			'character' => 'char',
797
			'integer' => 'int',
798
			'inet' => 'inet',
799
			'time without time zone' => 'time',
800
			'timestamp without time zone' => 'datetime',
801
			'numeric' => 'decimal',
802
		);
803
	}
804
805
	// Got it? Change it!
806
	if (isset($types[$type_name]))
807
	{
808
		if ($type_name == 'tinytext')
809
			$type_size = 255;
810
		$type_name = $types[$type_name];
811
	}
812
813
	// Only char fields got size
814
	if (strpos($type_name, 'char') === false)
815
		$type_size = null;
816
817
	return array($type_name, $type_size);
818
}
819
820
/**
821
 * Get table structure.
822
 *
823
 * @param string $table_name The name of the table
824
 * @return array An array of table structure - the name, the column info from {@link smf_db_list_columns()} and the index info from {@link smf_db_list_indexes()}
825
 */
826
function smf_db_table_structure($table_name)
827
{
828
	global $smcFunc, $db_prefix;
829
830
	$parsed_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
831
	$real_table_name = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $parsed_table_name, $match) === 1 ? $match[3] : $parsed_table_name;
832
833
	return array(
834
		'name' => $real_table_name,
835
		'columns' => $smcFunc['db_list_columns']($table_name, true),
836
		'indexes' => $smcFunc['db_list_indexes']($table_name, true),
837
	);
838
}
839
840
/**
841
 * Return column information for a table.
842
 *
843
 * @param string $table_name The name of the table to get column info for
844
 * @param bool $detail Whether or not to return detailed info. If true, returns the column info. If false, just returns the column names.
845
 * @param array $parameters Not used?
846
 * @return array An array of column names or detailed column info, depending on $detail
847
 */
848
function smf_db_list_columns($table_name, $detail = false, $parameters = array())
849
{
850
	global $smcFunc, $db_prefix, $db_name;
851
852
	$parsed_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
853
	$real_table_name = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $parsed_table_name, $match) === 1 ? $match[3] : $parsed_table_name;
854
	$database = !empty($match[2]) ? $match[2] : $db_name;
0 ignored issues
show
Unused Code introduced by
The assignment to $database is dead and can be removed.
Loading history...
855
856
	$result = $smcFunc['db_query']('', '
857
		SELECT column_name, column_default, is_nullable, data_type, character_maximum_length
858
		FROM information_schema.columns
859
		WHERE table_schema = {string:schema_public}
860
			AND table_name = {string:table_name}
861
		ORDER BY ordinal_position',
862
		array(
863
			'schema_public' => 'public',
864
			'table_name' => $real_table_name,
865
		)
866
	);
867
	$columns = array();
868
	while ($row = $smcFunc['db_fetch_assoc']($result))
869
	{
870
		if (!$detail)
871
		{
872
			$columns[] = $row['column_name'];
873
		}
874
		else
875
		{
876
			$auto = false;
877
			// What is the default?
878
			if (preg_match('~nextval\(\'(.+?)\'(.+?)*\)~i', $row['column_default'], $matches) != 0)
879
			{
880
				$default = null;
881
				$auto = true;
882
			}
883
			elseif (trim($row['column_default']) != '')
884
				$default = trim(strpos($row['column_default'], '::') === false ? $row['column_default'] : substr($row['column_default'], 0, strpos($row['column_default'], '::')), '\'');
885
			else
886
				$default = null;
887
888
			// Make the type generic.
889
			list ($type, $size) = $smcFunc['db_calculate_type']($row['data_type'], $row['character_maximum_length'], true);
890
891
			$columns[$row['column_name']] = array(
892
				'name' => $row['column_name'],
893
				'not_null' => $row['is_nullable'] == 'YES' ? false : true,
894
				'null' => $row['is_nullable'] == 'YES' ? true : false,
895
				'default' => $default,
896
				'type' => $type,
897
				'size' => $size,
898
				'auto' => $auto,
899
			);
900
		}
901
	}
902
	$smcFunc['db_free_result']($result);
903
904
	return $columns;
905
}
906
907
/**
908
 * Get index information.
909
 *
910
 * @param string $table_name The name of the table to get indexes for
911
 * @param bool $detail Whether or not to return detailed info.
912
 * @param array $parameters Not used?
913
 * @return array An array of index names or a detailed array of index info, depending on $detail
914
 */
915
function smf_db_list_indexes($table_name, $detail = false, $parameters = array())
916
{
917
	global $smcFunc, $db_prefix, $db_name;
918
919
	$parsed_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
920
	$real_table_name = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $parsed_table_name, $match) === 1 ? $match[3] : $parsed_table_name;
921
	$database = !empty($match[2]) ? $match[2] : $db_name;
0 ignored issues
show
Unused Code introduced by
The assignment to $database is dead and can be removed.
Loading history...
922
923
	$result = $smcFunc['db_query']('', '
924
		SELECT CASE WHEN i.indisprimary THEN 1 ELSE 0 END AS is_primary,
925
			CASE WHEN i.indisunique THEN 1 ELSE 0 END AS is_unique,
926
			c2.relname AS name,
927
			pg_get_indexdef(i.indexrelid) AS inddef
928
		FROM pg_class AS c, pg_class AS c2, pg_index AS i
929
		WHERE c.relname = {string:table_name}
930
			AND c.oid = i.indrelid
931
			AND i.indexrelid = c2.oid',
932
		array(
933
			'table_name' => $real_table_name,
934
		)
935
	);
936
	$indexes = array();
937
	while ($row = $smcFunc['db_fetch_assoc']($result))
938
	{
939
		// Try get the columns that make it up.
940
		if (preg_match('~\(([^\)]+?)\)~i', $row['inddef'], $matches) == 0)
941
			continue;
942
943
		$columns = explode(',', $matches[1]);
944
945
		if (empty($columns))
946
			continue;
947
948
		foreach ($columns as $k => $v)
949
			$columns[$k] = trim($v);
950
951
		// Fix up the name to be consistent cross databases
952
		if (substr($row['name'], -5) == '_pkey' && $row['is_primary'] == 1)
953
			$row['name'] = 'PRIMARY';
954
		else
955
			$row['name'] = str_replace($real_table_name . '_', '', $row['name']);
956
957
		if (!$detail)
958
			$indexes[] = $row['name'];
959
		else
960
		{
961
			$indexes[$row['name']] = array(
962
				'name' => $row['name'],
963
				'type' => $row['is_primary'] ? 'primary' : ($row['is_unique'] ? 'unique' : 'index'),
964
				'columns' => $columns,
965
			);
966
		}
967
	}
968
	$smcFunc['db_free_result']($result);
969
970
	return $indexes;
971
}
972
973
?>