DbExtra-postgresql.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. <?php
  2. /**
  3. * This file contains rarely used extended database functionality.
  4. *
  5. * Simple Machines Forum (SMF)
  6. *
  7. * @package SMF
  8. * @author Simple Machines http://www.simplemachines.org
  9. * @copyright 2011 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('Hacking attempt...');
  16. /**
  17. * Add the functions implemented in this file to the $smcFunc array.
  18. */
  19. function db_extra_init()
  20. {
  21. global $smcFunc;
  22. if (!isset($smcFunc['db_backup_table']) || $smcFunc['db_backup_table'] != 'smf_db_backup_table')
  23. $smcFunc += array(
  24. 'db_backup_table' => 'smf_db_backup_table',
  25. 'db_optimize_table' => 'smf_db_optimize_table',
  26. 'db_insert_sql' => 'smf_db_insert_sql',
  27. 'db_table_sql' => 'smf_db_table_sql',
  28. 'db_list_tables' => 'smf_db_list_tables',
  29. 'db_get_version' => 'smf_db_get_version',
  30. );
  31. }
  32. /**
  33. * Backup $table to $backup_table.
  34. * @param string $table
  35. * @param string $backup_table
  36. * @return resource -the request handle to the table creation query
  37. */
  38. function smf_db_backup_table($table, $backup_table)
  39. {
  40. global $smcFunc, $db_prefix;
  41. $table = str_replace('{db_prefix}', $db_prefix, $table);
  42. // Do we need to drop it first?
  43. $tables = smf_db_list_tables(false, $backup_table);
  44. if (!empty($tables))
  45. $smcFunc['db_query']('', '
  46. DROP TABLE {raw:backup_table}',
  47. array(
  48. 'backup_table' => $backup_table,
  49. )
  50. );
  51. /**
  52. * @todo Should we create backups of sequences as well?
  53. */
  54. $smcFunc['db_query']('', '
  55. CREATE TABLE {raw:backup_table}
  56. (
  57. LIKE {raw:table}
  58. INCLUDING DEFAULTS
  59. )',
  60. array(
  61. 'backup_table' => $backup_table,
  62. 'table' => $table,
  63. )
  64. );
  65. $smcFunc['db_query']('', '
  66. INSERT INTO {raw:backup_table}
  67. SELECT * FROM {raw:table}',
  68. array(
  69. 'backup_table' => $backup_table,
  70. 'table' => $table,
  71. )
  72. );
  73. }
  74. /**
  75. * This function optimizes a table.
  76. * @param string $table - the table to be optimized
  77. * @return how much it was gained
  78. */
  79. function smf_db_optimize_table($table)
  80. {
  81. global $smcFunc, $db_prefix;
  82. $table = str_replace('{db_prefix}', $db_prefix, $table);
  83. $request = $smcFunc['db_query']('', '
  84. VACUUM ANALYZE {raw:table}',
  85. array(
  86. 'table' => $table,
  87. )
  88. );
  89. if (!$request)
  90. return -1;
  91. $row = $smcFunc['db_fetch_assoc']($request);
  92. $smcFunc['db_free_result']($request);
  93. if (isset($row['Data_free']))
  94. return $row['Data_free'] / 1024;
  95. else
  96. return 0;
  97. }
  98. /**
  99. * This function lists all tables in the database.
  100. * The listing could be filtered according to $filter.
  101. * @param mixed $db, string holding the table name, or false, default false
  102. * @param mixed $filter, string to filter by, or false, default false
  103. * @return array, an array of table names. (strings)
  104. */
  105. function smf_db_list_tables($db = false, $filter = false)
  106. {
  107. global $smcFunc;
  108. $request = $smcFunc['db_query']('', '
  109. SELECT tablename
  110. FROM pg_tables
  111. WHERE schemaname = {string:schema_public}' . ($filter == false ? '' : '
  112. AND tablename LIKE {string:filter}') . '
  113. ORDER BY tablename',
  114. array(
  115. 'schema_public' => 'public',
  116. 'filter' => $filter,
  117. )
  118. );
  119. $tables = array();
  120. while ($row = $smcFunc['db_fetch_row']($request))
  121. $tables[] = $row[0];
  122. $smcFunc['db_free_result']($request);
  123. return $tables;
  124. }
  125. /**
  126. * Gets all the necessary INSERTs for the table named table_name.
  127. * It goes in 250 row segments.
  128. * @param string $tableName - the table to create the inserts for.
  129. * @return string, the query to insert the data back in, or an empty
  130. * string if the table was empty.
  131. */
  132. function smf_db_insert_sql($tableName, $new_table = false)
  133. {
  134. global $smcFunc, $db_prefix, $detected_id;
  135. static $start = 0, $num_rows, $fields, $limit, $last_id;
  136. if ($new_table)
  137. {
  138. $limit = strstr($tableName, 'log_') !== false ? 500 : 250;
  139. $start = 0;
  140. $last_id = 0;
  141. }
  142. $data = '';
  143. $tableName = str_replace('{db_prefix}', $db_prefix, $tableName);
  144. if ($tableName != $db_prefix . 'messages' || $tableName != $db_prefix . 'topics')
  145. $detected_id = 0;
  146. // This will be handy...
  147. $crlf = "\r\n";
  148. // This is done this way because retrieve data only with LIMIT will become slower after each query
  149. // and for long tables (e.g. {db_prefix}messages) it could be a pain...
  150. // Instead using WHERE speeds up thing *a lot* (especially after the first 50'000 records)
  151. $result = $smcFunc['db_query']('', '
  152. SELECT *
  153. FROM ' . $tableName .
  154. (!empty($last_id) && !empty($detected_id) ? '
  155. WHERE ' . $detected_id . ' > ' . $last_id : '') . '
  156. LIMIT ' . (empty($last_id) ? $start . ', ' : '') . $limit,
  157. array(
  158. 'security_override' => true,
  159. )
  160. );
  161. // The number of rows, just for record keeping and breaking INSERTs up.
  162. $num_rows = $smcFunc['db_num_rows']($result);
  163. if ($num_rows == 0)
  164. return '';
  165. if ($new_table)
  166. {
  167. $fields = array_keys($smcFunc['db_fetch_assoc']($result));
  168. $smcFunc['db_data_seek']($result, 0);
  169. }
  170. // Start it off with the basic INSERT INTO.
  171. $data = '';
  172. $insert_msg = $crlf . 'INSERT INTO ' . $tableName . $crlf . "\t" . '(' . implode(', ', $fields) . ')' . $crlf . 'VALUES ' . $crlf . "\t";
  173. // Loop through each row.
  174. while ($row = $smcFunc['db_fetch_assoc']($result))
  175. {
  176. // Get the fields in this row...
  177. $field_list = array();
  178. foreach ($row as $key => $item)
  179. {
  180. // Try to figure out the type of each field. (NULL, number, or 'string'.)
  181. if (!isset($item))
  182. $field_list[] = 'NULL';
  183. elseif (is_numeric($item) && (int) $item == $item)
  184. $field_list[] = $item;
  185. else
  186. $field_list[] = '\'' . $smcFunc['db_escape_string']($item) . '\'';
  187. }
  188. if (!empty($detected_id) && isset($row[$detected_id]))
  189. $last_id = $row[$detected_id];
  190. // 'Insert' the data.
  191. $data .= $insert_msg . '(' . implode(', ', $field_list) . ');' . $crlf;
  192. }
  193. $smcFunc['db_free_result']($result);
  194. $data .= $crlf;
  195. $start += $limit;
  196. return $data;
  197. }
  198. /**
  199. * Dumps the schema (CREATE) for a table.
  200. * @todo why is this needed for?
  201. * @param string $tableName - the table
  202. * @return string - the CREATE statement as string
  203. */
  204. function smf_db_table_sql($tableName)
  205. {
  206. global $smcFunc, $db_prefix, $detected_id;
  207. $tableName = str_replace('{db_prefix}', $db_prefix, $tableName);
  208. $detected_id = '';
  209. // This will be needed...
  210. $crlf = "\r\n";
  211. // Start the create table...
  212. $schema_create = 'CREATE TABLE ' . $tableName . ' (' . $crlf;
  213. $index_create = '';
  214. $seq_create = '';
  215. // Find all the fields.
  216. $result = $smcFunc['db_query']('', '
  217. SELECT column_name, column_default, is_nullable, data_type, character_maximum_length
  218. FROM information_schema.columns
  219. WHERE table_name = {string:table}
  220. ORDER BY ordinal_position',
  221. array(
  222. 'table' => $tableName,
  223. )
  224. );
  225. while ($row = $smcFunc['db_fetch_assoc']($result))
  226. {
  227. if ($row['data_type'] == 'character varying')
  228. $row['data_type'] = 'varchar';
  229. elseif ($row['data_type'] == 'character')
  230. $row['data_type'] = 'char';
  231. if ($row['character_maximum_length'])
  232. $row['data_type'] .= '(' . $row['character_maximum_length'] . ')';
  233. // Make the CREATE for this column.
  234. $schema_create .= ' "' . $row['column_name'] . '" ' . $row['data_type'] . ($row['is_nullable'] != 'YES' ? ' NOT NULL' : '');
  235. // Add a default...?
  236. if (trim($row['column_default']) != '')
  237. {
  238. $schema_create .= ' default ' . $row['column_default'] . '';
  239. // Auto increment?
  240. if (preg_match('~nextval\(\'(.+?)\'(.+?)*\)~i', $row['column_default'], $matches) != 0)
  241. {
  242. // Get to find the next variable first!
  243. $count_req = $smcFunc['db_query']('', '
  244. SELECT MAX("{raw:column}")
  245. FROM {raw:table}',
  246. array(
  247. 'column' => $row['column_name'],
  248. 'table' => $tableName,
  249. )
  250. );
  251. list ($max_ind) = $smcFunc['db_fetch_row']($count_req);
  252. $smcFunc['db_free_result']($count_req);
  253. // Get the right bloody start!
  254. $seq_create .= 'CREATE SEQUENCE ' . $matches[1] . ' START WITH ' . ($max_ind + 1) . ';' . $crlf . $crlf;
  255. $detected_id = $row['column_name'];
  256. }
  257. }
  258. $schema_create .= ',' . $crlf;
  259. }
  260. $smcFunc['db_free_result']($result);
  261. // Take off the last comma.
  262. $schema_create = substr($schema_create, 0, -strlen($crlf) - 1);
  263. $result = $smcFunc['db_query']('', '
  264. SELECT CASE WHEN i.indisprimary THEN 1 ELSE 0 END AS is_primary, pg_get_indexdef(i.indexrelid) AS inddef
  265. FROM pg_class AS c
  266. INNER JOIN pg_index AS i ON (i.indrelid = c.oid)
  267. INNER JOIN pg_class AS c2 ON (c2.oid = i.indexrelid)
  268. WHERE c.relname = {string:table}',
  269. array(
  270. 'table' => $tableName,
  271. )
  272. );
  273. $indexes = array();
  274. while ($row = $smcFunc['db_fetch_assoc']($result))
  275. {
  276. if ($row['is_primary'])
  277. {
  278. if (preg_match('~\(([^\)]+?)\)~i', $row['inddef'], $matches) == 0)
  279. continue;
  280. $index_create .= $crlf . 'ALTER TABLE ' . $tableName . ' ADD PRIMARY KEY ("' . $matches[1] . '");';
  281. }
  282. else
  283. $index_create .= $crlf . $row['inddef'] . ';';
  284. }
  285. $smcFunc['db_free_result']($result);
  286. // Finish it off!
  287. $schema_create .= $crlf . ');';
  288. return $seq_create . $schema_create . $index_create;
  289. }
  290. /**
  291. * Get the version number.
  292. * @return string - the version
  293. */
  294. function smf_db_get_version()
  295. {
  296. global $smcFunc;
  297. $request = $smcFunc['db_query']('', '
  298. SHOW server_version',
  299. array(
  300. )
  301. );
  302. list ($ver) = $smcFunc['db_fetch_row']($request);
  303. $smcFunc['db_free_result']($request);
  304. return $ver;
  305. }
  306. ?>