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

smf_db_create_query_column()   F

Complexity

Conditions 17
Paths 1536

Size

Total Lines 37
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 17
eloc 20
c 1
b 0
f 0
nc 1536
nop 1
dl 0
loc 37
rs 1.0499

How to fix   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 Extra parameters. Currently only 'engine', the desired MySQL storage engine, is used.
102
 * @param string $if_exists What to do if the table exists.
103
 * @param string $error
104
 * @return boolean Whether or not the operation was successful
105
 */
106
function smf_db_create_table($table_name, $columns, $indexes = array(), $parameters = array(), $if_exists = 'ignore', $error = 'fatal')
107
{
108
	global $reservedTables, $smcFunc, $db_package_log, $db_prefix, $db_character_set, $db_name;
109
110
	static $engines = array();
111
112
	$old_table_exists = false;
113
114
	// Strip out the table name, we might not need it in some cases
115
	$real_prefix = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $db_prefix, $match) === 1 ? $match[3] : $db_prefix;
116
	$database = !empty($match[2]) ? $match[2] : $db_name;
117
118
	// With or without the database name, the fullname looks like this.
119
	$full_table_name = str_replace('{db_prefix}', $real_prefix, $table_name);
120
	// Do not overwrite $table_name, this causes issues if we pass it onto a helper function.
121
	$short_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
122
123
	// First - no way do we touch SMF tables.
124
	if (in_array(strtolower($short_table_name), $reservedTables))
125
		return false;
126
127
	// Log that we'll want to remove this on uninstall.
128
	$db_package_log[] = array('remove_table', $short_table_name);
129
130
	// Slightly easier on MySQL than the others...
131
	$tables = $smcFunc['db_list_tables']($database);
132
133
	if (in_array($full_table_name, $tables))
134
	{
135
		// This is a sad day... drop the table? If not, return false (error) by default.
136
		if ($if_exists == 'overwrite')
137
			$smcFunc['db_drop_table']($table_name);
138
		elseif ($if_exists == 'update')
139
		{
140
			$smcFunc['db_transaction']('begin');
141
			$db_trans = true;
0 ignored issues
show
Unused Code introduced by
The assignment to $db_trans is dead and can be removed.
Loading history...
142
			$smcFunc['db_drop_table']($short_table_name . '_old');
143
			$smcFunc['db_query']('', '
144
				RENAME TABLE ' . $short_table_name . ' TO ' . $short_table_name . '_old',
145
				array(
146
					'security_override' => true,
147
				)
148
			);
149
			$old_table_exists = true;
150
		}
151
		else
152
			return $if_exists == 'ignore';
153
	}
154
155
	// Righty - let's do the damn thing!
156
	$table_query = 'CREATE TABLE ' . $short_table_name . "\n" . '(';
157
	foreach ($columns as $column)
158
		$table_query .= "\n\t" . smf_db_create_query_column($column) . ',';
159
160
	// Loop through the indexes next...
161
	foreach ($indexes as $index)
162
	{
163
		// MySQL If its a text column, we need to add a size.
164
		foreach ($index['columns'] as &$c)
165
		{
166
			$c = trim($c);
167
168
			// If a size was already specified, we won't be able to match it anyways.
169
			$key = array_search($c, array_column($columns, 'name'));
170
			if ($key === false || !isset($columns[$key]) || !in_array($columns[$key]['type'], array('text', 'mediumntext', 'largetext', 'varchar', 'char')))
171
				continue;
172
173
			$c .= '(191)';
174
		}
175
176
		$idx_columns = implode(',', $index['columns']);
177
178
		// Is it the primary?
179
		if (isset($index['type']) && $index['type'] == 'primary')
180
			$table_query .= "\n\t" . 'PRIMARY KEY (' . implode(',', $index['columns']) . '),';
181
		else
182
		{
183
			if (empty($index['name']))
184
				$index['name'] = trim(implode('_', preg_replace('~(\(\d+\))~', '', $index['columns'])));
185
186
			$table_query .= "\n\t" . (isset($index['type']) && $index['type'] == 'unique' ? 'UNIQUE' : 'KEY') . ' ' . $index['name'] . ' (' . $idx_columns . '),';
187
		}
188
	}
