DbExtra-postgresql.php 8.4 KB

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