Newer
Older
smart-home-server / server / SHServ / Migrations / Migration.php
<?php

namespace SHServ\Migrations;

/**
 * Base class for database migrations.
 * Each migration file extends this class and implements up() and down().
 */
abstract class Migration {

	/**
	 * Run the migration (apply changes).
	 */
	abstract public function up(): void;

	/**
	 * Reverse the migration (rollback changes).
	 */
	abstract public function down(): void;

	/**
	 * ThinBuilder instance for raw SQL queries.
	 *
	 * @return \Fury\Modules\ThinBuilder\ThinBuilder
	 */
	protected function tb(): \Fury\Modules\ThinBuilder\ThinBuilder {
		return app() -> thin_builder;
	}

	/**
	 * Execute a raw SQL query.
	 *
	 * @param string $sql
	 * @return \PDOStatement
	 */
	protected function query(string $sql): \PDOStatement {
		return $this -> tb() -> query($sql);
	}

	/**
	 * Check if a table exists.
	 *
	 * @param string $tablename
	 * @return bool
	 */
	protected function table_exists(string $tablename): bool {
		$result = $this -> tb() -> query(
			"SHOW TABLES LIKE '{$tablename}'",
			'fetch',
			\PDO::FETCH_NUM
		);
		return (bool) $result;
	}

	/**
	 * Drop a table if it exists.
	 *
	 * @param string $tablename
	 * @return void
	 */
	protected function drop_table_if_exists(string $tablename): void {
		$this -> query("DROP TABLE IF EXISTS `{$tablename}`");
	}
}