main.swift 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import PostgresKit
  2. import Vapor
  3. var env = try Environment.detect()
  4. try LoggingSystem.bootstrap(from: &env)
  5. let app = Application(env)
  6. defer { app.shutdown() }
  7. app.http.server.configuration.serverName = "Vapor"
  8. app.logger.notice("💧 VAPOR")
  9. app.logger.notice("System.coreCount: \(System.coreCount)")
  10. app.logger.notice("System.maxConnectionsPerEventLoop: \(System.maxConnectionsPerEventLoop)")
  11. let pools = EventLoopGroupConnectionPool(
  12. source: PostgresConnectionSource(configuration: .init(
  13. hostname: "tfb-database",
  14. username: "benchmarkdbuser",
  15. password: "benchmarkdbpass",
  16. database: "hello_world"
  17. )),
  18. maxConnectionsPerEventLoop: System.maxConnectionsPerEventLoop,
  19. on: app.eventLoopGroup
  20. )
  21. extension Request {
  22. func db(_ pools: EventLoopGroupConnectionPool<PostgresConnectionSource>) -> PostgresDatabase {
  23. pools.pool(for: self.eventLoop).database(logger: self.logger)
  24. }
  25. }
  26. app.get("db") { req in
  27. req.db(pools).query("SELECT id, randomnumber FROM World WHERE id = $1", [
  28. PostgresData(int32: .random(in: 1...10_000))
  29. ]).map {
  30. $0.first
  31. }.unwrap(or: Abort(.notFound)).map {
  32. World(
  33. id: $0.column("id")?.int32 ?? 0,
  34. randomnumber: $0.column("randomnumber")?.int ?? 0
  35. )
  36. }
  37. }
  38. app.get("queries") { req -> EventLoopFuture<[World]> in
  39. let queries = (req.query["queries"] ?? 1).bounded(to: 1...500)
  40. let db = req.db(pools)
  41. return (0 ..< queries).map { _ -> EventLoopFuture<World> in
  42. db.query("SELECT id, randomnumber FROM World WHERE id = $1", [
  43. PostgresData(int32: .random(in: 1...10_000))
  44. ]).map {
  45. $0.first
  46. }.unwrap(or: Abort(.notFound)).map {
  47. World(
  48. id: $0.column("id")?.int32 ?? 0,
  49. randomnumber: $0.column("randomnumber")?.int ?? 0
  50. )
  51. }
  52. }.flatten(on: req.eventLoop)
  53. }
  54. try app.run()