adapter.php 26.4 KB
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 1065 1066 1067 1068 1069 1070 1071 1072
<?php

namespace Yoast\WP\Lib\Migrations;

use Exception;
use Yoast\WP\Lib\Model;

/**
 * Yoast migrations adapter class.
 */
class Adapter {

	/**
	 * The version of this adapter.
	 *
	 * @var string
	 */
	private $version = '1.0';

	/**
	 * Whether or not a transaction has been started.
	 *
	 * @var bool
	 */
	private $in_transaction = false;

	/**
	 * Returns the current database name.
	 *
	 * @return string
	 */
	public function get_database_name() {
		global $wpdb;

		return $wpdb->dbname;
	}

	/**
	 * Checks support for migrations.
	 *
	 * @return bool
	 */
	public function supports_migrations() {
		return true;
	}

	/**
	 * Returns all column native types.
	 *
	 * @return array
	 */
	public function native_database_types() {
		$types = [
			'primary_key'   => [
				'name'  => 'integer',
				'limit' => 11,
				'null'  => false,
			],
			'string'        => [
				'name'  => 'varchar',
				'limit' => 255,
			],
			'text'          => [ 'name' => 'text' ],
			'tinytext'      => [ 'name' => 'tinytext' ],
			'mediumtext'    => [ 'name' => 'mediumtext' ],
			'integer'       => [
				'name'  => 'int',
				'limit' => 11,
			],
			'tinyinteger'   => [ 'name' => 'tinyint' ],
			'smallinteger'  => [ 'name' => 'smallint' ],
			'mediuminteger' => [ 'name' => 'mediumint' ],
			'biginteger'    => [ 'name' => 'bigint' ],
			'float'         => [ 'name' => 'float' ],
			'decimal'       => [
				'name'      => 'decimal',
				'scale'     => 0,
				'precision' => 10,
			],
			'datetime'      => [ 'name' => 'datetime' ],
			'timestamp'     => [ 'name' => 'timestamp' ],
			'time'          => [ 'name' => 'time' ],
			'date'          => [ 'name' => 'date' ],
			'binary'        => [ 'name' => 'blob' ],
			'tinybinary'    => [ 'name' => 'tinyblob' ],
			'mediumbinary'  => [ 'name' => 'mediumblob' ],
			'longbinary'    => [ 'name' => 'longblob' ],
			'boolean'       => [
				'name'  => 'tinyint',
				'limit' => 1,
			],
			'enum'          => [
				'name'   => 'enum',
				'values' => [],
			],
			'uuid'          => [
				'name'  => 'char',
				'limit' => 36,
			],
			'char'          => [ 'name' => 'char' ],
		];

		return $types;
	}

	/**
	 * Checks if a table exists.
	 *
	 * @param string $table The table name.
	 *
	 * @return bool
	 */
	public function has_table( $table ) {
		return $this->table_exists( $table );
	}

	/**
	 * Allows overriding the hardcoded schema table name constant in case of parallel migrations.
	 *
	 * @return string
	 */
	public function get_schema_version_table_name() {
		return Model::get_table_name( 'migrations' );
	}

	/**
	 * Create the schema table, if necessary.
	 */
	public function create_schema_version_table() {
		if ( ! $this->has_table( $this->get_schema_version_table_name() ) ) {
			$t = $this->create_table( $this->get_schema_version_table_name() );
			$t->column( 'version', 'string', [ 'limit' => 191 ] );
			$t->finish();
			$this->add_index( $this->get_schema_version_table_name(), 'version', [ 'unique' => true ] );
		}
	}

	/**
	 * Starts a transaction.
	 */
	public function start_transaction() {
		if ( $this->in_transaction() === false ) {
			$this->begin_transaction();
		}
	}

	/**
	 * Commits a transaction.
	 */
	public function commit_transaction() {
		if ( $this->in_transaction() ) {
			$this->commit();
		}
	}

	/**
	 * Rollbacks a transaction.
	 */
	public function rollback_transaction() {
		if ( $this->in_transaction() ) {
			$this->rollback();
		}
	}

	/**
	 * Quotes a table name string.
	 *
	 * @param string $text Table name.
	 *
	 * @return string
	 */
	public function quote_table( $text ) {
		return '`' . $text . '`';
	}

