feat: sqlite migration

This commit is contained in:
kaichaosun 2025-07-04 15:08:45 +08:00
parent 1dd9cd9ac8
commit 670b128c71
No known key found for this signature in database
GPG Key ID: 223E0F992F4F03BF
4 changed files with 60 additions and 1 deletions

9
.gitignore vendored
View File

@ -10,4 +10,11 @@ nimcache/
*.a
# OS
.DS_Store
.DS_Store
# Temporary files
*.db
# Compiled files
chat_sdk/*
!*.nim

View File

@ -16,3 +16,6 @@ task buildSharedLib, "Build shared library for C bindings":
task buildStaticLib, "Build static library for C bindings":
exec "nim c --app:staticLib --out:../library/c-bindings/libchatsdk.a chat_sdk/chat_sdk.nim"
task migrate, "Run database migrations":
exec "nim c -r chat_sdk/migration.nim"

40
chat_sdk/migration.nim Normal file
View File

@ -0,0 +1,40 @@
import os, osproc, sequtils, algorithm
import db_connector/db_sqlite
proc ensureMigrationTable(db: DbConn) =
db.exec(sql"""
CREATE TABLE IF NOT EXISTS schema_migrations (
filename TEXT PRIMARY KEY,
applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
proc hasMigrationRun(db: DbConn, filename: string): bool =
for row in db.fastRows(sql"SELECT 1 FROM schema_migrations WHERE filename = ?", filename):
return true
return false
proc markMigrationRun(db: DbConn, filename: string) =
db.exec(sql"INSERT INTO schema_migrations (filename) VALUES (?)", filename)
proc runMigrations*(db: DbConn, dir = "migrations") =
ensureMigrationTable(db)
let files = walkFiles(dir / "*.sql").toSeq().sorted()
for file in files:
if hasMigrationRun(db, file):
echo "Already applied: ", file
else:
echo "Applying: ", file
let sql = readFile(file)
db.exec(sql(sql))
markMigrationRun(db, file)
proc main() =
let db = open("test.db", "", "", "")
try:
runMigrations(db)
finally:
db.close()
when isMainModule:
main()

9
migrations/README.md Normal file
View File

@ -0,0 +1,9 @@
## Database Migrations
This directory contains SQL migration files for the Nim Chat SDK.
Each migration file should be named in the format `NNN_description.sql`, where `NNN` is a zero-padded number indicating the order of the migration. For example, `001_create_user_table.sql` is the first migration.
## Running Migrations
If you want to install a test sqlite database with tables setup, you can run `nimble migrate` from the command line. This will execute all migration files in order, ensuring that your database schema is up to date.