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

smf_db_add_index()   D

Complexity

Conditions 18
Paths 86

Size

Total Lines 65
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 18
eloc 34
c 1
b 0
f 0
nc 86
nop 5
dl 0
loc 65
rs 4.8666

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
		// If we have an auto increment do it!
158
		if (!empty($column['auto']))
159
		{
160
			if (!$old_table_exists)
161
				$smcFunc['db_query']('', '
162
					DROP SEQUENCE IF EXISTS ' . $short_table_name . '_seq',
163
					array(
164
						'security_override' => true,
165
					)
166
				);
167
168
			if (!$old_table_exists)
169
				$smcFunc['db_query']('', '
170
					CREATE SEQUENCE ' . $short_table_name . '_seq',
171
					array(
172
						'security_override' => true,
173
					)
174
				);
175
			$default = 'default nextval(\'' . $short_table_name . '_seq\')';
176
		}
177
		elseif (isset($column['default']) && $column['default'] !== null)
178
			$default = 'default \'' . $smcFunc['db_escape_string']($column['default']) . '\'';
179
		else
180
			$default = '';
181
182
		// Sort out the size...
183
		$column['size'] = isset($column['size']) && is_numeric($column['size']) ? $column['size'] : null;
184
		list ($type, $size) = $smcFunc['db_calculate_type']($column['type'], $column['size']);
185
		if ($size !== null)
186
			$type = $type . '(' . $size . ')';
187
188
		// backward compatibility
189
		if (isset($column['null']) && !isset($column['not_null']))
190
			$column['not_null'] = !$column['null'];
191
192
		// Now just put it together!
193
		$table_query .= "\n\t\"" . $column['name'] . '" ' . $type . ' ' . (!empty($column['not_null']) ? 'NOT NULL' : '') . ' ' . $default . ',';
194
	}
195
196
	// Loop through the indexes a sec...
197
	$index_queries = array();
198
	foreach ($indexes as $index)
199
	{
200
		$columns = implode(',', $index['columns']);
201
202
		// Primary goes in the table...
203
		if (isset($index['type']) && $index['type'] == 'primary')
204
			$table_query .= "\n\t" . 'PRIMARY KEY (' . implode(',', $index['columns']) . '),';
205
		else
206
		{
207
			if (empty($index['name']))
208
				$index['name'] = implode('_', $index['columns']);
209
			$index_queries[] = 'CREATE ' . (isset($index['type']) && $index['type'] == 'unique' ? 'UNIQUE' : '') . ' INDEX ' . $table_name . '_' . $index['name'] . ' ON ' . $table_name . ' (' . $columns . ')';
210
		}
211
	}
212
213
	// No trailing commas!
214
	if (substr($table_query, -1) == ',')
215
		$table_query = substr($table_query, 0, -1);
216
217
	$table_query .= ')';
218
219
	// Create the table!
220
	$smcFunc['db_query']('', $table_query,
221
		array(
222
			'security_override' => true,
223
		)
224
	);
225
226
	// Fill the old data
227
	if ($old_table_exists)
228
	{
229
		$same_col = array();
230
231
		$request = $smcFunc['db_query']('', '
232
			SELECT count(*), column_name
233
			FROM information_schema.columns
234
			WHERE table_name in ({string:table1},{string:table2}) AND table_schema = {string:schema}
235
			GROUP BY column_name
236
			HAVING count(*) > 1',
237
			array(
238
				'table1' => $short_table_name,
239
				'table2' => $short_table_name . '_old',
240
				'schema' => 'public',
241
			)
242
		);
243
244
		while ($row = $smcFunc['db_fetch_assoc']($request))
245
		{
246
			$same_col[] = $row['column_name'];
247
		}
248
249
		$smcFunc['db_query']('', '
250
			INSERT INTO ' . $short_table_name . '('
251
			. implode(',', $same_col) .
252
			')
253
			SELECT ' . implode(',', $same_col) . '
254
			FROM ' . $short_table_name . '_old',
255
			array()
256
		);
257
	}
258
259
	// And the indexes...
260
	foreach ($index_queries as $query)
261
		$smcFunc['db_query']('', $query,
262
			array(
263
				'security_override' => true,
264
			)
265
		);
266
267
	// Go, go power rangers!
268
	$smcFunc['db_transaction']('commit');
269
270
	if ($old_table_exists)
271
		$smcFunc['db_drop_table']($table_name . '_old');
272
273
	return true;
274
}
275
276
/**
277
 * Drop a table and its associated sequences.
278
 *
279
 * @param string $table_name The name of the table to drop
280
 * @param array $parameters Not used at the moment
281
 * @param string $error
282
 * @return boolean Whether or not the operation was successful
283
 */
