新版本的 PostgreSQL 中 IDENTITY 是否连续?

Dol*_*hin 0 postgresql identity

现在我serial在PostgreSQL 13中生成表主键,但是今天我发现ID跳跃并且ID空间有很大的间隙。会浪费很多ID。我阅读了文档,发现 PostgreSQL 有identity作为 SQL 标准生成的主键。我找到了在新版本的PostgreSQL中使用的建议identity,但我不知道ID是否连续。

在 PostgreSQL 13 中我应该怎么做才能获得没有间隙的主键 id?

在此输入图像描述

解决方案1:我尝试更改serialidentity这样:

BEGIN;
ALTER TABLE public.article ALTER id DROP DEFAULT; -- drop default

DROP SEQUENCE public.article_id_seq;              -- drop owned sequence

ALTER TABLE public.article 
-- ALTER clientid SET DATA TYPE int,              -- not needed: already int
   ALTER id ADD GENERATED ALWAYS AS IDENTITY (RESTART 2270886);
COMMIT;
Run Code Online (Sandbox Code Playgroud)

还是有差距。

解决方案 2:我尝试添加关于我的应用程序插入文章的 Redis 分发锁,如下所示:

def save_single(guid, pub_time, title, author, content, source, link):
    if content is not None and len(content) > 0:
        article = Article()
        article_content = ArticleContent()
        beta_parser = CnbetaParser()
        second_parsed_content = beta_parser.parse_cnbeta_content(content, link)
        article_content.article_content = second_parsed_content

        cover_image = None
        lock_identifier = None
        try:
            
            # cover_image = Utils.get_cover_image_url(self, content, link)
            lock_identifier = acquire_lock("article-save", 5, 5)
            article.save(title, guid, author, pub_time, article_content, link, source, cover_image)
        except Exception as e:
            logger.error("save article data error,rss:" + source.sub_url, e)
        finally:
            if lock_identifier is not None:
                release_lock("article-save", lock_identifier)
    else:
        logger.error("article content is null,title:" + title)
Run Code Online (Sandbox Code Playgroud)

还是有差距。

Erw*_*ter 6

这个词是IDENTITY,不是IDENTIFY。(我在你的问题中修复了它。)

IDENTITY列 ( )与旧列一样GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY基于 a 。您必须预料到序列号中可能存在间隙,这是它们的本质,无需担心。SEQUENCEserial

我在 stackexchange 上的回答中解决了差异(您显然找到了将您的代码转换serialIDENTITY列的代码):

但我并没有建议转换会消除 ID 空间中的间隙。或者说这是可取的。如果您确实认为需要这样做,请考虑:

它以类似的免责声明开头,就像您在评论中收到的那样(以及一些替代方案):

首先,序列中存在间隙是可以预料的。问问自己是否真的需要删除它们。[...]