189
190
	// No trailing commas!
191
	if (substr($table_query, -1) == ',')
192
		$table_query = substr($table_query, 0, -1);
193
194
	// Which engine do we want here?
195
	if (empty($engines))
196
	{
197
		// Figure out which engines we have
198
		$get_engines = $smcFunc['db_query']('', 'SHOW ENGINES', array());
199
200
		while ($row = $smcFunc['db_fetch_assoc']($get_engines))
201
		{
202
			if ($row['Support'] == 'YES' || $row['Support'] == 'DEFAULT')
203
				$engines[] = $row['Engine'];
204
		}
205
206
		$smcFunc['db_free_result']($get_engines);
207
	}
208
209
	// If we don't have this engine, or didn't specify one, default to InnoDB or MyISAM
210
	// depending on which one is available
211
	if (!isset($parameters['engine']) || !in_array($parameters['engine'], $engines))
212
	{
213
		$parameters['engine'] = in_array('InnoDB', $engines) ? 'InnoDB' : 'MyISAM';
214
	}
215
216
	$table_query .= ') ENGINE=' . $parameters['engine'];
217
	if (!empty($db_character_set) && $db_character_set == 'utf8')
218
		$table_query .= ' DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci';
219
220
	// Create the table!
221
	$smcFunc['db_query']('', $table_query,
222
		array(
223
			'security_override' => true,
224
		)
225
	);
226
227
	// Fill the old data
228
	if ($old_table_exists)
229
	{
230
		$same_col = array();
231
232
		$request = $smcFunc['db_query']('', '
233
			SELECT count(*), column_name
234
			FROM information_schema.columns
235
			WHERE table_name in ({string:table1},{string:table2}) AND table_schema = {string:schema}
236
			GROUP BY column_name
237
			HAVING count(*) > 1',
238
			array(
239
				'table1' => $short_table_name,
240
				'table2' => $short_table_name . '_old',
241
				'schema' => $db_name,
242
			)
243
		);
244
245
		while ($row = $smcFunc['db_fetch_assoc']($request))
246
		{
247
			$same_col[] = $row['column_name'];
248
		}
249
250
		$smcFunc['db_query']('', '
251
			INSERT INTO ' . $short_table_name . '('
252
			. implode(',', $same_col) .
253
			')
254
			SELECT ' . implode(',', $same_col) . '
255
			FROM ' . $short_table_name . '_old',
256
			array()
257
		);
258
259
		$smcFunc['db_drop_table']($short_table_name . '_old');
260
	}
261
262
	return true;
263
}
264
265
/**
266
 * Drop a table.
267
 *
268
 * @param string $table_name The name of the table to drop
269
 * @param array $parameters Not used at the moment
270
 * @param string $error
271
 * @return boolean Whether or not the operation was successful
272
 */
273
function smf_db_drop_table($table_name, $parameters = array(), $error = 'fatal')
274
{
275
	global $reservedTables, $smcFunc, $db_prefix, $db_name;
276
277
	// After stripping away the database name, this is what's left.
278
	$real_prefix = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $db_prefix, $match) === 1 ? $match[3] : $db_prefix;
279
	$database = !empty($match[2]) ? $match[2] : $db_name;
280
281
	// Get some aliases.
282
	$full_table_name = str_replace('{db_prefix}', $real_prefix, $table_name);
283
	// Do not overwrite $table_name, this causes issues if we pass it onto a helper function.
284
	$short_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
285
286
	// God no - dropping one of these = bad.
287
	if (in_array(strtolower($short_table_name), $reservedTables))
288
		return false;
289
290
	// Does it exist?
291
	$tables = $smcFunc['db_list_tables']($database);
292
	if (in_array($full_table_name, $tables))
293
	{
294
		$query = 'DROP TABLE ' . $short_table_name;
295
		$smcFunc['db_query']('',
296
			$query,
297
			array(
298
				'security_override' => true,
299
			)
300
		);
301
302
		return true;
303
	}
304
305
	// Otherwise do 'nout.
306
	return false;
