2
0

DbPackages-postgresql.php 26 KB

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