Subversion Repository Public Repository

paulgoughbooks_old

This repository has no backups
This repository's network speed is throttled to 100KB/sec

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
<?php
/**
 * CodeIgniter
 *
 * An open source application development framework for PHP
 *
 * This content is released under the MIT License (MIT)
 *
 * Copyright (c) 2014-2019 British Columbia Institute of Technology
 * Copyright (c) 2019-2020 CodeIgniter Foundation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @package    CodeIgniter
 * @author     CodeIgniter Dev Team
 * @copyright  2019-2020 CodeIgniter Foundation
 * @license    https://opensource.org/licenses/MIT	MIT License
 * @link       https://codeigniter.com
 * @since      Version 4.0.0
 * @filesource
 */

namespace CodeIgniter\Database;

use CodeIgniter\CLI\CLI;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Exceptions\ConfigException;
use Config\Services;

/**
 * Class MigrationRunner
 */
class MigrationRunner
{

	/**
	 * Whether or not migrations are allowed to run.
	 *
	 * @var boolean
	 */
	protected $enabled = false;

	/**
	 * Name of table to store meta information
	 *
	 * @var string
	 */
	protected $table;

	/**
	 * The Namespace  where migrations can be found.
	 *
	 * @var string
	 */
	protected $namespace;

	/**
	 * The database Group to migrate.
	 *
	 * @var string
	 */
	protected $group;

	/**
	 * The migration name.
	 *
	 * @var string
	 */
	protected $name;

	/**
	 * The pattern used to locate migration file versions.
	 *
	 * @var string
	 */
	protected $regex = '/^\d{4}[_-]?\d{2}[_-]?\d{2}[_-]?\d{6}_(\w+)$/';

	/**
	 * The main database connection. Used to store
	 * migration information in.
	 *
	 * @var ConnectionInterface
	 */
	protected $db;

	/**
	 * If true, will continue instead of throwing
	 * exceptions.
	 *
	 * @var boolean
	 */
	protected $silent = false;

	/**
	 * used to return messages for CLI.
	 *
	 * @var array
	 */
	protected $cliMessages = [];

	/**
	 * Tracks whether we have already ensured
	 * the table exists or not.
	 *
	 * @var boolean
	 */
	protected $tableChecked = false;

	/**
	 * The full path to locate migration files.
	 *
	 * @var string
	 */
	protected $path;

	/**
	 * The database Group filter.
	 *
	 * @var string
	 */
	protected $groupFilter;

	/**
	 * Used to skip current migration.
	 *
	 * @var boolean
	 */
	protected $groupSkip = false;

	//--------------------------------------------------------------------

	/**
	 * Constructor.
	 *
	 * When passing in $db, you may pass any of the following to connect:
	 * - group name
	 * - existing connection instance
	 * - array of database configuration values
	 *
	 * @param BaseConfig                                             $config
	 * @param \CodeIgniter\Database\ConnectionInterface|array|string $db
	 *
	 * @throws ConfigException
	 */
	public function __construct(BaseConfig $config, $db = null)
	{
		$this->enabled = $config->enabled ?? false;
		$this->table   = $config->table ?? 'migrations';

		// Default name space is the app namespace
		$this->namespace = APP_NAMESPACE;

		// get default database group
		$config      = config('Database');
		$this->group = $config->defaultGroup;
		unset($config);

		// If no db connection passed in, use
		// default database group.
		$this->db = db_connect($db);
	}

	//--------------------------------------------------------------------