284
function smf_db_drop_table($table_name, $parameters = array(), $error = 'fatal')
285
{
286
	global $reservedTables, $smcFunc, $db_prefix, $db_name;
287
288
	// After stripping away the database name, this is what's left.
289
	$real_prefix = preg_match('~^("?)(.+?)\\1\\.(.*?)$~', $db_prefix, $match) === 1 ? $match[3] : $db_prefix;
290
	$database = !empty($match[2]) ? $match[2] : $db_name;
291
292
	// Get some aliases.
293
	$full_table_name = str_replace('{db_prefix}', $real_prefix, $table_name);
294
	$short_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
295
296
	// God no - dropping one of these = bad.
297
	if (in_array(strtolower($table_name), $reservedTables))
298
		return false;
299
300
	// Does it exist?
301
	$tables = $smcFunc['db_list_tables']($database);
302
	if (in_array($full_table_name, $tables))
303
	{
304
		// We can then drop the table.
305
		$smcFunc['db_transaction']('begin');
306
307
		// the table
308
		$table_query = 'DROP TABLE ' . $short_table_name;
309
310
		// and the assosciated sequence, if any
311
		$sequence_query = 'DROP SEQUENCE IF EXISTS ' . $short_table_name . '_seq';
312
313
		// drop them
314
		$smcFunc['db_query']('',
315
			$table_query,
316
			array(
317
				'security_override' => true,
318
			)
319
		);
320
		$smcFunc['db_query']('',
321
			$sequence_query,
322
			array(
323
				'security_override' => true,
324
			)
325
		);
326
327
		$smcFunc['db_transaction']('commit');
328
329
		return true;
330
	}
331
332
	// Otherwise do 'nout.
333
	return false;
334
}
335
336
/**
337
 * This function adds a column.
338
 *
339
 * @param string $table_name The name of the table to add the column to
340
 * @param array $column_info An array of column info (see {@link smf_db_create_table()})
341
 * @param array $parameters Not used?
342
 * @param string $if_exists What to do if the column exists. If 'update', column is updated.
343
 * @param string $error
344
 * @return boolean Whether or not the operation was successful
345
 */
346
function smf_db_add_column($table_name, $column_info, $parameters = array(), $if_exists = 'update', $error = 'fatal')
347
{
348
	global $smcFunc, $db_package_log, $db_prefix;
349
350
	$short_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
351
352
	// Log that we will want to uninstall this!
353
	$db_package_log[] = array('remove_column', $short_table_name, $column_info['name']);
354
355
	// Does it exist - if so don't add it again!
356
	$columns = $smcFunc['db_list_columns']($table_name, false);
357
	foreach ($columns as $column)
358
		if ($column == $column_info['name'])
359
		{
360
			// If we're going to overwrite then use change column.
361
			if ($if_exists == 'update')
362
				return $smcFunc['db_change_column']($table_name, $column_info['name'], $column_info);
363
			else
364
				return false;
365
		}
366
367
	// Get the specifics...
368
	$column_info['size'] = isset($column_info['size']) && is_numeric($column_info['size']) ? $column_info['size'] : null;
369
	list ($type, $size) = $smcFunc['db_calculate_type']($column_info['type'], $column_info['size']);
370
	if ($size !== null)
371
		$type = $type . '(' . $size . ')';
372
373
	// Now add the thing!
374
	$query = '
375
		ALTER TABLE ' . $short_table_name . '
376
		ADD COLUMN ' . $column_info['name'] . ' ' . $type;
377
	$smcFunc['db_query']('', $query,
378
		array(
379
			'security_override' => true,
380
		)
381
	);
382
383
	// If there's more attributes they need to be done via a change on PostgreSQL.
384
	unset($column_info['type'], $column_info['size']);
385
386
	if (count($column_info) != 1)
387
		return $smcFunc['db_change_column']($table_name, $column_info['name'], $column_info);
388
	else
389
		return true;
390
}
391
392
/**
393
 * Removes a column.
394
 *
395
 * @param string $table_name The name of the table to drop the column from
396
 * @param string $column_name The name of the column to drop
397
 * @param array $parameters Not used?
398
 * @param string $error
399
 * @return boolean Whether or not the operation was successful
400
 */
