DbExtra-postgresql.php 8.2 KB

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