DbExtra-postgresql.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. // This will be handy...
  145. $crlf = "\r\n";
  146. // This is done this way because retrieve data only with LIMIT will become slower after each query
  147. // and for long tables (e.g. {db_prefix}messages) it could be a pain...
  148. // Instead using WHERE speeds up thing *a lot* (especially after the first 50'000 records)
  149. $result = $smcFunc['db_query']('', '
  150. SELECT *
  151. FROM ' . $tableName .
  152. (!empty($last_id) && !empty($detected_id) ? '
  153. WHERE ' . $detected_id . ' > ' . $last_id : '') . '
  154. LIMIT ' . (empty($last_id) ? $start . ', ' : '') . $limit,
  155. array(
  156. 'security_override' => true,
  157. )
  158. );
  159. // The number of rows, just for record keeping and breaking INSERTs up.
  160. $num_rows = $smcFunc['db_num_rows']($result);
  161. if ($num_rows == 0)
  162. return '';
  163. if ($new_table)
  164. {
  165. $fields = array_keys($smcFunc['db_fetch_assoc']($result));
  166. $smcFunc['db_data_seek']($result, 0);
  167. }
  168. // Start it off with the basic INSERT INTO.
  169. $data = '';
  170. $insert_msg = $crlf . 'INSERT INTO ' . $tableName . $crlf . "\t" . '(' . implode(', ', $fields) . ')' . $crlf . 'VALUES ' . $crlf . "\t";
  171. // Loop through each row.
  172. while ($row = $smcFunc['db_fetch_assoc']($result))
  173. {
  174. // Get the fields in this row...
  175. $field_list = array();
  176. foreach ($row as $key => $item)
  177. {
  178. // Try to figure out the type of each field. (NULL, number, or 'string'.)
  179. if (!isset($item))
  180. $field_list[] = 'NULL';
  181. elseif (is_numeric($item) && (int) $item == $item)
  182. $field_list[] = $item;
  183. else
  184. $field_list[] = '\'' . $smcFunc['db_escape_string']($item) . '\'';
  185. }
  186. if (!empty($detected_id) && isset($row[$detected_id]))
  187. $last_id = $row[$detected_id];
  188. // 'Insert' the data.
  189. $data .= $insert_msg . '(' . implode(', ', $field_list) . ');' . $crlf;
  190. }
  191. $smcFunc['db_free_result']($result);
  192. $data .= $crlf;
  193. $start += $limit;
  194. return $data;
  195. }
  196. /**
  197. * Dumps the schema (CREATE) for a table.
  198. * @todo why is this needed for?
  199. * @param string $tableName - the table
  200. * @return string - the CREATE statement as string
  201. */
  202. function smf_db_table_sql($tableName)
  203. {
  204. global $smcFunc, $db_prefix, $detected_id;
  205. $tableName = str_replace('{db_prefix}', $db_prefix, $tableName);
  206. $detected_id = '';
  207. // This will be needed...
  208. $crlf = "\r\n";
  209. // Start the create table...
  210. $schema_create = 'CREATE TABLE ' . $tableName . ' (' . $crlf;
  211. $index_create = '';
  212. $seq_create = '';
  213. // Find all the fields.
  214. $result = $smcFunc['db_query']('', '
  215. SELECT column_name, column_default, is_nullable, data_type, character_maximum_length
  216. FROM information_schema.columns
  217. WHERE table_name = {string:table}
  218. ORDER BY ordinal_position',
  219. array(
  220. 'table' => $tableName,
  221. )
  222. );
  223. while ($row = $smcFunc['db_fetch_assoc']($result))
  224. {
  225. if ($row['data_type'] == 'character varying')
  226. $row['data_type'] = 'varchar';
  227. elseif ($row['data_type'] == 'character')
  228. $row['data_type'] = 'char';
  229. if ($row['character_maximum_length'])
  230. $row['data_type'] .= '(' . $row['character_maximum_length'] . ')';
  231. // Make the CREATE for this column.
  232. $schema_create .= ' "' . $row['column_name'] . '" ' . $row['data_type'] . ($row['is_nullable'] != 'YES' ? ' NOT NULL' : '');
  233. // Add a default...?
  234. if (trim($row['column_default']) != '')
  235. {
  236. $schema_create .= ' default ' . $row['column_default'] . '';
  237. // Auto increment?
  238. if (preg_match('~nextval\(\'(.+?)\'(.+?)*\)~i', $row['column_default'], $matches) != 0)
  239. {
  240. // Get to find the next variable first!
  241. $count_req = $smcFunc['db_query']('', '
  242. SELECT MAX("{raw:column}")
  243. FROM {raw:table}',
  244. array(
  245. 'column' => $row['column_name'],
  246. 'table' => $tableName,
  247. )
  248. );
  249. list ($max_ind) = $smcFunc['db_fetch_row']($count_req);
  250. $smcFunc['db_free_result']($count_req);
  251. // Get the right bloody start!
  252. $seq_create .= 'CREATE SEQUENCE ' . $matches[1] . ' START WITH ' . ($max_ind + 1) . ';' . $crlf . $crlf;
  253. $detected_id = $row['column_name'];
  254. }
  255. }
  256. $schema_create .= ',' . $crlf;
  257. }
  258. $smcFunc['db_free_result']($result);
  259. // Take off the last comma.
  260. $schema_create = substr($schema_create, 0, -strlen($crlf) - 1);
  261. $result = $smcFunc['db_query']('', '
  262. SELECT CASE WHEN i.indisprimary THEN 1 ELSE 0 END AS is_primary, pg_get_indexdef(i.indexrelid) AS inddef
  263. FROM pg_class AS c
  264. INNER JOIN pg_index AS i ON (i.indrelid = c.oid)
  265. INNER JOIN pg_class AS c2 ON (c2.oid = i.indexrelid)
  266. WHERE c.relname = {string:table}',
  267. array(
  268. 'table' => $tableName,
  269. )
  270. );
  271. $indexes = array();
  272. while ($row = $smcFunc['db_fetch_assoc']($result))
  273. {
  274. if ($row['is_primary'])
  275. {
  276. if (preg_match('~\(([^\)]+?)\)~i', $row['inddef'], $matches) == 0)
  277. continue;
  278. $index_create .= $crlf . 'ALTER TABLE ' . $tableName . ' ADD PRIMARY KEY ("' . $matches[1] . '");';
  279. }
  280. else
  281. $index_create .= $crlf . $row['inddef'] . ';';
  282. }
  283. $smcFunc['db_free_result']($result);
  284. // Finish it off!
  285. $schema_create .= $crlf . ');';
  286. return $seq_create . $schema_create . $index_create;
  287. }
  288. /**
  289. * Get the version number.
  290. * @return string - the version
  291. */
  292. function smf_db_get_version()
  293. {
  294. global $smcFunc;
  295. $request = $smcFunc['db_query']('', '
  296. SHOW server_version',
  297. array(
  298. )
  299. );
  300. list ($ver) = $smcFunc['db_fetch_row']($request);
  301. $smcFunc['db_free_result']($request);
  302. return $ver;
  303. }
  304. ?>