Skip to content

Commit

Permalink
Squashed 'src/db/' changes from c51130a..a61928c
Browse files Browse the repository at this point in the history
a61928c 修改更新和新增时,表名是Mysql关键字会报错的BUG (#204)
3bd24b2 Fix Travis Ci (#201)
0c4bcc6 表模型中存在下划线的字段名时,使用 Swoft\Helper\StringHelper::camel() 转换 (#191)
f4e7212 Features/db bug (#200)
ef53911 DbConnection::check时,验证闲置时间是否超过最大值 (#189)
805ab2c QueryBuilder根据Entity注解参数主动切换数据库 (#164)
00eee11 修改DB事务回滚BUG (#173)

git-subtree-dir: src/db
git-subtree-split: a61928c544093fbf6582b1d4bee7fc41b921e6aa
  • Loading branch information
swoft-bot committed Oct 6, 2018
1 parent 8bf7ea5 commit b506b71
Show file tree
Hide file tree
Showing 17 changed files with 372 additions and 16 deletions.
10 changes: 10 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,16 @@ before_install:
`alert` int(1) NOT NULL DEFAULT '0',
`desc` varchar(240) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `no_inc` (
`id` bigint(20) unsigned NOT NULL,
`name` varchar(32) NOT NULL DEFAULT "",
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `group` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(32) NOT NULL DEFAULT "",
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;'
- mysql -e 'CREATE DATABASE IF NOT EXISTS test2;
USE test2;
Expand Down
10 changes: 10 additions & 0 deletions src/AbstractDbConnection.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,14 @@ protected function pushSqlToStack(string $sql)

RequestContext::setContextDataByKey($contextSqlKey, $stack);
}

/**
* Verify whether the idle time exceeds the maximum value.
*/
protected function isIdleTimeOut(): bool
{
$idleTime = time() - $this->getLastTime();
$maxIdleTime = $this->getPool()->getPoolConfig()->getMaxIdleTime();
return $idleTime > $maxIdleTime;
}
}
6 changes: 5 additions & 1 deletion src/Driver/Mysql/MysqlConnection.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,12 +106,13 @@ public function execute(array $params = [])
public function receive()
{
$result = $this->connection->recv();
$this->recv = true;

if ($result === false) {
throw new MysqlException('Mysql recv error,connectError=' . $this->connection->connect_error . ' error=' . $this->connection->error);
}
$this->connection->setDefer(false);

$this->recv = true;
$this->result = $result;

return $result;
Expand Down Expand Up @@ -204,6 +205,9 @@ public function reconnect()
*/
public function check(): bool
{
if ($this->isIdleTimeOut()) {
return false;
}
return $this->connection->connected;
}

Expand Down
4 changes: 4 additions & 0 deletions src/Driver/Mysql/SyncMysqlConnection.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,10 @@ public function reconnect()
*/
public function check(): bool
{
if ($this->isIdleTimeOut()) {
return false;
}

try {
$this->connection->getAttribute(\PDO::ATTR_SERVER_INFO);
} catch (\Throwable $e) {
Expand Down
10 changes: 9 additions & 1 deletion src/Executor.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,16 @@ public static function save($entity): ResultInterface
// Set Primary Id to Entity
$query->addDecorator(function ($primaryId) use ($entity, $className) {
list(, , $idColumn) = self::getTable($className);
// When Primary Id is auto increment
$getter = 'get' . StringHelper::camel($idColumn, false);
$setter = 'set' . StringHelper::camel($idColumn, false);
method_exists($entity, $setter) && $entity->$setter($primaryId);
if (method_exists($entity, $getter) && method_exists($entity, $setter)) {
if ($entity->$getter() === null) {
$entity->$setter($primaryId);
} else {
$primaryId = $entity->$getter();
}
}
return $primaryId;
});
return $query->insert($fields);
Expand Down
13 changes: 12 additions & 1 deletion src/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -264,14 +264,25 @@ public function setAttrs(array $attrs)
* @param array $attributes
*
* $attributes = [
* 'name' => $value
* 'userName' => $value
* ]
* or
* $attributes = [
* 'UserName' => $value
* ]
* or
* $attributes = [
* 'user_name' => $value
* ]
*
* @return \Swoft\Db\Model
*/
public function fill(array $attributes): self
{
foreach ($attributes as $name => $value) {
if (1 === preg_match('/_/', $name)) {
$name = StringHelper::camel($name);
}
$methodName = sprintf('set%s', ucfirst($name));
if (method_exists($this, $methodName)) {
$this->$methodName($value);
Expand Down
2 changes: 2 additions & 0 deletions src/QueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -1242,6 +1242,8 @@ private function getTableNameByClassName($tableName): string
if (!isset($entities[$tableName]['table']['name'])) {
throw new DbException('Class is not an entity,className=' . $tableName);
}
// 选择数据库
$this->selectInstance($entities[$tableName]['instance']);

return $entities[$tableName]['table']['name'];
}
Expand Down
4 changes: 2 additions & 2 deletions src/Statement.php
Original file line number Diff line number Diff line change
Expand Up @@ -684,7 +684,7 @@ protected function getInsertString(): string

$statement .= $this->getInsert();
if (!empty($statement)) {
$statement = 'INSERT INTO ' . $statement;
$statement = sprintf('INSERT INTO `%s`', $statement);
}

return $statement;
Expand All @@ -708,7 +708,7 @@ protected function getUpdateString(): string
$statement .= ' ' . $this->getJoinString();
$statement = rtrim($statement);
if (!empty($statement)) {
$statement = 'UPDATE ' . $statement;
$statement = sprintf('UPDATE `%s`', $statement);
}

return $statement;
Expand Down
2 changes: 1 addition & 1 deletion src/Validator/BigintValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public function validate(string $column, $value, ...$params): bool
$min = '-9223372036854775808';
$max = '18446744073709551615';

if (!preg_match("/^-?[1-9][0-9]*$/", $value)) {
if (!preg_match("/^-?[0-9]+$/", $value)) {
throw new ValidatorException("数据库字段值验证失败,当前值 {$value} 不为有效整数,column={$column}");
}

Expand Down
26 changes: 26 additions & 0 deletions test/Cases/Mysql/BugTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use SwoftTest\Db\Cases\AbstractMysqlCase;
use SwoftTest\Db\Testing\Entity\Count;
use SwoftTest\Db\Testing\Entity\Keyword;
use SwoftTest\Db\Testing\Entity\NoInc;
use SwoftTest\Db\Testing\Entity\User;

/**
Expand Down Expand Up @@ -347,5 +348,30 @@ public function testListTypeByCo(int $uid)
});
}

public function testNoInc()
{
NoInc::query()->where('id',0)->delete()->getResult();

$entity = new NoInc();
$entity->setId(0);
$entity->setName('Agnes');
$id = $entity->save()->getResult();

$this->assertEquals(0,$id);
$entity = NoInc::findById(0)->getResult();
$this->assertEquals(0,$entity->getId());

NoInc::query()->where('id',123445)->delete()->getResult();

$entity = new NoInc();
$entity->setId(123445);
$entity->setName('limx');
$id = $entity->save()->getResult();

$this->assertEquals(123445,$id);
$entity = NoInc::findById(123445)->getResult();
$this->assertEquals(123445,$entity->getId());
}


}
20 changes: 16 additions & 4 deletions test/Cases/Mysql/QueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -162,12 +162,24 @@ public function testSelectinstance()
'description' => 'this my desc instance',
'age' => mt_rand(1, 100),
];
$userid = Query::table(User::class)->selectInstance('other')->insert($data)->getResult();
$userId = Query::table(User::class)->selectInstance('other')->insert($data)->getResult();
$data['description']='this my desc default instance';
$userId2 = Query::table(User::class)->insert($data)->getResult();

$user = OtherUser::findById($userid)->getResult();
$user2 = Query::table(User::class)->selectInstance('other')->where('id', $userid)->one()->getResult();
$user2 = Query::table(User::class)->selectInstance('other')->where('id', $userId)->one()->getResult();
$this->assertEquals($user2['description'], 'this my desc instance');
$this->assertEquals($user2['id'], $userid);
$this->assertEquals($user2['id'], $userId);

$otherUser = Query::table(OtherUser::class)->where('id', $userId)->one()->getResult();
$this->assertEquals($otherUser['age'], $data['age']);
$this->assertEquals($otherUser['id'], $userId);

$otherUser2 = Query::table(OtherUser::class)->selectInstance('default')->where('id', $userId2)->one()->getResult();
$this->assertEquals('this my desc default instance', $otherUser2['description']);

$user = OtherUser::findById($userId)->getResult();
$this->assertEquals($user->getAge(), $data['age']);
$this->assertEquals($user->getId(), $userId);
}

public function testSelectinstanceByCo()
Expand Down
64 changes: 58 additions & 6 deletions test/Cases/Mysql/SqlTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
namespace SwoftTest\Db\Cases\Mysql;

use Swoft\Db\Db;
use SwoftTest\Db\Testing\Entity\Group;
use SwoftTest\Db\Testing\Entity\User;
use SwoftTest\Db\Cases\AbstractMysqlCase;

Expand All @@ -20,14 +21,14 @@ class SqlTest extends AbstractMysqlCase
{
public function testInsert()
{
$name = 'swoft insert';
$name = 'swoft insert';
$result = Db::query('insert into user(name, sex,description, age) values("' . $name . '", 1, "xxxx", 99)')->getResult();
$user = User::findById($result)->getResult();
$user = User::findById($result)->getResult();

$this->assertEquals($user['name'], $name);

$result = Db::query('INSERT into user(name, sex,description, age) values("' . $name . '", 1, "xxxx", 99)')->getResult();
$user = User::findById($result)->getResult();
$user = User::findById($result)->getResult();
$this->assertEquals($user['name'], $name);
}

Expand Down Expand Up @@ -71,7 +72,7 @@ public function testSelectByCo($id)
*/
public function testSelect2($id)
{
$result = Db::query('select * from user where id=:id and name=:name', ['id' => $id, ':name'=>'name'])->getResult();
$result = Db::query('select * from user where id=:id and name=:name', ['id' => $id, ':name' => 'name'])->getResult();
$result2 = Db::query('select * from user where id=? and name=?', [$id, 'name'])->getResult();
$this->assertEquals($id, $result[0]['id']);
$this->assertEquals($id, $result2[0]['id']);
Expand Down Expand Up @@ -119,11 +120,11 @@ public function testDeleteByCo($id)
*/
public function testUpdate($id)
{
$name = 'update name1';
$name = 'update name1';
$result = Db::query('update user set name="' . $name . '" where id=' . $id)->getResult();
$this->assertEquals(1, $result);

$name = 'update name 协程框架';
$name = 'update name 协程框架';
$result = Db::query('UPDATE user set name="' . $name . '" where id=' . $id)->getResult();
$this->assertEquals(1, $result);

Expand All @@ -142,4 +143,55 @@ public function testUpdateByCo($id)
$this->testUpdate($id);
});
}

public function testErrorSql()
{
Db::beginTransaction();

try {
$user = new User();
$user->setName('limx');
$user->setSex(1);
$user->setAge(27);
$user->setDesc('Swoft');
$id = $user->save()->getResult();

$sql = 'SELECT des FROM `user` WHERE id = ?';
$res = Db::query($sql, [$id])->getResult();
$this->assertTrue(false);
Db::commit();
} catch (\Exception $ex) {
Db::rollback();

$user = User::findById($id)->getResult();
$this->assertNull($user);
}
}

public function testErrorSqlByCo()
{
go(function () {
$this->testErrorSql();
});
}

public function testTableNameIsDbKeyword()
{
$model = new Group();
$model->setName(uniqid());
$id = $model->save()->getResult();
$this->assertTrue($id > 0);

$model = Group::findById($id)->getResult();
$model->setName(uniqid());
$rows = $model->update()->getResult();
$this->assertEquals(1, $rows);
}

public function testTableNameIsDbKeywordByCo()
{
go(function () {
$this->testTableNameIsDbKeyword();
});
}
}
34 changes: 34 additions & 0 deletions test/Cases/PoolTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use SwoftTest\Db\Testing\Pool\DbPptPoolConfig;
use SwoftTest\Db\Testing\Pool\DbSlaveEnvPoolConfig;
use SwoftTest\Db\Testing\Pool\DbSlavePptConfig;
use SwoftTest\Db\Testing\Pool\OtherDbPool;

/**
* PoolTest
Expand Down Expand Up @@ -89,4 +90,37 @@ public function testDbSlaveEnv()
$this->assertEquals($pConfig->isUseProvider(), false);
$this->assertEquals($pConfig->getMaxWait(), 10);
}

public function testMaxIdleTime()
{
$pool = App::getPool('idle.master');
$connection = $pool->getConnection();
$this->assertTrue($connection->check());
$connection->release(true);
$connection2 = $pool->getConnection();
$this->assertTrue($connection2->check());
$connection2->release(true);
}

public function testMaxIdleTimeByCo()
{
go(function () {
$this->testMaxIdleTime();

$pool = App::getPool('idle.master');
$connection = $pool->getConnection();
$this->assertTrue($connection->check());
$connection->release(true);

\co::sleep(2);

$connection2 = $pool->getConnection();
$this->assertFalse($connection2->check());
$connection2->release(true);

$connection3 = $pool->getConnection();
$this->assertTrue($connection3->check());
$connection2->release(true);
});
}
}
Loading

0 comments on commit b506b71

Please sign in to comment.