401
function smf_db_remove_column($table_name, $column_name, $parameters = array(), $error = 'fatal')
402
{
403
	global $smcFunc, $db_prefix;
404
405
	$short_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
406
407
	// Does it exist?
408
	$columns = $smcFunc['db_list_columns']($table_name, true);
409
410
	foreach ($columns as $column)
411
		if (strtolower($column['name']) == strtolower($column_name))
412
		{
413
			// If there is an auto we need remove it!
414
			if ($column['auto'])
415
				$smcFunc['db_query']('', '
416
					DROP SEQUENCE IF EXISTS ' . $short_table_name . '_seq',
417
					array(
418
						'security_override' => true,
419
					)
420
				);
421
422
			$smcFunc['db_query']('', '
423
				ALTER TABLE ' . $short_table_name . '
424
				DROP COLUMN ' . $column_name,
425
				array(
426
					'security_override' => true,
427
				)
428
			);
429
430
			return true;
431
		}
432
433
	// If here we didn't have to work - joy!
434
	return false;
435
}
436
437
/**
438
 * Change a column.
439
 *
440
 * @param string $table_name The name of the table this column is in
441
 * @param string $old_column The name of the column we want to change
442
 * @param array $column_info An array of info about the "new" column definition (see {@link smf_db_create_table()})
443
 * @return bool
444
 */
