Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
解决写入分区表时
ON CONFLICT(key)
找不到key的问题。相关issue
思路是用
on conflict on constraint <constraint_name>
来代替on conflict(<field_name>)
。获取constraint名称的方法是查询pg_indexes,因为PG在建立唯一约束时会自动建立同名唯一索引,所以从pg_indexes可以查出对应的约束名称。用以下sql取名称字典序第一的约束:
用户需要确保要用的唯一约束在上述sql执行结果中排第一,这与历史版本的sql里先按照表名排序,再按照索引名排序取第一条的逻辑一致。
用户需要建立约束(constraint)而非索引(index)来确保唯一性,使用索引做唯一性约束时,上述sql查出来的是索引名称,同名的约束并不存在,所以执行
insert xxx on conflict on constraint <constraint_name> do xxx
会报找不到约束。而建立唯一约束时,pg会自动建立同名唯一索引,所以上述sql查出来的既是索引名称又是约束名称,就可以用这个索引名称找到对应的约束。