DbPackages-postgresql.php 22 KB

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