Issues (1065)

Sources/DbPackages-postgresql.php (2 issues)

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