<?php
/**
 * Helper class for making a copy of the database, mostly for unit testing.
 *
 * @license GPL-2.0-or-later
 * @file
 * @ingroup Database
 */
use MediaWiki\MediaWikiServices;
use Wikimedia\Rdbms\IMaintainableDatabase;

class CloneDatabase {
	/** Table prefix for cloning */
	private string $newTablePrefix;

	/** Current table prefix */
	private string $oldTablePrefix;

	/** List of tables to be cloned */
	private array $tablesToClone;

	/** Should we DROP tables containing the new names? */
	private bool $dropCurrentTables;

	/** Whether to use temporary tables or not */
	private bool $useTemporaryTables = true;

	private IMaintainableDatabase $db;

	/**
	 * @param IMaintainableDatabase $db A database subclass
	 * @param array $tablesToClone An array of tables to clone, unprefixed
	 * @param string $newTablePrefix Prefix to assign to the tables
	 * @param string|null $oldTablePrefix Prefix on current tables, if not $wgDBprefix
	 * @param bool $dropCurrentTables
	 */
	public function __construct(
		IMaintainableDatabase $db,
		array $tablesToClone,
		string $newTablePrefix,
		?string $oldTablePrefix = null,
		bool $dropCurrentTables = true
	) {
		if ( !$tablesToClone ) {
			throw new InvalidArgumentException( 'Empty list of tables to clone' );
		}
		$this->db = $db;
		$this->tablesToClone = $tablesToClone;
		$this->newTablePrefix = $newTablePrefix;
		$this->oldTablePrefix = $oldTablePrefix ?? $this->db->tablePrefix();
		$this->dropCurrentTables = $dropCurrentTables;
	}

	/**
	 * Set whether to use temporary tables or not
	 * @param bool $u Use temporary tables when cloning the structure
	 */
	public function useTemporaryTables( bool $u = true ): void {
		$this->useTemporaryTables = $u;
	}

	public function cloneTableStructure(): void {
		global $wgSharedTables, $wgSharedDB;
		foreach ( $this->tablesToClone as $tbl ) {
			if ( $wgSharedDB && in_array( $tbl, $wgSharedTables, true ) ) {
				// Shared tables don't work properly when cloning due to
				// how prefixes are handled (T67654)
				throw new RuntimeException( "Cannot clone shared table $tbl." );
			}
			# Clean up from previous aborted run.  So that table escaping
			# works correctly across DB engines, we need to change the pre-
			# fix back and forth so tableName() works right.

			$this->db->tablePrefix( $this->oldTablePrefix );
			$oldTableName = $this->db->tableName( $tbl, 'raw' );

			$this->db->tablePrefix( $this->newTablePrefix );
			$newTableName = $this->db->tableName( $tbl, 'raw' );

			// Postgres: Temp tables are automatically deleted upon end of session
			//           Same Temp table name hides existing table for current session
			if ( $this->dropCurrentTables ) {
				if ( $oldTableName === $newTableName ) {
					// Last ditch check to avoid data loss
					throw new LogicException( "Not dropping new table, as '$newTableName'"
						. " is name of both the old and the new table." );
				}
				$this->db->dropTable( $tbl, __METHOD__ );
				// Dropping the oldTable because the prefix was changed
			}

			# Create new table
			$this->db->duplicateTableStructure(
				$oldTableName, $newTableName, $this->useTemporaryTables, __METHOD__ );
		}
	}

	/**
	 * Change the prefix back to the original.
	 * @param bool $dropTables Optionally drop the tables we created
	 */
	public function destroy( bool $dropTables = false ): void {
		if ( $dropTables ) {
			$this->db->tablePrefix( $this->newTablePrefix );
			foreach ( $this->tablesToClone as $tbl ) {
				$this->db->dropTable( $tbl, __METHOD__ );
			}
		}
		$this->db->tablePrefix( $this->oldTablePrefix );
	}

	/**
	 * Change the table prefix on all open DB connections
	 *
	 * @param string $prefix
	 * @return void
	 */
	public static function changePrefix( string $prefix ): void {
		global $wgDBprefix, $wgDBname;

		$lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
		$lbFactory->setLocalDomainPrefix( $prefix );

		$aliases = [
			$wgDBname => $lbFactory->getLocalDomainID()
		];
		$lbFactory->setDomainAliases( $aliases );
		foreach ( $lbFactory->getAllLBs() as $lb ) {
			$lb->setDomainAliases( $aliases );
		}

		$wgDBprefix = $prefix;
	}
}
