how to build a vapor app from an already existing database?

851 views Asked by At

I have built a MySQL database with multiple tables and complex relationships, but when I go through the vapor documentation, specifically, in the building the model phase, there is a method for creating the table (that my model class will interact with).

static func prepare(_ database: Database) throws {
    try database.create("users") { users in
        users.id()
        users.string("name")
    }
}

However, I don't want to use it because the table that I already have contain foreign keys and types like DATETIME (which I don't know how to declare within the swift context.) is there a way to link my already built tables with vapor?

2

There are 2 answers

0
tobygriffin On BEST ANSWER

This is somewhere Vapor (or more correctly Fluent, which is the database level of Vapor) is a bit limited.

Yes, you can use your existing tables. In your prepare(_:) method, you can simply leave the implementation empty without creating a table at all. You should also leave revert(_:) empty as well.

In your init(node:in:) initialiser and makeNode(context:) method, you will need to map between the column names and types in your table and the property types in your Swift model.

0
Alex Andrews On

In the model object class (User here), the prepare method can be left unimplemented since we don't need to create the tables explicitly from the code. So should be like

static func prepare(_ database: Database) throws { 
   ...
}

But should add a static variable named entity which will map the table name in db without model class, like following

final class User: Model {
    static let entity = "users"
    ...
}

And finally, we should add the model to the droplet's preparations array with drop.preparations.append(User.self)

So that we can use any existing table in a database which has complex relationships, to map from a model object in Vapor.