<?

require_once ('DBTable.php');
require_once ('BasicEnum.php');

final class DBFactory extends DBTable
{

	/**
	 * Execute the input SQL directly
	 *
	 * @return affected rows number if executed successfully, otherwise return false
	 */
	public function execute($sql)
	{
		$this::$logger->debug("SQL: " . $sql);

		$stmt = sqlsrv_query( $this::$db->getInstance(), $sql );
		$rows_affected = sqlsrv_rows_affected( $stmt);
		if( $rows_affected === false) {
     	$this::$logger->error("Caught exception: " . print_r(sqlsrv_errors(), true));
		} elseif( $rows_affected == -1) {
      $rows_affected = 0;
		} else {
      $this::$logger->debug($rows_affected." rows were updated.");
		}
		return $rows_affected;
	}

	/**
	 * Inquiry data with input SQL directly
	 *
	 * @return array of inquiry rows
	 */
	public function query($sql)
	{
		$this::$logger->debug("SQL: " . $sql);

		$stmt = sqlsrv_query( $this::$db->getInstance(), $sql );
		if($stmt === false) {
			$this::$logger->error("Caught exception: " . print_r(sqlsrv_errors(), true));
		}
		$rows = array();
		while( $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
			array_push( $rows, $row );
		}

		sqlsrv_free_stmt( $stmt);
		return $rows;
	}
}
