Search code examples
swiftvapor

Vapor fluent doesn't throw upon violating foreign key constraint


When I'm adding a model to the database using create, Vapor fluent doesn't throw an exception when one of the foreign keys is violated. It's also not inserted, the create function just returns as normal.

Is this the standard behavior of Vapor Fluent?

I'm using Vapor 3 with PostgreSQL.

This is my migration to add the foreign key constraints:

struct AddAddressForeignKeys: Migration {
    typealias Database = PostgreSQLDatabase

    static func prepare(on conn: PostgreSQLConnection) -> Future<Void> {
        return PostgreSQLDatabase.update(Address.self, on: conn) { builder in
            builder.reference(from: \.regionId, to: \CodeRegion.id)
            builder.reference(from: \.countryId, to: \CodeCountry.id)
        }
    }

    static func revert(on conn: PostgreSQLConnection) -> Future<Void> {
        return PostgreSQLDatabase.update(Address.self, on: conn) { builder in
            builder.deleteReference(from: \.regionId, to: \CodeRegion.id)
            builder.deleteReference(from: \.countryId, to: \CodeCountry.id)
        }
    }
}

Update: I've added enableReferences as mentioned in the answer of Jacob Relkin, but there's still no exception thrown. H

// Configure database
let config = PostgreSQLDatabaseConfig(hostname: "localhost", port: 5432, username: "postgres", database: "test", password: nil, transport: .cleartext)
let postgres = PostgreSQLDatabase(config: config)

// Register the configured database to the database config.
var databases = DatabasesConfig()
databases.add(database: postgres, as: .psql)
databases.enableReferences(on: .psql)
services.register(databases)

Solution

  • In order to enforce foreign key violations, you must call enableReferences(on:) on your DatabasesConfig when you set it up.