445
function smf_db_change_column($table_name, $old_column, $column_info)
446
{
447
	global $smcFunc, $db_prefix;
448
449
	$short_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
450
451
	// backward compatibility
452
	if (isset($column_info['null']) && !isset($column_info['not_null']))
453
		$column_info['not_null'] = !$column_info['null'];
454
455
	// Check it does exist!
456
	$columns = $smcFunc['db_list_columns']($table_name, true);
457
	$old_info = null;
458
	foreach ($columns as $column)
459
		if ($column['name'] == $old_column)
460
			$old_info = $column;
461
462
	// Nothing?
463
	if ($old_info == null)
464
		return false;
465
466
	// Now we check each bit individually and ALTER as required.
467
	if (isset($column_info['name']) && $column_info['name'] != $old_column)
468
	{
469
		$smcFunc['db_query']('', '
470
			ALTER TABLE ' . $short_table_name . '
471
			RENAME COLUMN ' . $old_column . ' TO ' . $column_info['name'],
472
			array(
473
				'security_override' => true,
474
			)
475
		);
476
	}
477
	// Different default?
478
	if (array_key_exists('default', $column_info) && $column_info['default'] != $old_info['default'])
479
	{
480
		// Fix the default.
481
		$default = '';
482
		if (array_key_exists('default', $column_info) && is_null($column_info['default']))
483
			$default = 'NULL';
484
		elseif (isset($column_info['default']) && is_numeric($column_info['default']))
485
			$default = strpos($column_info['default'], '.') ? floatval($column_info['default']) : intval($column_info['default']);
486
		else
487
			$default = '\'' . $smcFunc['db_escape_string']($column_info['default']) . '\'';
488
489
		$action = $default === '' ? 'DROP DEFAULT' : 'SET DEFAULT ' . $default;
490
		$smcFunc['db_query']('', '
491
			ALTER TABLE ' . $short_table_name . '
492
			ALTER COLUMN ' . $column_info['name'] . ' ' . $action,
493
			array(
494
				'security_override' => true,
495
			)
496
		);
497
	}
498
499
	// Is it null - or otherwise?
500
	if (isset($column_info['not_null']) && $column_info['not_null'] != $old_info['not_null'])
501
	{
502
		$action = $column_info['not_null'] ? 'SET' : 'DROP';
503
		$smcFunc['db_transaction']('begin');
504
		if ($column_info['not_null'])
505
		{
506
			// We have to set it to something if we are making it NOT NULL. And we must comply with the current column format.
507
			$setTo = isset($column_info['default']) ? $column_info['default'] : (strpos($old_info['type'], 'int') !== false ? 0 : '');
508
			$smcFunc['db_query']('', '
509
				UPDATE ' . $short_table_name . '
510
				SET ' . $column_info['name'] . ' = \'' . $setTo . '\'
511
				WHERE ' . $column_info['name'] . ' IS NULL',
512
				array(
513
					'security_override' => true,
514
				)
515
			);
516
		}
517
		$smcFunc['db_query']('', '
518
			ALTER TABLE ' . $short_table_name . '
519
			ALTER COLUMN ' . $column_info['name'] . ' ' . $action . ' NOT NULL',
520
			array(
521
				'security_override' => true,
522
			)
523
		);
524
		$smcFunc['db_transaction']('commit');
525
	}
526
	// What about a change in type?
527
	if (isset($column_info['type']) && ($column_info['type'] != $old_info['type'] || (isset($column_info['size']) && $column_info['size'] != $old_info['size'])))
528
	{
529
		$column_info['size'] = isset($column_info['size']) && is_numeric($column_info['size']) ? $column_info['size'] : null;
530
		list ($type, $size) = $smcFunc['db_calculate_type']($column_info['type'], $column_info['size']);
531
		if ($size !== null)
532
			$type = $type . '(' . $size . ')';
533
534
		// The alter is a pain.
535
		$smcFunc['db_transaction']('begin');
536
		$smcFunc['db_query']('', '
537
			ALTER TABLE ' . $short_table_name . '
538
			ADD COLUMN ' . $column_info['name'] . '_tempxx ' . $type,
539
			array(
540
				'security_override' => true,
541
			)
542
		);
543
		$smcFunc['db_query']('', '
544
			UPDATE ' . $short_table_name . '
545
			SET ' . $column_info['name'] . '_tempxx = CAST(' . $column_info['name'] . ' AS ' . $type . ')',
546
			array(
547
				'security_override' => true,
548
			)
549
		);
550
		$smcFunc['db_query']('', '
551
			ALTER TABLE ' . $short_table_name . '
552
			DROP COLUMN ' . $column_info['name'],
553
			array(
554
				'security_override' => true,
555
			)
556
		);
557
		$smcFunc['db_query']('', '
558
			ALTER TABLE ' . $short_table_name . '
559
			RENAME COLUMN ' . $column_info['name'] . '_tempxx TO ' . $column_info['name'],
560
			array(
561
				'security_override' => true,
562
			)
563
		);
564
		$smcFunc['db_transaction']('commit');
565
	}
566
	// Finally - auto increment?!
567
	if (isset($column_info['auto']) && $column_info['auto'] != $old_info['auto'])
568
	{
569
		// Are we removing an old one?
570
		if ($old_info['auto'])
571
		{
572
			// Alter the table first - then drop the sequence.
573
			$smcFunc['db_query']('', '
574
				ALTER TABLE ' . $short_table_name . '
575
				ALTER COLUMN ' . $column_info['name'] . ' SET DEFAULT \'0\'',
576
				array(
577
					'security_override' => true,
578
				)
579
			);
580
			$smcFunc['db_query']('', '
581
				DROP SEQUENCE IF EXISTS ' . $short_table_name . '_seq',
582
				array(
583
					'security_override' => true,
584
				)
585
			);
586
		}
587
		// Otherwise add it!
588
		else
589
		{
590
			$smcFunc['db_query']('', '
591
				DROP SEQUENCE IF EXISTS ' . $short_table_name . '_seq',
592
				array(
593
					'security_override' => true,
594
				)
595
			);
596
597
			$smcFunc['db_query']('', '
598
				CREATE SEQUENCE ' . $short_table_name . '_seq',
599
				array(
600
					'security_override' => true,
601
				)
602
			);
603
			$smcFunc['db_query']('', '
604
				ALTER TABLE ' . $short_table_name . '
605
				ALTER COLUMN ' . $column_info['name'] . ' SET DEFAULT nextval(\'' . $short_table_name . '_seq\')',
606
				array(
607
					'security_override' => true,
608
				)
609
			);
610
		}
611
	}
612
613
	return true;
614
}
615
616
/**
617
 * Add an index.
618
 *
619
 * @param string $table_name The name of the table to add the index to
620
 * @param array $index_info An array of index info (see {@link smf_db_create_table()})
621
 * @param array $parameters Not used?
622
 * @param string $if_exists What to do if the index exists. If 'update', the definition will be updated.
623
 * @param string $error
624
 * @return boolean Whether or not the operation was successful
625
 */
626
function smf_db_add_index($table_name, $index_info, $parameters = array(), $if_exists = 'update', $error = 'fatal')
627
{
628
	global $smcFunc, $db_package_log, $db_prefix;
629
630
	$parsed_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
631
	$real_table_name = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $parsed_table_name, $match) === 1 ? $match[3] : $parsed_table_name;
632
633
	// No columns = no index.
634
	if (empty($index_info['columns']))
635
		return false;
636
637
	// MySQL you can do a "column_name (length)", postgresql does not allow this.  Strip it.
638
	foreach ($index_info['columns'] as &$c)
639
		$c = preg_replace('~\s+(\(\d+\))~', '', $c);
640
641
	$columns = implode(',', $index_info['columns']);
642
643
	// No name - make it up!
644
	if (empty($index_info['name']))
645
	{
646
		// No need for primary.
647
		if (isset($index_info['type']) && $index_info['type'] == 'primary')
648
			$index_info['name'] = '';
649
		else
650
			$index_info['name'] = trim(implode('_', preg_replace('~(\(\d+\))~', '', $index_info['columns'])));
651
	}
652
	else
653
		$index_info['name'] = $index_info['name'];
654
655
	// Log that we are going to want to remove this!
656
	$db_package_log[] = array('remove_index', $parsed_table_name, $index_info['name']);
657
658
	// Let's get all our indexes.
659
	$indexes = $smcFunc['db_list_indexes']($table_name, true);
660
661
	// Do we already have it?
662
	foreach ($indexes as $index)
663
	{
664
		if ($index['name'] == $index_info['name'] || ($index['type'] == 'primary' && isset($index_info['type']) && $index_info['type'] == 'primary'))
665
		{
666
			// If we want to overwrite simply remove the current one then continue.
667
			if ($if_exists != 'update' || $index['type'] == 'primary')
668
				return false;
669
			else
670
				$smcFunc['db_remove_index']($table_name, $index_info['name']);
671
		}
672
	}
673
674
	// If we're here we know we don't have the index - so just add it.
675
	if (!empty($index_info['type']) && $index_info['type'] == 'primary')
676
	{
677
		$smcFunc['db_query']('', '
678
			ALTER TABLE ' . $real_table_name . '
679
			ADD PRIMARY KEY (' . $columns . ')',
680
			array(
681
				'security_override' => true,
682
			)
683
		);
684
	}
685
	else
686
	{
687
		$smcFunc['db_query']('', '
688
			CREATE ' . (isset($index_info['type']) && $index_info['type'] == 'unique' ? 'UNIQUE' : '') . ' INDEX ' . $real_table_name . '_' . $index_info['name'] . ' ON ' . $real_table_name . ' (' . $columns . ')',
689
			array(
690
				'security_override' => true,
691
			)
692
		);
693
	}
694
}
695
696
/**
697
 * Remove an index.
698
 *
699
 * @param string $table_name The name of the table to remove the index from
700
 * @param string $index_name The name of the index to remove
701
 * @param array $parameters Not used?
702
 * @param string $error
703
 * @return boolean Whether or not the operation was successful
704
 */
