Git 删除数据库操作指南,理解版本控制中的数据库管理

文章导读
结论:Git 不适合直接版本控制数据库文件,尤其是二进制文件如 SQLite 或大数据库 dump。推荐使用数据库迁移工具如 Flyway、Liquibase 或 Django migrations 来管理 schema 变更,而不是 git add 数据库文件。删除数据库操作时,先 git rm --cached database.db,然后 .gitignore 添加 *.db,commit
📋 目录
  1. 从 Stack Overflow 聚合
  2. 从 GitHub 博客
  3. 从 Medium 文章
  4. 从 CSDN 博客
  5. 从知乎讨论
  6. 从官方 Git 文档相关
A A

结论:Git 不适合直接版本控制数据库文件,尤其是二进制文件如 SQLite 或大数据库 dump。推荐使用数据库迁移工具如 Flyway、Liquibase 或 Django migrations 来管理 schema 变更,而不是 git add 数据库文件。删除数据库操作时,先 git rm --cached database.db,然后 .gitignore 添加 *.db,commit 后推送。理解:数据库变更应通过 SQL 脚本版本化,git 跟踪脚本而非数据。

从 Stack Overflow 聚合

You shouldn't version control database files with git. Databases are binary files and huge. Instead, version control your database schema and seed data with migration files. To remove: git rm --cached mydb.sqlitedb; echo 'mydb.sqlitedb' >> .gitignore; git add .gitignore; git commit -m "Remove database from tracking".

从 GitHub 博客

Never commit production databases to git. For development DBs, if accidentally committed: git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch path/to/database.db' --prune-empty --tag-name-filter cat -- --all; Then git for-each-ref --format='delete %(refname)' refs/original | git update-ref --stdin; git reflog expire --expire=now --all; git gc --prune=now.

从 Medium 文章

Understanding Git for DB management: Treat DB changes as code. Use tools like Sqitch for versioning DB changes. Git tracks the migration scripts (up.sql, down.sql). To delete accidental DB commit: git rm -r --cached .; git add .gitignore; git commit -m "Untrack database".

从 CSDN 博客

Git 删除数据库文件:如果已提交数据库文件,先本地删除文件 git rm database.db,然后 git commit -m "删除数据库文件"; 如果要从历史中完全移除,使用 git filter-repo --path database.db --invert-paths。注意备份!数据库管理中,git 只管 DDL 脚本,不碰数据文件。

Git 删除数据库操作指南,理解版本控制中的数据库管理

从知乎讨论

版本控制数据库的最佳实践:不要 git add *.db 或 dump.sql 大文件。使用 .gitignore 排除。删除已跟踪的:git rm --cached *.db; git commit -m "Ignore db files". 理解:Git 适合文本,数据库用专用工具管理变更历史。

从官方 Git 文档相关

To remove a file from git tracking but keep locally: git rm --cached filename. Add to .gitignore to prevent future adds. For large files like DB dumps, use Git LFS if necessary, but better avoid.

FAQ
Q: 为什么不能直接 git add 数据库文件?
A: 数据库文件大、二进制、变更频繁,会让仓库膨胀,clone 慢。
Q: 误提交数据库怎么彻底删除历史?
A: 用 git filter-branch 或 BFG Repo-Cleaner 重写历史,但会改变 commit hash,小心团队协作。
Q: 数据库管理推荐什么工具?
A: Alembic (Python)、Flyway (Java)、Liquibase,多语言支持。
Q: .gitignore 如何写数据库文件?
A: *.db *.sqlite *.sql.gz dump/*