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