307
}
308
309
/**
310
 * This function adds a column.
311
 *
312
 * @param string $table_name The name of the table to add the column to
313
 * @param array $column_info An array of column info ({@see smf_db_create_table})
314
 * @param array $parameters Not used?
315
 * @param string $if_exists What to do if the column exists. If 'update', column is updated.
316
 * @param string $error
317
 * @return boolean Whether or not the operation was successful
318
 */
319
function smf_db_add_column($table_name, $column_info, $parameters = array(), $if_exists = 'update', $error = 'fatal')
320
{
321
	global $smcFunc, $db_package_log, $db_prefix;
322
323
	$short_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
324
	$column_info = array_change_key_case($column_info);
325
326
	// Log that we will want to uninstall this!
327
	$db_package_log[] = array('remove_column', $short_table_name, $column_info['name']);
328
329
	// Does it exist - if so don't add it again!
330
	$columns = $smcFunc['db_list_columns']($table_name, false);
331
	foreach ($columns as $column)
332
		if ($column == $column_info['name'])
333
		{
334
			// If we're going to overwrite then use change column.
335
			if ($if_exists == 'update')
336
				return $smcFunc['db_change_column']($table_name, $column_info['name'], $column_info);
337
			else
338
				return false;
339
		}
340
341
	// Get the specifics...
342
	$column_info['size'] = isset($column_info['size']) && is_numeric($column_info['size']) ? $column_info['size'] : null;
343
344
	// Now add the thing!
345
	$query = '
346
		ALTER TABLE ' . $short_table_name . '
347
		ADD ' . smf_db_create_query_column($column_info) . (empty($column_info['auto']) ? '' : ' primary key'
348
	);
349
	$smcFunc['db_query']('', $query,
350
		array(
351
			'security_override' => true,
352
		)
353
	);
354
355
	return true;
356
}
357
358
/**
359
 * Removes a column.
360
 *
361
 * @param string $table_name The name of the table to drop the column from
362
 * @param string $column_name The name of the column to drop
363
 * @param array $parameters Not used?
364
 * @param string $error
365
 * @return boolean Whether or not the operation was successful
366
 */
367
function smf_db_remove_column($table_name, $column_name, $parameters = array(), $error = 'fatal')
368
{
369
	global $smcFunc, $db_prefix;
370
371
	$short_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
372
373
	// Does it exist?
374
	$columns = $smcFunc['db_list_columns']($table_name, true);
375
376
	foreach ($columns as $column)
377
		if ($column['name'] == $column_name)
378
		{
379
			$smcFunc['db_query']('', '
380
				ALTER TABLE ' . $short_table_name . '
381
				DROP COLUMN ' . $column_name,
382
				array(
383
					'security_override' => true,
384
				)
385
			);
386
387
			return true;
388
		}
389
390
	// If here we didn't have to work - joy!
391
	return false;
392
}
393
394
/**
395
 * Change a column.
396
 *
397
 * @param string $table_name The name of the table this column is in
398
 * @param string $old_column The name of the column we want to change
399
 * @param array $column_info An array of info about the "new" column definition (see {@link smf_db_create_table()})
400
 * @return bool
401
 */