	/**
	 * Locate and run all new migrations
	 *
	 * @param string|null $group
	 */
	public function latest(string $group = null)
	{
		if (! $this->enabled)
		{
			throw ConfigException::forDisabledMigrations();
		}

		$this->ensureTable();

		// Set database group if not null
		if (! is_null($group))
		{
			$this->groupFilter = $group;
			$this->setGroup($group);
		}

		// Locate the migrations
		$migrations = $this->findMigrations();

		// If nothing was found then we're done
		if (empty($migrations))
		{
			return true;
		}

		// Remove any migrations already in the history
		foreach ($this->getHistory($this->group) as $history)
		{
			unset($migrations[$this->getObjectUid($history)]);
		}

		// Start a new batch
		$batch = $this->getLastBatch() + 1;

		// Run each migration
		foreach ($migrations as $migration)
		{
			if ($this->migrate('up', $migration))
			{
				if ($this->groupSkip === true)
				{
					$this->groupSkip = false;
					continue;
				}

				$this->addHistory($migration, $batch);
			}
			// If a migration failed then try to back out what was done
			else
			{
				$this->regress(-1);

				$message = lang('Migrations.generalFault');

				if ($this->silent)
				{
					$this->cliMessages[] = "\t" . CLI::color($message, 'red');
					return false;
				}
				throw new \RuntimeException($message);
			}
		}

		return true;
	}

	//--------------------------------------------------------------------

	/**
	 * Migrate down to a previous batch
	 *
	 * Calls each migration step required to get to the provided batch
	 *
	 * @param integer     $targetBatch Target batch number, or negative for a relative batch, 0 for all
	 * @param string|null $group
	 *
	 * @return mixed Current batch number on success, FALSE on failure or no migrations are found
	 * @throws ConfigException
	 */
	public function regress(int $targetBatch = 0, string $group = null)
	{
		if (! $this->enabled)
		{
			throw ConfigException::forDisabledMigrations();
		}

		// Set database group if not null
		if (! is_null($group))
		{
			$this->setGroup($group);
		}

		$this->ensureTable();

		// Get all the batches
		$batches = $this->getBatches();

		// Convert a relative batch to its absolute
		if ($targetBatch < 0)
		{
			$targetBatch = $batches[count($batches) - 1 + $targetBatch] ?? 0;
		}

		// If the goal was rollback then check if it is done
		if (empty($batches) && $targetBatch === 0)
		{
			return true;
		}

		// Make sure $targetBatch is found
		if ($targetBatch !== 0 && ! in_array($targetBatch, $batches))
		{
			$message = lang('Migrations.batchNotFound') . $targetBatch;

			if ($this->silent)
			{
				$this->cliMessages[] = "\t" . CLI::color($message, 'red');
				return false;
			}
			throw new \RuntimeException($message);
		}

		// Save the namespace to restore it after loading migrations
		$tmpNamespace = $this->namespace;

		// Get all migrations
		$this->namespace = null;
		$allMigrations   = $this->findMigrations();

		// Gather migrations down through each batch until reaching the target
		$migrations = [];
		while ($batch = array_pop($batches))
		{
			// Check if reached target
			if ($batch <= $targetBatch)
			{
				break;
			}

			// Get the migrations from each history
			foreach ($this->getBatchHistory($batch, 'desc') as $history)
			{
				// Create a UID from the history to match its migration
				$uid = $this->getObjectUid($history);

				// Make sure the migration is still available
				if (! isset($allMigrations[$uid]))
				{
					$message = lang('Migrations.gap') . ' ' . $history->version;

					if ($this->silent)
					{
						$this->cliMessages[] = "\t" . CLI::color($message, 'red');
						return false;
					}
					throw new \RuntimeException($message);
				}

				// Add the history and put it on the list
				$migration          = $allMigrations[$uid];
				$migration->history = $history;
				$migrations[]       = $migration;
			}
		}

		// Run each migration
		foreach ($migrations as $migration)
		{
			if ($this->migrate('down', $migration))
			{
				$this->removeHistory($migration->history);
			}
			// If a migration failed then quit so as not to ruin the whole batch
			else
			{
				$message = lang('Migrations.generalFault');

				if ($this->silent)
				{
					$this->cliMessages[] = "\t" . CLI::color($message, 'red');
					return false;
				}
				throw new \RuntimeException($message);
			}
		}

		// Restore the namespace
		$this->namespace = $tmpNamespace;

		return true;
	}

	//--------------------------------------------------------------------

