SQLiteMigrationManager.swift 是一个用于 SQLite.swift 的 schema 管理系统。它的灵感主要来源于 FMDBMigrationManager。
SQLiteMigrationManager.swift 的工作原理是在数据库中引入一个 schema_migrations
表
CREATE TABLE "schema_migrations" (
"version" INTEGER NOT NULL UNIQUE
);
schema_migrations
表中的每一行都对应一个已应用的 migration,并代表 schema 的一个唯一版本。该 schema 支持任何基于整数的版本控制方案,但建议您使用编码时间戳的整数。
请查看示例项目。
let db = try Connection("path/to/store.sqlite")
let manager = SQLiteMigrationManager(db: self.db)
if !manager.hasMigrationsTable() {
try manager.createMigrationsTable()
}
在您的 migration bundle 中创建一个 migration 文件
$ touch "`ruby -e "puts Time.now.strftime('%Y%m%d%H%M%S').to_i"`"_name.sql
SQLiteMigrationManager.swift 只会识别格式为 <version>_<name>.sql
的文件名。 以下文件名是有效的
1.sql
2_add_new_table.sql
3_add-new-table.sql
4_add new table.sql
可以通过遵循 Migration
协议来实现基于 Swift 的 migrations
import Foundation
import SQLiteMigrationManager
import SQLite
struct SwiftMigration: Migration {
var version: Int64 = 2016_01_19_13_12_06
func migrateDatabase(_ db: Connection) throws {
// perform the migration here
}
}
let db = try Connection("path/to/store.sqlite")
let manager = SQLiteMigrationManager(db: self.db, migrations: [ SwiftMigration() ], bundle: NSBundle.mainBundle())
if manager.needsMigration() {
try manager.migrateDatabase()
}
let db = try Connection("path/to/store.sqlite")
let manager = SQLiteMigrationManager(db: self.db, migrations: [ SwiftMigration() ], bundle: NSBundle.mainBundle())
print("hasMigrationsTable() \(manager.hasMigrationsTable())")
print("currentVersion() \(manager.currentVersion())")
print("originVersion() \(manager.originVersion())")
print("appliedVersions() \(manager.appliedVersions())")
print("pendingMigrations() \(manager.pendingMigrations())")
print("needsMigration() \(manager.needsMigration())")
SQLiteMigrationManager.swift 可以通过 Swift Package Manager 获得。 要安装它,请将以下依赖项添加到您的 Package.swift
文件中
.package(url: "https://github.com/garriguv/SQLiteMigrationManager.swift.git", from: "0.8.2")
SQLiteMigrationManager.swift 可以通过 CocoaPods 获得。 要安装它,请将以下行添加到您的 Podfile
中
pod "SQLiteMigrationManager.swift"
SQLiteMigrationManager.swift 可以通过 Carthage 获得。 要安装它,请将以下行添加到您的 Cartfile
中
github "garriguv/SQLiteMigrationManager.swift"
bin/setup
)git checkout -b my-new-feature
)git commit -am 'Add some feature'
)git push origin my-new-feature
)Vincent Garrigues, vincent@garriguv.io
SQLiteMigrationManager.swift 在 MIT 许可证下可用。 详情请参阅 LICENSE 文件。