Timestamps
If you’re like me, when you design a database model you want all tables to always include three key fields:
- createdAt: indicates when the record was created.
- updatedAt: reflects the last time it was updated.
- deletedAt: marks when it was logically deleted (without physically deleting the record).
Problem
As you can see, in each migration we have to manually write the three timestamp fields. This is not only repetitive, but also error-prone if we forget a field or misspell the data type.
try await db.schema(model)
.id()
.field(.name, .string, .required)
.field(.createdAt, .datetime, .required)
.field(.updatedAt, .datetime, .required)
.field(.deletedAt, .datetime)
.create()
Solution
The solution is to create a SchemaBuilder extension that adds a timestamps() method. This extension encapsulates the repetitive logic in one place, making the code cleaner and more maintainable.
extension SchemaBuilder {
func timestamps() -> Self {
self.field(.createdAt, .datetime, .required)
.field(.updatedAt, .datetime, .required)
.field(.deletedAt, .datetime)
}
}
Result
Now our migrations are much cleaner and more readable. By calling .timestamps() we add the three necessary fields. This reduces the possibility of errors and makes the code easier to maintain.
try await db.schema(model)
.id()
.field(.name, .string, .required)
.timestamps()
.create()
Keep coding, keep running 🏃♂️