vapor/fluent-mysql-driver

A default database is required if no database ID is passed to User.query(_:on:)

Closed this issue · 2 comments

A default database is required if no database ID is passed to User.query(_:on:) or if User is being looked up statically.

I have a custom id User model like:

extension User: Model,Timestampable {
    public static var createdAtKey: CreatedAtKey {return \.createdAt }
    public static var updatedAtKey: UpdatedAtKey { return \.updatedAt}

    typealias Database = MySQLDatabase
    public typealias ID = String
    public static var idKey: IDKey{ return \.username }
}  

The error was sent by Xcode at run process immediately, in the controller I have

func usuarios(_ req: Request)  -> Future<[User]>{
        return req.withConnection(to: .eccdatabase , closure: { db -> Future<[User]> in
            return  db.query(User.self).all()
        })
    }  
0xTim commented

@zerausolrac what does your MigrationConfig look like?

@0xTim I posted here as it is, to solve it, you have to put User.defaultDatabase = .eccdatabase at the very beginning of configure func

import Vapor
import Authentication

extension DatabaseIdentifier {
    static var mysql: DatabaseIdentifier<MySQLDatabase> {
        return .init("eccmexico")
    }
}

/// Called before your application initializes.
///
/// [Learn More →](https://docs.vapor.codes/3.0/getting-started/structure/#configureswift)
public func configure(
    _ config: inout Config,
    _ env: inout Environment,
    _ services: inout Services
) throws {
    // Register providers first
   
  try services.register(FluentProvider())

    // Register routes to the router
    let router = EngineRouter.default()
    try routes(router)
    services.register(router, as: Router.self)
    
    //Configure MySQL
    var databaseConfig = DatabaseConfig()
    let username = "root"
    let password = "eccmexico"
    let database = "eccmexico"
    let db = MySQLDatabase(hostname: "127.0.0.1", user: username, password: password, database: database)
    databaseConfig.add(database: db, as: .eccdatabase)

    services.register(databaseConfig)
    
    try services.register(AuthenticationProvider())

    
    // Configure migrations
    var migrations = MigrationConfig()
    migrations.add(model: Todo.self, database: .eccdatabase)
    migrations.add(model: User.self, database: .eccdatabase)
    migrations.add(model: Token.self, database: .eccdatabase)
    services.register(migrations)
    
    // Configure the rest of your application here
    
    
}
extension DatabaseIdentifier{
    static var eccdatabase: DatabaseIdentifier<MySQLDatabase> {
        return .init("eccmexico")
    }
}