Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is is possible to use Vapor 3 Postgres Fluent in a standalone script?

Tags:

swift

vapor

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.

like image 328
Kirby Avatar asked Nov 06 '22 23:11

Kirby


1 Answers

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:_:)

like image 58
Caleb Kleveter Avatar answered Nov 15 '22 08:11

Caleb Kleveter