402
function smf_db_change_column($table_name, $old_column, $column_info)
403
{
404
	global $smcFunc, $db_prefix;
405
406
	$short_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
407
	$column_info = array_change_key_case($column_info);
408
409
	// Check it does exist!
410
	$columns = $smcFunc['db_list_columns']($table_name, true);
411
	$old_info = null;
412
	foreach ($columns as $column)
413
		if ($column['name'] == $old_column)
414
			$old_info = $column;
415
416
	// Nothing?
417
	if ($old_info == null)
418
		return false;
419
420
	// backward compatibility
421
	if (isset($column_info['null']))
422
		$column_info['not_null'] = !$column_info['null'];
423
	if (isset($old_info['null']))
424
		$old_info['not_null'] = !$old_info['null'];
425
426
	// Get the right bits.
427
	if (!isset($column_info['name']))
428
		$column_info['name'] = $old_column;
429
	if (!isset($column_info['default']))
430
		$column_info['default'] = $old_info['default'];
431
	if (!isset($column_info['not_null']))
432
		$column_info['not_null'] = $old_info['not_null'];
433
	if (!isset($column_info['auto']))
434
		$column_info['auto'] = $old_info['auto'];
435
	if (!isset($column_info['type']))
436
		$column_info['type'] = $old_info['type'];
437
	if (!isset($column_info['size']) || !is_numeric($column_info['size']))
438
		$column_info['size'] = $old_info['size'];
439
	if (!isset($column_info['unsigned']) || !in_array($column_info['type'], array('int', 'tinyint', 'smallint', 'mediumint', 'bigint')))
440
		$column_info['unsigned'] = '';
441
442
	list ($type, $size) = $smcFunc['db_calculate_type']($column_info['type'], $column_info['size']);
443
444
	// Allow for unsigned integers (mysql only)
445
	$unsigned = in_array($type, array('int', 'tinyint', 'smallint', 'mediumint', 'bigint')) && !empty($column_info['unsigned']) ? 'unsigned ' : '';
446
447
	// Fix the default.
448
	$default = '';
449
	if (array_key_exists('default', $column_info) && is_null($column_info['default']))
450
		$default = 'NULL';
451
	elseif (isset($column_info['default']) && is_numeric($column_info['default']))
452
		$default = strpos($column_info['default'], '.') ? floatval($column_info['default']) : intval($column_info['default']);
453
	else
454
		$default = '\'' . $smcFunc['db_escape_string']($column_info['default']) . '\'';
455
456
	if ($size !== null)
457
		$type = $type . '(' . $size . ')';
458
459
	$smcFunc['db_query']('', '
460
		ALTER TABLE ' . $short_table_name . '
461
		CHANGE COLUMN `' . $old_column . '` `' . $column_info['name'] . '` ' . $type . ' ' . (!empty($unsigned) ? $unsigned : '') . (!empty($column_info['not_null']) ? 'NOT NULL' : '') . ' ' .
462
				($default === '' ? '' : 'DEFAULT ' . $default) . ' ' .
463
			(empty($column_info['auto']) ? '' : 'auto_increment') . ' ',
464
		array(
465
			'security_override' => true,
466
		)
467
	);
468
}
469
470
/**
471
 * Add an index.
472
 *
473
 * @param string $table_name The name of the table to add the index to
474
 * @param array $index_info An array of index info (see {@link smf_db_create_table()})
475
 * @param array $parameters Not used?
476
 * @param string $if_exists What to do if the index exists. If 'update', the definition will be updated.
477
 * @param string $error
478
 * @return boolean Whether or not the operation was successful
479
 */
480
function smf_db_add_index($table_name, $index_info, $parameters = array(), $if_exists = 'update', $error = 'fatal')
481
{
482
	global $smcFunc, $db_package_log, $db_prefix;
483
484
	$short_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
485
486
	// No columns = no index.
487
	if (empty($index_info['columns']))
488
		return false;
489
490
	// MySQL If its a text column, we need to add a size.
491
	$cols = $smcFunc['db_list_columns']($table_name, true);
492
	foreach ($index_info['columns'] as &$c)
493
	{
494
		$c = trim($c);
495
496
		// If a size was already specified, we won't be able to match it anyways.
497
		if (!isset($cols[$c]) || !in_array($cols[$c]['type'], array('text', 'mediumntext', 'largetext', 'varchar', 'char')))
498
			continue;
499
500
		$c .= '(191)';
501
	}
502
503
	$columns = implode(',', $index_info['columns']);
504
505
	// No name - make it up!
506
	if (empty($index_info['name']))
507
	{
508
		// No need for primary.
509
		if (isset($index_info['type']) && $index_info['type'] == 'primary')
510
			$index_info['name'] = '';
511
		else
512
			$index_info['name'] = trim(implode('_', preg_replace('~(\(\d+\))~', '', $index_info['columns'])));
513
	}
514
515
	// Log that we are going to want to remove this!
516
	$db_package_log[] = array('remove_index', $short_table_name, $index_info['name']);
517
518
	// Let's get all our indexes.
519
	$indexes = $smcFunc['db_list_indexes']($table_name, true);
520
	// Do we already have it?
521
	foreach ($indexes as $index)
522
	{
523
		if ($index['name'] == $index_info['name'] || ($index['type'] == 'primary' && isset($index_info['type']) && $index_info['type'] == 'primary'))
524
		{
525
			// If we want to overwrite simply remove the current one then continue.
526
			if ($if_exists != 'update' || $index['type'] == 'primary')
527
				return false;
528
			else
529
				$smcFunc['db_remove_index']($table_name, $index_info['name']);
530
		}
531
	}
532
533
	// If we're here we know we don't have the index - so just add it.
534
	if (!empty($index_info['type']) && $index_info['type'] == 'primary')
535
	{
536
		$smcFunc['db_query']('', '
537
			ALTER TABLE ' . $short_table_name . '
538
			ADD PRIMARY KEY (' . $columns . ')',
539
			array(
540
				'security_override' => true,
541
			)
542
		);
543
	}
544
	else
545
	{
546
		$smcFunc['db_query']('', '
547
			ALTER TABLE ' . $short_table_name . '
548
			ADD ' . (isset($index_info['type']) && $index_info['type'] == 'unique' ? 'UNIQUE' : 'INDEX') . ' ' . $index_info['name'] . ' (' . $columns . ')',
549
			array(
550
				'security_override' => true,
551
			)
552
		);
553
	}
554
}
555
556
/**
557
 * Remove an index.
558
 *
559
 * @param string $table_name The name of the table to remove the index from
560
 * @param string $index_name The name of the index to remove
561
 * @param array $parameters Not used?
562
 * @param string $error
563
 * @return boolean Whether or not the operation was successful
564
 */
