sql - Golang pq sql 驱动程序 : get record ids after bulk import

标签 sql postgresql go

使用 golang 的 pq sql 驱动程序,我正在执行批量导入,如所述 in the pq docs .有什么办法可以获取已创建记录的 ID?

最佳答案

我假设您在 COPY 语句中引用的 id 列是基于由此类语句创建的串行生成序列:

CREATE SEQUENCE my_serial_name;

这意味着您可以像这样查询 id 的当前值:

SELECT currval('my_serial_name');

这将返回 id 计数器的当前值。

作为回答有关此方法的任何进一步疑问:

  • 这个语句是线程本地的并且完全隔离,
  • 上述声明证明此方法在多用户环境中有用,并且会产生正确的值,不会被其他插入查询修改使用此序列在表上执行

如需进一步阅读,请参阅说明以下内容的网址:

The sequence functions, listed in Table 9-42 (currval included), provide simple, multiuser-safe methods for obtaining successive sequence values from sequence objects.

https://www.postgresql.org/docs/9.3/static/functions-sequence.html

Because nextval and setval calls are never rolled back, sequence objects cannot be used if "gapless" assignment of sequence numbers is needed. It is possible to build gapless assignment by using exclusive locking of a table containing a counter; but this solution is much more expensive than sequence objects, especially if many transactions need sequence numbers concurrently.

https://www.postgresql.org/docs/9.5/static/sql-createsequence.html

To set the transaction isolation level of a transaction, use the command SET TRANSACTION.

Important: Some PostgreSQL data types and functions have special rules regarding transactional behavior. In particular, changes made to a sequence (and therefore the counter of a column declared using serial) are immediately visible to all other transactions and are not rolled back if the transaction that made the changes aborts. See Section 9.16 and Section 8.1.4.

https://www.postgresql.org/docs/9.5/static/transaction-iso.html

我希望这能回答您的问题。 Postgresql 是一个很棒的数据库,在细节上掌握后可以成为一个非常强大的工具。祝你好运! :D

关于sql - Golang pq sql 驱动程序 : get record ids after bulk import,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27835828/

相关文章:

sql - 忽略违反重复键索引的行的插入

sql - 按周过滤查询

sql - postgresql中选择查询的划分

sql - 我可以将 gorilla 模式与 sql.NullString 一起使用吗?

dictionary - 落在引用/指针上的类型断言

java - 使用java中的公钥实现进行RSA解密

sql - 获得每日错误的百分比

sql - Advantage 数据库、区分大小写和排序规则

sql - 如何 md5 所有列而不考虑类型

xml - liquibase数据库重构xml createIndex