iOS应用GRDB迁移中如何将列默认值设为当前日期?
在GRDB迁移中设置日期列默认值为当前日期
要给新增的initialDate列设置默认值为当前日期,有两种常用实现方式,可根据需求选择:
方式一:利用SQL数据库原生函数(推荐)
直接使用SQLite的CURRENT_TIMESTAMP表达式作为默认值,数据库会自动为现有行填充当前日期,同时未来插入新行时也会自动使用当前时间作为默认值。GRDB支持通过SQL()包裹原生SQL表达式传入defaults(to:):
migrator.registerMigration("v7") { db in try db.alter(table: "DocAlertThirdPartyTrackingUrl") { t in t.add(column: DocAlertThirdPartyTrackingUrl.CodingKeys.initialDate.rawValue, .date) .defaults(to: SQL("CURRENT_TIMESTAMP")) } }
注:CURRENT_TIMESTAMP在SQLite中存储为ISO8601格式字符串,GRDB的.date类型会自动将其解析为Swift的Date对象,无需额外处理。默认生成的是UTC时间,这是存储日期的推荐做法。
方式二:手动控制迁移时的日期值
如果需要给所有现有行设置统一的当前时间(比如确保所有行用同一个时间戳,而非数据库逐行执行时的不同时间),可以分三步操作:
migrator.registerMigration("v7") { db in // 1. 先添加允许为空的日期列 try db.alter(table: "DocAlertThirdPartyTrackingUrl") { t in t.add(column: DocAlertThirdPartyTrackingUrl.CodingKeys.initialDate.rawValue, .date) } // 2. 给所有现有行设置当前日期 let currentDate = Date() try db.update(table: "DocAlertThirdPartyTrackingUrl") { t in t.set(DocAlertThirdPartyTrackingUrl.CodingKeys.initialDate.rawValue, to: currentDate) } // 3. 可选:设置列的默认值为当前日期,并改为非空约束(如果业务需要) try db.alter(table: "DocAlertThirdPartyTrackingUrl") { t in t.alter(column: DocAlertThirdPartyTrackingUrl.CodingKeys.initialDate.rawValue) .defaults(to: SQL("CURRENT_TIMESTAMP")) .notNull() } }
内容的提问来源于stack exchange,提问作者Rob Bonner
相关产品推荐
相关产品推荐

