<?php
/**
 * DbManager 添加链接、onQuery回调等基础操作
 * User: Tioncico
 * Date: 2019/10/22 0022
 * Time: 10:51
 */

namespace EasySwoole\ORM\Tests;


use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\ORM\Db\Config;
use EasySwoole\ORM\Db\Connection;
use EasySwoole\ORM\Db\Result;
use EasySwoole\ORM\DbManager;
use PHPUnit\Framework\TestCase;

class DbManagerTest extends TestCase
{

    /**
     * @var $connection Connection
     */
    protected $connection;

    function setUp(): void
    {
        parent::setUp(); // TODO: Change the autogenerated stub
        $config = new Config(MYSQL_CONFIG);
        $this->connection = new Connection($config);

        DbManager::getInstance()->addConnection($this->connection);
        $connection = DbManager::getInstance()->getConnection();
        $this->assertTrue($connection === $this->connection);

    }

    function testAddConnection()
    {
        $config = new Config(MYSQL_CONFIG);
        DbManager::getInstance()->addConnection(new Connection($config), 'test');

        $connection = DbManager::getInstance()->getConnection('test');
        $this->assertFalse($connection === $this->connection);
    }


    function testOnQuery()
    {
        DbManager::getInstance()->onQuery(function ($ret, $temp, $start) {
            $this->assertTrue($ret instanceof Result);
            $this->assertTrue($temp instanceof QueryBuilder);
            $this->assertIsFloat($start);
        });

        $queryBuild = new QueryBuilder();
        $queryBuild->raw("show tables");

        $data = DbManager::getInstance()->query($queryBuild);
        $this->assertTrue($data instanceof Result);
    }

    function testGetConnection()
    {
        $connection = DbManager::getInstance()->getConnection();

        $queryBuild = new QueryBuilder();
        $queryBuild->raw("show tables");
        $data = $connection->defer()->query($queryBuild);
        $this->assertTrue($data instanceof Result);
    }


    function testQuery()
    {
        $queryBuild = new QueryBuilder();
        $queryBuild->raw("show tables");
        $data = DbManager::getInstance()->query($queryBuild);
        $this->assertTrue($data instanceof Result);

    }

}