	/**
	 * Migrate a single file regardless of order or batches.
	 * Method "up" or "down" determined by presence in history.
	 * NOTE: This is not recommended and provided mostly for testing.
	 *
	 * @param string      $path  Full path to a valid migration file
	 * @param string      $path  Namespace of the target migration
	 * @param string|null $group
	 */
	public function force(string $path, string $namespace, string $group = null)
	{
		if (! $this->enabled)
		{
			throw ConfigException::forDisabledMigrations();
		}

		$this->ensureTable();

		// Set database group if not null
		if (! is_null($group))
		{
			$this->groupFilter = $group;
			$this->setGroup($group);
		}

		// Create and validate the migration
		$migration = $this->migrationFromFile($path, $namespace);
		if (empty($migration))
		{
			$message = lang('Migrations.notFound');

			if ($this->silent)
			{
				$this->cliMessages[] = "\t" . CLI::color($message, 'red');
				return false;
			}
			throw new \RuntimeException($message);
		}

		// Check the history for a match
		$method = 'up';
		$this->setNamespace($migration->namespace);
		foreach ($this->getHistory($this->group) as $history)
		{
			if ($this->getObjectUid($history) === $migration->uid)
			{
				$method             = 'down';
				$migration->history = $history;
				break;
			}
		}

		// up
		if ($method === 'up')
		{
			// Start a new batch
			$batch = $this->getLastBatch() + 1;

			if ($this->migrate('up', $migration) && $this->groupSkip === false)
			{
				$this->addHistory($migration, $batch);
				return true;
			}

			$this->groupSkip = false;
		}

		// down
		elseif ($this->migrate('down', $migration))
		{
			$this->removeHistory($migration->history);
			return true;
		}

		// If it came this far the migration failed
		$message = lang('Migrations.generalFault');

		if ($this->silent)
		{
			$this->cliMessages[] = "\t" . CLI::color($message, 'red');
			return false;
		}
		throw new \RuntimeException($message);
	}

	//--------------------------------------------------------------------

	/**
	 * Retrieves list of available migration scripts
	 *
	 * @return array    List of all located migrations by their UID
	 */
	public function findMigrations(): array
	{
		// If a namespace is set then use it, otherwise load all namespaces from the autoloader
		$namespaces = $this->namespace ? [$this->namespace] : array_keys(Services::autoloader()->getNamespace());

		// Collect the migrations to run by their sortable UID
		$migrations = [];
		foreach ($namespaces as $namespace)
		{
			foreach ($this->findNamespaceMigrations($namespace) as $migration)
			{
				$migrations[$migration->uid] = $migration;
			}
		}

		// Sort migrations ascending by their UID (version)
		ksort($migrations);

		return $migrations;
	}

	//--------------------------------------------------------------------

	/**
	 * Retrieves a list of available migration scripts for one namespace
	 *
	 * @param string $namespace The namespace to search for migrations
	 *
	 * @return array    List of unsorted migrations from the namespace
	 */
	public function findNamespaceMigrations(string $namespace): array
	{
		$migrations = [];
		$locator    = Services::locator(true);

		// If $this->path contains a valid directory use it.
		if (! empty($this->path))
		{
			helper('filesystem');
			$dir   = rtrim($this->path, DIRECTORY_SEPARATOR) . '/';
			$files = get_filenames($dir, true);
		}
		// Otherwise use FileLocator to search files in the subdirectory of the namespace
		else
		{
			$files = $locator->listNamespaceFiles($namespace, '/Database/Migrations/');
		}

		// Load all *_*.php files in the migrations path
		// We can't use glob if we want it to be testable....
		foreach ($files as $file)
		{
			// Clean up the file path
			$file = empty($this->path) ? $file : $this->path . str_replace($this->path, '', $file);

			// Create the migration object from the file and save it
			if ($migration = $this->migrationFromFile($file, $namespace))
			{
				$migrations[] = $migration;
			}
		}

		return $migrations;
	}

	//--------------------------------------------------------------------

