Skip to content

Commit 2821642

Browse files
committed
修改pgsql兼容,在事务内,没有自增id返回时,因为sql报错,事务中止,不能提交,只能回滚
https://stackoverflow.com/a/22743521
1 parent 17005c9 commit 2821642

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

src/db/connector/Pgsql.php

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
namespace think\db\connector;
1313

1414
use PDO;
15+
use think\db\BaseQuery;
1516
use think\db\PDOConnection;
1617

1718
/**
@@ -108,4 +109,69 @@ protected function supportSavepoint(): bool
108109
{
109110
return true;
110111
}
112+
113+
/**
114+
* 插入记录.
115+
*
116+
* @param BaseQuery $query 查询对象
117+
* @param bool $getLastInsID 返回自增主键
118+
*
119+
* @return mixed
120+
*/
121+
public function insert(BaseQuery $query, bool $getLastInsID = false)
122+
{
123+
// 分析查询表达式
124+
$options = $query->parseOptions();
125+
126+
// 生成SQL语句
127+
$sql = $this->builder->insert($query);
128+
129+
// 执行操作
130+
$result = '' == $sql ? 0 : $this->pdoExecute($query, $sql);
131+
132+
if ($result) {
133+
$sequence = $options['sequence'] ?? null;
134+
$lastInsId = $getLastInsID ? $this->getLastInsID($query, $sequence) : null;
135+
136+
$data = $options['data'];
137+
138+
if ($lastInsId) {
139+
$pk = $query->getAutoInc();
140+
if ($pk) {
141+
$data[$pk] = $lastInsId;
142+
}
143+
}
144+
145+
$query->setOption('data', $data);
146+
147+
$this->db->trigger('after_insert', $query);
148+
149+
if ($getLastInsID && $lastInsId) {
150+
return $lastInsId;
151+
}
152+
}
153+
154+
return $result;
155+
}
156+
157+
/**
158+
* 获取最近插入的ID.
159+
*
160+
* @param BaseQuery $query 查询对象
161+
* @param null|string $sequence 自增序列名
162+
*
163+
* @return mixed
164+
*
165+
* @throws \Exception
166+
*/
167+
public function getLastInsID(BaseQuery $query, ?string $sequence = null)
168+
{
169+
try {
170+
$insertId = $this->linkID->lastInsertId($sequence);
171+
} catch (\Exception $e) {
172+
throw $e;
173+
}
174+
175+
return $this->autoInsIDType($query, $insertId);
176+
}
111177
}

0 commit comments

Comments
 (0)