PageRenderTime 45ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/system/libraries/Migration.php

https://github.com/appleboy/CodeIgniter
PHP | 429 lines | 184 code | 68 blank | 177 comment | 25 complexity | 1d500032c35ee3f5f9402ee0a0f81a87 MD5 | raw file
  1. <?php
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP 5.2.4 or newer
  6. *
  7. * NOTICE OF LICENSE
  8. *
  9. * Licensed under the Open Software License version 3.0
  10. *
  11. * This source file is subject to the Open Software License (OSL 3.0) that is
  12. * bundled with this package in the files license.txt / license.rst. It is
  13. * also available through the world wide web at this URL:
  14. * http://opensource.org/licenses/OSL-3.0
  15. * If you did not receive a copy of the license and are unable to obtain it
  16. * through the world wide web, please send an email to
  17. * licensing@ellislab.com so we can send you a copy immediately.
  18. *
  19. * @package CodeIgniter
  20. * @author EllisLab Dev Team
  21. * @copyright Copyright (c) 2006 - 2013, EllisLab, Inc. (http://ellislab.com/)
  22. * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
  23. * @link http://codeigniter.com
  24. * @since Version 3.0
  25. * @filesource
  26. */
  27. defined('BASEPATH') OR exit('No direct script access allowed');
  28. /**
  29. * Migration Class
  30. *
  31. * All migrations should implement this, forces up() and down() and gives
  32. * access to the CI super-global.
  33. *
  34. * @package CodeIgniter
  35. * @subpackage Libraries
  36. * @category Libraries
  37. * @author Reactor Engineers
  38. * @link
  39. */
  40. class CI_Migration {
  41. /**
  42. * Whether the library is enabled
  43. *
  44. * @var bool
  45. */
  46. protected $_migration_enabled = FALSE;
  47. /**
  48. * Migration numbering type
  49. *
  50. * @var bool
  51. */
  52. protected $_migration_type = 'sequential';
  53. /**
  54. * Path to migration classes
  55. *
  56. * @var string
  57. */
  58. protected $_migration_path = NULL;
  59. /**
  60. * Current migration version
  61. *
  62. * @var mixed
  63. */
  64. protected $_migration_version = 0;
  65. /**
  66. * Database table with migration info
  67. *
  68. * @var string
  69. */
  70. protected $_migration_table = 'migrations';
  71. /**
  72. * Whether to automatically run migrations
  73. *
  74. * @var bool
  75. */
  76. protected $_migration_auto_latest = FALSE;
  77. /**
  78. * Migration basename regex
  79. *
  80. * @var bool
  81. */
  82. protected $_migration_regex = NULL;
  83. /**
  84. * Error message
  85. *
  86. * @var string
  87. */
  88. protected $_error_string = '';
  89. /**
  90. * Initialize Migration Class
  91. *
  92. * @param array $config
  93. * @return void
  94. */
  95. public function __construct($config = array())
  96. {
  97. # Only run this constructor on main library load
  98. if (get_parent_class($this) !== FALSE)
  99. {
  100. return;
  101. }
  102. foreach ($config as $key => $val)
  103. {
  104. $this->{'_'.$key} = $val;
  105. }
  106. log_message('debug', 'Migrations class initialized');
  107. // Are they trying to use migrations while it is disabled?
  108. if ($this->_migration_enabled !== TRUE)
  109. {
  110. show_error('Migrations has been loaded but is disabled or set up incorrectly.');
  111. }
  112. // If not set, set it
  113. $this->_migration_path !== '' OR $this->_migration_path = APPPATH.'migrations/';
  114. // Add trailing slash if not set
  115. $this->_migration_path = rtrim($this->_migration_path, '/').'/';
  116. // Load migration language
  117. $this->lang->load('migration');
  118. // They'll probably be using dbforge
  119. $this->load->dbforge();
  120. // Make sure the migration table name was set.
  121. if (empty($this->_migration_table))
  122. {
  123. show_error('Migrations configuration file (migration.php) must have "migration_table" set.');
  124. }
  125. // Migration basename regex
  126. $this->_migration_regex = ($this->_migration_type === 'timestamp')
  127. ? '/^\d{14}_(\w+)$/'
  128. : '/^\d{3}_(\w+)$/';
  129. // Make sure a valid migration numbering type was set.
  130. if ( ! in_array($this->_migration_type, array('sequential', 'timestamp')))
  131. {
  132. show_error('An invalid migration numbering type was specified: '.$this->_migration_type);
  133. }
  134. // If the migrations table is missing, make it
  135. if ( ! $this->db->table_exists($this->_migration_table))
  136. {
  137. $this->dbforge->add_field(array(
  138. 'version' => array('type' => 'BIGINT', 'constraint' => 20),
  139. ));
  140. $this->dbforge->create_table($this->_migration_table, TRUE);
  141. $this->db->insert($this->_migration_table, array('version' => 0));
  142. }
  143. // Do we auto migrate to the latest migration?
  144. if ($this->_migration_auto_latest === TRUE && ! $this->latest())
  145. {
  146. show_error($this->error_string());
  147. }
  148. }
  149. // --------------------------------------------------------------------
  150. /**
  151. * Migrate to a schema version
  152. *
  153. * Calls each migration step required to get to the schema version of
  154. * choice
  155. *
  156. * @param int $target_version Target schema version
  157. * @return mixed TRUE if already latest, FALSE if failed, int if upgraded
  158. */
  159. public function version($target_version)
  160. {
  161. $current_version = (int) $this->_get_version();
  162. $target_version = (int) $target_version;
  163. $migrations = $this->find_migrations();
  164. if ($target_version > 0 && ! isset($migrations[$target_version]))
  165. {
  166. $this->_error_string = sprintf($this->lang->line('migration_not_found'), $target_version);
  167. return FALSE;
  168. }
  169. if ($target_version > $current_version)
  170. {
  171. // Moving Up
  172. $method = 'up';
  173. }
  174. else
  175. {
  176. // Moving Down, apply in reverse order
  177. $method = 'down';
  178. krsort($migrations);
  179. }
  180. if (empty($migrations))
  181. {
  182. return TRUE;
  183. }
  184. $previous = FALSE;
  185. // Validate all available migrations, and run the ones within our target range
  186. foreach ($migrations as $number => $file)
  187. {
  188. // Check for sequence gaps
  189. if ($this->_migration_type === 'sequential' && $previous !== FALSE && abs($number - $previous) > 1)
  190. {
  191. $this->_error_string = sprintf($this->lang->line('migration_sequence_gap'), $number);
  192. return FALSE;
  193. }
  194. include_once $file;
  195. $class = 'Migration_'.ucfirst(strtolower($this->_get_migration_name(basename($file, '.php'))));
  196. // Validate the migration file structure
  197. if ( ! class_exists($class))
  198. {
  199. $this->_error_string = sprintf($this->lang->line('migration_class_doesnt_exist'), $class);
  200. return FALSE;
  201. }
  202. $previous = $number;
  203. // Run migrations that are inside the target range
  204. if (
  205. ($method === 'up' && $number > $current_version && $number <= $target_version) OR
  206. ($method === 'down' && $number <= $current_version && $number > $target_version)
  207. )
  208. {
  209. $instance = new $class();
  210. if ( ! is_callable(array($instance, $method)))
  211. {
  212. $this->_error_string = sprintf($this->lang->line('migration_missing_'.$method.'_method'), $class);
  213. return FALSE;
  214. }
  215. log_message('debug', 'Migrating '.$method.' from version '.$current_version.' to version '.$number);
  216. call_user_func(array($instance, $method));
  217. $current_version = $number;
  218. $this->_update_version($current_version);
  219. }
  220. }
  221. // This is necessary when moving down, since the the last migration applied
  222. // will be the down() method for the next migration up from the target
  223. if ($current_version <> $target_version)
  224. {
  225. $current_version = $target_version;
  226. $this->_update_version($current_version);
  227. }
  228. log_message('debug', 'Finished migrating to '.$current_version);
  229. return $current_version;
  230. }
  231. // --------------------------------------------------------------------
  232. /**
  233. * Set's the schema to the latest migration
  234. *
  235. * @return mixed TRUE if already latest, FALSE if failed, int if upgraded
  236. */
  237. public function latest()
  238. {
  239. $migrations = $this->find_migrations();
  240. if (empty($migrations))
  241. {
  242. $this->_error_string = $this->lang->line('migration_none_found');
  243. return FALSE;
  244. }
  245. $last_migration = basename(end($migrations));
  246. // Calculate the last migration step from existing migration
  247. // filenames and procceed to the standard version migration
  248. return $this->version($this->_get_migration_number($last_migration));
  249. }
  250. // --------------------------------------------------------------------
  251. /**
  252. * Set's the schema to the migration version set in config
  253. *
  254. * @return mixed TRUE if already current, FALSE if failed, int if upgraded
  255. */
  256. public function current()
  257. {
  258. return $this->version($this->_migration_version);
  259. }
  260. // --------------------------------------------------------------------
  261. /**
  262. * Error string
  263. *
  264. * @return string Error message returned as a string
  265. */
  266. public function error_string()
  267. {
  268. return $this->_error_string;
  269. }
  270. // --------------------------------------------------------------------
  271. /**
  272. * Retrieves list of available migration scripts
  273. *
  274. * @return array list of migration file paths sorted by version
  275. */
  276. public function find_migrations()
  277. {
  278. $migrations = array();
  279. // Load all *_*.php files in the migrations path
  280. foreach (glob($this->_migration_path.'*_*.php') as $file)
  281. {
  282. $name = basename($file, '.php');
  283. // Filter out non-migration files
  284. if (preg_match($this->_migration_regex, $name))
  285. {
  286. $number = $this->_get_migration_number($name);
  287. // There cannot be duplicate migration numbers
  288. if (isset($migrations[$number]))
  289. {
  290. $this->_error_string = sprintf($this->lang->line('migration_multiple_version'), $number);
  291. show_error($this->_error_string);
  292. }
  293. $migrations[$number] = $file;
  294. }
  295. }
  296. ksort($migrations);
  297. return $migrations;
  298. }
  299. // --------------------------------------------------------------------
  300. /**
  301. * Extracts the migration number from a filename
  302. *
  303. * @param string $migration
  304. * @return int Numeric portion of a migration filename
  305. */
  306. protected function _get_migration_number($migration)
  307. {
  308. return sscanf($migration, '%d', $number)
  309. ? $number : 0;
  310. }
  311. // --------------------------------------------------------------------
  312. /**
  313. * Extracts the migration class name from a filename
  314. *
  315. * @param string $migration
  316. * @return string text portion of a migration filename
  317. */
  318. protected function _get_migration_name($migration)
  319. {
  320. $parts = explode('_', $migration);
  321. array_shift($parts);
  322. return implode('_', $parts);
  323. }
  324. // --------------------------------------------------------------------
  325. /**
  326. * Retrieves current schema version
  327. *
  328. * @return int Current Migration
  329. */
  330. protected function _get_version()
  331. {
  332. $row = $this->db->select('version')->get($this->_migration_table)->row();
  333. return $row ? $row->version : 0;
  334. }
  335. // --------------------------------------------------------------------
  336. /**
  337. * Stores the current schema version
  338. *
  339. * @param int $migration Migration reached
  340. * @return void Outputs a report of the migration
  341. */
  342. protected function _update_version($migration)
  343. {
  344. return $this->db->update($this->_migration_table, array(
  345. 'version' => $migration
  346. ));
  347. }
  348. // --------------------------------------------------------------------
  349. /**
  350. * Enable the use of CI super-global
  351. *
  352. * @param string $var
  353. * @return mixed
  354. */
  355. public function __get($var)
  356. {
  357. return get_instance()->$var;
  358. }
  359. }
  360. /* End of file Migration.php */
  361. /* Location: ./system/libraries/Migration.php */