簡體   English   中英

為什么我的代碼在本地安裝和 GitHub 操作之間生成不同的 SQLite 文件?

[英]Why is my code producing a different SQLite file between my local installation and GitHub Action?

我有一個 Python 模塊來處理我的 SQLite 數據庫,這個模塊提供了兩個功能:

  • init_database()使用所有CREATE TABLE語句創建數據庫文件,如果數據庫尚不存在則執行。
  • upgrade_database()更新數據庫的架構( ALTER TABLE和其他更改),它在從我的程序的舊版本遷移時執行。

為了確保應用程序的這個關鍵部分按預期工作,我為 PyTest 編寫了一些測試,以檢查一旦執行這些功能,我們是否准確地獲得了一些內容。

我檢查 init 部分的測試如下所示:

def test_init_database():
    # PATH_DIRNAME is a constant with the path where the files are stored
    db_path = f"{PATH_DIRNAME}/files/database.db"

    if path.exists(db_path):
        # Delete the file if it exists (happens if the test has already been run)
        remove(db_path)

    get_db(db_path).init_database()

    with open(f"{PATH_DIRNAME}/files/database/database.sha256", "r") as file:
        # The file may contain a blank line at the end, we just take the first one
        # This is the hash sum we should get if the file is correctly generated
        expected_sum = file.read().split("\n")[0]

    with open(db_path, "rb") as file:
        # Compute the SHA-256 hash sum of the generated database file, and compare it
        assert hashlib.sha256(file.read()).hexdigest() == expected_sum

如果我在本地運行此測試,它會毫無問題地通過。 但是如果我在 GitHub Action 上運行它,斷言就會失敗,因為 hash 是不同的。 然后我配置了我的 GH Action 工作流程以將生成的文件上傳到一個工件中,這樣我就可以自己檢查它們,看起來在我的本地環境中生成的文件與在我的工作流程中生成的文件之間存在細微差別:

$ xxd gha_workflow/database.db > gha_workflow.hex
$ xxd local/database.db > local.hex
$ diff local.hex gha_workflow.hex
7c7
< 00000060: 002e 5f1d 0d0f f800 0a0b ac00 0f6a 0fc7  .._..........j..
---
> 00000060: 002e 5f1c 0d0f f800 0a0b ac00 0f6a 0fc7  .._..........j..

請注意,第四個字節不同( 1d1c )。

是什么導致了這種差異? 我做錯了嗎?

根據 sqlite 版本或構建選項,您生成的數據庫的格式可能會有所不同。 例如,版本和頁面大小可能會發生變化,這可能會改變數據庫的物理格式。 根據您要實現的目標,您可能想要嘗試與您的架構和內容的邏輯表示進行比較。

您可以查看這些文檔頁面以獲取有關文件格式和構建選項的更多信息:

根據評論中給出的建議,我認為我找到了一種更好的方法來測試我的數據庫模式,而不依賴於我的文件的元數據。

我沒有計算 SHA-256 總和,而是獲取表架構並將其與我希望查看數據庫格式是否正確的字段進行比較。

要獲取架構,SQLite 提供以下語法:

PRAGMA table_info('my_table');

我可以像任何常規 SQL 查詢一樣使用 Python 運行它,它會返回包含每個字段的元組列表:

  • position
  • 字段名稱
  • 字段類型
  • 如果可為空則為 0,否則為 1
  • 默認值(如果沒有則為None
  • 1 如果它是主鍵

感謝您幫助我理解我的錯誤!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM