短的
使用 將 git 修訂哈希 (SHA-1) 存盤f844cdc09651448d6c3e765fadac448253a16928到PostgreSQL資料庫 (> 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()
目前我git_sha1在資料庫中有一個欄位 as VARCHAR(40),但由于 git修訂哈希是一個十六進制字串,最好將字符限制為 [0-9a-f]。但是我覺得只為那個領域手動設定一個域并不舒服......我覺得它應該存在一種更好、更健壯的方式來做到這一點。
那么,是否存在這樣一種更好更優雅的方式來在PostgreSQL資料庫中寫入此類資料?
版本控制:
- Python 3.6.9(默認,2021 年 1 月 26 日,15:33:00)
- 版本 2.33.1
- psql (PostgreSQL) 12.4 (Ubuntu 12.4-1.pgdg18.04 1)
- Ubuntu 18.04(5.4.0-87-generic x86_64 GNU/Linux)
uj5u.com熱心網友回復:
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;
在 psycop2 中,或者您可以將其轉換為bytespsycop 會做正確的事情。
curs.execute(
sql,
vars = {
"git_sha1": bytes.fromhex(git_sha1)
}
)
請參閱psycop 檔案中的二進制改編。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/330980.html
標籤:蟒蛇-3.x PostgreSQL 混帐 psycopg2 沙1