565
function smf_db_remove_index($table_name, $index_name, $parameters = array(), $error = 'fatal')
566
{
567
	global $smcFunc, $db_prefix;
568
569
	$short_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
570
571
	// Better exist!
572
	$indexes = $smcFunc['db_list_indexes']($table_name, true);
573
574
	foreach ($indexes as $index)
575
	{
576
		// If the name is primary we want the primary key!
577
		if ($index['type'] == 'primary' && $index_name == 'primary')
578
		{
579
			// Dropping primary key?
580
			$smcFunc['db_query']('', '
581
				ALTER TABLE ' . $short_table_name . '
582
				DROP PRIMARY KEY',
583
				array(
584
					'security_override' => true,
585
				)
586
			);
587
588
			return true;
589
		}
590
		if ($index['name'] == $index_name)
591
		{
592
			// Drop the bugger...
593
			$smcFunc['db_query']('', '
594
				ALTER TABLE ' . $short_table_name . '
595
				DROP INDEX ' . $index_name,
596
				array(
597
					'security_override' => true,
598
				)
599
			);
600
601
			return true;
602
		}
603
	}
604
605
	// Not to be found ;(
606
	return false;
607
}
608
609
/**
610
 * Get the schema formatted name for a type.
611
 *
612
 * @param string $type_name The data type (int, varchar, smallint, etc.)
613
 * @param int $type_size The size (8, 255, etc.)
614
 * @param boolean $reverse
615
 * @return array An array containing the appropriate type and size for this DB type
616
 */
617
function smf_db_calculate_type($type_name, $type_size = null, $reverse = false)
618
{
619
	// MySQL is actually the generic baseline.
620
621
	$type_name = strtolower($type_name);
622
	// Generic => Specific.
623
	if (!$reverse)
624
	{
625
		$types = array(
626
			'inet' => 'varbinary',
627
		);
628
	}
629
	else
630
	{
631
		$types = array(
632
			'varbinary' => 'inet',
633
		);
634
	}
635
636
	// Got it? Change it!
637
	if (isset($types[$type_name]))
638
	{
639
		if ($type_name == 'inet' && !$reverse)
640
		{
641
			$type_size = 16;
642
			$type_name = 'varbinary';
643
		}
644
		elseif ($type_name == 'varbinary' && $reverse && $type_size == 16)
645
		{
646
			$type_name = 'inet';
647
			$type_size = null;
648
		}
649
		elseif ($type_name == 'varbinary')
650
			$type_name = 'varbinary';
651
		else
652
			$type_name = $types[$type_name];
653
	}
654
	elseif ($type_name == 'boolean')
655
		$type_size = null;
656
657
	return array($type_name, $type_size);
658
}
659
660
/**
661
 * Get table structure.
662
 *
663
 * @param string $table_name The name of the table
664
 * @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()}
665
 */
