main.swift 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 sql(_ pools: EventLoopGroupConnectionPool<PostgresConnectionSource>) -> SQLDatabase {
  23. pools.pool(for: self.eventLoop).database(logger: self.logger).sql()
  24. }
  25. }
  26. app.get("db") { req async throws -> World in
  27. guard let world = try await req.sql(pools).select()
  28. .column("id")
  29. .column("randomnumber")
  30. .from("World")
  31. .where("id", .equal, Int32.random(in: 1...10_000))
  32. .first(decoding: World.self)
  33. .get()
  34. else {
  35. throw Abort(.notFound)
  36. }
  37. return world
  38. }
  39. app.get("queries") { req async throws -> [World] in
  40. let queries = (req.query["queries"] ?? 1).bounded(to: 1...500)
  41. var worlds: [World] = []
  42. let db = req.sql(pools)
  43. for _ in queries {
  44. guard let world = try await db.select()
  45. .column("id")
  46. .column("randomnumber")
  47. .from("World")
  48. .where("id", .equal, Int32.random(in: 1...10_000))
  49. .first(decoding: World.self).get() else {
  50. throw Abort(.notFound)
  51. }
  52. worlds.append(world)
  53. }
  54. return worlds
  55. }
  56. extension Int: Sequence {
  57. public func makeIterator() -> CountableRange<Int>.Iterator {
  58. return (0..<self).makeIterator()
  59. }
  60. }
  61. try app.run()