Create new row if table is empty. #318
Answered
by
mbrandonw
StewartLynch
asked this question in
Q&A
|
When my app launches, I want to be able to insert a new row into a table like Reminders if it is empty as you suggest as an exercise for the viewers in part 2 of the triggers section. But only when the table is empty. |
Answered by
mbrandonw
Dec 3, 2025
Replies: 1 comment 5 replies
|
Hi @StewartLynch, the simplest way would be to perform two queries in a single transaction: try await database.write { db in
guard try Property.fetchCount(db) == 0
else { return }
try Property.insert { Property.Draft(…) }
.execute(db)
}But it's also possible to do it as a single query using an "INSERT … SELECT … WHERE …", but honestly not sure it's worth the extra work when the above is already quite simple. |
5 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ah sorry, that is something that was added recently but has not yet been released (see #296). We will cut a 1.4 soon that will make it available, but until then you have to do: