gpt4 book ai didi

postgresql - 时间戳分辨率

转载 作者:行者123 更新时间:2023-11-29 11:40:32 25 4
gpt4 key购买 nike

我需要将时间戳类型设置为主键(在每种情况下它必须是唯一的,某些指令可以一次插入 k 条记录),默认值为“current_timestamp”。它是一种日志文件。为此,我应该将时间戳分辨率提高到微秒(我认为 pg 不可能在一秒内写入一百万条记录)。这种精度对于 postgres 是可能的。 See here它是这样的:

  CREATE TABLE upsistema
(
t timestamp(6) without time zone NOT NULL DEFAULT current_timestamp(6) without time zone,
blabla bigint,
foo bigint,
CONSTRAINT "XIDS3w" PRIMARY KEY (t)
)

但它不起作用。当我使用 pgAdmin3 检查时,它以毫秒精度写入。当然,在同一毫秒内写入更多记录也是可能的。那么,我是否需要设置一些神秘变量或其他东西,以便以微秒精度保存?

最佳答案

默认情况下,PostgreSQL 以尽可能高的精度存储时间戳。

如果我处在你的位置,我可能会为时间戳使用不同的默认值。 current_timestamp 的值是当前事务开始的时间。它在事务执行期间不会改变,无论您插入多少行,也无论花费多长时间。这意味着 INSERT 语句可能会因为重复的主键值而失败。

create table upsistema (
t timestamp without time zone primary key
default current_timestamp,
foo bigint
);
insert into upsistema (foo) values (42), (43), (44);
ERROR:  duplicate key value violates unique constraint "upsistema_pkey"

Try clock_timestamp() as the default instead. This doesn't guarantee success, but it does make it more likely.

create table upsistema (
t timestamp without time zone primary key
default clock_timestamp(),
foo bigint
);
insert into upsistema (foo) values (42), (43), (44);

select * from upsistema;
t                              foo--2014-11-19 19:17:23.369432     422014-11-19 19:17:23.36958      432014-11-19 19:17:23.369587     44

To absolutely guarantee success, either change the primary key constraint, or drop it altogether. Whether this makes sense is application-dependent, but I would not be surprised to find multiple clients logging data at the same microsecond.

Your table uses timestamp without time zone, but current_timestamp and clock_timestamp() return timestamp with time zone. It might be a good idea to change the time zone to UTC for your session before you run SQL statements.

set time zone 'UTC';
select ... ;

set time zone 'UTC';
insert ... ;

如果将服务器设置为默认使用UTC 有意义,您可以将postgresql.conf 中的timezone 参数设置为“UTC”。这样您就不必在每个 session 中都设置时区。

关于postgresql - 时间戳分辨率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27027112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com