	/**
	 * Create a migration object from a file path.
	 *
	 * @param string $path The path to the file
	 * @param string $path The namespace of the target migration
	 *
	 * @return object|false    Returns the migration object, or false on failure
	 */
	protected function migrationFromFile(string $path, string $namespace)
	{
		if (substr($path, -4) !== '.php')
		{
			return false;
		}

		// Remove the extension
		$name = basename($path, '.php');

		// Filter out non-migration files
		if (! preg_match($this->regex, $name))
		{
			return false;
		}

		$locator = Services::locator(true);

		// Create migration object using stdClass
		$migration = new \stdClass();

		// Get migration version number
		$migration->version   = $this->getMigrationNumber($name);
		$migration->name      = $this->getMigrationName($name);
		$migration->path      = $path;
		$migration->class     = $locator->getClassname($path);
		$migration->namespace = $namespace;
		$migration->uid       = $this->getObjectUid($migration);

		return $migration;
	}

	//--------------------------------------------------------------------

	/**
	 * Set namespace.
	 * Allows other scripts to modify on the fly as needed.
	 *
	 * @param string $namespace or null for "all"
	 *
	 * @return MigrationRunner
	 */
	public function setNamespace(?string $namespace)
	{
		$this->namespace = $namespace;

		return $this;
	}

	//--------------------------------------------------------------------

	/**
	 * Set database Group.
	 * Allows other scripts to modify on the fly as needed.
	 *
	 * @param string $group
	 *
	 * @return MigrationRunner
	 */
	public function setGroup(string $group)
	{
		$this->group = $group;

		return $this;
	}

	//--------------------------------------------------------------------

	/**
	 * Set migration Name.
	 *
	 * @param string $name
	 *
	 * @return \CodeIgniter\Database\MigrationRunner
	 */
	public function setName(string $name)
	{
		$this->name = $name;

		return $this;
	}

	//--------------------------------------------------------------------

	/**
	 * If $silent == true, then will not throw exceptions and will
	 * attempt to continue gracefully.
	 *
	 * @param boolean $silent
	 *
	 * @return MigrationRunner
	 */
	public function setSilent(bool $silent)
	{
		$this->silent = $silent;

		return $this;
	}

	//--------------------------------------------------------------------

	/**
	 * Extracts the migration number from a filename
	 *
	 * @param string $migration
	 *
	 * @return string    Numeric portion of a migration filename
	 */
	protected function getMigrationNumber(string $migration): string
	{
		preg_match('/^\d{4}[_-]?\d{2}[_-]?\d{2}[_-]?\d{6}/', $migration, $matches);

		return count($matches) ? $matches[0] : '0';
	}

	//--------------------------------------------------------------------

	/**
	 * Extracts the migration class name from a filename
	 *
	 * @param string $migration
	 *
	 * @return string    text portion of a migration filename
	 */
	protected function getMigrationName(string $migration): string
	{
		$parts = explode('_', $migration);
		array_shift($parts);

		return implode('_', $parts);
	}

	//--------------------------------------------------------------------

	/**
	 * Uses the non-repeatable portions of a migration or history
	 * to create a sortable unique key
	 *
	 * @param object $migration or $history
	 *
	 * @return string
	 */
	public function getObjectUid($object): string
	{
		return preg_replace('/[^0-9]/', '', $object->version) . $object->class;
	}

	//--------------------------------------------------------------------

	/**
	 * Retrieves messages formatted for CLI output
	 *
	 * @return array    Current migration version
	 */
	public function getCliMessages(): array
	{
		return $this->cliMessages;
	}

	//--------------------------------------------------------------------

	/**
	 * Clears any CLI messages.
	 *
	 * @return MigrationRunner
	 */
	public function clearCliMessages()
	{
		$this->cliMessages = [];

		return $this;
	}

	//--------------------------------------------------------------------

	/**
	 * Truncates the history table.
	 *
	 * @return boolean
	 */
	public function clearHistory()
	{
		if ($this->db->tableExists($this->table))
		{
			$this->db->table($this->table)
					 ->truncate();
		}
	}

