ReplaceIntoTest.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace EasySwoole\ORM\Tests;
  3. use EasySwoole\ORM\Db\Config;
  4. use EasySwoole\ORM\Db\Connection;
  5. use EasySwoole\ORM\DbManager;
  6. use EasySwoole\ORM\Exception\Exception;
  7. use EasySwoole\ORM\Tests\models\TestUserModel;
  8. use PHPUnit\Framework\TestCase;
  9. class ReplaceIntoTest extends TestCase
  10. {
  11. /**
  12. * @var $connection Connection
  13. */
  14. protected $connection;
  15. protected $ids = [];
  16. protected function setUp(): void
  17. {
  18. parent::setUp(); // TODO: Change the autogenerated stub
  19. $config = new Config(MYSQL_CONFIG);
  20. $config->setReturnCollection(true);
  21. $this->connection = new Connection($config);
  22. DbManager::getInstance()->addConnection($this->connection);
  23. $connection = DbManager::getInstance()->getConnection();
  24. $this->assertTrue($connection === $this->connection);
  25. }
  26. public function testException()
  27. {
  28. $model = TestUserModel::create();
  29. $addTime = date('Y-m-d');
  30. $data = [
  31. 'name' => '史迪仔',
  32. 'age' => 21,
  33. 'addTime' => $addTime,
  34. 'state' => 1
  35. ];
  36. $id = $model->data($data)->save();
  37. $this->assertIsInt($id);
  38. $this->expectException(Exception::class);
  39. $this->expectExceptionMessage("SQLSTATE[23000] [1062] Duplicate entry '{$id}' for key 'PRIMARY' [INSERT INTO `test_user_model` (`name`, `age`, `addTime`, `state`, `id`) VALUES ('史迪仔', 21, '{$addTime}', 1, {$id})]");
  40. $model->data($data)->save();
  41. $this->fail('replace test exception error');
  42. }
  43. public function testReplaceInto()
  44. {
  45. TestUserModel::create()->destroy(null, true);
  46. $model = TestUserModel::create();
  47. $addTime = date('Y-m-d');
  48. $data = [
  49. 'name' => '史迪仔',
  50. 'age' => 21,
  51. 'addTime' => $addTime,
  52. 'state' => 1
  53. ];
  54. $id = $model->data($data)->save();
  55. $this->assertIsInt($id);
  56. $data['name'] = 'replace into';
  57. $model->data($data)->replace()->save();
  58. $sql = DbManager::getInstance()->getLastQuery()->getLastQuery();
  59. $this->assertEquals("REPLACE INTO `test_user_model` (`name`, `age`, `addTime`, `state`, `id`) VALUES ('replace into', 21, '{$addTime}', 1, {$id})", $sql);
  60. $ret = TestUserModel::create()->get($id);
  61. $this->assertEquals('replace into', $ret->name);
  62. }
  63. public function tearDown(): void
  64. {
  65. TestUserModel::create()->destroy(null, true);
  66. }
  67. }