My Problem 🤔
When I define a data model in Vapor, I can specify the schema, which corresponds to the table name in the database. But keeping every table in the default schema doesn’t scale for me: to maintain an organized architecture, I want to group my tables into different namespaces by functional criteria instead of concentrating them all in one place. That way I get a logical separation by domain or application module.
My Solution 🧩
To assign a table to a specific namespace, I override the static space property on the model. This property lets me define the namespace where the table will reside, giving me a more granular organization of my database structure.
public final class LocationCityModel: Model {
public static let schema = "cities"
public static let space: String? = "location"
@ID() public var id: UUID?
@Field(.name) public var name: String
public init() { }
}
My Result 🎯
There’s one detail I had to get right: I must declare the space property as type String? (optional). When I declared it as String (non-optional), it didn’t override the property inherited from the Model protocol, but created a new property with the same name instead. That made the framework ignore my namespace configuration and keep the tables in the default schema, without any apparent error to warn me.
If you’re wondering how to create these namespaces automatically in the database, I explain how to turn that into a migration in Migrate Spaces.
Keep coding, keep running 🏃♂️