【问题标题】:How to change column type with migration with GRDB Swift?如何使用 GRDB Swift 迁移更改列类型?
【发布时间】:2021-12-04 10:55:04
【问题描述】:

我有几个表,其列类型为 UUID

我想将这些列转换为String 而不是UUID,因为调试很麻烦(例如,使用 DB Browser for SQLite 浏览 sqlite 文件> 要求我执行 SQL 查询只是为了将 UUID 对象转换为 Strings 以​​查看 id 值。

回到这个问题,最实用的方法是什么?

我正在考虑,并且即将做,但我想先问这个:

  1. registerMigration 中,创建一个新表。
  2. 新表现在有字符串列。
  3. 循环遍历旧表中的行,并将这些行移动到新表中,但请确保 ID 现在位于 Strings 而不是 UUIDs 中。
  4. 删除旧表
  5. 将新表重命名为旧表的名称。
registerMigration("UUIDMigrationToString") { db in
      try db.create(table: "new_table") { table in
        table.autoIncrementedPrimaryKey("id")
        table.column("someIdStuff", .text).notNull()
      }

      // loop through the old table...
      // move the rows from the old table to the new table but with string Ids.
      // drop old table, and rename new table.
    }

【问题讨论】:

    标签: ios swift sqlite grdb


    【解决方案1】:

    GRDB 作者已在此处回答了此问题:https://github.com/groue/GRDB.swift/issues/1077

    但这是我基于该答案的解决方案,应该非常简单:

    import GRDB
    
    extension DatabaseMigrator {
      /**
       Migrate UUIDs to String
       
       References:
       
       - https://github.com/groue/GRDB.swift/issues/1077
       - https://stackoverflow.com/questions/69598215/how-to-change-column-type-with-migration-with-grdb-swift
       */
      mutating func v1_8() {
        migrateStream()
      }
      
      // MARK: - Stream
      
      mutating func migrateStream() {
        registerMigration("1.8 - Stream") { db in
          
          try db.create(table: "new_stream") { table in
            table.autoIncrementedPrimaryKey("id")
            table.column("contentId", .text).notNull()
            table.column("streamId", .text).notNull()
          }
          
          let rows = try Row.fetchCursor(db, sql: "SELECT * FROM stream")
          while let row = try rows.next() {
            try db.execute(
              sql: "INSERT INTO new_stream (id, contentId, streamId) VALUES (?, ?, ?)",
              arguments: [
                row["id"],
                (row["contentId"] as UUID).uuidString,
                (row["streamId"] as UUID).uuidString
              ])
          }
          
          try db.drop(table: "stream")
          try db.rename(table: "new_stream", to: "stream")
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2017-07-28
      • 2015-02-07
      • 1970-01-01
      • 2013-01-28
      • 2016-02-29
      • 2014-06-30
      • 2020-10-21
      • 2013-07-27
      相关资源
      最近更新 更多