I am experimenting with a standalone script that will query a Postgres database using Vapor and Fluent. In a normal Vapor API application this is simply done by:
router.get("products") { request in
return Product.query(on: request).all()
}
However, in a standalone script, since there is no "request", I get stuck on what to replace the "request" or DatabaseConnectable
with. Here's where I get stuck on:
import Fluent
import FluentPostgreSQL
let databaseConfig = PostgreSQLDatabaseConfig(hostname: "localhost",
username: "test",
database: "test",
password: nil)
let database = PostgreSQLDatabase(config: databaseConfig)
let foo = Product.query(on: <??WhatDoIPutHere??>)
I tried creating an object that conforms to DatabaseConnectable
, but couldn't figure out how to correctly get that object to conform.
You will need to create an event loop group to be able to make database requests. SwiftNIO's MultiThreadedEventLoopGroup
is good for this:
let worker = MultiThreadedEventLoopGroup(numberOfThreads: 2)
You can change the number of threads used as you need.
Now you can create a connection to the database with that worker:
let conn = try database.newConnection(on: worker)
The connection is in a future, so you can map
it and pass the connection in your query:
conn.flatMap { connection in
return Product.query(on: connection)...
}
Make sure you shutdown your worker when you are done with it using shutdownGracefully(queue:_:)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With