vapor / fluent

Vapor ORM (queries, models, and relations) for NoSQL and SQL databases
https://docs.vapor.codes/4.0/fluent/overview/
MIT License
1.32k stars 172 forks source link

Question: How do I execute migration action? #678

Closed diuming closed 4 years ago

diuming commented 4 years ago

macOS 10.15.4 Vapor 4.0.3

I create a Vapor server without using toolbox. It's running very well.

I also read the migrate session of Fluent. To run migrations, call vapor run migrate from the command line or add migrate as an argument to Xcode's Run scheme. what does this mean add migrate as an argument to Xcode's Run scheme?

But, migration looks like nothing happen and my psql also. Could you give me some advice? thanks

Configure function

public func configure(_ app: Application) throws {
    app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))

    //  PostgreSQL
    app.databases.use(.postgres(hostname: "localhost",
                                username: "vapor",
                                password: "vapor",
                                database: "vapor"),
                      as: .psql)

    //  migration
    app.migrations.add(CreateUser())

    //  template engine Leaf
    app.views.use(.leaf)

    // register routes
    try routes(app)
}

User Model

final class User: Model {
    struct FieldKeys {
        static var name: FieldKey { "name" }
        static var email: FieldKey { "email" }
        static var password: FieldKey { "password" }
    }

    public static let schema = "users"
    @ID(key: .id) public var id: UUID?
    @Field(key: FieldKeys.name) public var name: String
    @Field(key: FieldKeys.email) public var email: String
    @Field(key: FieldKeys.password) public var password: String

    public init() {}

    public init(id: User.IDValue? = nil, name: String, email: String, password: String) {
        self.id = id
        self.name = name
        self.email = email
        self.password = password
    }
}

User Migration

struct CreateUser: Migration {
    func prepare(on database: Database) -> EventLoopFuture<Void> {
        return database.schema("users")
                .id()
                .field(User.FieldKeys.name, .string)
                .field(User.FieldKeys.email, .string)
                .field(User.FieldKeys.password, .string)
                .create()
    }

   func revert(on database: Database) -> EventLoopFuture<Void> {
        return database.schema("users").delete()
    }
}