705
function smf_db_remove_index($table_name, $index_name, $parameters = array(), $error = 'fatal')
706
{
707
	global $smcFunc, $db_prefix;
708
709
	$parsed_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
710
	$real_table_name = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $parsed_table_name, $match) === 1 ? $match[3] : $parsed_table_name;
711
712
	// Better exist!
713
	$indexes = $smcFunc['db_list_indexes']($table_name, true);
714
715
	// Do not add the table name to the index if it is arleady there.
716
	if ($index_name != 'primary' && strpos($index_name, $real_table_name) !== false)
717
		$index_name = str_replace($real_table_name . '_', '', $index_name);
718
719
	foreach ($indexes as $index)
720
	{
721
		// If the name is primary we want the primary key!
722
		if ($index['type'] == 'primary' && $index_name == 'primary')
723
		{
724
			// Dropping primary key is odd...
725
			$smcFunc['db_query']('', '
726
				ALTER TABLE ' . $real_table_name . '
727
				DROP CONSTRAINT ' . $index['name'],
728
				array(
729
					'security_override' => true,
730
				)
731
			);
732
733
			return true;
734
		}
735
736
		if ($index['name'] == $index_name)
737
		{
738
			// Drop the bugger...
739
			$smcFunc['db_query']('', '
740
				DROP INDEX ' . $real_table_name . '_' . $index_name,
741
				array(
742
					'security_override' => true,
743
				)
744
			);
745
746
			return true;
747
		}
748
	}