	//--------------------------------------------------------------------

	/**
	 * Add a history to the table.
	 *
	 * @param object  $migration
	 * @param integer $batch
	 *
	 * @return void
	 */
	protected function addHistory($migration, int $batch)
	{
		$this->db->table($this->table)
				 ->insert([
					 'version'   => $migration->version,
					 'class'     => $migration->class,
					 'group'     => $this->group,
					 'namespace' => $migration->namespace,
					 'time'      => time(),
					 'batch'     => $batch,
				 ]);

		if (is_cli())
		{
			$this->cliMessages[] = "\t" . CLI::color(lang('Migrations.added'),
					'yellow') . "($migration->namespace) " . $migration->version . '_' . $migration->class;
		}
	}

	//--------------------------------------------------------------------

	/**
	 * Removes a single history
	 *
	 * @param string $version
	 *
	 * @return void
	 */
	protected function removeHistory($history)
	{
		$this->db->table($this->table)->where('id', $history->id)->delete();

		if (is_cli())
		{
			$this->cliMessages[] = "\t" . CLI::color(lang('Migrations.removed'),
					'yellow') . "($history->namespace) " . $history->version . '_' . $this->getMigrationName($history->class);
		}
	}

	//--------------------------------------------------------------------

	/**
	 * Grabs the full migration history from the database for a group
	 *
	 * @param string $group
	 *
	 * @return array
	 */
	public function getHistory(string $group = 'default'): array
	{
		$this->ensureTable();

		$criteria = ['group' => $group];

		// If a namespace was specified then use it
		if ($this->namespace)
		{
			$criteria['namespace'] = $this->namespace;
		}

		$query = $this->db->table($this->table)
						  ->where($criteria)
						  ->orderBy('id', 'ASC')
						  ->get();

		return $query ? $query->getResultObject() : [];
	}

	//--------------------------------------------------------------------

	/**
	 * Returns the migration history for a single batch.
	 *
	 * @param integer $batch
	 *
	 * @return array
	 */
	public function getBatchHistory(int $batch, $order = 'asc'): array
	{
		$this->ensureTable();

		$query = $this->db->table($this->table)
						  ->where('batch', $batch)
						  ->orderBy('id', $order)
						  ->get();

		return $query ? $query->getResultObject() : [];
	}

	//--------------------------------------------------------------------

	/**
	 * Returns all the batches from the database history in order
	 *
	 * @return array
	 */
	public function getBatches(): array
	{
		$this->ensureTable();

		$batches = $this->db->table($this->table)
						  ->select('batch')
						  ->distinct()
						  ->orderBy('batch', 'asc')
						  ->get()
						  ->getResultArray();

		return array_column($batches, 'batch');
	}

	//--------------------------------------------------------------------

	/**
	 * Returns the value of the last batch in the database.
	 *
	 * @return integer
	 */
	public function getLastBatch(): int
	{
		$this->ensureTable();

		$batch = $this->db->table($this->table)
						  ->selectMax('batch')
						  ->get()
						  ->getResultObject();

		$batch = is_array($batch) && count($batch)
			? end($batch)->batch
			: 0;

		return (int)$batch;
	}

	//--------------------------------------------------------------------

	/**
	 * Returns the version number of the first migration for a batch.
	 * Mostly just for tests.
	 *
	 * @param integer $batch
	 *
	 * @return string
	 */
	public function getBatchStart(int $batch): string
	{
		// Convert a relative batch to its absolute
		if ($batch < 0)
		{
			$batches = $this->getBatches();
			$batch   = $batches[count($batches) - 1 + $targetBatch] ?? 0;
		}

		$migration = $this->db->table($this->table)
			->where('batch', $batch)
			->orderBy('id', 'asc')
			->limit(1)
			->get()
			->getResultObject();

		return count($migration) ? $migration[0]->version : '0';
	}

	//--------------------------------------------------------------------

