I'm trying to figure out how to use UUIDs as primary keys and I'm close but am having trouble generating the UUIDs for inserts.
I use the following column definition in my migration
t.column("id", .text).notNull().defaults(sql: generateUuidSql())
where
static func generateUuidSql() -> String {
return "(lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6))))"
}
I also have
mutating func didInsert(with rowId: UUID, for _: UUID?) {
id = rowId
}
in the record's extension for MutablePersistableRecord
.
If I run this migration and open up the database in sqlite3 then I'm able to insert rows successfully. When I try to insert a record from GRDB though it includes the id
column in the insert statement with a value of null
and sqlite throws a not null constraint error.
Is there some way to customise which columns are used for the insert statement?
Alternatively, how might I populate the id
using a UUID()
column prior to insert? (I went looking for a willInsert
)