DbPackages-sqlite.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  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_alter_table' => 'smf_db_alter_table',
  49. 'db_calculate_type' => 'smf_db_calculate_type',
  50. 'db_change_column' => 'smf_db_change_column',
  51. 'db_create_table' => 'smf_db_create_table',
  52. 'db_drop_table' => 'smf_db_drop_table',
  53. 'db_table_structure' => 'smf_db_table_structure',
  54. 'db_list_columns' => 'smf_db_list_columns',
  55. 'db_list_indexes' => 'smf_db_list_indexes',
  56. 'db_remove_column' => 'smf_db_remove_column',
  57. 'db_remove_index' => 'smf_db_remove_index',
  58. );
  59. $db_package_log = array();
  60. }
  61. // We setup an array of SMF tables we can't do auto-remove on - in case a mod writer cocks it up!
  62. $reservedTables = array('admin_info_files', 'approval_queue', 'attachments', 'ban_groups', 'ban_items',
  63. 'board_permissions', 'boards', 'calendar', 'calendar_holidays', 'categories', 'collapsed_categories',
  64. 'custom_fields', 'group_moderators', 'log_actions', 'log_activity', 'log_banned', 'log_boards',
  65. 'log_digest', 'log_errors', 'log_floodcontrol', 'log_group_requests', 'log_karma', 'log_mark_read',
  66. 'log_notify', 'log_online', 'log_packages', 'log_polls', 'log_reported', 'log_reported_comments',
  67. 'log_scheduled_tasks', 'log_search_messages', 'log_search_results', 'log_search_subjects',
  68. 'log_search_topics', 'log_topics', 'mail_queue', 'membergroups', 'members', 'message_icons',
  69. 'messages', 'moderators', 'package_servers', 'permission_profiles', 'permissions', 'personal_messages',
  70. 'pm_recipients', 'poll_choices', 'polls', 'scheduled_tasks', 'sessions', 'settings', 'smileys',
  71. 'themes', 'topics');
  72. foreach ($reservedTables as $k => $table_name)
  73. $reservedTables[$k] = strtolower($db_prefix . $table_name);
  74. // We in turn may need the extra stuff.
  75. db_extend('extra');
  76. }
  77. // Create a table.
  78. function smf_db_create_table($table_name, $columns, $indexes = array(), $parameters = array(), $if_exists = 'ignore', $error = 'fatal')
  79. {
  80. global $reservedTables, $smcFunc, $db_package_log, $db_prefix;
  81. // With or without the database name, the full name looks like this.
  82. $real_prefix = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $db_prefix, $match) === 1 ? $match[3] : $db_prefix;
  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. // Commented out for now. We need to alter SMF tables in order to use this in the upgrade.
  87. /*
  88. if (in_array(strtolower($table_name), $reservedTables))
  89. return false;
  90. */
  91. // Log that we'll want to remove this on uninstall.
  92. $db_package_log[] = array('remove_table', $table_name);
  93. // Does this table exist or not?
  94. $tables = $smcFunc['db_list_tables']();
  95. if (in_array($full_table_name, $tables))
  96. {
  97. // This is a sad day... drop the table? If not, return false (error) by default.
  98. if ($if_exists == 'overwrite')
  99. $smcFunc['db_drop_table']($table_name);
  100. else
  101. return $if_exists == 'ignore';
  102. }
  103. // Righty - let's do the damn thing!
  104. $table_query = 'CREATE TABLE ' . $table_name . "\n" . '(';
  105. $done_primary = false;
  106. foreach ($columns as $column)
  107. {
  108. // Auto increment is special
  109. if (!empty($column['auto']))
  110. {
  111. $table_query .= "\n" . $column['name'] . ' integer PRIMARY KEY,';
  112. $done_primary = true;
  113. continue;
  114. }
  115. elseif (isset($column['default']) && $column['default'] !== null)
  116. $default = 'default \'' . $smcFunc['db_escape_string']($column['default']) . '\'';
  117. else
  118. $default = '';
  119. // Sort out the size... and stuff...
  120. $column['size'] = isset($column['size']) && is_numeric($column['size']) ? $column['size'] : null;
  121. list ($type, $size) = $smcFunc['db_calculate_type']($column['type'], $column['size']);
  122. if ($size !== null)
  123. $type = $type . '(' . $size . ')';
  124. // Now just put it together!
  125. $table_query .= "\n\t" . $column['name'] . ' ' . $type . ' ' . (!empty($column['null']) ? '' : 'NOT NULL') . ' ' . $default . ',';
  126. }
  127. // Loop through the indexes next...
  128. $index_queries = array();
  129. foreach ($indexes as $index)
  130. {
  131. $columns = implode(',', $index['columns']);
  132. // Is it the primary?
  133. if (isset($index['type']) && $index['type'] == 'primary')
  134. {
  135. // If we've done the primary via auto_inc, don't do it again!
  136. if (!$done_primary)
  137. $table_query .= "\n\t" . 'PRIMARY KEY (' . implode(',', $index['columns']) . '),';
  138. }
  139. else
  140. {
  141. if (empty($index['name']))
  142. $index['name'] = implode('_', $index['columns']);
  143. $index_queries[] = 'CREATE ' . (isset($index['type']) && $index['type'] == 'unique' ? 'UNIQUE' : '') . ' INDEX ' . $table_name . '_' . $index['name'] . ' ON ' . $table_name . ' (' . $columns . ')';
  144. }
  145. }
  146. // No trailing commas!
  147. if (substr($table_query, -1) == ',')
  148. $table_query = substr($table_query, 0, -1);
  149. $table_query .= ')';
  150. if (empty($parameters['skip_transaction']))
  151. $smcFunc['db_transaction']('begin');
  152. // Do the table and indexes...
  153. $smcFunc['db_query']('', $table_query,
  154. array(
  155. 'security_override' => true,
  156. )
  157. );
  158. foreach ($index_queries as $query)
  159. $smcFunc['db_query']('', $query,
  160. array(
  161. 'security_override' => true,
  162. )
  163. );
  164. if (empty($parameters['skip_transaction']))
  165. $smcFunc['db_transaction']('commit');
  166. }
  167. // Drop a table.
  168. function smf_db_drop_table($table_name, $parameters = array(), $error = 'fatal')
  169. {
  170. global $reservedTables, $smcFunc, $db_prefix;
  171. // Strip out the table name, we might not need it in some cases
  172. $real_prefix = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $db_prefix, $match) === 1 ? $match[3] : $db_prefix;
  173. $full_table_name = str_replace('{db_prefix}', $real_prefix, $table_name);
  174. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  175. // God no - dropping one of these = bad.
  176. if (in_array(strtolower($table_name), $reservedTables))
  177. return false;
  178. // Does it exist?
  179. if (in_array($full_table_name, $smcFunc['db_list_tables']()))
  180. {
  181. $query = 'DROP TABLE ' . $table_name;
  182. $smcFunc['db_query']('', $query,
  183. array(
  184. 'security_override' => true,
  185. )
  186. );
  187. return true;
  188. }
  189. // Otherwise do 'nout.
  190. return false;
  191. }
  192. // Add a column.
  193. function smf_db_add_column($table_name, $column_info, $parameters = array(), $if_exists = 'update', $error = 'fatal')
  194. {
  195. global $smcFunc, $db_package_log, $txt, $db_prefix;
  196. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  197. // Log that we will want to uninstall this!
  198. $db_package_log[] = array('remove_column', $table_name, $column_info['name']);
  199. // Does it exist - if so don't add it again!
  200. $columns = $smcFunc['db_list_columns']($table_name, false);
  201. foreach ($columns as $column)
  202. if ($column == $column_info['name'])
  203. {
  204. // If we're going to overwrite then use change column.
  205. if ($if_exists == 'update')
  206. return $smcFunc['db_change_column']($table_name, $column_info['name'], $column_info);
  207. else
  208. return false;
  209. }
  210. // Alter the table to add the column.
  211. if ($smcFunc['db_alter_table']($table_name, array('add' => array($column_info))) === false)
  212. return false;
  213. return true;
  214. }
  215. // We can't reliably do this on SQLite - damn!
  216. function smf_db_remove_column($table_name, $column_name, $parameters = array(), $error = 'fatal')
  217. {
  218. global $smcFunc, $db_prefix;
  219. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  220. if ($smcFunc['db_alter_table']($table_name, array('remove' => array(array('name' => $column_name)))))
  221. return true;
  222. else
  223. return false;
  224. }
  225. // Change a column.
  226. function smf_db_change_column($table_name, $old_column, $column_info, $parameters = array(), $error = 'fatal')
  227. {
  228. global $smcFunc, $db_prefix;
  229. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  230. if ($smcFunc['db_alter_table']($table_name, array('change' => array(array('name' => $old_column) + $column_info))))
  231. return true;
  232. else
  233. return false;
  234. }
  235. // Add an index.
  236. function smf_db_add_index($table_name, $index_info, $parameters = array(), $if_exists = 'update', $error = 'fatal')
  237. {
  238. global $smcFunc, $db_package_log, $db_prefix;
  239. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  240. // No columns = no index.
  241. if (empty($index_info['columns']))
  242. return false;
  243. $columns = implode(',', $index_info['columns']);
  244. // No name - make it up!
  245. if (empty($index_info['name']))
  246. {
  247. // No need for primary.
  248. if (isset($index_info['type']) && $index_info['type'] == 'primary')
  249. $index_info['name'] = '';
  250. else
  251. $index_info['name'] = implode('_', $index_info['columns']);
  252. }
  253. else
  254. $index_info['name'] = $index_info['name'];
  255. // Log that we are going to want to remove this!
  256. $db_package_log[] = array('remove_index', $table_name, $index_info['name']);
  257. // Let's get all our indexes.
  258. $indexes = $smcFunc['db_list_indexes']($table_name, true);
  259. // Do we already have it?
  260. foreach ($indexes as $index)
  261. {
  262. if ($index['name'] == $index_info['name'] || ($index['type'] == 'primary' && isset($index_info['type']) && $index_info['type'] == 'primary'))
  263. {
  264. // If we want to overwrite simply remove the current one then continue.
  265. if ($if_exists != 'update' || $index['type'] == 'primary')
  266. return false;
  267. else
  268. $smcFunc['db_remove_index']($table_name, $index_info['name']);
  269. }
  270. }
  271. // If we're here we know we don't have the index - so just add it.
  272. if (!empty($index_info['type']) && $index_info['type'] == 'primary')
  273. {
  274. //!!! Doesn't work with PRIMARY KEY yet.
  275. }
  276. else
  277. {
  278. $smcFunc['db_query']('', '
  279. CREATE ' . (isset($index_info['type']) && $index_info['type'] == 'unique' ? 'UNIQUE' : '') . ' INDEX ' . $index_info['name'] . ' ON ' . $table_name . ' (' . $columns . ')',
  280. array(
  281. 'security_override' => true,
  282. )
  283. );
  284. }
  285. }
  286. // Remove an index.
  287. function smf_db_remove_index($table_name, $index_name, $parameters = array(), $error = 'fatal')
  288. {
  289. global $smcFunc, $db_prefix;
  290. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  291. // Better exist!
  292. $indexes = $smcFunc['db_list_indexes']($table_name, true);
  293. foreach ($indexes as $index)
  294. {
  295. //!!! Doesn't do primary key at the moment!
  296. if ($index['type'] != 'primary' && $index['name'] == $index_name)
  297. {
  298. // Drop the bugger...
  299. $smcFunc['db_query']('', '
  300. DROP INDEX ' . $index_name,
  301. array(
  302. 'security_override' => true,
  303. )
  304. );
  305. return true;
  306. }
  307. }
  308. // Not to be found ;(
  309. return false;
  310. }
  311. // Get the schema formatted name for a type.
  312. function smf_db_calculate_type($type_name, $type_size = null, $reverse = false)
  313. {
  314. // Generic => Specific.
  315. if (!$reverse)
  316. {
  317. $types = array(
  318. 'mediumint' => 'int',
  319. 'tinyint' => 'smallint',
  320. 'mediumtext' => 'text',
  321. 'largetext' => 'text',
  322. );
  323. }
  324. else
  325. {
  326. $types = array(
  327. 'integer' => 'int',
  328. );
  329. }
  330. // Got it? Change it!
  331. if (isset($types[$type_name]))
  332. {
  333. if ($type_name == 'tinytext')
  334. $type_size = 255;
  335. $type_name = $types[$type_name];
  336. }
  337. // Numbers don't have a size.
  338. if (strpos($type_name, 'int') !== false)
  339. $type_size = null;
  340. return array($type_name, $type_size);
  341. }
  342. // Get table structure.
  343. function smf_db_table_structure($table_name, $parameters = array())
  344. {
  345. global $smcFunc, $db_prefix;
  346. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  347. return array(
  348. 'name' => $table_name,
  349. 'columns' => $smcFunc['db_list_columns']($table_name, true),
  350. 'indexes' => $smcFunc['db_list_indexes']($table_name, true),
  351. );
  352. }
  353. // Harder than it should be on sqlite!
  354. function smf_db_list_columns($table_name, $detail = false, $parameters = array())
  355. {
  356. global $smcFunc, $db_prefix;
  357. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  358. $result = $smcFunc['db_query']('', '
  359. PRAGMA table_info(' . $table_name . ')',
  360. array(
  361. 'security_override' => true,
  362. )
  363. );
  364. $columns = array();
  365. $primaries = array();
  366. while ($row = $smcFunc['db_fetch_assoc']($result))
  367. {
  368. if (!$detail)
  369. {
  370. $columns[] = $row['name'];
  371. }
  372. else
  373. {
  374. // Auto increment is hard to tell really... if there's only one primary it probably is.
  375. if ($row['pk'])
  376. $primaries[] = $row['name'];
  377. // Can we split out the size?
  378. if (preg_match('~(.+?)\s*\((\d+)\)~i', $row['type'], $matches))
  379. {
  380. $type = $matches[1];
  381. $size = $matches[2];
  382. }
  383. else
  384. {
  385. $type = $row['type'];
  386. $size = null;
  387. }
  388. $columns[$row['name']] = array(
  389. 'name' => $row['name'],
  390. 'null' => $row['notnull'] ? false : true,
  391. 'default' => $row['dflt_value'],
  392. 'type' => $type,
  393. 'size' => $size,
  394. 'auto' => false,
  395. );
  396. }
  397. }
  398. $smcFunc['db_free_result']($result);
  399. // Put in our guess at auto_inc.
  400. if (count($primaries) == 1)
  401. $columns[$primaries[0]]['auto'] = true;
  402. return $columns;
  403. }
  404. // What about some index information?
  405. function smf_db_list_indexes($table_name, $detail = false, $parameters = array())
  406. {
  407. global $smcFunc, $db_prefix;
  408. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  409. $result = $smcFunc['db_query']('', '
  410. PRAGMA index_list(' . $table_name . ')',
  411. array(
  412. 'security_override' => true,
  413. )
  414. );
  415. $indexes = array();
  416. while ($row = $smcFunc['db_fetch_assoc']($result))
  417. {
  418. if (!$detail)
  419. $indexes[] = $row['name'];
  420. else
  421. {
  422. $result2 = $smcFunc['db_query']('', '
  423. PRAGMA index_info(' . $row['name'] . ')',
  424. array(
  425. 'security_override' => true,
  426. )
  427. );
  428. while ($row2 = $smcFunc['db_fetch_assoc']($result2))
  429. {
  430. // What is the type?
  431. if ($row['unique'])
  432. $type = 'unique';
  433. else
  434. $type = 'index';
  435. // This is the first column we've seen?
  436. if (empty($indexes[$row['name']]))
  437. {
  438. $indexes[$row['name']] = array(
  439. 'name' => $row['name'],
  440. 'type' => $type,
  441. 'columns' => array(),
  442. );
  443. }
  444. // Add the column...
  445. $indexes[$row['name']]['columns'][] = $row2['name'];
  446. }
  447. $smcFunc['db_free_result']($result2);
  448. }
  449. }
  450. $smcFunc['db_free_result']($result);
  451. return $indexes;
  452. }
  453. function smf_db_alter_table($table_name, $columns)
  454. {
  455. global $smcFunc, $db_prefix, $db_name, $boarddir;
  456. $db_file = substr($db_name, -3) === '.db' ? $db_name : $db_name . '.db';
  457. $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
  458. // Let's get the current columns for the table.
  459. $current_columns = $smcFunc['db_list_columns']($table_name, true);
  460. // Let's get a list of columns for the temp table.
  461. $temp_table_columns = array();
  462. // Let's see if we have columns to remove or columns that are being added that already exist.
  463. foreach ($current_columns as $key => $column)
  464. {
  465. $exists = false;
  466. if (isset($columns['remove']))
  467. foreach ($columns['remove'] as $drop)
  468. if ($drop['name'] == $column['name'])
  469. {
  470. $exists = true;
  471. break;
  472. }
  473. if (isset($columns['add']))
  474. foreach ($columns['add'] as $key2 => $add)
  475. if ($add['name'] == $column['name'])
  476. {
  477. unset($columns['add'][$key2]);
  478. break;
  479. }
  480. // Doesn't exist then we 'remove'.
  481. if (!$exists)
  482. $temp_table_columns[] = $column['name'];
  483. }
  484. // 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.
  485. if (count($temp_table_columns) == count($current_columns) && empty($columns['change']) && empty($columns['add']))
  486. return true;
  487. // Drop the temp table.
  488. $smcFunc['db_query']('', '
  489. DROP TABLE {raw:temp_table_name}',
  490. array(
  491. 'temp_table_name' => $table_name . '_tmp',
  492. 'db_error_skip' => true,
  493. )
  494. );
  495. // Let's make a backup of the current database.
  496. // 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
  497. $db_backup_file = $boarddir . '/Packages/backups/backup_' . $table_name . '_' . basename($db_file) . md5($table_name . $db_file);
  498. if (file_exists($db_backup_file) && time() - filemtime($db_backup_file) > 3600)
  499. {
  500. @unlink($db_backup_file);
  501. @copy($db_file, $db_backup_file);
  502. }
  503. elseif (!file_exists($db_backup_file))
  504. @copy($db_file, $db_backup_file);
  505. // If we don't have temp tables then everything crapped out. Just exit.
  506. if (empty($temp_table_columns))
  507. return false;
  508. // Start
  509. $smcFunc['db_transaction']('begin');
  510. // Let's create the temporary table.
  511. $createTempTable = $smcFunc['db_query']('', '
  512. CREATE TEMPORARY TABLE {raw:temp_table_name}
  513. (
  514. {raw:columns}
  515. );',
  516. array(
  517. 'temp_table_name' => $table_name . '_tmp',
  518. 'columns' => implode(', ', $temp_table_columns),
  519. 'db_error_skip' => true,
  520. )
  521. ) !== false;
  522. if (!$createTempTable)
  523. return false;
  524. // Insert into temp table.
  525. $smcFunc['db_query']('', '
  526. INSERT INTO {raw:temp_table_name}
  527. ({raw:columns})
  528. SELECT {raw:columns}
  529. FROM {raw:table_name}',
  530. array(
  531. 'table_name' => $table_name,
  532. 'columns' => implode(', ', $temp_table_columns),
  533. 'temp_table_name' => $table_name . '_tmp',
  534. )
  535. );
  536. // Drop the current table.
  537. $dropTable = $smcFunc['db_query']('', '
  538. DROP TABLE {raw:table_name}',
  539. array(
  540. 'table_name' => $table_name,
  541. 'db_error_skip' => true,
  542. )
  543. ) !== false;
  544. // If you can't drop the main table then there is no where to go from here. Just return.
  545. if (!$dropTable)
  546. return false;
  547. // We need to keep track of the structure for the current columns and the new columns.
  548. $new_columns = array();
  549. $column_names = array();
  550. // Let's get the ones that we already have first.
  551. foreach ($current_columns as $name => $column)
  552. {
  553. if (in_array($name, $temp_table_columns))
  554. {
  555. $new_columns[$name] = array(
  556. 'name' => $name,
  557. 'type' => $column['type'],
  558. 'size' => isset($column['size']) ? (int) $column['size'] : null,
  559. 'null' => !empty($column['null']),
  560. 'auto' => isset($column['auto']) ? $column['auto'] : false,
  561. 'default' => isset($column['default']) ? $column['default'] : '',
  562. );
  563. // Lets keep track of the name for the column.
  564. $column_names[$name] = $name;
  565. }
  566. }
  567. // Now the new.
  568. if (!empty($columns['add']))
  569. foreach ($columns['add'] as $add)
  570. {
  571. $new_columns[$add['name']] = array(
  572. 'name' => $add['name'],
  573. 'type' => $add['type'],
  574. 'size' => isset($add['size']) ? (int) $add['size'] : null,
  575. 'null' => !empty($add['null']),
  576. 'auto' => isset($add['auto']) ? $add['auto'] : false,
  577. 'default' => isset($add['default']) ? $add['default'] : '',
  578. );
  579. // Let's keep track of the name for the column.
  580. $column_names[$add['name']] = strstr('int', $add['type']) ? ' 0 AS ' . $add['name'] : ' {string:empty_string} AS ' . $add['name'];
  581. }
  582. // Now to change a column. Not drop but change it.
  583. if (isset($columns['change']))
  584. foreach ($columns['change'] as $change)
  585. if (isset($new_columns[$change['name']]))
  586. $new_columns[$change['name']] = array(
  587. 'name' => $change['name'],
  588. 'type' => $change['type'],
  589. 'size' => isset($change['size']) ? (int) $change['size'] : null,
  590. 'null' => !empty($change['null']),
  591. 'auto' => isset($change['auto']) ? $change['auto'] : false,
  592. 'default' => isset($change['default']) ? $change['default'] : '',
  593. );
  594. // Now let's create the table.
  595. $createTable = $smcFunc['db_create_table']($table_name, $new_columns, array(), array('skip_transaction' => true));
  596. // Did it create correctly?
  597. if ($createTable === false)
  598. return false;
  599. // Back to it's original table.
  600. $insertData = $smcFunc['db_query']('', '
  601. INSERT INTO {raw:table_name}
  602. ({raw:columns})
  603. SELECT ' . implode(', ', $column_names) . '
  604. FROM {raw:temp_table_name}',
  605. array(
  606. 'table_name' => $table_name,
  607. 'columns' => implode(', ', array_keys($new_columns)),
  608. 'columns_select' => implode(', ', $column_names),
  609. 'temp_table_name' => $table_name . '_tmp',
  610. 'empty_string' => '',
  611. )
  612. );
  613. // Did everything insert correctly?
  614. if (!$insertData)
  615. return false;
  616. // Drop the temp table.
  617. $smcFunc['db_query']('', '
  618. DROP TABLE {raw:temp_table_name}',
  619. array(
  620. 'temp_table_name' => $table_name . '_tmp',
  621. 'db_error_skip' => true,
  622. )
  623. );
  624. // Commit or else there is no point in doing the previous steps.
  625. $smcFunc['db_transaction']('commit');
  626. // We got here so we're good. The temp table should be deleted, if not it will be gone later on >:D.
  627. return true;
  628. }
  629. ?>