Class
PostgresClient
PostgresClient.Configuration to change the client’s behavior.final class PostgresClient
Creating a client
You create a PostgresClient by first creating a PostgresClient.Configuration struct that you can use to modify the client’s behavior.
let config = PostgresClient.Configuration(
host: "localhost",
port: 5432,
username: "my_username",
password: "my_password",
database: "my_database",
tls: .disable
)
Now you can create a client with your configuration object:
let client = PostgresClient(configuration: config)
Running a client
PostgresClient relies on structured concurrency. Because of this it needs a task in which it can schedule all the background work that it needs to do in order to manage connections on the user’s behalf. For this reason, developers must provide a task to the client by scheduling the client’s run method in a long running task:
await withTaskGroup(of: Void.self) { taskGroup in
taskGroup.addTask {
await client.run() // !important
}
// You can use the client while the `client.run()` method is not cancelled.
// To shutdown the client, cancel its run method, by cancelling the taskGroup.
taskGroup.cancelAll()
}
PostgresClient cannot lease connections if its run() method isn’t active. Cancelling the run() method is equivalent to closing the client. Once a client’s run() method has been cancelled, executing queries or prepared statements will fail.
Topics
Structures
Initializers
init(configuration:eventLoopGroup:)Creates a newPostgresClient, that does not log any background information.init(configuration:eventLoopGroup:backgroundLogger:)Creates a newPostgresClient. Don’t forget torun()the client in a long-running task.
Instance Methods
execute(_:logger:file:line:)Execute a prepared statement, taking care of the preparation when necessary.query(_:logger:file:line:)Run a query on the Postgres server the client is connected to.run()The structured root task for the client’s background work.withConnection(_:)Lease a connection for the providedclosure’s lifetime.withConnection(isolation:_:)Lease a connection for the providedclosure’s lifetime.withTransaction(logger:file:line:isolation:_:)Lease a connection, which is in an open transaction state, for the providedclosure’s lifetime.
Type Properties
defaultEventLoopGroupReturns the defaultEventLoopGroupsingleton, automatically selecting the best for the platform.
Relationships
Conforms To
ServiceLifecycle.ServiceSwift.SendableSwift.SendableMetatype
See Also
Essentials
PostgresClient.ConfigurationPostgresConnectionA Postgres connection. Use it to run queries against a Postgres server.- Running QueriesInteract with the PostgreSQL database by running Queries.