749
750
	// Not to be found ;(
751
	return false;
752
}
753
754
/**
755
 * Get the schema formatted name for a type.
756
 *
757
 * @param string $type_name The data type (int, varchar, smallint, etc.)
758
 * @param int $type_size The size (8, 255, etc.)
759
 * @param boolean $reverse If true, returns specific types for a generic type
760
 * @return array An array containing the appropriate type and size for this DB type
761
 */
762
function smf_db_calculate_type($type_name, $type_size = null, $reverse = false)
763
{
764
	// Let's be sure it's lowercase MySQL likes both, others no.
765
	$type_name = strtolower($type_name);
766
	// Generic => Specific.
767
	if (!$reverse)
768
	{
769
		$types = array(
770
			'varchar' => 'character varying',
771
			'char' => 'character',
772
			'mediumint' => 'int',
773
			'tinyint' => 'smallint',
774
			'tinytext' => 'character varying',
775
			'mediumtext' => 'text',
776
			'largetext' => 'text',
777
			'inet' => 'inet',
778
			'time' => 'time without time zone',
779
			'datetime' => 'timestamp without time zone',
780
			'timestamp' => 'timestamp without time zone',
781
		);
782
	}
783
	else
784
	{
785
		$types = array(
786
			'character varying' => 'varchar',
787
			'character' => 'char',
788
			'integer' => 'int',
789
			'inet' => 'inet',
790
			'time without time zone' => 'time',
791
			'timestamp without time zone' => 'datetime',
792
			'numeric' => 'decimal',
793
		);
794
	}
795
796
	// Got it? Change it!
797
	if (isset($types[$type_name]))
798
	{
799
		if ($type_name == 'tinytext')
800
			$type_size = 255;
801
		$type_name = $types[$type_name];
802
	}
803
804
	// Only char fields got size
805
	if (strpos($type_name, 'char') === false)
806
		$type_size = null;
807
808
	return array($type_name, $type_size);
809
}
810
811
/**
812
 * Get table structure.
813
 *
814
 * @param string $table_name The name of the table
815
 * @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()}
816
 */
817
function smf_db_table_structure($table_name)
818
{
819
	global $smcFunc, $db_prefix;
820
821
	$parsed_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
822
	$real_table_name = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $parsed_table_name, $match) === 1 ? $match[3] : $parsed_table_name;
823
824
	return array(
825
		'name' => $real_table_name,
826
		'columns' => $smcFunc['db_list_columns']($table_name, true),
827
		'indexes' => $smcFunc['db_list_indexes']($table_name, true),
828
	);
829
}
830
831
/**
832
 * Return column information for a table.
833
 *
834
 * @param string $table_name The name of the table to get column info for
835
 * @param bool $detail Whether or not to return detailed info. If true, returns the column info. If false, just returns the column names.
836
 * @param array $parameters Not used?
837
 * @return array An array of column names or detailed column info, depending on $detail
838
 */
839
function smf_db_list_columns($table_name, $detail = false, $parameters = array())
840
{
841
	global $smcFunc, $db_prefix, $db_name;
842
843
	$parsed_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
844
	$real_table_name = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $parsed_table_name, $match) === 1 ? $match[3] : $parsed_table_name;
845
	$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...
