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

解决写入分区表时ON CONFLICT(key)找不到key的问题 #3

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

Snorlaxa
Copy link

@Snorlaxa Snorlaxa commented Mar 6, 2023

解决写入分区表时ON CONFLICT(key)找不到key的问题。
相关issue

思路是用on conflict on constraint <constraint_name>来代替on conflict(<field_name>)

获取constraint名称的方法是查询pg_indexes,因为PG在建立唯一约束时会自动建立同名唯一索引,所以从pg_indexes可以查出对应的约束名称。用以下sql取名称字典序第一的约束:

SELECT indexname FROM pg_indexes WHERE tablename = '{table}' order by indexname

用户需要确保要用的唯一约束在上述sql执行结果中排第一,这与历史版本的sql里先按照表名排序,再按照索引名排序取第一条的逻辑一致。

用户需要建立约束(constraint)而非索引(index)来确保唯一性,使用索引做唯一性约束时,上述sql查出来的是索引名称,同名的约束并不存在,所以执行insert xxx on conflict on constraint <constraint_name> do xxx会报找不到约束。
而建立唯一约束时,pg会自动建立同名唯一索引,所以上述sql查出来的既是索引名称又是约束名称,就可以用这个索引名称找到对应的约束。

@Snorlaxa Snorlaxa changed the title 使用唯一约束作为冲突条件 解决写入分区表时ON CONFLICT(key)找不到key的问题 Mar 6, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant