环境: Vapor v4.77
数据库: Postgresql@15 通过 Homebrew
/Users/Ric> echo $DATABASE_NAME
ToDo
/Users/Ric> echo $DATABASE_HOST
localhost
/Users/Ric> echo $DATABASE_PORT
5432
这是配置:
public func configure(_ app: Application) async throws {
// uncomment to serve files from /Public folder
// app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))
app.databases.use(DatabaseConfigurationFactory.postgres(configuration: .init(
hostname: Environment.get("DATABASE_HOST") ?? "localhost",
port: Environment.get("DATABASE_PORT").flatMap(Int.init(_:)) ?? SQLPostgresConfiguration.ianaPortNumber,
username: Environment.get("DATABASE_USERNAME") ?? "vapor_username",
password: Environment.get("DATABASE_PASSWORD") ?? "vapor_password",
database: Environment.get("DATABASE_NAME") ?? "vapor_database",
tls: .prefer(try .init(configuration: .clientDefault)))
), as: .psql)
// Migrations:
app.migrations.add(CreateTodo())
try await app.autoMigrate().get()
// register routes
try routes(app)
这是迁移:
{暂时从“name”更改为“first_name”等}
import Fluent
struct CreateTodo: AsyncMigration {
func prepare(on database: Database) async throws {
try await database.schema("todos")
.deleteField("title")
.field("first_name", .string)
.field("last_name", .string)
.update()
}
func revert(on database: Database) async throws {
try await database.schema("todos").delete()
}
}
我已经通过命令问题检查了 PostgreSQL,但无法找到 Todo 数据库:
我能够执行 post 和 get 来证明存在持久数据。但我无法通过提示找到数据库。
我尝试使用现有的数据库名称“Turkey”(见上文):app.databases.use(DatabaseConfigurationFactory.postgres(configuration: .init(
hostname: Environment.get("DATABASE_HOST") ?? "localhost",
port: Environment.get("DATABASE_PORT").flatMap(Int.init(_:)) ?? SQLPostgresConfiguration.ianaPortNumber,
username: Environment.get("DATABASE_USERNAME") ?? "vapor_username",
password: Environment.get("DATABASE_PASSWORD") ?? "vapor_password",
// database: Environment.get("DATABASE_NAME") ?? "vapor_database",
database: "Turkey",
tls: .prefer(try .init(configuration: .clientDefault)))
), as: .psql)
...并将其他数据库引用更改为“土耳其”。
这是我进行>快速跑步后得到的结果:
解释?
我终于让它发挥作用了。
我的问题是损坏的 Vapor 代码和大小写拼写的组合。
解决方案:
1)从存储库回滚代码;
2) 根据 Postgres 的意愿,使用全局常量将数据库名称声明为小写。这减少了大小写不匹配的麻烦。