Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

修改pgsql兼容,在事务内,没有自增id返回时,因为sql报错,事务中止,不能提交,只能回滚 #593

Open
wants to merge 1 commit into
base: 3.0
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions src/db/connector/Pgsql.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace think\db\connector;

use PDO;
use think\db\BaseQuery;
use think\db\PDOConnection;

/**
Expand Down Expand Up @@ -108,4 +109,69 @@ protected function supportSavepoint(): bool
{
return true;
}

/**
* 插入记录.
*
* @param BaseQuery $query 查询对象
* @param bool $getLastInsID 返回自增主键
*
* @return mixed
*/
public function insert(BaseQuery $query, bool $getLastInsID = false)
{
// 分析查询表达式
$options = $query->parseOptions();

// 生成SQL语句
$sql = $this->builder->insert($query);

// 执行操作
$result = '' == $sql ? 0 : $this->pdoExecute($query, $sql);

if ($result) {
$sequence = $options['sequence'] ?? null;
$lastInsId = $getLastInsID ? $this->getLastInsID($query, $sequence) : null;

$data = $options['data'];

if ($lastInsId) {
$pk = $query->getAutoInc();
if ($pk) {
$data[$pk] = $lastInsId;
}
}

$query->setOption('data', $data);

$this->db->trigger('after_insert', $query);

if ($getLastInsID && $lastInsId) {
return $lastInsId;
}
}

return $result;
}

/**
* 获取最近插入的ID.
*
* @param BaseQuery $query 查询对象
* @param null|string $sequence 自增序列名
*
* @return mixed
*
* @throws \Exception
*/
public function getLastInsID(BaseQuery $query, ?string $sequence = null)
{
try {
$insertId = $this->linkID->lastInsertId($sequence);
} catch (\Exception $e) {
throw $e;
}

return $this->autoInsIDType($query, $insertId);
}
}