Schemas and Namespaces

Jorge sitting programming thinking about Schemas and Spaces

Table of contents


Schema and Namespace

When defining a data model in Vapor, it’s possible to specify the schema, which corresponds to the table name in the database. However, to maintain an organized architecture, it’s recommended to group tables into different namespaces based on functional criteria, rather than concentrating them all in the default schema. This practice facilitates logical separation by domains or application modules.


Implementation

To assign a table to a specific namespace, you must override the static space property in the model. This property allows you to define the namespace where the table will reside, providing more granular organization of the 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() { }
}

Consideration

It’s essential to declare the space property as type String? (optional). If declared as String (non-optional), it won’t override the inherited property from the Model protocol, but will create a new property with the same name instead. This will cause the framework to ignore the namespace configuration, keeping the tables in the default schema without any apparent error indication.

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 🏃‍♂️