dbutil.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. <?php
  2. /**
  3. * Part of the Fuel framework.
  4. *
  5. * @package Fuel
  6. * @version 1.5
  7. * @author Fuel Development Team
  8. * @license MIT License
  9. * @copyright 2010 - 2013 Fuel Development Team
  10. * @link http://fuelphp.com
  11. */
  12. namespace Fuel\Core;
  13. /**
  14. * DBUtil Class
  15. *
  16. * @package Fuel
  17. * @category Core
  18. * @author Dan Horrigan
  19. */
  20. class DBUtil
  21. {
  22. /**
  23. * @var string $connection the database connection (identifier)
  24. */
  25. protected static $connection = null;
  26. /**
  27. * Sets the database connection to use for following DBUtil calls.
  28. *
  29. * @param string|object string connection name or \Database_Connection object, null for default
  30. */
  31. public static function set_connection($connection, $db = null)
  32. {
  33. if ( ! is_string($connection) and ($connection instanceof Database_Connection))
  34. {
  35. throw new \FuelException('A connection must be supplied as a string or a Database_Connection object.');
  36. }
  37. static::$connection = $connection;
  38. }
  39. /**
  40. * Creates a database. Will throw a Database_Exception if it cannot.
  41. *
  42. * @throws Fuel\Database_Exception
  43. * @param string $database the database name
  44. * @param string $database the character set
  45. * @param boolean $if_not_exists whether to add an IF NOT EXISTS statement.
  46. * @return int the number of affected rows
  47. */
  48. public static function create_database($database, $charset = null, $if_not_exists = true, $db = null)
  49. {
  50. $sql = 'CREATE DATABASE';
  51. $sql .= $if_not_exists ? ' IF NOT EXISTS ' : ' ';
  52. $charset = static::process_charset($charset, true);
  53. return \DB::query($sql.\DB::quote_identifier($database, $db ? $db : static::$connection).$charset, \DB::UPDATE)->execute($db ? $db : static::$connection);
  54. }
  55. /**
  56. * Drops a database. Will throw a Database_Exception if it cannot.
  57. *
  58. * @throws Fuel\Database_Exception
  59. * @param string $database the database name
  60. * @return int the number of affected rows
  61. */
  62. public static function drop_database($database, $db = null)
  63. {
  64. return \DB::query('DROP DATABASE '.\DB::quote_identifier($database, $db ? $db : static::$connection), \DB::DELETE)->execute($db ? $db : static::$connection);
  65. }
  66. /**
  67. * Drops a table. Will throw a Database_Exception if it cannot.
  68. *
  69. * @throws Fuel\Database_Exception
  70. * @param string $table the table name
  71. * @return int the number of affected rows
  72. */
  73. public static function drop_table($table, $db = null)
  74. {
  75. return \DB::query('DROP TABLE IF EXISTS '.\DB::quote_identifier(\DB::table_prefix($table, $db ? $db : static::$connection), $db ? $db : static::$connection), \DB::DELETE)->execute($db ? $db : static::$connection);
  76. }
  77. /**
  78. * Renames a table. Will throw a Database_Exception if it cannot.
  79. *
  80. * @throws \Database_Exception
  81. * @param string $table the old table name
  82. * @param string $new_table_name the new table name
  83. * @return int the number of affected
  84. */
  85. public static function rename_table($table, $new_table_name, $db = null)
  86. {
  87. return \DB::query('RENAME TABLE '.\DB::quote_identifier(\DB::table_prefix($table, $db ? $db : static::$connection), $db ? $db : static::$connection).' TO '.\DB::quote_identifier(\DB::table_prefix($new_table_name)),\DB::UPDATE)->execute($db ? $db : static::$connection);
  88. }
  89. /**
  90. * Creates a table.
  91. *
  92. * @throws \Database_Exception
  93. * @param string $table the table name
  94. * @param array $fields the fields array
  95. * @param array $primary_keys an array of primary keys
  96. * @param boolean $if_not_exists whether to add an IF NOT EXISTS statement.
  97. * @param string $engine storage engine overwrite
  98. * @param string $charset default charset overwrite
  99. * @param array $foreign_keys an array of foreign keys
  100. * @return int number of affected rows.
  101. */
  102. public static function create_table($table, $fields, $primary_keys = array(), $if_not_exists = true, $engine = false, $charset = null, $foreign_keys = array(), $db = null)
  103. {
  104. $sql = 'CREATE TABLE';
  105. $sql .= $if_not_exists ? ' IF NOT EXISTS ' : ' ';
  106. $sql .= \DB::quote_identifier(\DB::table_prefix($table, $db ? $db : static::$connection), $db ? $db : static::$connection).' (';
  107. $sql .= static::process_fields($fields);
  108. if ( ! empty($primary_keys))
  109. {
  110. $key_name = \DB::quote_identifier(implode('_', $primary_keys), $db ? $db : static::$connection);
  111. $primary_keys = \DB::quote_identifier($primary_keys, $db ? $db : static::$connection);
  112. $sql .= ",\n\tPRIMARY KEY ".$key_name." (" . implode(', ', $primary_keys) . ")";
  113. }
  114. empty($foreign_keys) or $sql .= static::process_foreign_keys($foreign_keys);
  115. $sql .= "\n)";
  116. $sql .= ($engine !== false) ? ' ENGINE = '.$engine.' ' : '';
  117. $sql .= static::process_charset($charset, true).";";
  118. return \DB::query($sql, \DB::UPDATE)->execute($db ? $db : static::$connection);
  119. }
  120. /**
  121. * Adds fields to a table a table. Will throw a Database_Exception if it cannot.
  122. *
  123. * @throws Fuel\Database_Exception
  124. * @param string $table the table name
  125. * @param array $fields the new fields
  126. * @return int the number of affected
  127. */
  128. public static function add_fields($table, $fields, $db = null)
  129. {
  130. return static::alter_fields('ADD', $table, $fields, $db);
  131. }
  132. /**
  133. * Modifies fields in a table. Will throw a Database_Exception if it cannot.
  134. *
  135. * @throws Fuel\Database_Exception
  136. * @param string $table the table name
  137. * @param array $fields the modified fields
  138. * @return int the number of affected
  139. */
  140. public static function modify_fields($table, $fields, $db = null)
  141. {
  142. return static::alter_fields('MODIFY', $table, $fields, $db);
  143. }
  144. /**
  145. * Drops fields from a table a table. Will throw a Database_Exception if it cannot.
  146. *
  147. * @throws Fuel\Database_Exception
  148. * @param string $table the table name
  149. * @param string|array $fields the fields
  150. * @return int the number of affected
  151. */
  152. public static function drop_fields($table, $fields, $db = null)
  153. {
  154. return static::alter_fields('DROP', $table, $fields, $db);
  155. }
  156. protected static function alter_fields($type, $table, $fields, $db = null)
  157. {
  158. $sql = 'ALTER TABLE '.\DB::quote_identifier(\DB::table_prefix($table, $db ?: static::$connection), $db ?: static::$connection).' ';
  159. if ($type === 'DROP')
  160. {
  161. if ( ! is_array($fields))
  162. {
  163. $fields = array($fields);
  164. }
  165. $drop_fields = array();
  166. foreach ($fields as $field)
  167. {
  168. $drop_fields[] = 'DROP '.\DB::quote_identifier($field, $db ?: static::$connection);
  169. }
  170. $sql .= implode(', ', $drop_fields);
  171. }
  172. else
  173. {
  174. $use_brackets = ! in_array($type, array('ADD', 'CHANGE', 'MODIFY'));
  175. $use_brackets and $sql .= $type.' ';
  176. $use_brackets and $sql .= '(';
  177. $sql .= static::process_fields($fields, (( ! $use_brackets) ? $type.' ' : ''));
  178. $use_brackets and $sql .= ')';
  179. }
  180. return \DB::query($sql, \DB::UPDATE)->execute($db ?: static::$connection);
  181. }
  182. /**
  183. * Creates an index on that table.
  184. *
  185. * @access public
  186. * @static
  187. * @param string $table
  188. * @param string $index_name
  189. * @param string $index_columns
  190. * @param string $index (should be 'unique', 'fulltext', 'spatial' or 'nonclustered')
  191. * @return bool
  192. * @author Thomas Edwards
  193. */
  194. public static function create_index($table, $index_columns, $index_name = '', $index = '', $db = null)
  195. {
  196. static $accepted_index = array('UNIQUE', 'FULLTEXT', 'SPATIAL', 'NONCLUSTERED');
  197. // make sure the index type is uppercase
  198. $index !== '' and $index = strtoupper($index);
  199. if (empty($index_name))
  200. {
  201. if (is_array($index_columns))
  202. {
  203. foreach ($index_columns as $key => $value)
  204. {
  205. if (is_numeric($key))
  206. {
  207. $index_name .= ($index_name == '' ? '' : '_').$value;
  208. }
  209. else
  210. {
  211. $index_name .= ($index_name == '' ? '' : '_').str_replace(array('(', ')', ' '), '', $key);
  212. }
  213. }
  214. }
  215. else
  216. {
  217. $index_name = $index_columns;
  218. }
  219. }
  220. $sql = 'CREATE ';
  221. $index !== '' and $sql .= (in_array($index, $accepted_index)) ? $index.' ' : '';
  222. $sql .= 'INDEX ';
  223. $sql .= \DB::quote_identifier($index_name, $db ? $db : static::$connection);
  224. $sql .= ' ON ';
  225. $sql .= \DB::quote_identifier(\DB::table_prefix($table, $db ? $db : static::$connection), $db ? $db : static::$connection);
  226. if (is_array($index_columns))
  227. {
  228. $columns = '';
  229. foreach ($index_columns as $key => $value)
  230. {
  231. if (is_numeric($key))
  232. {
  233. $columns .= ($columns=='' ? '' : ', ').\DB::quote_identifier($value, $db ? $db : static::$connection);
  234. }
  235. else
  236. {
  237. $columns .= ($columns=='' ? '' : ', ').\DB::quote_identifier($key, $db ? $db : static::$connection).' '.strtoupper($value);
  238. }
  239. }
  240. $sql .= ' ('.$columns.')';
  241. }
  242. else
  243. {
  244. $sql .= ' ('.\DB::quote_identifier($index_columns, $db ? $db : static::$connection).')';
  245. }
  246. return \DB::query($sql, \DB::UPDATE)->execute($db ? $db : static::$connection);
  247. }
  248. /**
  249. * Drop an index from a table.
  250. *
  251. * @access public
  252. * @static
  253. * @param string $table
  254. * @param string $index_name
  255. * @return bool
  256. * @author Thomas Edwards
  257. */
  258. public static function drop_index($table, $index_name, $db = null)
  259. {
  260. $sql = 'DROP INDEX '.\DB::quote_identifier($index_name, $db ? $db : static::$connection);
  261. $sql .= ' ON '.\DB::quote_identifier(\DB::table_prefix($table, $db ? $db : static::$connection), $db ? $db : static::$connection);
  262. return \DB::query($sql, \DB::UPDATE)->execute($db ? $db : static::$connection);
  263. }
  264. protected static function process_fields($fields, $prefix = '', $db = null)
  265. {
  266. $sql_fields = array();
  267. foreach ($fields as $field => $attr)
  268. {
  269. $attr = array_change_key_case($attr, CASE_UPPER);
  270. $_prefix = $prefix;
  271. if(array_key_exists('NAME', $attr) and $field !== $attr['NAME'] and $_prefix === 'MODIFY ')
  272. {
  273. $_prefix = 'CHANGE ';
  274. }
  275. $sql = "\n\t".$_prefix;
  276. $sql .= \DB::quote_identifier($field);
  277. $sql .= (array_key_exists('NAME', $attr) and $attr['NAME'] !== $field) ? ' '.\DB::quote_identifier($attr['NAME'], $db ? $db : static::$connection).' ' : '';
  278. $sql .= array_key_exists('TYPE', $attr) ? ' '.$attr['TYPE'] : '';
  279. if(array_key_exists('CONSTRAINT',$attr))
  280. {
  281. if(is_array($attr['CONSTRAINT']))
  282. {
  283. $sql .= "('".implode("', '",$attr['CONSTRAINT'])."')";
  284. }
  285. else
  286. {
  287. $sql .= '('.$attr['CONSTRAINT'].')';
  288. }
  289. }
  290. $sql .= array_key_exists('CHARSET', $attr) ? static::process_charset($attr['CHARSET'], $db ? $db : static::$connection) : '';
  291. if (array_key_exists('UNSIGNED', $attr) and $attr['UNSIGNED'] === true)
  292. {
  293. $sql .= ' UNSIGNED';
  294. }
  295. if(array_key_exists('DEFAULT', $attr))
  296. {
  297. $sql .= ' DEFAULT '.(($attr['DEFAULT'] instanceof \Database_Expression) ? $attr['DEFAULT'] : \DB::escape($attr['DEFAULT']));
  298. }
  299. if(array_key_exists('NULL', $attr) and $attr['NULL'] === true)
  300. {
  301. $sql .= ' NULL';
  302. }
  303. else
  304. {
  305. $sql .= ' NOT NULL';
  306. }
  307. if (array_key_exists('AUTO_INCREMENT', $attr) and $attr['AUTO_INCREMENT'] === true)
  308. {
  309. $sql .= ' AUTO_INCREMENT';
  310. }
  311. if (array_key_exists('FIRST', $attr) and $attr['FIRST'] === true)
  312. {
  313. $sql .= ' FIRST';
  314. }
  315. elseif (array_key_exists('AFTER', $attr) and strval($attr['AFTER']))
  316. {
  317. $sql .= ' AFTER '.\DB::quote_identifier($attr['AFTER'], $db ? $db : static::$connection);
  318. }
  319. if (array_key_exists('COMMENT', $attr))
  320. {
  321. $sql .= ' COMMENT '.\DB::escape($attr['COMMENT'], $db ? $db : static::$connection);
  322. }
  323. $sql_fields[] = $sql;
  324. }
  325. return \implode(',', $sql_fields);
  326. }
  327. /**
  328. * Formats the default charset.
  329. *
  330. * @param string $charset the character set
  331. * @param bool $is_default whether to use default
  332. * @return string the formated charset sql
  333. */
  334. protected static function process_charset($charset = null, $is_default = false, $db = null)
  335. {
  336. $charset or $charset = \Config::get('db.'.($db ? $db : \Config::get('db.active')).'.charset', null);
  337. if (empty($charset))
  338. {
  339. return '';
  340. }
  341. if (($pos = stripos($charset, '_')) !== false)
  342. {
  343. $charset = ' CHARACTER SET '.substr($charset, 0, $pos).' COLLATE '.$charset;
  344. }
  345. else
  346. {
  347. $charset = ' CHARACTER SET '.$charset;
  348. }
  349. $is_default and $charset = ' DEFAULT'.$charset;
  350. return $charset;
  351. }
  352. /**
  353. * Adds a single foreign key to a table
  354. *
  355. * @param string $table the table name
  356. * @param array $foreign_key a single foreign key
  357. * @return int number of affected rows
  358. */
  359. public static function add_foreign_key($table, $foreign_key)
  360. {
  361. if ( ! is_array($foreign_key))
  362. {
  363. throw new InvalidArgumentException('Foreign key for add_foreign_key() must be specified as an array');
  364. }
  365. $sql = 'ALTER TABLE ';
  366. $sql .= \DB::quote_identifier(\DB::table_prefix($table)).' ';
  367. $sql .= 'ADD ';
  368. $sql .= ltrim(static::process_foreign_keys(array($foreign_key)), ',');
  369. return \DB::query($sql, \DB::UPDATE)->execute();
  370. }
  371. /**
  372. * Drops a foreign key from a table
  373. *
  374. * @param string $table the table name
  375. * @param string $fk_name the foreign key name
  376. * @return int number of affected rows
  377. */
  378. public static function drop_foreign_key($table, $fk_name)
  379. {
  380. $sql = 'ALTER TABLE ';
  381. $sql .= \DB::quote_identifier(\DB::table_prefix($table)).' ';
  382. $sql .= 'DROP FOREIGN KEY '.\DB::quote_identifier($fk_name);
  383. return \DB::query($sql, \DB::UPDATE)->execute();
  384. }
  385. /**
  386. * Returns string of foreign keys
  387. *
  388. * @param array $foreign_keys Array of foreign key rules
  389. * @return string the formated foreign key string
  390. */
  391. public static function process_foreign_keys($foreign_keys, $db = null)
  392. {
  393. if ( ! is_array($foreign_keys))
  394. {
  395. throw new \Database_Exception('Foreign keys on create_table() must be specified as an array');
  396. }
  397. $fk_list = array();
  398. foreach($foreign_keys as $definition)
  399. {
  400. // some sanity checks
  401. if (empty($definition['key']))
  402. {
  403. throw new \Database_Exception('Foreign keys on create_table() must specify a foreign key name');
  404. }
  405. if ( empty($definition['reference']))
  406. {
  407. throw new \Database_Exception('Foreign keys on create_table() must specify a foreign key reference');
  408. }
  409. if (empty($definition['reference']['table']) or empty($definition['reference']['column']))
  410. {
  411. throw new \Database_Exception('Foreign keys on create_table() must specify a reference table and column name');
  412. }
  413. $sql = '';
  414. ! empty($definition['constraint']) and $sql .= " CONSTRAINT ".\DB::quote_identifier($definition['constraint']);
  415. $sql .= " FOREIGN KEY (".\DB::quote_identifier($definition['key']).')';
  416. $sql .= " REFERENCES ".\DB::quote_identifier(\DB::table_prefix($definition['reference']['table'])).' (';
  417. if (is_array($definition['reference']['column']))
  418. {
  419. $sql .= implode(', ', \DB::quote_identifier($definition['reference']['column']));
  420. }
  421. else
  422. {
  423. $sql .= \DB::quote_identifier($definition['reference']['column']);
  424. }
  425. $sql .= ')';
  426. ! empty($definition['on_update']) and $sql .= " ON UPDATE ".$definition['on_update'];
  427. ! empty($definition['on_delete']) and $sql .= " ON DELETE ".$definition['on_delete'];
  428. $fk_list[] = "\n\t".ltrim($sql);
  429. }
  430. return ', '.implode(',', $fk_list);
  431. }
  432. /**
  433. * Truncates a table.
  434. *
  435. * @throws Fuel\Database_Exception
  436. * @param string $table the table name
  437. * @return int the number of affected rows
  438. */
  439. public static function truncate_table($table, $db = null)
  440. {
  441. return \DB::query('TRUNCATE TABLE '.\DB::quote_identifier(\DB::table_prefix($table, $db ? $db : static::$connection), $db ? $db : static::$connection), \DB::DELETE)
  442. ->execute($db ? $db : static::$connection);
  443. }
  444. /**
  445. * Analyzes a table.
  446. *
  447. * @param string $table the table name
  448. * @return bool whether the table is OK
  449. */
  450. public static function analyze_table($table, $db = null)
  451. {
  452. return static::table_maintenance('ANALYZE TABLE', $table, $db);
  453. }
  454. /**
  455. * Checks a table.
  456. *
  457. * @param string $table the table name
  458. * @return bool whether the table is OK
  459. */
  460. public static function check_table($table, $db = null)
  461. {
  462. return static::table_maintenance('CHECK TABLE', $table, $db);
  463. }
  464. /**
  465. * Optimizes a table.
  466. *
  467. * @param string $table the table name
  468. * @return bool whether the table has been optimized
  469. */
  470. public static function optimize_table($table, $db = null)
  471. {
  472. return static::table_maintenance('OPTIMIZE TABLE', $table, $db);
  473. }
  474. /**
  475. * Repairs a table.
  476. *
  477. * @param string $table the table name
  478. * @return bool whether the table has been repaired
  479. */
  480. public static function repair_table($table, $db = null)
  481. {
  482. return static::table_maintenance('REPAIR TABLE', $table, $db);
  483. }
  484. /**
  485. * Checks if a given table exists.
  486. *
  487. * @param string $table Table name
  488. * @return bool
  489. */
  490. public static function table_exists($table, $db = null)
  491. {
  492. try
  493. {
  494. \DB::select()->from($table)->limit(1)->execute($db ? $db : static::$connection);
  495. return true;
  496. }
  497. catch (\Database_Exception $e)
  498. {
  499. // check if we have a DB connection at all
  500. $connection = \Database_Connection::instance($db ? $db : static::$connection)->connection();
  501. // if no connection could be made, re throw the exception
  502. if ( ! $connection)
  503. {
  504. throw $e;
  505. }
  506. return false;
  507. }
  508. }
  509. /**
  510. * Checks if given field(s) in a given table exists.
  511. *
  512. * @param string $table Table name
  513. * @param string|array $columns columns to check
  514. * @return bool
  515. */
  516. public static function field_exists($table, $columns, $db = null)
  517. {
  518. if ( ! is_array($columns))
  519. {
  520. $columns = array($columns);
  521. }
  522. try
  523. {
  524. \DB::select_array($columns)->from($table)->limit(1)->execute($db ? $db : static::$connection);
  525. return true;
  526. }
  527. catch (\Database_Exception $e)
  528. {
  529. return false;
  530. }
  531. }
  532. /*
  533. * Executes table maintenance. Will throw FuelException when the operation is not supported.
  534. *
  535. * @throws FuelException
  536. * @param string $table the table name
  537. * @return bool whether the operation has succeeded
  538. */
  539. protected static function table_maintenance($operation, $table, $db = null)
  540. {
  541. $result = \DB::query($operation.' '.\DB::quote_identifier(\DB::table_prefix($table, $db ? $db : static::$connection), $db ? $db : static::$connection), \DB::SELECT)->execute($db ? $db : static::$connection);
  542. $type = $result->get('Msg_type');
  543. $message = $result->get('Msg_text');
  544. $table = $result->get('Table');
  545. if ($type === 'status' and in_array(strtolower($message), array('ok','table is already up to date')))
  546. {
  547. return true;
  548. }
  549. if ($type === 'error')
  550. {
  551. logger(\Fuel::L_ERROR, 'Table: '.$table.', Operation: '.$operation.', Message: '.$result->get('Msg_text'), 'DBUtil::table_maintenance');
  552. }
  553. else
  554. {
  555. logger(ucfirst($type), 'Table: '.$table.', Operation: '.$operation.', Message: '.$result->get('Msg_text'), 'DBUtil::table_maintenance');
  556. }
  557. return false;
  558. }
  559. /*
  560. * Load the db config, the Database_Connection might not have fired jet.
  561. *
  562. */
  563. public static function _init()
  564. {
  565. \Config::load('db', true);
  566. }
  567. }