666
function smf_db_table_structure($table_name)
667
{
668
	global $smcFunc, $db_prefix, $db_name;
669
670
	$parsed_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
671
	$real_table_name = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $parsed_table_name, $match) === 1 ? $match[3] : $parsed_table_name;
672
	$database = !empty($match[2]) ? $match[2] : $db_name;
673
674
	// Find the table engine and add that to the info as well
675
	$table_status = $smcFunc['db_query']('', '
676
		SHOW TABLE STATUS
677
		IN {raw:db}
678
		LIKE {string:table}',
679
		array(
680
			'db' => $database,
681
			'table' => $real_table_name
682
		)
683
	);
684
685
	// Only one row, so no need for a loop...
686
	$row = $smcFunc['db_fetch_assoc']($table_status);
687
688
	$smcFunc['db_free_result']($table_status);
689
690
	return array(
691
		'name' => $parsed_table_name,
692
		'columns' => $smcFunc['db_list_columns']($table_name, true),
693
		'indexes' => $smcFunc['db_list_indexes']($table_name, true),
694
		'engine' => $row['Engine'],
695
	);
696
}
697
698
/**
699
 * Return column information for a table.
700
 *
701
 * @param string $table_name The name of the table to get column info for
702
 * @param bool $detail Whether or not to return detailed info. If true, returns the column info. If false, just returns the column names.
703
 * @param array $parameters Not used?
704
 * @return array An array of column names or detailed column info, depending on $detail
705
 */
706
function smf_db_list_columns($table_name, $detail = false, $parameters = array())
707
{
708
	global $smcFunc, $db_prefix, $db_name;
709
710
	$parsed_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
711
	$real_table_name = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $parsed_table_name, $match) === 1 ? $match[3] : $parsed_table_name;
712
	$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...
713
714
	$result = $smcFunc['db_query']('', '
715
		SELECT column_name "Field", COLUMN_TYPE "Type", is_nullable "Null", COLUMN_KEY "Key" , column_default "Default", extra "Extra"
716
		FROM information_schema.columns
717
		WHERE table_name = {string:table_name}
718
			AND table_schema = {string:db_name}
719
		ORDER BY ordinal_position',
720
		array(
721
			'table_name' => $real_table_name,
722
			'db_name' => $db_name,
723
		)
724
	);
725
	$columns = array();
726
	while ($row = $smcFunc['db_fetch_assoc']($result))
727
	{
728
		if (!$detail)
729
		{
730
			$columns[] = $row['Field'];
731
		}
732
		else
733
		{
734
			// Is there an auto_increment?
735
			$auto = strpos($row['Extra'], 'auto_increment') !== false ? true : false;
736
737
			// Can we split out the size?
738
			if (preg_match('~(.+?)\s*\((\d+)\)(?:(?:\s*)?(unsigned))?~i', $row['Type'], $matches) === 1)
739
			{
740
				$type = $matches[1];
741
				$size = $matches[2];
742
				if (!empty($matches[3]) && $matches[3] == 'unsigned')
743
					$unsigned = true;
744
			}
745
			else
746
			{
747
				$type = $row['Type'];
748
				$size = null;
749
			}
750
751
			$columns[$row['Field']] = array(
752
				'name' => $row['Field'],
753
				'not_null' => $row['Null'] != 'YES',
754
				'null' => $row['Null'] == 'YES',
755
				'default' => isset($row['Default']) ? $row['Default'] : null,
756
				'type' => $type,
757
				'size' => $size,
758
				'auto' => $auto,
759
			);
760
761
			if (isset($unsigned))
762
			{
763
				$columns[$row['Field']]['unsigned'] = $unsigned;
764
				unset($unsigned);
765
			}
766
		}
767
	}
768
	$smcFunc['db_free_result']($result);
769
770
	return $columns;