846
847
	$result = $smcFunc['db_query']('', '
848
		SELECT column_name, column_default, is_nullable, data_type, character_maximum_length
849
		FROM information_schema.columns
850
		WHERE table_schema = {string:schema_public}
851
			AND table_name = {string:table_name}
852
		ORDER BY ordinal_position',
853
		array(
854
			'schema_public' => 'public',
855
			'table_name' => $real_table_name,
856
		)
857
	);
858
	$columns = array();
859
	while ($row = $smcFunc['db_fetch_assoc']($result))
860
	{
861
		if (!$detail)
862
		{
863
			$columns[] = $row['column_name'];
864
		}
865
		else
866
		{
867
			$auto = false;
868
			// What is the default?
869
			if (preg_match('~nextval\(\'(.+?)\'(.+?)*\)~i', $row['column_default'], $matches) != 0)
870
			{
871
				$default = null;
872
				$auto = true;
873
			}
874
			elseif (trim($row['column_default']) != '')
875
				$default = trim(strpos($row['column_default'], '::') === false ? $row['column_default'] : substr($row['column_default'], 0, strpos($row['column_default'], '::')), '\'');
876
			else
877
				$default = null;
878
879
			// Make the type generic.
880
			list ($type, $size) = $smcFunc['db_calculate_type']($row['data_type'], $row['character_maximum_length'], true);
881
882
			$columns[$row['column_name']] = array(
883
				'name' => $row['column_name'],
884
				'not_null' => $row['is_nullable'] == 'YES' ? false : true,
885
				'null' => $row['is_nullable'] == 'YES' ? true : false,
886
				'default' => $default,
887
				'type' => $type,
888
				'size' => $size,
889
				'auto' => $auto,
890
			);
891
		}
892
	}
893
	$smcFunc['db_free_result']($result);
894
895
	return $columns;
896
}
897
898
/**
899
 * Get index information.
900
 *
901
 * @param string $table_name The name of the table to get indexes for
902
 * @param bool $detail Whether or not to return detailed info.
903
 * @param array $parameters Not used?
904
 * @return array An array of index names or a detailed array of index info, depending on $detail
905
 */
906
function smf_db_list_indexes($table_name, $detail = false, $parameters = array())
907
{
908
	global $smcFunc, $db_prefix, $db_name;
909
910
	$parsed_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
911
	$real_table_name = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $parsed_table_name, $match) === 1 ? $match[3] : $parsed_table_name;
912
	$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...
913
914
	$result = $smcFunc['db_query']('', '
915
		SELECT CASE WHEN i.indisprimary THEN 1 ELSE 0 END AS is_primary,
916
			CASE WHEN i.indisunique THEN 1 ELSE 0 END AS is_unique,
917
			c2.relname AS name,
918
			pg_get_indexdef(i.indexrelid) AS inddef
919
		FROM pg_class AS c, pg_class AS c2, pg_index AS i
920
		WHERE c.relname = {string:table_name}
921
			AND c.oid = i.indrelid
922
			AND i.indexrelid = c2.oid',
923
		array(
924
			'table_name' => $real_table_name,
925
		)
926
	);
927
	$indexes = array();
928
	while ($row = $smcFunc['db_fetch_assoc']($result))
929
	{
930
		// Try get the columns that make it up.
931
		if (preg_match('~\(([^\)]+?)\)~i', $row['inddef'], $matches) == 0)
932
			continue;
933
934
		$columns = explode(',', $matches[1]);
935
936
		if (empty($columns))
937
			continue;
938
939
		foreach ($columns as $k => $v)
940
			$columns[$k] = trim($v);
941
942
		// Fix up the name to be consistent cross databases
943
		if (substr($row['name'], -5) == '_pkey' && $row['is_primary'] == 1)
944
			$row['name'] = 'PRIMARY';
945
		else
946
			$row['name'] = str_replace($real_table_name . '_', '', $row['name']);
947
948
		if (!$detail)
949
			$indexes[] = $row['name'];
950
		else
951
		{
952
			$indexes[$row['name']] = array(
953
				'name' => $row['name'],
954
				'type' => $row['is_primary'] ? 'primary' : ($row['is_unique'] ? 'unique' : 'index'),
955
				'columns' => $columns,
956
			);
957
		}
958
	}
959
	$smcFunc['db_free_result']($result);
960
961
	return $indexes;
962
}
963
964
?>