SQLiteMigrationManager.swift

Build Version License Platform Carthage compatible

SQLiteMigrationManager.swift 是一个用于 SQLite.swift 的 schema 管理系统。它的灵感主要来源于 FMDBMigrationManager

概念

SQLiteMigrationManager.swift 的工作原理是在数据库中引入一个 schema_migrations

CREATE TABLE "schema_migrations" (
  "version" INTEGER NOT NULL UNIQUE
);

schema_migrations 表中的每一行都对应一个已应用的 migration,并代表 schema 的一个唯一版本。该 schema 支持任何基于整数的版本控制方案,但建议您使用编码时间戳的整数。

用法

请查看示例项目

创建 Migrations 表

let db = try Connection("path/to/store.sqlite")

let manager = SQLiteMigrationManager(db: self.db)

if !manager.hasMigrationsTable() {
  try manager.createMigrationsTable()
}

创建 SQL 文件 Migrations

在您的 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 的文件名。 以下文件名是有效的

创建 Swift Migration

可以通过遵循 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()
}

检查 Schema 状态

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())")

安装

Swift Package Manager

SQLiteMigrationManager.swift 可以通过 Swift Package Manager 获得。 要安装它,请将以下依赖项添加到您的 Package.swift 文件中

.package(url: "https://github.com/garriguv/SQLiteMigrationManager.swift.git", from: "0.8.2")

CocoaPods

SQLiteMigrationManager.swift 可以通过 CocoaPods 获得。 要安装它,请将以下行添加到您的 Podfile

pod "SQLiteMigrationManager.swift"

Carthage

SQLiteMigrationManager.swift 可以通过 Carthage 获得。 要安装它,请将以下行添加到您的 Cartfile

github "garriguv/SQLiteMigrationManager.swift"

贡献

  1. Fork 它 ( https://github.com/garriguv/SQLiteMigrationManager.swift/fork )
  2. 安装开发依赖 (bin/setup)
  3. 创建您的 feature branch (git checkout -b my-new-feature)
  4. 提交您的更改 (git commit -am 'Add some feature')
  5. 推送到 branch (git push origin my-new-feature)
  6. 创建一个新的 Pull Request
  7. 你太棒了! 👍

作者

Vincent Garrigues, vincent@garriguv.io

许可证

SQLiteMigrationManager.swift 在 MIT 许可证下可用。 详情请参阅 LICENSE 文件。