当我使用Vapor与Mysql时,我的数据库不会自动生成表格

时间:2018-04-11 06:45:51

标签: mysql swift vapor

我的服务器可以打开,但我的数据库没有创建表用户,我不知道我的代码问题,我所做的只是根据蒸汽文件。

我在Config + Setup.swift中添加了准备和addProvider

日志:

The current hash key "0000000000000000" is not secure.
Update hash.key in Config/crypto.json before using in production.
Use `openssl rand -base64 <length>` to generate a random string.
The current cipher key "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" is not secure.
Update cipher.key in Config/crypto.json before using in production.
Use `openssl rand -base64 32` to generate a random string.
[2018-04-11 06:40:12 +0000] SELECT COUNT(*) as _fluent_aggregate FROM `fluent`
[2018-04-11 06:40:12 +0000] CREATE TABLE `fluent` (`id` INTEGER PRIMARY KEY NOT NULL, `name` TEXT NOT NULL, `batch` INTEGER NOT NULL, `created_at` TEXT NOT NULL, `updated_at` TEXT NOT NULL)
[2018-04-11 06:40:12 +0000] SELECT `fluent`.* FROM `fluent` ORDER BY `fluent`.`batch` DESC LIMIT 0, 1
[2018-04-11 06:40:12 +0000] SELECT `fluent`.* FROM `fluent` WHERE `fluent`.`name` = ? LIMIT 0, 1 [Post]
[2018-04-11 06:40:12 +0000] CREATE TABLE `posts` (`id` INTEGER PRIMARY KEY NOT NULL, `content` TEXT NOT NULL)
[2018-04-11 06:40:12 +0000] INSERT INTO `fluent` (`name`, `updated_at`, `id`, `batch`, `created_at`) VALUES (?, ?, ?, ?, ?) [Post, 2018-04-11T06:40:12.762Z, , 1, 2018-04-11T06:40:12.762Z]
[2018-04-11 06:40:12 +0000] SELECT `fluent`.* FROM `fluent` WHERE `fluent`.`name` = ? LIMIT 0, 1 [Users]
[2018-04-11 06:40:12 +0000] CREATE TABLE `userss` (`id` INTEGER PRIMARY KEY NOT NULL, `usename` TEXT NOT NULL, `passWord` INTEGER NOT NULL)
[2018-04-11 06:40:12 +0000] INSERT INTO `fluent` (`name`, `updated_at`, `id`, `batch`, `created_at`) VALUES (?, ?, ?, ?, ?) [Users, 2018-04-11T06:40:12.766Z, , 1, 2018-04-11T06:40:12.766Z]
[2018-04-11 06:40:12 +0000] SELECT `fluent`.* FROM `fluent` WHERE `fluent`.`name` = ? LIMIT 0, 1 [Festival]
[2018-04-11 06:40:12 +0000] CREATE TABLE `festivals` (`id` INTEGER PRIMARY KEY NOT NULL, `date` TEXT NOT NULL, `name` TEXT NOT NULL)
[2018-04-11 06:40:12 +0000] INSERT INTO `fluent` (`name`, `updated_at`, `id`, `batch`, `created_at`) VALUES (?, ?, ?, ?, ?) [Festival, 2018-04-11T06:40:12.770Z, , 1, 2018-04-11T06:40:12.770Z]
Database prepared
No command supplied, defaulting to serve...
Starting server on 0.0.0.0:8080

这是我的模型user.swift

import MySQLProvider

final class Users: Model {
    var usename: String
    var passWord: Int
    let storage = Storage()

    init(row: Row) throws {
        usename = try row.get("name")
        passWord = try row.get("passWord")
    }

    init(usename: String, passWord: Int) {
        self.usename = usename
        self.passWord = passWord
    }


    func makeRow() throws -> Row {
        var row = Row()
        try row.set("usename", usename)
        try row.set("passWord", passWord)
        return row
    }
}


extension Users: Preparation {
    static func prepare(_ database: Database) throws {
        try database.create(self) { user in
            user.id()
            user.string("usename")
            user.int("passWord")
        }
    }

    static func revert(_ database: Database) throws {
        try database.delete(self)
    }
}

mysql.json

{
    "hostname": "localhost",
    "user": "root",
    "password": "123456",
    "database": "User"
}

我的Config + Setup.swift

extension Config {
    public func setup() throws {
        // allow fuzzy conversions for these types
        // (add your own types here)
        Node.fuzzy = [Row.self, JSON.self, Node.self]

        try setupProviders()
        try setupPreparations()
    }

