使用 psycopg2 将 git 修订哈希 (SHA-1) 写入 PostgreSQL 数据库

s.k*_*s.k 4 git postgresql sha1 psycopg2 python-3.x

短的

将 git 修订哈希值 (SHA-1) 存储f844cdc09651448d6c3e765fadac448253a16928PostgreSQL数据库 (> v.11)中的最高效且有效的方法是什么psycopg2

详细信息和代码

我有一个 SHA-1 哈希作为 Python 中的十六进制字符串,我想将其存储在 PostgreSQL 数据库中:

import psycopg2
from subprocess import Popen, PIPE

psycopg2.__version__ # prints '2.9.1 (dt dec pq3 ext lo64)'

cmd_list = [ "git", "rev-parse", "HEAD", ]
process = Popen(cmd_list, stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
git_sha1 = stdout.decode('ascii').strip()

conn = psycopg.connect(**DB_PARAMETERS)
curs = conn.cursor()
sql = """UPDATE table SET git_sha1 = %(git_sha1)s WHERE id=1;"""

curs.execute(
    sql,
    vars = {
        "git_sha1": git_sha1
    }
)

conn.commit()
conn.close()
Run Code Online (Sandbox Code Playgroud)

目前我git_sha1在数据库中有一个字段为VARCHAR(40),但由于 git修订哈希是一个十六进制字符串,因此最好将字符限制为仅 [0-9a-f]。但我觉得只为该字段手动设置一个域不太舒服......我觉得应该存在一种更好、更强大的方法来做到这一点。

那么,是否存在一种更好、更优雅的方式在PostgreSQL数据库中写入此类数据呢?

版本控制:

  • Python 3.6.9(默认,2021 年 1 月 26 日,15:33:00)
  • git 版本 2.33.1
  • psql (PostgreSQL) 12.4 (Ubuntu 12.4-1.pgdg18.04+1)
  • Ubuntu 18.04(5.4.0-87-通用 x86_64 GNU/Linux)

Sch*_*ern 5

Git ID 是SHA-1 校验和。这些被表示为 40 个字符的十六进制字符串,但它们实际上是 20 个字节的数字。将它们存储为二进制数据:bytea. 这将使存储空间减少一半。

decode插入时为十六进制字符串,encode获取时返回十六进制。

create temporary table foo ( git_id bytea );

insert into foo (git_id) values 
  (
    decode('f844cdc09651448d6c3e765fadac448253a16928', 'hex')
  );

select encode(git_id, 'hex') from foo;
Run Code Online (Sandbox Code Playgroud)

在 psycop2 中,或者您可以将其转换为bytespsycop 会做正确的事情。

curs.execute(
    sql,
    vars = {
        "git_sha1": bytes.fromhex(git_sha1)
    }
)
Run Code Online (Sandbox Code Playgroud)

请参阅psycop 文档中的二进制适应。