You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

477 lines
12 KiB

7 years ago
  1. <?php
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP
  6. *
  7. * This content is released under the MIT License (MIT)
  8. *
  9. * Copyright (c) 2014 - 2017, British Columbia Institute of Technology
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining a copy
  12. * of this software and associated documentation files (the "Software"), to deal
  13. * in the Software without restriction, including without limitation the rights
  14. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. * copies of the Software, and to permit persons to whom the Software is
  16. * furnished to do so, subject to the following conditions:
  17. *
  18. * The above copyright notice and this permission notice shall be included in
  19. * all copies or substantial portions of the Software.
  20. *
  21. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27. * THE SOFTWARE.
  28. *
  29. * @package CodeIgniter
  30. * @author EllisLab Dev Team
  31. * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
  32. * @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
  33. * @license http://opensource.org/licenses/MIT MIT License
  34. * @link https://codeigniter.com
  35. * @since Version 3.0.0
  36. * @filesource
  37. */
  38. defined('BASEPATH') OR exit('No direct script access allowed');
  39. /**
  40. * Migration Class
  41. *
  42. * All migrations should implement this, forces up() and down() and gives
  43. * access to the CI super-global.
  44. *
  45. * @package CodeIgniter
  46. * @subpackage Libraries
  47. * @category Libraries
  48. * @author Reactor Engineers
  49. * @link
  50. */
  51. class CI_Migration {
  52. /**
  53. * Whether the library is enabled
  54. *
  55. * @var bool
  56. */
  57. protected $_migration_enabled = FALSE;
  58. /**
  59. * Migration numbering type
  60. *
  61. * @var bool
  62. */
  63. protected $_migration_type = 'sequential';
  64. /**
  65. * Path to migration classes
  66. *
  67. * @var string
  68. */
  69. protected $_migration_path = NULL;
  70. /**
  71. * Current migration version
  72. *
  73. * @var mixed
  74. */
  75. protected $_migration_version = 0;
  76. /**
  77. * Database table with migration info
  78. *
  79. * @var string
  80. */
  81. protected $_migration_table = 'migrations';
  82. /**
  83. * Whether to automatically run migrations
  84. *
  85. * @var bool
  86. */
  87. protected $_migration_auto_latest = FALSE;
  88. /**
  89. * Migration basename regex
  90. *
  91. * @var string
  92. */
  93. protected $_migration_regex;
  94. /**
  95. * Error message
  96. *
  97. * @var string
  98. */
  99. protected $_error_string = '';
  100. /**
  101. * Initialize Migration Class
  102. *
  103. * @param array $config
  104. * @return void
  105. */
  106. public function __construct($config = array())
  107. {
  108. // Only run this constructor on main library load
  109. if ( ! in_array(get_class($this), array('CI_Migration', config_item('subclass_prefix').'Migration'), TRUE))
  110. {
  111. return;
  112. }
  113. foreach ($config as $key => $val)
  114. {
  115. $this->{'_'.$key} = $val;
  116. }
  117. log_message('info', 'Migrations Class Initialized');
  118. // Are they trying to use migrations while it is disabled?
  119. if ($this->_migration_enabled !== TRUE)
  120. {
  121. show_error('Migrations has been loaded but is disabled or set up incorrectly.');
  122. }
  123. // If not set, set it
  124. $this->_migration_path !== '' OR $this->_migration_path = APPPATH.'migrations/';
  125. // Add trailing slash if not set
  126. $this->_migration_path = rtrim($this->_migration_path, '/').'/';
  127. // Load migration language
  128. $this->lang->load('migration');
  129. // They'll probably be using dbforge
  130. $this->load->dbforge();
  131. // Make sure the migration table name was set.
  132. if (empty($this->_migration_table))
  133. {
  134. show_error('Migrations configuration file (migration.php) must have "migration_table" set.');
  135. }
  136. // Migration basename regex
  137. $this->_migration_regex = ($this->_migration_type === 'timestamp')
  138. ? '/^\d{14}_(\w+)$/'
  139. : '/^\d{3}_(\w+)$/';
  140. // Make sure a valid migration numbering type was set.
  141. if ( ! in_array($this->_migration_type, array('sequential', 'timestamp')))
  142. {
  143. show_error('An invalid migration numbering type was specified: '.$this->_migration_type);
  144. }
  145. // If the migrations table is missing, make it
  146. if ( ! $this->db->table_exists($this->_migration_table))
  147. {
  148. $this->dbforge->add_field(array(
  149. 'version' => array('type' => 'BIGINT', 'constraint' => 20),
  150. ));
  151. $this->dbforge->create_table($this->_migration_table, TRUE);
  152. $this->db->insert($this->_migration_table, array('version' => 0));
  153. }
  154. // Do we auto migrate to the latest migration?
  155. if ($this->_migration_auto_latest === TRUE && ! $this->latest())
  156. {
  157. show_error($this->error_string());
  158. }
  159. }
  160. // --------------------------------------------------------------------
  161. /**
  162. * Migrate to a schema version
  163. *
  164. * Calls each migration step required to get to the schema version of
  165. * choice
  166. *
  167. * @param string $target_version Target schema version
  168. * @return mixed TRUE if no migrations are found, current version string on success, FALSE on failure
  169. */
  170. public function version($target_version)
  171. {
  172. // Note: We use strings, so that timestamp versions work on 32-bit systems
  173. $current_version = $this->_get_version();
  174. if ($this->_migration_type === 'sequential')
  175. {
  176. $target_version = sprintf('%03d', $target_version);
  177. }
  178. else
  179. {
  180. $target_version = (string) $target_version;
  181. }
  182. $migrations = $this->find_migrations();
  183. if ($target_version > 0 && ! isset($migrations[$target_version]))
  184. {
  185. $this->_error_string = sprintf($this->lang->line('migration_not_found'), $target_version);
  186. return FALSE;
  187. }
  188. if ($target_version > $current_version)
  189. {
  190. $method = 'up';
  191. }
  192. elseif ($target_version < $current_version)
  193. {
  194. $method = 'down';
  195. // We need this so that migrations are applied in reverse order
  196. krsort($migrations);
  197. }
  198. else
  199. {
  200. // Well, there's nothing to migrate then ...
  201. return TRUE;
  202. }
  203. // Validate all available migrations within our target range.
  204. //
  205. // Unfortunately, we'll have to use another loop to run them
  206. // in order to avoid leaving the procedure in a broken state.
  207. //
  208. // See https://github.com/bcit-ci/CodeIgniter/issues/4539
  209. $pending = array();
  210. foreach ($migrations as $number => $file)
  211. {
  212. // Ignore versions out of our range.
  213. //
  214. // Because we've previously sorted the $migrations array depending on the direction,
  215. // we can safely break the loop once we reach $target_version ...
  216. if ($method === 'up')
  217. {
  218. if ($number <= $current_version)
  219. {
  220. continue;
  221. }
  222. elseif ($number > $target_version)
  223. {
  224. break;
  225. }
  226. }
  227. else
  228. {
  229. if ($number > $current_version)
  230. {
  231. continue;
  232. }
  233. elseif ($number <= $target_version)
  234. {
  235. break;
  236. }
  237. }
  238. // Check for sequence gaps
  239. if ($this->_migration_type === 'sequential')
  240. {
  241. if (isset($previous) && abs($number - $previous) > 1)
  242. {
  243. $this->_error_string = sprintf($this->lang->line('migration_sequence_gap'), $number);
  244. return FALSE;
  245. }
  246. $previous = $number;
  247. }
  248. include_once($file);
  249. $class = 'Migration_'.ucfirst(strtolower($this->_get_migration_name(basename($file, '.php'))));
  250. // Validate the migration file structure
  251. if ( ! class_exists($class, FALSE))
  252. {
  253. $this->_error_string = sprintf($this->lang->line('migration_class_doesnt_exist'), $class);
  254. return FALSE;
  255. }
  256. elseif ( ! is_callable(array($class, $method)))
  257. {
  258. $this->_error_string = sprintf($this->lang->line('migration_missing_'.$method.'_method'), $class);
  259. return FALSE;
  260. }
  261. $pending[$number] = array($class, $method);
  262. }
  263. // Now just run the necessary migrations
  264. foreach ($pending as $number => $migration)
  265. {
  266. log_message('debug', 'Migrating '.$method.' from version '.$current_version.' to version '.$number);
  267. $migration[0] = new $migration[0];
  268. call_user_func($migration);
  269. $current_version = $number;
  270. $this->_update_version($current_version);
  271. }
  272. // This is necessary when moving down, since the the last migration applied
  273. // will be the down() method for the next migration up from the target
  274. if ($current_version <> $target_version)
  275. {
  276. $current_version = $target_version;
  277. $this->_update_version($current_version);
  278. }
  279. log_message('debug', 'Finished migrating to '.$current_version);
  280. return $current_version;
  281. }
  282. // --------------------------------------------------------------------
  283. /**
  284. * Sets the schema to the latest migration
  285. *
  286. * @return mixed Current version string on success, FALSE on failure
  287. */
  288. public function latest()
  289. {
  290. $migrations = $this->find_migrations();
  291. if (empty($migrations))
  292. {
  293. $this->_error_string = $this->lang->line('migration_none_found');
  294. return FALSE;
  295. }
  296. $last_migration = basename(end($migrations));
  297. // Calculate the last migration step from existing migration
  298. // filenames and proceed to the standard version migration
  299. return $this->version($this->_get_migration_number($last_migration));
  300. }
  301. // --------------------------------------------------------------------
  302. /**
  303. * Sets the schema to the migration version set in config
  304. *
  305. * @return mixed TRUE if no migrations are found, current version string on success, FALSE on failure
  306. */
  307. public function current()
  308. {
  309. return $this->version($this->_migration_version);
  310. }
  311. // --------------------------------------------------------------------
  312. /**
  313. * Error string
  314. *
  315. * @return string Error message returned as a string
  316. */
  317. public function error_string()
  318. {
  319. return $this->_error_string;
  320. }
  321. // --------------------------------------------------------------------
  322. /**
  323. * Retrieves list of available migration scripts
  324. *
  325. * @return array list of migration file paths sorted by version
  326. */
  327. public function find_migrations()
  328. {
  329. $migrations = array();
  330. // Load all *_*.php files in the migrations path
  331. foreach (glob($this->_migration_path.'*_*.php') as $file)
  332. {
  333. $name = basename($file, '.php');
  334. // Filter out non-migration files
  335. if (preg_match($this->_migration_regex, $name))
  336. {
  337. $number = $this->_get_migration_number($name);
  338. // There cannot be duplicate migration numbers
  339. if (isset($migrations[$number]))
  340. {
  341. $this->_error_string = sprintf($this->lang->line('migration_multiple_version'), $number);
  342. show_error($this->_error_string);
  343. }
  344. $migrations[$number] = $file;
  345. }
  346. }
  347. ksort($migrations);
  348. return $migrations;
  349. }
  350. // --------------------------------------------------------------------
  351. /**
  352. * Extracts the migration number from a filename
  353. *
  354. * @param string $migration
  355. * @return string Numeric portion of a migration filename
  356. */
  357. protected function _get_migration_number($migration)
  358. {
  359. return sscanf($migration, '%[0-9]+', $number)
  360. ? $number : '0';
  361. }
  362. // --------------------------------------------------------------------
  363. /**
  364. * Extracts the migration class name from a filename
  365. *
  366. * @param string $migration
  367. * @return string text portion of a migration filename
  368. */
  369. protected function _get_migration_name($migration)
  370. {
  371. $parts = explode('_', $migration);
  372. array_shift($parts);
  373. return implode('_', $parts);
  374. }
  375. // --------------------------------------------------------------------
  376. /**
  377. * Retrieves current schema version
  378. *
  379. * @return string Current migration version
  380. */
  381. protected function _get_version()
  382. {
  383. $row = $this->db->select('version')->get($this->_migration_table)->row();
  384. return $row ? $row->version : '0';
  385. }
  386. // --------------------------------------------------------------------
  387. /**
  388. * Stores the current schema version
  389. *
  390. * @param string $migration Migration reached
  391. * @return void
  392. */
  393. protected function _update_version($migration)
  394. {
  395. $this->db->update($this->_migration_table, array(
  396. 'version' => $migration
  397. ));
  398. }
  399. // --------------------------------------------------------------------
  400. /**
  401. * Enable the use of CI super-global
  402. *
  403. * @param string $var
  404. * @return mixed
  405. */
  406. public function __get($var)
  407. {
  408. return get_instance()->$var;
  409. }
  410. }