    /// Configure providers
    private func setupProviders() throws {
        try addProvider(FluentProvider.Provider.self)
        try addProvider(MySQLProvider.Provider.self)
    }

    /// Add all models that should have their
    /// schemas prepared before the app boots
    private func setupPreparations() throws {
        preparations.append(Post.self)
        preparations.append(Users.self)
        preparations.append(Festival.self)
    }
}

我不知道问题出在哪里,所以我真的希望你能帮我解决这个问题

2 个答案:

答案 0 :(得分:0)

您是否已将模型添加到准备工作中?

答案 1 :(得分:0)

从它创建数据库的证据,但你找不到它,它很可能使用默认的,基于内存的SQLite。查看fluent.json并更改driver设置,如下所示:

"//": "The underlying database technology to use.",
"//": "memory: SQLite in-memory DB.",
"//": "sqlite: Persisted SQLite DB (configure with sqlite.json)",
"//": "Other drivers are available through Vapor providers",
"//": "https://github.com/search?q=topic:vapor-provider+topic:database",
"driver": "mysql",

您也没有提及Driver + Config.swift文件,其示例如下:

import URI
import Vapor
import Fluent
import MySQLDriver

extension MySQLDriver.Driver: ConfigInitializable {
    /// Creates a MySQLDriver from a `mysql.json`
    /// config file.
    ///
    /// The file should contain similar JSON:
    ///
    ///     {
    ///         "hostname": "127.0.0.1",
    ///         "user": "root",
    ///         "password": "",
    ///         "database": "test",
    ///         "port": 3306, // optional
    ///         "flag": 0, // optional
    ///         "encoding": "utf8" // optional
    ///     }
    ///
    /// Optionally include a url instead:
    ///
    ///     {
    ///         "url": "mysql://user:pass@host:3306/database"
    ///     }
    public convenience init(config: Config) throws {
        guard let mysql = config["mysql"]?.object else {
            throw ConfigError.missingFile("mysql")
        }

        let flag = mysql["flag"]?.uint
        let encoding = mysql["encoding"]?.string

        if let url = mysql["url"]?.string {
            try self.init(url: url, flag: flag, encoding: encoding)
        } else {
            let masterHostname: String
            if let master = mysql["hostname"]?.string {
                masterHostname = master
            } else if let master = mysql["master"]?.string {
                masterHostname = master
            } else {
                throw ConfigError.missing(key: ["hostname"], file: "mysql", desiredType: String.self)
            }

            let readReplicaHostnames: [String]
            if let array = mysql["readReplicas"]?.array?.flatMap({ $0.string }) {
                readReplicaHostnames = array
            } else if let string = mysql["readReplicas"]?.string {
                readReplicaHostnames = string.commaSeparatedArray()
            } else {
                readReplicaHostnames = []
            }

            guard let user = mysql["user"]?.string else {
                throw ConfigError.missing(key: ["user"], file: "mysql", desiredType: String.self)
            }

            guard let password = mysql["password"]?.string else {
                throw ConfigError.missing(key: ["password"], file: "mysql", desiredType: String.self)
            }

            guard let database = mysql["database"]?.string else {
                throw ConfigError.missing(key: ["database"], file: "mysql", desiredType: String.self)
            }

            let port = mysql["port"]?.uint

            try self.init(
                masterHostname: masterHostname,
                readReplicaHostnames: readReplicaHostnames,
                user: user,
                password: password,
                database: database,
                port: port ?? 3306,
                flag: flag ?? 0,
                encoding: encoding ?? "utf8"
            )
        }
    }

    /// See MySQLDriver.init(host: String, ...)
    public convenience init(url: String, flag: UInt?, encoding: String?) throws {
        let uri = try URI(url)
        guard
            let user = uri.userInfo?.username,
            let pass = uri.userInfo?.info
        else {
            throw ConfigError.missing(key: ["url(userInfo)"], file: "mysql", desiredType: URI.self)
        }

        let db = uri.path
            .split(separator: "/")
            .map { String($0) }
            .joined(separator: "")

        try self.init(
            masterHostname: uri.hostname,
            readReplicaHostnames: [],
            user: user,
            password: pass,
            database: db,
            port: uri.port.flatMap { UInt($0) } ?? 3306,
            flag: flag ?? 0,
            encoding: encoding ?? "utf8"
        )
    }
}