	/**
	 * Returns the version number of the last migration for a batch.
	 * Mostly just for tests.
	 *
	 * @param integer $batch
	 *
	 * @return string
	 */
	public function getBatchEnd(int $batch): string
	{
		// Convert a relative batch to its absolute
		if ($batch < 0)
		{
			$batches = $this->getBatches();
			$batch   = $batches[count($batches) - 1 + $targetBatch] ?? 0;
		}

		$migration = $this->db->table($this->table)
			  ->where('batch', $batch)
			  ->orderBy('id', 'desc')
			  ->limit(1)
			  ->get()
			  ->getResultObject();

		return count($migration) ? $migration[0]->version : 0;
	}

	//--------------------------------------------------------------------

	/**
	 * Ensures that we have created our migrations table
	 * in the database.
	 */
	public function ensureTable()
	{
		if ($this->tableChecked || $this->db->tableExists($this->table))
		{
			return;
		}

		$forge = \Config\Database::forge($this->db);

		$forge->addField([
			'id'        => [
				'type'           => 'BIGINT',
				'constraint'     => 20,
				'unsigned'       => true,
				'auto_increment' => true,
			],
			'version'   => [
				'type'       => 'VARCHAR',
				'constraint' => 255,
				'null'       => false,
			],
			'class'     => [
				'type' => 'TEXT',
				'null' => false,
			],
			'group'     => [
				'type'       => 'VARCHAR',
				'constraint' => 255,
				'null'       => false,
			],
			'namespace' => [
				'type'       => 'VARCHAR',
				'constraint' => 255,
				'null'       => false,
			],
			'time'      => [
				'type'       => 'INT',
				'constraint' => 11,
				'null'       => false,
			],
			'batch'     => [
				'type'       => 'INT',
				'constraint' => 11,
				'unsigned'   => true,
				'null'       => false,
			],
		]);

		$forge->addPrimaryKey('id');
		$forge->createTable($this->table, true);

		$this->tableChecked = true;
	}

	/**
	 * Handles the actual running of a migration.
	 *
	 * @param $direction   "up" or "down"
	 * @param $migration   The migration to run
	 *
	 * @return boolean
	 */
	protected function migrate($direction, $migration): bool
	{
		include_once $migration->path;

		$class = $migration->class;
		$this->setName($migration->name);

		// Validate the migration file structure
		if (! class_exists($class, false))
		{
			$message = sprintf(lang('Migrations.classNotFound'), $class);

			if ($this->silent)
			{
				$this->cliMessages[] = "\t" . CLI::color($message, 'red');
				return false;
			}
			throw new \RuntimeException($message);
		}

		// Initialize migration
		$instance = new $class();
		// Determine DBGroup to use
		$group = $instance->getDBGroup() ?? config('Database')->defaultGroup;

		// Skip tests db group when not running in testing environment
		if (ENVIRONMENT !== 'testing' && $group === 'tests' && $this->groupFilter !== 'tests')
		{
			// @codeCoverageIgnoreStart
			$this->groupSkip = true;
			return true;
			// @codeCoverageIgnoreEnd
		}

		// Skip migration if group filtering was set
		if ($direction === 'up' && ! is_null($this->groupFilter) && $this->groupFilter !== $group)
		{
			$this->groupSkip = true;
			return true;
		}

		$this->setGroup($group);

		if (! is_callable([$instance, $direction]))
		{
			$message = sprintf(lang('Migrations.missingMethod'), $direction);

			if ($this->silent)
			{
				$this->cliMessages[] = "\t" . CLI::color($message, 'red');
				return false;
			}
			throw new \RuntimeException($message);
		}

		$instance->{$direction}();

		return true;
	}
}

Commits for paulgoughbooks_old/trunk/system/Database/MigrationRunner.php

Diff revisions: vs.
Revision Author Commited Message
2 tporter picture tporter Tue 03 Nov, 2020 08:50:21 +0000

Migration of Paul Goughs Books site to Codeignitor 4