DbPackages-postgresql.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  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 2012 Simple Machines
  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
  80. * @param array $columns in the format specified.
  81. * @param array $indexes default array(), in the format specified.
  82. * @param array $parameters default array()
  83. * @param string $if_exists default 'ignore'
  84. * @param string $error default 'fatal'
  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.
  174. *
  175. * @param string $table_name
  176. * @param array $parameters default array()
  177. * @param string $error default 'fatal'
  178. */
  179. function smf_db_drop_table($table_name, $parameters = array(), $error = 'fatal')
  180. {
  181. global $reservedTables, $smcFunc, $db_prefix;
  182. // After stripping away the database name, this is what's left.
  183. $real_prefix = preg_match('~^("?)(.+?)\\1\\.(.*?)$~', $db_prefix, $match) === 1 ? $match[3] : $db_prefix;
  184. // Get some aliases.
  185. $full_table_name = str_replace('{db_prefix}', $real_prefix, $table_name);
  186. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  187. // God no - dropping one of these = bad.
  188. if (in_array(strtolower($table_name), $reservedTables))
  189. return false;
  190. // Does it exist?
  191. if (in_array($full_table_name, $smcFunc['db_list_tables']()))
  192. {
  193. // We can then drop the table.
  194. $smcFunc['db_transaction']('begin');
  195. // the table
  196. $table_query = 'DROP TABLE ' . $table_name;
  197. // and the assosciated sequence, if any
  198. $sequence_query = 'DROP SEQUENCE IF EXISTS ' . $table_name . '_seq';
  199. // drop them
  200. $smcFunc['db_query']('',
  201. $table_query,
  202. array(
  203. 'security_override' => true,
  204. )
  205. );
  206. $smcFunc['db_query']('',
  207. $sequence_query,
  208. array(
  209. 'security_override' => true,
  210. )
  211. );
  212. $smcFunc['db_transaction']('commit');
  213. return true;
  214. }
  215. // Otherwise do 'nout.
  216. return false;
  217. }
  218. /**
  219. * This function adds a column.
  220. *
  221. * @param string $table_name the name of the table
  222. * @param array $column_info with column information
  223. * @param array $parameters default array()
  224. * @param string $if_exists default 'update'
  225. * @param string $error default 'fatal'
  226. */
  227. function smf_db_add_column($table_name, $column_info, $parameters = array(), $if_exists = 'update', $error = 'fatal')
  228. {
  229. global $smcFunc, $db_package_log, $txt, $db_prefix;
  230. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  231. // Log that we will want to uninstall this!
  232. $db_package_log[] = array('remove_column', $table_name, $column_info['name']);
  233. // Does it exist - if so don't add it again!
  234. $columns = $smcFunc['db_list_columns']($table_name, false);
  235. foreach ($columns as $column)
  236. if ($column == $column_info['name'])
  237. {
  238. // If we're going to overwrite then use change column.
  239. if ($if_exists == 'update')
  240. return $smcFunc['db_change_column']($table_name, $column_info['name'], $column_info);
  241. else
  242. return false;
  243. }
  244. // Get the specifics...
  245. $column_info['size'] = isset($column_info['size']) && is_numeric($column_info['size']) ? $column_info['size'] : null;
  246. list ($type, $size) = $smcFunc['db_calculate_type']($column_info['type'], $column_info['size']);
  247. if ($size !== null)
  248. $type = $type . '(' . $size . ')';
  249. // Now add the thing!
  250. $query = '
  251. ALTER TABLE ' . $table_name . '
  252. ADD COLUMN ' . $column_info['name'] . ' ' . $type;
  253. $smcFunc['db_query']('', $query,
  254. array(
  255. 'security_override' => true,
  256. )
  257. );
  258. // If there's more attributes they need to be done via a change on PostgreSQL.
  259. unset($column_info['type'], $column_info['size']);
  260. if (count($column_info) != 1)
  261. return $smcFunc['db_change_column']($table_name, $column_info['name'], $column_info);
  262. else
  263. return true;
  264. }
  265. /**
  266. * Removes a column.
  267. *
  268. * @param string $table_name
  269. * @param string $column_name
  270. * @param array $parameters default array()
  271. * @param string $error default 'fatal'
  272. */
  273. function smf_db_remove_column($table_name, $column_name, $parameters = array(), $error = 'fatal')
  274. {
  275. global $smcFunc, $db_prefix;
  276. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  277. // Does it exist?
  278. $columns = $smcFunc['db_list_columns']($table_name, true);
  279. foreach ($columns as $column)
  280. if ($column['name'] == $column_name)
  281. {
  282. // If there is an auto we need remove it!
  283. if ($column['auto'])
  284. $smcFunc['db_query']('',
  285. 'DROP SEQUENCE ' . $table_name . '_seq',
  286. array(
  287. 'security_override' => true,
  288. )
  289. );
  290. $smcFunc['db_query']('', '
  291. ALTER TABLE ' . $table_name . '
  292. DROP COLUMN ' . $column_name,
  293. array(
  294. 'security_override' => true,
  295. )
  296. );
  297. return true;
  298. }
  299. // If here we didn't have to work - joy!
  300. return false;
  301. }
  302. /**
  303. * Change a column.
  304. *
  305. * @param string $table_name
  306. * @param $old_column
  307. * @param $column_info
  308. * @param array $parameters default array()
  309. * @param string $error default 'fatal'
  310. */
  311. function smf_db_change_column($table_name, $old_column, $column_info, $parameters = array(), $error = 'fatal')
  312. {
  313. global $smcFunc, $db_prefix;
  314. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  315. // Check it does exist!
  316. $columns = $smcFunc['db_list_columns']($table_name, true);
  317. $old_info = null;
  318. foreach ($columns as $column)
  319. if ($column['name'] == $old_column)
  320. $old_info = $column;
  321. // Nothing?
  322. if ($old_info == null)
  323. return false;
  324. // Now we check each bit individually and ALTER as required.
  325. if (isset($column_info['name']) && $column_info['name'] != $old_column)
  326. {
  327. $smcFunc['db_query']('', '
  328. ALTER TABLE ' . $table_name . '
  329. RENAME COLUMN ' . $old_column . ' TO ' . $column_info['name'],
  330. array(
  331. 'security_override' => true,
  332. )
  333. );
  334. }
  335. // Different default?
  336. if (isset($column_info['default']) && $column_info['default'] != $old_info['default'])
  337. {
  338. $action = $column_info['default'] !== null ? 'SET DEFAULT \'' . $smcFunc['db_escape_string']($column_info['default']) . '\'' : 'DROP DEFAULT';
  339. $smcFunc['db_query']('', '
  340. ALTER TABLE ' . $table_name . '
  341. ALTER COLUMN ' . $column_info['name'] . ' ' . $action,
  342. array(
  343. 'security_override' => true,
  344. )
  345. );
  346. }
  347. // Is it null - or otherwise?
  348. if (isset($column_info['null']) && $column_info['null'] != $old_info['null'])
  349. {
  350. $action = $column_info['null'] ? 'DROP' : 'SET';
  351. $smcFunc['db_transaction']('begin');
  352. if (!$column_info['null'])
  353. {
  354. // We have to set it to something if we are making it NOT NULL. And we must comply with the current column format.
  355. $setTo = isset($column_info['default']) ? $column_info['default'] : (strpos($old_info['type'], 'int') !== false ? 0 : '');
  356. $smcFunc['db_query']('', '
  357. UPDATE ' . $table_name . '
  358. SET ' . $column_info['name'] . ' = \'' . $setTo . '\'
  359. WHERE ' . $column_info['name'] . ' IS NULL',
  360. array(
  361. 'security_override' => true,
  362. )
  363. );
  364. }
  365. $smcFunc['db_query']('', '
  366. ALTER TABLE ' . $table_name . '
  367. ALTER COLUMN ' . $column_info['name'] . ' ' . $action . ' NOT NULL',
  368. array(
  369. 'security_override' => true,
  370. )
  371. );
  372. $smcFunc['db_transaction']('commit');
  373. }
  374. // What about a change in type?
  375. if (isset($column_info['type']) && ($column_info['type'] != $old_info['type'] || (isset($column_info['size']) && $column_info['size'] != $old_info['size'])))
  376. {
  377. $column_info['size'] = isset($column_info['size']) && is_numeric($column_info['size']) ? $column_info['size'] : null;
  378. list ($type, $size) = $smcFunc['db_calculate_type']($column_info['type'], $column_info['size']);
  379. if ($size !== null)
  380. $type = $type . '(' . $size . ')';
  381. // The alter is a pain.
  382. $smcFunc['db_transaction']('begin');
  383. $smcFunc['db_query']('', '
  384. ALTER TABLE ' . $table_name . '
  385. ADD COLUMN ' . $column_info['name'] . '_tempxx ' . $type,
  386. array(
  387. 'security_override' => true,
  388. )
  389. );
  390. $smcFunc['db_query']('', '
  391. UPDATE ' . $table_name . '
  392. SET ' . $column_info['name'] . '_tempxx = CAST(' . $column_info['name'] . ' AS ' . $type . ')',
  393. array(
  394. 'security_override' => true,
  395. )
  396. );
  397. $smcFunc['db_query']('', '
  398. ALTER TABLE ' . $table_name . '
  399. DROP COLUMN ' . $column_info['name'],
  400. array(
  401. 'security_override' => true,
  402. )
  403. );
  404. $smcFunc['db_query']('', '
  405. ALTER TABLE ' . $table_name . '
  406. RENAME COLUMN ' . $column_info['name'] . '_tempxx TO ' . $column_info['name'],
  407. array(
  408. 'security_override' => true,
  409. )
  410. );
  411. $smcFunc['db_transaction']('commit');
  412. }
  413. // Finally - auto increment?!
  414. if (isset($column_info['auto']) && $column_info['auto'] != $old_info['auto'])
  415. {
  416. // Are we removing an old one?
  417. if ($old_info['auto'])
  418. {
  419. // Alter the table first - then drop the sequence.
  420. $smcFunc['db_query']('', '
  421. ALTER TABLE ' . $table_name . '
  422. ALTER COLUMN ' . $column_info['name'] . ' SET DEFAULT \'0\'',
  423. array(
  424. 'security_override' => true,
  425. )
  426. );
  427. $smcFunc['db_query']('', '
  428. DROP SEQUENCE ' . $table_name . '_seq',
  429. array(
  430. 'security_override' => true,
  431. )
  432. );
  433. }
  434. // Otherwise add it!
  435. else
  436. {
  437. $smcFunc['db_query']('', '
  438. CREATE SEQUENCE ' . $table_name . '_seq',
  439. array(
  440. 'security_override' => true,
  441. )
  442. );
  443. $smcFunc['db_query']('', '
  444. ALTER TABLE ' . $table_name . '
  445. ALTER COLUMN ' . $column_info['name'] . ' SET DEFAULT nextval(\'' . $table_name . '_seq\')',
  446. array(
  447. 'security_override' => true,
  448. )
  449. );
  450. }
  451. }
  452. }
  453. /**
  454. * Add an index.
  455. *
  456. * @param string $table_name
  457. * @param array $index_info
  458. * @param array $parameters default array()
  459. * @param string $if_exists default 'update'
  460. * @param string $error default 'fatal'
  461. */
  462. function smf_db_add_index($table_name, $index_info, $parameters = array(), $if_exists = 'update', $error = 'fatal')
  463. {
  464. global $smcFunc, $db_package_log, $db_prefix;
  465. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  466. // No columns = no index.
  467. if (empty($index_info['columns']))
  468. return false;
  469. $columns = implode(',', $index_info['columns']);
  470. // No name - make it up!
  471. if (empty($index_info['name']))
  472. {
  473. // No need for primary.
  474. if (isset($index_info['type']) && $index_info['type'] == 'primary')
  475. $index_info['name'] = '';
  476. else
  477. $index_info['name'] = $table_name . implode('_', $index_info['columns']);
  478. }
  479. else
  480. $index_info['name'] = $table_name . $index_info['name'];
  481. // Log that we are going to want to remove this!
  482. $db_package_log[] = array('remove_index', $table_name, $index_info['name']);
  483. // Let's get all our indexes.
  484. $indexes = $smcFunc['db_list_indexes']($table_name, true);
  485. // Do we already have it?
  486. foreach ($indexes as $index)
  487. {
  488. if ($index['name'] == $index_info['name'] || ($index['type'] == 'primary' && isset($index_info['type']) && $index_info['type'] == 'primary'))
  489. {
  490. // If we want to overwrite simply remove the current one then continue.
  491. if ($if_exists != 'update' || $index['type'] == 'primary')
  492. return false;
  493. else
  494. $smcFunc['db_remove_index']($table_name, $index_info['name']);
  495. }
  496. }
  497. // If we're here we know we don't have the index - so just add it.
  498. if (!empty($index_info['type']) && $index_info['type'] == 'primary')
  499. {
  500. $smcFunc['db_query']('', '
  501. ALTER TABLE ' . $table_name . '
  502. ADD PRIMARY KEY (' . $columns . ')',
  503. array(
  504. 'security_override' => true,
  505. )
  506. );
  507. }
  508. else
  509. {
  510. $smcFunc['db_query']('', '
  511. CREATE ' . (isset($index_info['type']) && $index_info['type'] == 'unique' ? 'UNIQUE' : '') . ' INDEX ' . $index_info['name'] . ' ON ' . $table_name . ' (' . $columns . ')',
  512. array(
  513. 'security_override' => true,
  514. )
  515. );
  516. }
  517. }
  518. /**
  519. * Remove an index.
  520. *
  521. * @param string $table_name
  522. * @param string $index_name
  523. * @param array$parameters default array()
  524. * @param string $error default 'fatal'
  525. */
  526. function smf_db_remove_index($table_name, $index_name, $parameters = array(), $error = 'fatal')
  527. {
  528. global $smcFunc, $db_prefix;
  529. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  530. // Better exist!
  531. $indexes = $smcFunc['db_list_indexes']($table_name, true);
  532. if ($index_name != 'primary')
  533. $index_name = $table_name . '_' . $index_name;
  534. foreach ($indexes as $index)
  535. {
  536. // If the name is primary we want the primary key!
  537. if ($index['type'] == 'primary' && $index_name == 'primary')
  538. {
  539. // Dropping primary key is odd...
  540. $smcFunc['db_query']('', '
  541. ALTER TABLE ' . $table_name . '
  542. DROP CONSTRAINT ' . $index['name'],
  543. array(
  544. 'security_override' => true,
  545. )
  546. );
  547. return true;
  548. }
  549. if ($index['name'] == $index_name)
  550. {
  551. // Drop the bugger...
  552. $smcFunc['db_query']('', '
  553. DROP INDEX ' . $index_name,
  554. array(
  555. 'security_override' => true,
  556. )
  557. );
  558. return true;
  559. }
  560. }
  561. // Not to be found ;(
  562. return false;
  563. }
  564. /**
  565. * Get the schema formatted name for a type.
  566. *
  567. * @param string $type_name
  568. * @param $type_size
  569. * @param $reverse
  570. */
  571. function smf_db_calculate_type($type_name, $type_size = null, $reverse = false)
  572. {
  573. // Let's be sure it's lowercase MySQL likes both, others no.
  574. $type_name = strtolower($type_name);
  575. // Generic => Specific.
  576. if (!$reverse)
  577. {
  578. $types = array(
  579. 'varchar' => 'character varying',
  580. 'char' => 'character',
  581. 'mediumint' => 'int',
  582. 'tinyint' => 'smallint',
  583. 'tinytext' => 'character varying',
  584. 'mediumtext' => 'text',
  585. 'largetext' => 'text',
  586. );
  587. }
  588. else
  589. {
  590. $types = array(
  591. 'character varying' => 'varchar',
  592. 'character' => 'char',
  593. 'integer' => 'int',
  594. );
  595. }
  596. // Got it? Change it!
  597. if (isset($types[$type_name]))
  598. {
  599. if ($type_name == 'tinytext')
  600. $type_size = 255;
  601. $type_name = $types[$type_name];
  602. }
  603. // Numbers don't have a size.
  604. if (strpos($type_name, 'int') !== false)
  605. $type_size = null;
  606. return array($type_name, $type_size);
  607. }
  608. /**
  609. * Get table structure.
  610. *
  611. * @param string $table_name
  612. * @param array $parameters default array()
  613. */
  614. function smf_db_table_structure($table_name, $parameters = array())
  615. {
  616. global $smcFunc, $db_prefix;
  617. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  618. return array(
  619. 'name' => $table_name,
  620. 'columns' => $smcFunc['db_list_columns']($table_name, true),
  621. 'indexes' => $smcFunc['db_list_indexes']($table_name, true),
  622. );
  623. }
  624. /**
  625. * Return column information for a table.
  626. *
  627. * @param string $table_name
  628. * @param bool $detail
  629. * @param array $parameters default array()
  630. * @return mixed
  631. */
  632. function smf_db_list_columns($table_name, $detail = false, $parameters = array())
  633. {
  634. global $smcFunc, $db_prefix;
  635. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  636. $result = $smcFunc['db_query']('', '
  637. SELECT column_name, column_default, is_nullable, data_type, character_maximum_length
  638. FROM information_schema.columns
  639. WHERE table_name = \'' . $table_name . '\'
  640. ORDER BY ordinal_position',
  641. array(
  642. 'security_override' => true,
  643. )
  644. );
  645. $columns = array();
  646. while ($row = $smcFunc['db_fetch_assoc']($result))
  647. {
  648. if (!$detail)
  649. {
  650. $columns[] = $row['column_name'];
  651. }
  652. else
  653. {
  654. $auto = false;
  655. // What is the default?
  656. if (preg_match('~nextval\(\'(.+?)\'(.+?)*\)~i', $row['column_default'], $matches) != 0)
  657. {
  658. $default = null;
  659. $auto = true;
  660. }
  661. elseif (trim($row['column_default']) != '')
  662. $default = strpos($row['column_default'], '::') === false ? $row['column_default'] : substr($row['column_default'], 0, strpos($row['column_default'], '::'));
  663. else
  664. $default = null;
  665. // Make the type generic.
  666. list ($type, $size) = $smcFunc['db_calculate_type']($row['data_type'], $row['character_maximum_length'], true);
  667. $columns[$row['column_name']] = array(
  668. 'name' => $row['column_name'],
  669. 'null' => $row['is_nullable'] ? true : false,
  670. 'default' => $default,
  671. 'type' => $type,
  672. 'size' => $size,
  673. 'auto' => $auto,
  674. );
  675. }
  676. }
  677. $smcFunc['db_free_result']($result);
  678. return $columns;
  679. }
  680. /**
  681. * Get index information.
  682. *
  683. * @param string $table_name
  684. * @param bool $detail
  685. * @param array $parameters
  686. * @return mixed
  687. */
  688. function smf_db_list_indexes($table_name, $detail = false, $parameters = array())
  689. {
  690. global $smcFunc, $db_prefix;
  691. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  692. $result = $smcFunc['db_query']('', '
  693. SELECT CASE WHEN i.indisprimary THEN 1 ELSE 0 END AS is_primary,
  694. CASE WHEN i.indisunique THEN 1 ELSE 0 END AS is_unique,
  695. c2.relname AS name,
  696. pg_get_indexdef(i.indexrelid) AS inddef
  697. FROM pg_class AS c, pg_class AS c2, pg_index AS i
  698. WHERE c.relname = \'' . $table_name . '\'
  699. AND c.oid = i.indrelid
  700. AND i.indexrelid = c2.oid',
  701. array(
  702. 'security_override' => true,
  703. )
  704. );
  705. $indexes = array();
  706. while ($row = $smcFunc['db_fetch_assoc']($result))
  707. {
  708. // Try get the columns that make it up.
  709. if (preg_match('~\(([^\)]+?)\)~i', $row['inddef'], $matches) == 0)
  710. continue;
  711. $columns = explode(',', $matches[1]);
  712. if (empty($columns))
  713. continue;
  714. foreach ($columns as $k => $v)
  715. $columns[$k] = trim($v);
  716. // Fix up the name to be consistent cross databases
  717. if (substr($row['name'], -5) == '_pkey' && $row['is_primary'] == 1)
  718. $row['name'] = 'PRIMARY';
  719. else
  720. $row['name'] = str_replace($table_name . '_', '', $row['name']);
  721. if (!$detail)
  722. $indexes[] = $row['name'];
  723. else
  724. {
  725. $indexes[$row['name']] = array(
  726. 'name' => $row['name'],
  727. 'type' => $row['is_primary'] ? 'primary' : ($row['is_unique'] ? 'unique' : 'index'),
  728. 'columns' => $columns,
  729. );
  730. }
  731. }
  732. $smcFunc['db_free_result']($result);
  733. return $indexes;
  734. }
  735. ?>