	/**
	 * Return the SQL definition of a column.
	 *
	 * @param string     $column_name The column name.
	 * @param string     $type        The type of the column.
	 * @param array|null $options     Column options.
	 *
	 * @return string
	 */
	public function column_definition( $column_name, $type, $options = null ) {
		$col = new Column( $this, $column_name, $type, $options );

		return $col->__toString();
	}

	/**
	 * Checks if a database exists.
	 *
	 * @param string $database The database name.
	 *
	 * @return bool
	 */
	public function database_exists( $database ) {
		$ddl    = 'SHOW DATABASES';
		$result = $this->select_all( $ddl );
		if ( \count( $result ) === 0 ) {
			return false;
		}
		foreach ( $result as $dbrow ) {
			if ( $dbrow['Database'] === $database ) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Creates a database.
	 *
	 * @param string $db The database name.
	 *
	 * @return bool
	 */
	public function create_database( $db ) {
		if ( $this->database_exists( $db ) ) {
			return false;
		}
		$ddl    = \sprintf( 'CREATE DATABASE %s', $this->identifier( $db ) );
		$result = $this->query( $ddl );

		return $result === true;
	}

	/**
	 * Drops a database.
	 *
	 * @param string $db The database name.
	 *
	 * @return bool
	 */
	public function drop_database( $db ) {
		if ( ! $this->database_exists( $db ) ) {
			return false;
		}
		$ddl    = \sprintf( 'DROP DATABASE IF EXISTS %s', $this->identifier( $db ) );
		$result = $this->query( $ddl );

		return $result === true;
	}

	/**
	 * Checks if a table exists.
	 *
	 * @param string $table The table name.
	 *
	 * @return bool
	 */
	public function table_exists( $table ) {
		global $wpdb;

		// We need last error to be clear so we can check against it easily.
		$previous_last_error      = $wpdb->last_error;
		$previous_suppress_errors = $wpdb->suppress_errors;
		$wpdb->last_error         = '';
		$wpdb->suppress_errors    = true;

		$result = $wpdb->query( "SELECT * FROM $table LIMIT 1" );

		// Restore the last error, as this is not truly an error and we don't want to alarm people.
		$wpdb->last_error      = $previous_last_error;
		$wpdb->suppress_errors = $previous_suppress_errors;

		return $result !== false;
	}

	/**
	 * Wrapper to execute a query.
	 *
	 * @param string $query The query to run.
	 *
	 * @return bool
	 */
	public function execute( $query ) {
		return $this->query( $query );
	}

	/**
	 * Executes a query.
	 *
	 * @param string $query The query to run.
	 *
	 * @return bool Whether or not the query was performed succesfully.
	 */
	public function query( $query ) {
		global $wpdb;

		$query_type = $this->determine_query_type( $query );
		$data       = [];
		if ( $query_type === Constants::SQL_SELECT || $query_type === Constants::SQL_SHOW ) {
			$data = $wpdb->get_results( $query, ARRAY_A );
			if ( $data === false ) {
				return false;
			}

			return $data;
		}
		else {
			// INSERT, DELETE, etc...
			$result = $wpdb->query( $query );
			if ( $result === false ) {
				return false;
			}
			if ( $query_type === Constants::SQL_INSERT ) {
				return $wpdb->insert_id;
			}

			return true;
		}
	}

	/**
	 * Returns a single result for a query.
	 *
	 * @param string $query The query to run.
	 *
	 * @return array|false An associative array of the result.
	 */
	public function select_one( $query ) {
		global $wpdb;

		$query_type = $this->determine_query_type( $query );
		if ( $query_type === Constants::SQL_SELECT || $query_type === Constants::SQL_SHOW ) {
			$result = $wpdb->query( $query );
			if ( $result === false ) {
				return false;
			}

			return $wpdb->last_result[0];
		}

		return false;
	}

	/**
	 * Returns all results for a query.
	 *
	 * @param string $query The query to run.
	 *
	 * @return array An array of associative arrays.
	 */
	public function select_all( $query ) {
		return $this->query( $query );
	}

	/**
	 * Use this method for non-SELECT queries.
	 * Or anything where you dont necessarily expect a result string, e.g. DROPs, CREATEs, etc.
	 *
	 * @param string $ddl The query to run.
	 *
	 * @return bool
	 */
	public function execute_ddl( $ddl ) {
		return $this->query( $ddl );
	}

	/**
	 * Drops a table
	 *
	 * @param string $table The table name.
	 *
	 * @return bool Whether or not the table was succesfully dropped.
	 */
	public function drop_table( $table ) {
		$ddl = \sprintf( 'DROP TABLE IF EXISTS %s', $this->identifier( $table ) );
		return $this->query( $ddl );
	}

	/**
	 * Creates a table.
	 *
	 * @param string $table_name The table name.
	 * @param array  $options    The options.
	 *
	 * @return Table
	 */
	public function create_table( $table_name, $options = [] ) {
		return new Table( $this, $table_name, $options );
	}

	/**
	 * Escapes a string for usage in queries.
	 *
	 * @param string $text The string.
	 *
	 * @return string
	 */
	public function quote_string( $text ) {
		global $wpdb;

		return $wpdb->_escape( $text );
	}

	/**
	 * Returns a quoted string.
	 *
	 * @param string $text The string.
	 *
	 * @return string
	 */
	public function identifier( $text ) {
		return '`' . $text . '`';
	}

	/**
	 * Renames a table.
	 *
	 * @param string $name     The current table name.
	 * @param string $new_name The new table name.
	 *
	 * @return bool
	 */
	public function rename_table( $name, $new_name ) {
		if ( empty( $name ) || empty( $new_name ) ) {
			return false;
		}
		$sql = \sprintf( 'RENAME TABLE %s TO %s', $this->identifier( $name ), $this->identifier( $new_name ) );

		return $this->execute_ddl( $sql );
	}

	/**
	 * Adds a column.
	 *
	 * @param string $table_name  The table name.
	 * @param string $column_name The column name.
	 * @param string $type        The column type.
	 * @param array  $options     Column options.
	 *
	 * @return bool
	 */
	public function add_column( $table_name, $column_name, $type, $options = [] ) {
		if ( empty( $table_name ) || empty( $column_name ) || empty( $type ) ) {
			return false;
		}
		// Default types.
		if ( ! \array_key_exists( 'limit', $options ) ) {
			$options['limit'] = null;
		}
		if ( ! \array_key_exists( 'precision', $options ) ) {
			$options['precision'] = null;
		}
		if ( ! \array_key_exists( 'scale', $options ) ) {
			$options['scale'] = null;
		}
		$sql  = \sprintf( 'ALTER TABLE %s ADD `%s` %s', $this->identifier( $table_name ), $column_name, $this->type_to_sql( $type, $options ) );
		$sql .= $this->add_column_options( $type, $options );

		return $this->execute_ddl( $sql );
	}

	/**
	 * Drops a column.
	 *
	 * @param string $table_name  The table name.
	 * @param string $column_name The column name.
	 *
	 * @return bool
	 */
	public function remove_column( $table_name, $column_name ) {
		$sql = \sprintf( 'ALTER TABLE %s DROP COLUMN %s', $this->identifier( $table_name ), $this->identifier( $column_name ) );

		return $this->execute_ddl( $sql );
	}

	/**
	 * Renames a column.
	 *
	 * @param string $table_name      The table name.
	 * @param string $column_name     The column name.
	 * @param string $new_column_name The new column name.
	 *
	 * @return bool
	 */
	public function rename_column( $table_name, $column_name, $new_column_name ) {
		if ( empty( $table_name ) || empty( $column_name ) || empty( $new_column_name ) ) {
			return false;
		}
		$column_info  = $this->column_info( $table_name, $column_name );
		$current_type = $column_info['type'];
		$sql          = \sprintf( 'ALTER TABLE %s CHANGE %s %s %s', $this->identifier( $table_name ), $this->identifier( $column_name ), $this->identifier( $new_column_name ), $current_type );
		$sql         .= $this->add_column_options( $current_type, $column_info );

		return $this->execute_ddl( $sql );
	}

	/**
	 * Changes a column.
	 *
	 * @param string $table_name  The table name.
	 * @param string $column_name The column name.
	 * @param string $type        The column type.
	 * @param array  $options     Column options.
	 *
	 * @return bool
	 */
	public function change_column( $table_name, $column_name, $type, $options = [] ) {
		if ( empty( $table_name ) || empty( $column_name ) || empty( $type ) ) {
			return false;
		}
		$column_info = $this->column_info( $table_name, $column_name );
		// Default types.
		if ( ! \array_key_exists( 'limit', $options ) ) {
			$options['limit'] = null;
		}
		if ( ! \array_key_exists( 'precision', $options ) ) {
			$options['precision'] = null;
		}
		if ( ! \array_key_exists( 'scale', $options ) ) {
			$options['scale'] = null;
		}
		$sql  = \sprintf( 'ALTER TABLE `%s` CHANGE `%s` `%s` %s', $table_name, $column_name, $column_name, $this->type_to_sql( $type, $options ) );
		$sql .= $this->add_column_options( $type, $options );

		return $this->execute_ddl( $sql );
	}

	/**
	 * Returns the database information for a column.
	 *
	 * @param string $table  The table name.
	 * @param string $column The column name.
	 *
	 * @return array|null
	 */
	public function column_info( $table, $column ) {
		if ( empty( $table ) || empty( $column ) ) {
			return null;
		}

		try {
			$sql    = \sprintf( "SHOW FULL COLUMNS FROM %s LIKE '%s'", $this->identifier( $table ), $column );
			$result = $this->select_one( $sql );
			if ( \is_array( $result ) ) {
				$result = \array_change_key_case( $result, \CASE_LOWER );
			}

			return $result;
		} catch ( Exception $e ) {
			return null;
		}
	}

	/**
	 * Adds an index.
	 *
	 * @param string       $table_name  The table name.
	 * @param array|string $column_name The column name(s).
	 * @param array        $options     Index options.
	 *
	 * @return bool
	 */
	public function add_index( $table_name, $column_name, $options = [] ) {
		if ( empty( $table_name ) || empty( $column_name ) ) {
			return false;
		}
		// Unique index?
		if ( \is_array( $options ) && \array_key_exists( 'unique', $options ) && $options['unique'] === true ) {
			$unique = true;
		}
		else {
			$unique = false;
		}

		// Did the user specify an index name?
		if ( \is_array( $options ) && \array_key_exists( 'name', $options ) ) {
			$index_name = $options['name'];
		}
		else {
			$index_name = $this->get_index_name( $table_name, $column_name );
		}

		if ( \strlen( $index_name ) > Constants::MYSQL_MAX_IDENTIFIER_LENGTH ) {
			return false;
		}

		if ( ! \is_array( $column_name ) ) {
			$column_names = [ $column_name ];
		}
		else {
			$column_names = $column_name;
		}

		$cols = [];
		foreach ( $column_names as $name ) {
			$cols[] = $this->identifier( $name );
		}
		$sql = \sprintf(
			'CREATE %sINDEX %s ON %s(%s)',
			( $unique === true ) ? 'UNIQUE ' : '',
			$this->identifier( $index_name ),
			$this->identifier( $table_name ),
			\implode( ', ', $cols )
		);

		return $this->execute_ddl( $sql );
	}

	/**
	 * Drops an index.
	 *
	 * @param string       $table_name  The table name.
	 * @param array|string $column_name The column name(s).
	 * @param array        $options     Index options.
	 *
	 * @return bool
	 */
	public function remove_index( $table_name, $column_name, $options = [] ) {
		if ( empty( $table_name ) || empty( $column_name ) ) {
			return false;
		}
		// Did the user specify an index name?
		if ( \is_array( $options ) && \array_key_exists( 'name', $options ) ) {
			$index_name = $options['name'];
		}
		else {
			$index_name = $this->get_index_name( $table_name, $column_name );
		}

		$sql = \sprintf( 'DROP INDEX %s ON %s', $this->identifier( $index_name ), $this->identifier( $table_name ) );

		return $this->execute_ddl( $sql );
	}

	/**
	 * Adds timestamps.
	 *
	 * @param string $table_name          The table name.
	 * @param string $created_column_name Created at column name.
	 * @param string $updated_column_name Updated at column name.
	 *
	 * @return bool
	 */
	public function add_timestamps( $table_name, $created_column_name, $updated_column_name ) {
		if ( empty( $table_name ) || empty( $created_column_name ) || empty( $updated_column_name ) ) {
			return false;
		}
		$created_at = $this->add_column( $table_name, $created_column_name, 'datetime' );
		$updated_at = $this->add_column(
			$table_name,
			$updated_column_name,
			'timestamp',
			[
				'null'    => false,
				'default' => 'CURRENT_TIMESTAMP',
				'extra'   => 'ON UPDATE CURRENT_TIMESTAMP',
			]
		);

		return $created_at && $updated_at;
	}

	/**
	 * Removes timestamps.
	 *
	 * @param string $table_name          The table name.
	 * @param string $created_column_name Created at column name.
	 * @param string $updated_column_name Updated at column name.
	 *
	 * @return bool Whether or not the timestamps were removed.
	 */
	public function remove_timestamps( $table_name, $created_column_name, $updated_column_name ) {
		if ( empty( $table_name ) || empty( $created_column_name ) || empty( $updated_column_name ) ) {
			return false;
		}
		$updated_at = $this->remove_column( $table_name, $created_column_name );
		$created_at = $this->remove_column( $table_name, $updated_column_name );

		return $created_at && $updated_at;
	}

	/**
	 * Checks an index.
	 *
	 * @param string       $table_name  The table name.
	 * @param array|string $column_name The column name(s).
	 * @param array        $options     Index options.
	 *
	 * @return bool Whether or not the index exists.
	 */
	public function has_index( $table_name, $column_name, $options = [] ) {
		if ( empty( $table_name ) || empty( $column_name ) ) {
			return false;
		}
		// Did the user specify an index name?
		if ( \is_array( $options ) && \array_key_exists( 'name', $options ) ) {
			$index_name = $options['name'];
		}
		else {
			$index_name = $this->get_index_name( $table_name, $column_name );
		}
		$indexes = $this->indexes( $table_name );
		foreach ( $indexes as $idx ) {
			if ( $idx['name'] === $index_name ) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Returns all indexes of a table.
	 *
	 * @param string $table_name The table name.
	 *
	 * @return array
	 */
	public function indexes( $table_name ) {
		$sql     = \sprintf( 'SHOW KEYS FROM %s', $this->identifier( $table_name ) );
		$result  = $this->select_all( $sql );
		$indexes = [];
		foreach ( $result as $row ) {
			// Skip primary.
			if ( $row['Key_name'] === 'PRIMARY' ) {
				continue;
			}
			$indexes[] = [
				'name'   => $row['Key_name'],
				'unique' => (int) $row['Non_unique'] === 0,
			];
		}

		return $indexes;
	}

	/**
	 * Converts a type to sql. Default options:
	 * $limit = null, $precision = null, $scale = null
	 *
	 * @param string $type    The native type.
	 * @param array  $options The options.
	 *
	 * @return string The SQL type.
	 *
	 * @throws Exception If invalid arguments are supplied.
	 */
	public function type_to_sql( $type, $options = [] ) {
		$natives = $this->native_database_types();
		if ( ! \array_key_exists( $type, $natives ) ) {
			$error  = \sprintf( "Error:I dont know what column type of '%s' maps to for MySQL.", $type );
			$error .= "\nYou provided: {$type}\n";
			$error .= "Valid types are: \n";
			$types  = \array_keys( $natives );
			foreach ( $types as $t ) {
				if ( $t === 'primary_key' ) {
					continue;
				}
				$error .= "\t{$t}\n";
			}
			throw new Exception( $error );
		}
		$scale     = null;
		$precision = null;
		$limit     = null;
		if ( isset( $options['precision'] ) ) {
			$precision = $options['precision'];
		}
		if ( isset( $options['scale'] ) ) {
			$scale = $options['scale'];
		}
		if ( isset( $options['limit'] ) ) {
			$limit = $options['limit'];
		}
		if ( isset( $options['values'] ) ) {
			$values = $options['values'];
		}
		$native_type = $natives[ $type ];
		if ( \is_array( $native_type ) && \array_key_exists( 'name', $native_type ) ) {
			$column_type_sql = $native_type['name'];
		}
		else {
			return $native_type;
		}
		if ( $type === 'decimal' || $type === 'float' ) {
			// Ignore limit, use precison and scale.
			if ( $precision === null && \array_key_exists( 'precision', $native_type ) ) {
				$precision = $native_type['precision'];
			}
			if ( $scale === null && \array_key_exists( 'scale', $native_type ) ) {
				$scale = $native_type['scale'];
			}
			if ( $precision !== null ) {
				if ( \is_int( $scale ) ) {
					$column_type_sql .= \sprintf( '(%d, %d)', $precision, $scale );
				}
				else {
					$column_type_sql .= \sprintf( '(%d)', $precision );
				}
			}
			else {
				if ( $scale ) {
					throw new Exception( "Error adding $type column: precision cannot be empty if scale is specified" );
				}
			}
		}
		elseif ( $type === 'enum' ) {
			if ( empty( $values ) ) {
				throw new Exception( 'Error adding enum column: there must be at least one value defined' );
			}
			else {
				$column_type_sql .= \sprintf(
					"('%s')",
					\implode( "','", \array_map( [ $this, 'quote_string' ], $values ) )
				);
			}
		}
		// Not a decimal column.
		if ( $limit === null && \array_key_exists( 'limit', $native_type ) ) {
			$limit = $native_type['limit'];
		}
		if ( $limit ) {
			$column_type_sql .= \sprintf( '(%d)', $limit );
		}

		return $column_type_sql;
	}

	/**
	 * Adds column options.
	 *
	 * @param string $type    The native type.
	 * @param array  $options The options.
	 *
	 * @return string The SQL statement for the column options.
	 *
	 * @throws Exception If invalid arguments are supplied.
	 */
	public function add_column_options( $type, $options ) {
		$sql = '';
		if ( ! \is_array( $options ) ) {
			return $sql;
		}
		if ( \array_key_exists( 'unsigned', $options ) && $options['unsigned'] === true ) {
			$sql .= ' UNSIGNED';
		}
		if ( \array_key_exists( 'character', $options ) ) {
			$sql .= \sprintf( ' CHARACTER SET %s', $this->identifier( $options['character'] ) );
		}
		if ( \array_key_exists( 'collate', $options ) ) {
			$sql .= \sprintf( ' COLLATE %s', $this->identifier( $options['collate'] ) );
		}
		if ( \array_key_exists( 'auto_increment', $options ) && $options['auto_increment'] === true ) {
			$sql .= ' auto_increment';
		}
		if ( \array_key_exists( 'default', $options ) && $options['default'] !== null ) {
			if ( $this->is_sql_method_call( $options['default'] ) ) {
				throw new Exception( 'MySQL does not support function calls as default values, constants only.' );
			}
			if ( \is_int( $options['default'] ) ) {
				$default_format = '%d';
			}
			elseif ( \is_bool( $options['default'] ) ) {
				$default_format = "'%d'";
			}
			elseif ( $options['default'] === 'CURRENT_TIMESTAMP' ) {
				$default_format = '%s';
			}
			else {
				$default_format = "'%s'";
			}
			$default_value = \sprintf( $default_format, $options['default'] );
			$sql          .= \sprintf( ' DEFAULT %s', $default_value );
		}
		if ( \array_key_exists( 'null', $options ) ) {
			if ( $options['null'] === false || $options['null'] === 'NO' ) {
				$sql .= ' NOT NULL';
			}
			elseif ( $type === 'timestamp' ) {
				$sql .= ' NULL';
			}
		}
		if ( \array_key_exists( 'comment', $options ) ) {
			$sql .= \sprintf( " COMMENT '%s'", $this->quote_string( $options['comment'] ) );
		}
		if ( \array_key_exists( 'extra', $options ) ) {
			$sql .= \sprintf( ' %s', $this->quote_string( $options['extra'] ) );
		}
		if ( \array_key_exists( 'after', $options ) ) {
			$sql .= \sprintf( ' AFTER %s', $this->identifier( $options['after'] ) );
		}

		return $sql;
	}

	/**
	 * Returns a list of all versions that have been migrated.
	 *
	 * @return string[] The version numbers that have been migrated.
	 */
	public function get_migrated_versions() {
		$result = $this->select_all( \sprintf( 'SELECT version FROM %s', $this->get_schema_version_table_name() ) );
		return \array_column( $result, 'version' );
	}

	/**
	 * Adds a migrated version.
	 *
	 * @param string $version The version.
	 *
	 * @return bool Whether or not the version was succesfully set.
	 */
	public function add_version( $version ) {
		$sql = \sprintf( "INSERT INTO %s (version) VALUES ('%s')", $this->get_schema_version_table_name(), $version );

		return $this->execute_ddl( $sql );
	}

	/**
	 * Removes a migrated version.
	 *
	 * @param string $version The version.
	 *
	 * @return bool Whether or not the version was succesfully removed.
	 */
	public function remove_version( $version ) {
		$sql = \sprintf( "DELETE FROM %s WHERE version = '%s'", $this->get_schema_version_table_name(), $version );

		return $this->execute_ddl( $sql );
	}

	/**
	 * Returns a message displaying the current version
	 *
	 * @return string
	 */
	public function __toString() {
		return self::class . ', version ' . $this->version;
	}

	/**
	 * Returns an index name.
	 *
	 * @param string $table_name  The table name.
	 * @param string $column_name The column name.
	 *
	 * @return string The index name.
	 */
	private function get_index_name( $table_name, $column_name ) {
		$name = \preg_replace( '/\\W/', '_', $table_name );
		$name = \preg_replace( '/\\_{2,}/', '_', $name );
		// If the column parameter is an array then the user wants to create a multi-column index.
		if ( \is_array( $column_name ) ) {
			$column_str = \implode( '_and_', $column_name );
		}
		else {
			$column_str = $column_name;
		}
		$name .= \sprintf( '_%s', $column_str );
		return $name;
	}

	/**
	 * Returns the type of a query.
	 *
	 * @param string $query The query to run.
	 *
	 * @return int The query type.
	 */
	private function determine_query_type( $query ) {
		$query = \strtolower( \trim( $query ) );
		$match = [];
		\preg_match( '/^(\\w)*/i', $query, $match );
		$type = $match[0];
		switch ( $type ) {
			case 'select':
				return Constants::SQL_SELECT;
			case 'update':
				return Constants::SQL_UPDATE;
			case 'delete':
				return Constants::SQL_DELETE;
			case 'insert':
				return Constants::SQL_INSERT;
			case 'alter':
				return Constants::SQL_ALTER;
			case 'drop':
				return Constants::SQL_DROP;
			case 'create':
				return Constants::SQL_CREATE;
			case 'show':
				return Constants::SQL_SHOW;
			case 'rename':
				return Constants::SQL_RENAME;
			case 'set':
				return Constants::SQL_SET;
			default:
				return Constants::SQL_UNKNOWN_QUERY_TYPE;
		}
	}

	/**
	 * Detect whether or not the string represents a function call and if so
	 * do not wrap it in single-quotes, otherwise do wrap in single quotes.
	 *
	 * @param string $text The string.
	 *
	 * @return bool Whether or not it's a SQL function call.
	 */
	private function is_sql_method_call( $text ) {
		$text = \trim( $text );
		if ( \substr( $text, -2, 2 ) === '()' ) {
			return true;
		}
		return false;
	}

	/**
	 * Checks if a transaction is active.
	 *
	 * @return bool
	 */
	private function in_transaction() {
		return $this->in_transaction;
	}

	/**
	 * Starts a transaction.
	 *
	 * @return void
	 *
	 * @throws Exception If a transaction was already started.
	 */
	private function begin_transaction() {
		global $wpdb;

		if ( $this->in_transaction === true ) {
			throw new Exception( 'Transaction already started' );
		}
		$wpdb->query( 'START TRANSACTION' );
		$this->in_transaction = true;
	}

	/**
	 * Commits a transaction.
	 *
	 * @return void
	 *
	 * @throws Exception If no transaction was strated.
	 */
	private function commit() {
		global $wpdb;

		if ( $this->in_transaction === false ) {
			throw new Exception( 'Transaction not started' );
		}
		$wpdb->query( 'COMMIT' );
		$this->in_transaction = false;
	}

	/**
	 * Rollbacks a transaction.
	 *
	 * @return void
	 *
	 * @throws Exception If no transaction was started.
	 */
	private function rollback() {
		global $wpdb;

		if ( $this->in_transaction === false ) {
			throw new Exception( 'Transaction not started' );
		}
		$wpdb->query( 'ROLLBACK' );
		$this->in_transaction = false;
	}
}