771
}
772
773
/**
774
 * Get index information.
775
 *
776
 * @param string $table_name The name of the table to get indexes for
777
 * @param bool $detail Whether or not to return detailed info.
778
 * @param array $parameters Not used?
779
 * @return array An array of index names or a detailed array of index info, depending on $detail
780
 */
781
function smf_db_list_indexes($table_name, $detail = false, $parameters = array())
782
{
783
	global $smcFunc, $db_prefix, $db_name;
784
785
	$parsed_table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
786
	$real_table_name = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $parsed_table_name, $match) === 1 ? $match[3] : $parsed_table_name;
787
	$database = !empty($match[2]) ? $match[2] : $db_name;
788
789
	$result = $smcFunc['db_query']('', '
790
		SHOW KEYS
791
		FROM {raw:table_name}
792
		IN {raw:db}',
793
		array(
794
			'db' => $database,
795
			'table_name' => $real_table_name,
796
		)
797
	);
798
	$indexes = array();
799
	while ($row = $smcFunc['db_fetch_assoc']($result))
800
	{
801
		if (!$detail)
802
			$indexes[] = $row['Key_name'];
803
		else
804
		{
805
			// What is the type?
806
			if ($row['Key_name'] == 'PRIMARY')
807
				$type = 'primary';
808
			elseif (empty($row['Non_unique']))
809
				$type = 'unique';
810
			elseif (isset($row['Index_type']) && $row['Index_type'] == 'FULLTEXT')
811
				$type = 'fulltext';
812
			else
813
				$type = 'index';
814
815
			// This is the first column we've seen?
816
			if (empty($indexes[$row['Key_name']]))
817
			{
818
				$indexes[$row['Key_name']] = array(
819
					'name' => $row['Key_name'],
820
					'type' => $type,
821
					'columns' => array(),
822
				);
823
			}
824
825
			// Is it a partial index?
826
			if (!empty($row['Sub_part']))
827
				$indexes[$row['Key_name']]['columns'][] = $row['Column_name'] . '(' . $row['Sub_part'] . ')';
828
			else
829
				$indexes[$row['Key_name']]['columns'][] = $row['Column_name'];
830
		}
831
	}
832
	$smcFunc['db_free_result']($result);
833
834
	return $indexes;
835
}
836
837
/**
838
 * Creates a query for a column
839
 *
840
 * @param array $column An array of column info
841
 * @return string The column definition
842
 */
843
function smf_db_create_query_column($column)
844
{
845
	global $smcFunc;
846
847
	$column = array_change_key_case($column);
848
849
	// Auto increment is easy here!
850
	if (!empty($column['auto']))
851
		$default = 'auto_increment';
852
	// Make it null.
853
	elseif (array_key_exists('default', $column) && is_null($column['default']))
854
		$default = 'DEFAULT NULL';
855
	// Numbers don't need quotes.
856
	elseif (isset($column['default']) && is_numeric($column['default']))
857
		$default = 'DEFAULT ' . (strpos($column['default'], '.') ? floatval($column['default']) : intval($column['default']));
858
	// Non empty string.
859
	elseif (isset($column['default']))
860
		$default = 'DEFAULT \'' . $smcFunc['db_escape_string']($column['default']) . '\'';
861
	else
862
		$default = '';
863
864
	// Backwards compatible with the nullable column.
865
	if (isset($column['null']) && !isset($column['not_null']))
866
		$column['not_null'] = !$column['null'];
867
868
	// Sort out the size... and stuff...
869
	$column['size'] = isset($column['size']) && is_numeric($column['size']) ? $column['size'] : null;
870
	list ($type, $size) = $smcFunc['db_calculate_type']($column['type'], $column['size']);
871
872
	// Allow unsigned integers (mysql only)
873
	$unsigned = in_array($type, array('int', 'tinyint', 'smallint', 'mediumint', 'bigint')) && !empty($column['unsigned']) ? 'unsigned ' : '';
874
875
	if ($size !== null)
876
		$type = $type . '(' . $size . ')';
877
878
	// Now just put it together!
879
	return '`' . $column['name'] . '` ' . $type . ' ' . (!empty($unsigned) ? $unsigned : '') . (!empty($column['not_null']) ? 'NOT NULL' : '') . ' ' . $default;
880
}
881
882
?>