首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用GRDB改变随迁移的列类型?

如何用GRDB改变随迁移的列类型?
EN

Stack Overflow用户
提问于 2021-10-16 17:54:04
回答 1查看 578关注 0票数 0

我有两个表,其中UUID是它们的列的类型。

我希望将这些列转换为String,而不是UUID,因为调试非常困难(例如,使用DB浏览器为SQLite浏览sqlite文件需要我执行SQLite查询,只需将UUID对象转换为String以查看id值。

回到问题上,最实际的方法是什么?

我正在考虑,而且即将这样做,但我想先问一下:

UUIDs.

  • drop
  1. registerMigration中创建一个新表。
  2. 新表现在有字符串列。
  3. 循环遍历旧表的行,并将这些行移动到新表中,但确保ids现在位于String中,而不是将旧表

<代码>H 121重命名为旧表的名称。H 222G 223

代码语言:javascript
复制
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.
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-04 20:14:46

这个问题已经由GRDB作者在这里回答了:https://github.com/groue/GRDB.swift/issues/1077

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

代码语言:javascript
复制
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")
    }
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69598215

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档