PageRenderTime 43ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/sources/database/DbPackages-sqlite.php

https://github.com/Arantor/Elkarte
PHP | 824 lines | 504 code | 103 blank | 217 comment | 95 complexity | 645b0c4e179f8ff7ab472e6cd958f79e MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-3.0
  1. <?php
  2. /**
  3. * @name ElkArte Forum
  4. * @copyright ElkArte Forum contributors
  5. * @license BSD http://opensource.org/licenses/BSD-3-Clause
  6. *
  7. * This software is a derived product, based on:
  8. *
  9. * Simple Machines Forum (SMF)
  10. * copyright: 2011 Simple Machines (http://www.simplemachines.org)
  11. * license: BSD, See included LICENSE.TXT for terms and conditions.
  12. *
  13. * @version 1.0 Alpha
  14. *
  15. * This file contains database functionality specifically designed for packages (mods) to utilize.
  16. *
  17. */
  18. if (!defined('ELKARTE'))
  19. die('No access...');
  20. /**
  21. * Add the file functions to the $smcFunc array.
  22. */
  23. function db_packages_init()
  24. {
  25. global $smcFunc, $reservedTables, $db_package_log, $db_prefix;
  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_alter_table' => 'smf_db_alter_table',
  32. 'db_calculate_type' => 'smf_db_calculate_type',
  33. 'db_change_column' => 'smf_db_change_column',
  34. 'db_create_table' => 'smf_db_create_table',
  35. 'db_drop_table' => 'smf_db_drop_table',
  36. 'db_table_structure' => 'smf_db_table_structure',
  37. 'db_list_columns' => 'smf_db_list_columns',
  38. 'db_list_indexes' => 'smf_db_list_indexes',
  39. 'db_remove_column' => 'smf_db_remove_column',
  40. 'db_remove_index' => 'smf_db_remove_index',
  41. );
  42. $db_package_log = array();
  43. }
  44. // We setup an array of tables we can't do auto-remove on - in case a mod writer cocks it up!
  45. $reservedTables = array('admin_info_files', 'approval_queue', 'attachments', 'ban_groups', 'ban_items',
  46. 'board_permissions', 'boards', 'calendar', 'calendar_holidays', 'categories', 'collapsed_categories',
  47. 'custom_fields', 'group_moderators', 'log_actions', 'log_activity', 'log_banned', 'log_boards',
  48. 'log_digest', 'log_errors', 'log_floodcontrol', 'log_group_requests', 'log_karma', 'log_mark_read',
  49. 'log_notify', 'log_online', 'log_packages', 'log_polls', 'log_reported', 'log_reported_comments',
  50. 'log_scheduled_tasks', 'log_search_messages', 'log_search_results', 'log_search_subjects',
  51. 'log_search_topics', 'log_topics', 'mail_queue', 'membergroups', 'members', 'message_icons',
  52. 'messages', 'moderators', 'package_servers', 'permission_profiles', 'permissions', 'personal_messages',
  53. 'pm_recipients', 'poll_choices', 'polls', 'scheduled_tasks', 'sessions', 'settings', 'smileys',
  54. 'themes', 'topics');
  55. foreach ($reservedTables as $k => $table_name)
  56. $reservedTables[$k] = strtolower($db_prefix . $table_name);
  57. // We in turn may need the extra stuff.
  58. db_extend('extra');
  59. }
  60. /**
  61. * This function can be used to create a table without worrying about schema
  62. * compatabilities across supported database systems.
  63. * - If the table exists will, by default, do nothing.
  64. * - Builds table with columns as passed to it - at least one column must be sent.
  65. * The columns array should have one sub-array for each column - these sub arrays contain:
  66. * 'name' = Column name
  67. * 'type' = Type of column - values from (smallint, mediumint, int, text, varchar, char, tinytext, mediumtext, largetext)
  68. * 'size' => Size of column (If applicable) - for example 255 for a large varchar, 10 for an int etc.
  69. * If not set it will pick a size.
  70. * - 'default' = Default value - do not set if no default required.
  71. * - 'null' => Can it be null (true or false) - if not set default will be false.
  72. * - 'auto' => Set to true to make it an auto incrementing column. Set to a numerical value to set from what
  73. * it should begin counting.
  74. * - Adds indexes as specified within indexes parameter. Each index should be a member of $indexes. Values are:
  75. * - 'name' => Index name (If left empty it will be generated).
  76. * - 'type' => Type of index. Choose from 'primary', 'unique' or 'index'. If not set will default to 'index'.
  77. * - 'columns' => Array containing columns that form part of key - in the order the index is to be created.
  78. * - parameters: (None yet)
  79. * - if_exists values:
  80. * - 'ignore' will do nothing if the table exists. (And will return true)
  81. * - 'overwrite' will drop any existing table of the same name.
  82. * - 'error' will return false if the table already exists.
  83. *
  84. * @param string $table_name
  85. * @param array $columns in the format specified.
  86. * @param array $indexes default array(), in the format specified.
  87. * @param array $parameters default array()
  88. * @param string $if_exists default 'ignore'
  89. * @param string $error default 'fatal'
  90. */
  91. function smf_db_create_table($table_name, $columns, $indexes = array(), $parameters = array(), $if_exists = 'ignore', $error = 'fatal')
  92. {
  93. global $reservedTables, $smcFunc, $db_package_log, $db_prefix;
  94. // With or without the database name, the full name looks like this.
  95. $real_prefix = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $db_prefix, $match) === 1 ? $match[3] : $db_prefix;
  96. $full_table_name = str_replace('{db_prefix}', $real_prefix, $table_name);
  97. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  98. // First - no way do we touch our own tables.
  99. // Commented out for now. We need to alter our tables in order to use this in the upgrade.
  100. /*
  101. if (in_array(strtolower($table_name), $reservedTables))
  102. return false;
  103. */
  104. // Log that we'll want to remove this on uninstall.
  105. $db_package_log[] = array('remove_table', $table_name);
  106. // Does this table exist or not?
  107. $tables = $smcFunc['db_list_tables']();
  108. if (in_array($full_table_name, $tables))
  109. {
  110. // This is a sad day... drop the table? If not, return false (error) by default.
  111. if ($if_exists == 'overwrite')
  112. $smcFunc['db_drop_table']($table_name);
  113. else
  114. return $if_exists == 'ignore';
  115. }
  116. // Righty - let's do the damn thing!
  117. $table_query = 'CREATE TABLE ' . $table_name . "\n" . '(';
  118. $done_primary = false;
  119. foreach ($columns as $column)
  120. {
  121. // Auto increment is special
  122. if (!empty($column['auto']))
  123. {
  124. $table_query .= "\n" . $column['name'] . ' integer PRIMARY KEY,';
  125. $done_primary = true;
  126. continue;
  127. }
  128. elseif (isset($column['default']) && $column['default'] !== null)
  129. $default = 'default \'' . $smcFunc['db_escape_string']($column['default']) . '\'';
  130. else
  131. $default = '';
  132. // Sort out the size... and stuff...
  133. $column['size'] = isset($column['size']) && is_numeric($column['size']) ? $column['size'] : null;
  134. list ($type, $size) = $smcFunc['db_calculate_type']($column['type'], $column['size']);
  135. if ($size !== null)
  136. $type = $type . '(' . $size . ')';
  137. // Now just put it together!
  138. $table_query .= "\n\t" . $column['name'] . ' ' . $type . ' ' . (!empty($column['null']) ? '' : 'NOT NULL') . ' ' . $default . ',';
  139. }
  140. // Loop through the indexes next...
  141. $index_queries = array();
  142. foreach ($indexes as $index)
  143. {
  144. $columns = implode(',', $index['columns']);
  145. // Is it the primary?
  146. if (isset($index['type']) && $index['type'] == 'primary')
  147. {
  148. // If we've done the primary via auto_inc, don't do it again!
  149. if (!$done_primary)
  150. $table_query .= "\n\t" . 'PRIMARY KEY (' . implode(',', $index['columns']) . '),';
  151. }
  152. else
  153. {
  154. if (empty($index['name']))
  155. $index['name'] = implode('_', $index['columns']);
  156. $index_queries[] = 'CREATE ' . (isset($index['type']) && $index['type'] == 'unique' ? 'UNIQUE' : '') . ' INDEX ' . $table_name . '_' . $index['name'] . ' ON ' . $table_name . ' (' . $columns . ')';
  157. }
  158. }
  159. // No trailing commas!
  160. if (substr($table_query, -1) == ',')
  161. $table_query = substr($table_query, 0, -1);
  162. $table_query .= ')';
  163. if (empty($parameters['skip_transaction']))
  164. $smcFunc['db_transaction']('begin');
  165. // Do the table and indexes...
  166. $smcFunc['db_query']('', $table_query,
  167. array(
  168. 'security_override' => true,
  169. )
  170. );
  171. foreach ($index_queries as $query)
  172. $smcFunc['db_query']('', $query,
  173. array(
  174. 'security_override' => true,
  175. )
  176. );
  177. if (empty($parameters['skip_transaction']))
  178. $smcFunc['db_transaction']('commit');
  179. }
  180. /**
  181. * Drop a table.
  182. *
  183. * @param string $table_name
  184. * @param array $parameters default array()
  185. * @param bool $error
  186. * @param string $error default 'fatal'
  187. */
  188. function smf_db_drop_table($table_name, $parameters = array(), $error = 'fatal')
  189. {
  190. global $reservedTables, $smcFunc, $db_prefix;
  191. // Strip out the table name, we might not need it in some cases
  192. $real_prefix = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $db_prefix, $match) === 1 ? $match[3] : $db_prefix;
  193. $full_table_name = str_replace('{db_prefix}', $real_prefix, $table_name);
  194. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  195. // God no - dropping one of these = bad.
  196. if (in_array(strtolower($table_name), $reservedTables))
  197. return false;
  198. // Does it exist?
  199. if (in_array($full_table_name, $smcFunc['db_list_tables']()))
  200. {
  201. $query = 'DROP TABLE ' . $table_name;
  202. $smcFunc['db_query']('', $query,
  203. array(
  204. 'security_override' => true,
  205. )
  206. );
  207. return true;
  208. }
  209. // Otherwise do 'nout.
  210. return false;
  211. }
  212. /**
  213. * This function adds a column.
  214. *
  215. * @param string $table_name the name of the table
  216. * @param array $column_info with column information
  217. * @param array $parameters default array()
  218. * @param string $if_exists default 'update'
  219. * @param string $error default 'fatal'
  220. */
  221. function smf_db_add_column($table_name, $column_info, $parameters = array(), $if_exists = 'update', $error = 'fatal')
  222. {
  223. global $smcFunc, $db_package_log, $txt, $db_prefix;
  224. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  225. // Log that we will want to uninstall this!
  226. $db_package_log[] = array('remove_column', $table_name, $column_info['name']);
  227. // Does it exist - if so don't add it again!
  228. $columns = $smcFunc['db_list_columns']($table_name, false);
  229. foreach ($columns as $column)
  230. if ($column == $column_info['name'])
  231. {
  232. // If we're going to overwrite then use change column.
  233. if ($if_exists == 'update')
  234. return $smcFunc['db_change_column']($table_name, $column_info['name'], $column_info);
  235. else
  236. return false;
  237. }
  238. // Alter the table to add the column.
  239. if ($smcFunc['db_alter_table']($table_name, array('add' => array($column_info))) === false)
  240. return false;
  241. return true;
  242. }
  243. /**
  244. * Removes a column.
  245. *
  246. * We can't reliably do this on SQLite - damn!
  247. * @param string $table_name
  248. * @param string $column_name
  249. * @param array $parameters default array()
  250. * @param string $error default 'fatal'
  251. */
  252. function smf_db_remove_column($table_name, $column_name, $parameters = array(), $error = 'fatal')
  253. {
  254. global $smcFunc, $db_prefix;
  255. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  256. if ($smcFunc['db_alter_table']($table_name, array('remove' => array(array('name' => $column_name)))))
  257. return true;
  258. else
  259. return false;
  260. }
  261. /**
  262. * Change a column.
  263. *
  264. * @param string $table_name
  265. * @param $old_column
  266. * @param $column_info
  267. * @param array $parameters default array()
  268. * @param string $error default 'fatal'
  269. */
  270. function smf_db_change_column($table_name, $old_column, $column_info, $parameters = array(), $error = 'fatal')
  271. {
  272. global $smcFunc, $db_prefix;
  273. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  274. if ($smcFunc['db_alter_table']($table_name, array('change' => array(array('name' => $old_column) + $column_info))))
  275. return true;
  276. else
  277. return false;
  278. }
  279. /**
  280. * Add an index.
  281. *
  282. * @param string $table_name
  283. * @param array $index_info
  284. * @param array $parameters default array()
  285. * @param string $if_exists default 'update'
  286. * @param string $error default 'fatal'
  287. */
  288. function smf_db_add_index($table_name, $index_info, $parameters = array(), $if_exists = 'update', $error = 'fatal')
  289. {
  290. global $smcFunc, $db_package_log, $db_prefix;
  291. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  292. // No columns = no index.
  293. if (empty($index_info['columns']))
  294. return false;
  295. $columns = implode(',', $index_info['columns']);
  296. // No name - make it up!
  297. if (empty($index_info['name']))
  298. {
  299. // No need for primary.
  300. if (isset($index_info['type']) && $index_info['type'] == 'primary')
  301. $index_info['name'] = '';
  302. else
  303. $index_info['name'] = implode('_', $index_info['columns']);
  304. }
  305. else
  306. $index_info['name'] = $index_info['name'];
  307. // Log that we are going to want to remove this!
  308. $db_package_log[] = array('remove_index', $table_name, $index_info['name']);
  309. // Let's get all our indexes.
  310. $indexes = $smcFunc['db_list_indexes']($table_name, true);
  311. // Do we already have it?
  312. foreach ($indexes as $index)
  313. {
  314. if ($index['name'] == $index_info['name'] || ($index['type'] == 'primary' && isset($index_info['type']) && $index_info['type'] == 'primary'))
  315. {
  316. // If we want to overwrite simply remove the current one then continue.
  317. if ($if_exists != 'update' || $index['type'] == 'primary')
  318. return false;
  319. else
  320. $smcFunc['db_remove_index']($table_name, $index_info['name']);
  321. }
  322. }
  323. // If we're here we know we don't have the index - so just add it.
  324. if (!empty($index_info['type']) && $index_info['type'] == 'primary')
  325. {
  326. // @todo Doesn't work with PRIMARY KEY yet.
  327. }
  328. else
  329. {
  330. $smcFunc['db_query']('', '
  331. CREATE ' . (isset($index_info['type']) && $index_info['type'] == 'unique' ? 'UNIQUE' : '') . ' INDEX ' . $index_info['name'] . ' ON ' . $table_name . ' (' . $columns . ')',
  332. array(
  333. 'security_override' => true,
  334. )
  335. );
  336. }
  337. }
  338. /**
  339. * Remove an index.
  340. *
  341. * @param string $table_name
  342. * @param string $index_name
  343. * @param array$parameters default array()
  344. * @param string $error default 'fatal'
  345. */
  346. function smf_db_remove_index($table_name, $index_name, $parameters = array(), $error = 'fatal')
  347. {
  348. global $smcFunc, $db_prefix;
  349. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  350. // Better exist!
  351. $indexes = $smcFunc['db_list_indexes']($table_name, true);
  352. foreach ($indexes as $index)
  353. {
  354. // @todo Doesn't do primary key at the moment!
  355. if ($index['type'] != 'primary' && $index['name'] == $index_name)
  356. {
  357. // Drop the bugger...
  358. $smcFunc['db_query']('', '
  359. DROP INDEX ' . $index_name,
  360. array(
  361. 'security_override' => true,
  362. )
  363. );
  364. return true;
  365. }
  366. }
  367. // Not to be found ;(
  368. return false;
  369. }
  370. /**
  371. * Get the schema formatted name for a type.
  372. *
  373. * @param string $type_name
  374. * @param $type_size
  375. * @param $reverse
  376. */
  377. function smf_db_calculate_type($type_name, $type_size = null, $reverse = false)
  378. {
  379. // Let's be sure it's lowercase MySQL likes both, others no.
  380. $type_name = strtolower($type_name);
  381. // Generic => Specific.
  382. if (!$reverse)
  383. {
  384. $types = array(
  385. 'mediumint' => 'int',
  386. 'tinyint' => 'smallint',
  387. 'mediumtext' => 'text',
  388. 'largetext' => 'text',
  389. );
  390. }
  391. else
  392. {
  393. $types = array(
  394. 'integer' => 'int',
  395. );
  396. }
  397. // Got it? Change it!
  398. if (isset($types[$type_name]))
  399. {
  400. if ($type_name == 'tinytext')
  401. $type_size = 255;
  402. $type_name = $types[$type_name];
  403. }
  404. // Numbers don't have a size.
  405. if (strpos($type_name, 'int') !== false)
  406. $type_size = null;
  407. return array($type_name, $type_size);
  408. }
  409. /**
  410. * Get table structure.
  411. *
  412. * @param string $table_name
  413. * @param array $parameters default array()
  414. */
  415. function smf_db_table_structure($table_name, $parameters = array())
  416. {
  417. global $smcFunc, $db_prefix;
  418. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  419. return array(
  420. 'name' => $table_name,
  421. 'columns' => $smcFunc['db_list_columns']($table_name, true),
  422. 'indexes' => $smcFunc['db_list_indexes']($table_name, true),
  423. );
  424. }
  425. /**
  426. * Return column information for a table.
  427. * Harder than it should be, on sqlite!
  428. *
  429. * @param string $table_name
  430. * @param bool $detail
  431. * @param array $parameters default array()
  432. * @return mixed
  433. */
  434. function smf_db_list_columns($table_name, $detail = false, $parameters = array())
  435. {
  436. global $smcFunc, $db_prefix;
  437. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  438. $result = $smcFunc['db_query']('', '
  439. PRAGMA table_info(' . $table_name . ')',
  440. array(
  441. 'security_override' => true,
  442. )
  443. );
  444. $columns = array();
  445. $primaries = array();
  446. while ($row = $smcFunc['db_fetch_assoc']($result))
  447. {
  448. if (!$detail)
  449. {
  450. $columns[] = $row['name'];
  451. }
  452. else
  453. {
  454. // Auto increment is hard to tell really... if there's only one primary it probably is.
  455. if ($row['pk'])
  456. $primaries[] = $row['name'];
  457. // Can we split out the size?
  458. if (preg_match('~(.+?)\s*\((\d+)\)~i', $row['type'], $matches))
  459. {
  460. $type = $matches[1];
  461. $size = $matches[2];
  462. }
  463. else
  464. {
  465. $type = $row['type'];
  466. $size = null;
  467. }
  468. $columns[$row['name']] = array(
  469. 'name' => $row['name'],
  470. 'null' => $row['notnull'] ? false : true,
  471. 'default' => $row['dflt_value'],
  472. 'type' => $type,
  473. 'size' => $size,
  474. 'auto' => false,
  475. );
  476. }
  477. }
  478. $smcFunc['db_free_result']($result);
  479. // Put in our guess at auto_inc.
  480. if (count($primaries) == 1)
  481. $columns[$primaries[0]]['auto'] = true;
  482. return $columns;
  483. }
  484. /**
  485. * Get index information.
  486. *
  487. * @param string $table_name
  488. * @param bool $detail
  489. * @param array $parameters
  490. * @return mixed
  491. */
  492. function smf_db_list_indexes($table_name, $detail = false, $parameters = array())
  493. {
  494. global $smcFunc, $db_prefix;
  495. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  496. $result = $smcFunc['db_query']('', '
  497. PRAGMA index_list(' . $table_name . ')',
  498. array(
  499. 'security_override' => true,
  500. )
  501. );
  502. $indexes = array();
  503. while ($row = $smcFunc['db_fetch_assoc']($result))
  504. {
  505. if (!$detail)
  506. $indexes[] = $row['name'];
  507. else
  508. {
  509. $result2 = $smcFunc['db_query']('', '
  510. PRAGMA index_info(' . $row['name'] . ')',
  511. array(
  512. 'security_override' => true,
  513. )
  514. );
  515. while ($row2 = $smcFunc['db_fetch_assoc']($result2))
  516. {
  517. // What is the type?
  518. if ($row['unique'])
  519. $type = 'unique';
  520. else
  521. $type = 'index';
  522. // This is the first column we've seen?
  523. if (empty($indexes[$row['name']]))
  524. {
  525. $indexes[$row['name']] = array(
  526. 'name' => $row['name'],
  527. 'type' => $type,
  528. 'columns' => array(),
  529. );
  530. }
  531. // Add the column...
  532. $indexes[$row['name']]['columns'][] = $row2['name'];
  533. }
  534. $smcFunc['db_free_result']($result2);
  535. }
  536. }
  537. $smcFunc['db_free_result']($result);
  538. return $indexes;
  539. }
  540. /**
  541. * Alter table on SQLite.
  542. *
  543. * @param string $table_name
  544. * @param array $columns
  545. */
  546. function smf_db_alter_table($table_name, $columns)
  547. {
  548. global $smcFunc, $db_prefix, $db_name;
  549. $db_file = substr($db_name, -3) === '.db' ? $db_name : $db_name . '.db';
  550. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  551. // Let's get the current columns for the table.
  552. $current_columns = $smcFunc['db_list_columns']($table_name, true);
  553. // Let's get a list of columns for the temp table.
  554. $temp_table_columns = array();
  555. // Let's see if we have columns to remove or columns that are being added that already exist.
  556. foreach ($current_columns as $key => $column)
  557. {
  558. $exists = false;
  559. if (isset($columns['remove']))
  560. foreach ($columns['remove'] as $drop)
  561. if ($drop['name'] == $column['name'])
  562. {
  563. $exists = true;
  564. break;
  565. }
  566. if (isset($columns['add']))
  567. foreach ($columns['add'] as $key2 => $add)
  568. if ($add['name'] == $column['name'])
  569. {
  570. unset($columns['add'][$key2]);
  571. break;
  572. }
  573. // Doesn't exist then we 'remove'.
  574. if (!$exists)
  575. $temp_table_columns[] = $column['name'];
  576. }
  577. // If they are equal then that means that the column that we are adding exists or it doesn't exist and we are not looking to change any one of them.
  578. if (count($temp_table_columns) == count($current_columns) && empty($columns['change']) && empty($columns['add']))
  579. return true;
  580. // Drop the temp table.
  581. $smcFunc['db_query']('', '
  582. DROP TABLE {raw:temp_table_name}',
  583. array(
  584. 'temp_table_name' => $table_name . '_tmp',
  585. 'db_error_skip' => true,
  586. )
  587. );
  588. // Let's make a backup of the current database.
  589. // We only want the first backup of a table modification. So if there is a backup file and older than an hour just delete and back up again
  590. $db_backup_file = BOARDDIR . '/packages/backups/backup_' . $table_name . '_' . basename($db_file) . md5($table_name . $db_file);
  591. if (file_exists($db_backup_file) && time() - filemtime($db_backup_file) > 3600)
  592. {
  593. @unlink($db_backup_file);
  594. @copy($db_file, $db_backup_file);
  595. }
  596. elseif (!file_exists($db_backup_file))
  597. @copy($db_file, $db_backup_file);
  598. // If we don't have temp tables then everything crapped out. Just exit.
  599. if (empty($temp_table_columns))
  600. return false;
  601. // Start
  602. $smcFunc['db_transaction']('begin');
  603. // Let's create the temporary table.
  604. $createTempTable = $smcFunc['db_query']('', '
  605. CREATE TEMPORARY TABLE {raw:temp_table_name}
  606. (
  607. {raw:columns}
  608. );',
  609. array(
  610. 'temp_table_name' => $table_name . '_tmp',
  611. 'columns' => implode(', ', $temp_table_columns),
  612. 'db_error_skip' => true,
  613. )
  614. ) !== false;
  615. if (!$createTempTable)
  616. return false;
  617. // Insert into temp table.
  618. $smcFunc['db_query']('', '
  619. INSERT INTO {raw:temp_table_name}
  620. ({raw:columns})
  621. SELECT {raw:columns}
  622. FROM {raw:table_name}',
  623. array(
  624. 'table_name' => $table_name,
  625. 'columns' => implode(', ', $temp_table_columns),
  626. 'temp_table_name' => $table_name . '_tmp',
  627. )
  628. );
  629. // Drop the current table.
  630. $dropTable = $smcFunc['db_query']('', '
  631. DROP TABLE {raw:table_name}',
  632. array(
  633. 'table_name' => $table_name,
  634. 'db_error_skip' => true,
  635. )
  636. ) !== false;
  637. // If you can't drop the main table then there is no where to go from here. Just return.
  638. if (!$dropTable)
  639. return false;
  640. // We need to keep track of the structure for the current columns and the new columns.
  641. $new_columns = array();
  642. $column_names = array();
  643. // Let's get the ones that we already have first.
  644. foreach ($current_columns as $name => $column)
  645. {
  646. if (in_array($name, $temp_table_columns))
  647. {
  648. $new_columns[$name] = array(
  649. 'name' => $name,
  650. 'type' => $column['type'],
  651. 'size' => isset($column['size']) ? (int) $column['size'] : null,
  652. 'null' => !empty($column['null']),
  653. 'auto' => isset($column['auto']) ? $column['auto'] : false,
  654. 'default' => isset($column['default']) ? $column['default'] : '',
  655. );
  656. // Lets keep track of the name for the column.
  657. $column_names[$name] = $name;
  658. }
  659. }
  660. // Now the new.
  661. if (!empty($columns['add']))
  662. foreach ($columns['add'] as $add)
  663. {
  664. $new_columns[$add['name']] = array(
  665. 'name' => $add['name'],
  666. 'type' => $add['type'],
  667. 'size' => isset($add['size']) ? (int) $add['size'] : null,
  668. 'null' => !empty($add['null']),
  669. 'auto' => isset($add['auto']) ? $add['auto'] : false,
  670. 'default' => isset($add['default']) ? $add['default'] : '',
  671. );
  672. // Let's keep track of the name for the column.
  673. $column_names[$add['name']] = strstr('int', $add['type']) ? ' 0 AS ' . $add['name'] : ' {string:empty_string} AS ' . $add['name'];
  674. }
  675. // Now to change a column. Not drop but change it.
  676. if (isset($columns['change']))
  677. foreach ($columns['change'] as $change)
  678. if (isset($new_columns[$change['name']]))
  679. $new_columns[$change['name']] = array(
  680. 'name' => $change['name'],
  681. 'type' => $change['type'],
  682. 'size' => isset($change['size']) ? (int) $change['size'] : null,
  683. 'null' => !empty($change['null']),
  684. 'auto' => isset($change['auto']) ? $change['auto'] : false,
  685. 'default' => isset($change['default']) ? $change['default'] : '',
  686. );
  687. // Now let's create the table.
  688. $createTable = $smcFunc['db_create_table']($table_name, $new_columns, array(), array('skip_transaction' => true));
  689. // Did it create correctly?
  690. if ($createTable === false)
  691. return false;
  692. // Back to it's original table.
  693. $insertData = $smcFunc['db_query']('', '
  694. INSERT INTO {raw:table_name}
  695. ({raw:columns})
  696. SELECT ' . implode(', ', $column_names) . '
  697. FROM {raw:temp_table_name}',
  698. array(
  699. 'table_name' => $table_name,
  700. 'columns' => implode(', ', array_keys($new_columns)),
  701. 'columns_select' => implode(', ', $column_names),
  702. 'temp_table_name' => $table_name . '_tmp',
  703. 'empty_string' => '',
  704. )
  705. );
  706. // Did everything insert correctly?
  707. if (!$insertData)
  708. return false;
  709. // Drop the temp table.
  710. $smcFunc['db_query']('', '
  711. DROP TABLE {raw:temp_table_name}',
  712. array(
  713. 'temp_table_name' => $table_name . '_tmp',
  714. 'db_error_skip' => true,
  715. )
  716. );
  717. // Commit or else there is no point in doing the previous steps.
  718. $smcFunc['db_transaction']('commit');
  719. // We got here so we're good. The temp table should be deleted, if not it will be gone later on >:D.
  720. return true;
  721. }