DbExtra-postgresql.php 8.4 KB

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