dream_postgres_client
Postgresql client
Gleam wrapper around pgo library
Types
The configuration for a pool of connections.
pub type Config {
Config(
pool_name: process.Name(Message),
host: String,
port: Int,
database: String,
user: String,
password: option.Option(String),
ssl: Ssl,
connection_parameters: List(#(String, String)),
pool_size: Int,
queue_target: Int,
queue_interval: Int,
idle_interval: Int,
trace: Bool,
ip_version: IpVersion,
rows_as_map: Bool,
interceptor: option.Option(Interceptor),
)
}
Constructors
-
Config( pool_name: process.Name(Message), host: String, port: Int, database: String, user: String, password: option.Option(String), ssl: Ssl, connection_parameters: List(#(String, String)), pool_size: Int, queue_target: Int, queue_interval: Int, idle_interval: Int, trace: Bool, ip_version: IpVersion, rows_as_map: Bool, interceptor: option.Option(Interceptor), )Arguments
- pool_name
-
The Erlang name to register the pool with.
- host
-
(default: 127.0.0.1): Database server hostname.
- port
-
(default: 5432): Port the server is listening on.
- database
-
Name of database to use.
- user
-
Username to connect to database as.
- password
-
Password for the user.
- ssl
-
(default: SslDisabled): Whether to use SSL or not.
- connection_parameters
-
(default: []): List of 2-tuples, where key and value must be binary strings. You can include any Postgres connection parameter here, such as
#("application_name", "myappname")and#("timezone", "GMT"). - pool_size
-
(default: 1): Number of connections to keep open with the database
- queue_target
-
(default: 50) Checking out connections is handled through a queue. If it takes longer than queue_target to get out of the queue for longer than queue_interval then the queue_target will be doubled and checkouts will start to be dropped if that target is surpassed.
- queue_interval
-
(default: 1000)
- idle_interval
-
(default: 1000): The database is pinged every idle_interval when the connection is idle.
- trace
-
trace (default: False): pgo is instrumented with OpenCensus and when this option is true a span will be created (if sampled).
- ip_version
-
(default: Ipv4) Which internet protocol to use for this connection
- rows_as_map
-
(default: False) By default, pgo will return a n-tuple, in the order of the query. By setting
rows_as_maptoTrue, the result will beDict. - interceptor
-
(default: None): Optional query interceptor for logging, observability, or testing.
pub opaque type Connection
The result returned by an interceptor.
Continue: Execute the query normally against the databaseRespond: Return this data instead of querying the databaseFail: Return this error instead of querying the databaseCapture: Run the query and give its result toon_result
pub type InterceptResult {
Continue
Respond(count: Int, rows: List(dynamic.Dynamic))
Fail(error: QueryError)
Capture(
on_result: fn(
Result(#(Int, List(dynamic.Dynamic)), QueryError),
) -> Result(Nil, dynamic.Dynamic),
)
}
Constructors
-
ContinueExecute the query normally
-
Respond(count: Int, rows: List(dynamic.Dynamic))Return data without querying the database
-
Fail(error: QueryError)Return an error without querying the database.
To fail the query with a reason of its own, an interceptor gives
InterceptorFailed:let read_only = Interceptor(fn(request) { case string.starts_with(request.sql, "SELECT") { True -> Continue False -> Fail(InterceptorFailed(dynamic.string("read only"))) } }) -
Capture( on_result: fn(Result(#(Int, List(dynamic.Dynamic)), QueryError)) -> Result( Nil, dynamic.Dynamic, ), )Run the query and give its result to
on_result.When
on_resultreturnsOk(Nil), the query returns the result of the database. When it returnsError(reason), the query returnsError(InterceptorFailed(reason)), whatever the database gave.
Query interceptor for logging, observability, and testing.
Interceptors are called before query execution and can:
- Log queries for debugging and auditing
- Collect metrics and performance data
- Return mock data for testing (without a database)
The interceptor receives information about the query and can either continue with normal execution or provide an alternative result.
Example - Query logging
import gleam/io
let logger = Interceptor(fn(request) {
io.println("Executing: " <> request.sql)
Continue
})
pog.default_config(name)
|> pog.interceptor(Some(logger))
|> pog.start
pub type Interceptor {
Interceptor(intercept: fn(InterceptRequest) -> InterceptResult)
}
Constructors
-
Interceptor(intercept: fn(InterceptRequest) -> InterceptResult)
The internet protocol version to use.
pub type IpVersion {
Ipv4
Ipv6
}
Constructors
-
Ipv4Internet Protocol version 4 (IPv4)
-
Ipv6Internet Protocol version 6 (IPv6)
pub type QueryError {
ConstraintViolated(
message: String,
constraint: String,
detail: String,
)
PostgresqlError(code: String, name: String, message: String)
UnexpectedArgumentCount(expected: Int, got: Int)
UnexpectedArgumentType(expected: String, got: String)
UnexpectedResultType(List(decode.DecodeError))
QueryTimeout
ConnectionUnavailable
InterceptorFailed(reason: dynamic.Dynamic)
}
Constructors
-
ConstraintViolated( message: String, constraint: String, detail: String, )The query failed as a database constraint would have been violated by the change.
-
PostgresqlError(code: String, name: String, message: String)The query failed within the database. https://www.postgresql.org/docs/current/errcodes-appendix.html
-
UnexpectedArgumentCount(expected: Int, got: Int) -
UnexpectedArgumentType(expected: String, got: String)One of the arguments supplied was not of the type that the query required.
-
UnexpectedResultType(List(decode.DecodeError))The rows returned by the database could not be decoded using the supplied dynamic decoder.
-
QueryTimeoutThe query timed out.
-
ConnectionUnavailableNo connection was available to execute the query. This may be due to invalid connection details such as an invalid username or password.
-
InterceptorFailed(reason: dynamic.Dynamic)An interceptor failed the query.
reasonis the value that the interceptor gave; the package that made the interceptor reads it back.An interceptor fails a query before it runs with
Fail:Interceptor(fn(_request) { Fail(InterceptorFailed(dynamic.string("no queries now"))) })It fails a query after it runs when the
on_resultfunction ofCapturereturnsError(reason).
The rows and number of rows that are returned by a database query.
pub type Returned(t) {
Returned(count: Int, rows: List(t))
}
Constructors
-
Returned(count: Int, rows: List(t))
pub type Ssl {
SslVerified
SslVerifiedCaFile(path: String)
SslVerifiedChainOnly
SslVerifiedChainOnlyCaFile(path: String)
SslUnverified
SslDisabled
}
Constructors
-
SslVerifiedEnable SSL connection, and check CA certificate. It is the most secured option to use SSL and should be always used by default. Never ignore CA certificate checking unless you know exactly what you are doing.
-
SslVerifiedCaFile(path: String)Like
SslVerified, but the CA certificates come from the PEM file atpath, not from the operating system. Use it for a database with a private certificate authority. The file applies to this pool only.startfails when the file cannot be read or holds no PEM certificate. -
SslVerifiedChainOnlyEnable SSL connection, and check the certificate chain against the CA certificates of the operating system, but not the host name in the certificate. It is
sslmode=verify-caof libpq. Use it when you connect with a name or an address that the certificate does not hold. -
SslVerifiedChainOnlyCaFile(path: String)Like
SslVerifiedChainOnly, but the CA certificates come from the PEM file atpath, not from the operating system. The file applies to this pool only.startfails when the file cannot be read or holds no PEM certificate. -
SslUnverifiedEnable SSL connection, but don’t check CA certificate.
SslVerifiedshould always be prioritized uponSslUnverified. As it implies, that option enables SSL, but as it is unverified, the connection can be unsafe. Use this option only if you know what you’re doing. In casepogcan not find the proper CA certificate, take a look at the README to get some help to inject the CA certificate in your OS. -
SslDisabledDisable SSL connection completely. Using this option will let the connection unsecured, and should be avoided in production environment.
pub type TransactionError(error) {
TransactionQueryError(QueryError)
TransactionRolledBack(error)
}
Constructors
-
TransactionQueryError(QueryError) -
TransactionRolledBack(error)
Values
pub fn calendar_date(date: calendar.Date) -> Value
pub fn calendar_date_decoder() -> decode.Decoder(calendar.Date)
pub fn calendar_time_of_day(time: calendar.TimeOfDay) -> Value
pub fn calendar_time_of_day_decoder() -> decode.Decoder(
calendar.TimeOfDay,
)
pub fn connection_parameter(
config: Config,
name name: String,
value value: String,
) -> Config
Any Postgres connection parameter here, such as
"application_name: myappname" and "timezone: GMT"
pub fn default_config(
pool_name pool_name: process.Name(Message),
) -> Config
The default configuration for a connection pool, with a single connection. You will likely want to increase the size of the pool for your application.
pub fn disconnected(interceptor: Interceptor) -> Connection
Create a connection that uses an interceptor without a database.
No database connection is established. All queries are routed to the
interceptor. The interceptor must handle all queries - returning Continue
will result in a ConnectionUnavailable error.
Example
let interceptor = Interceptor(fn(request) {
case request.sql {
"SELECT * FROM users" -> Respond(1, [user_data])
_ -> Fail(PostgresqlError("UNSUPPORTED", "unsupported", "Query not supported"))
}
})
let connection = pog.disconnected(interceptor)
pub fn error_code_name(error_code: String) -> Result(String, Nil)
Get the name for a PostgreSQL error code.
> error_code_name("01007")
Ok("privilege_not_granted")
https://www.postgresql.org/docs/current/errcodes-appendix.html
pub fn execute(
query query: Query(t),
on pool: Connection,
) -> Result(Returned(t), QueryError)
Run a query against a PostgreSQL database.
pub fn idle_interval(
config: Config,
idle_interval: Int,
) -> Config
The database is pinged every idle_interval when the connection is idle.
default: 1000
pub fn interceptor(
config: Config,
interceptor: option.Option(Interceptor),
) -> Config
Set a query interceptor for logging, observability, or testing.
The interceptor is called before each query execution. Common use cases:
Logging: Log all SQL queries for debugging and auditing
import gleam/io
let logger = Interceptor(fn(req) {
io.println("SQL: " <> req.sql)
Continue
})
config |> pog.interceptor(Some(logger))
Metrics: Track query performance
let metrics = Interceptor(fn(req) {
metrics.record_query(req.sql, req.timeout)
Continue
})
Testing: Return test data without a database
let test_interceptor = Interceptor(fn(req) {
case req.sql {
"SELECT * FROM users" -> Respond(1, [test_user_data])
_ -> Continue
}
})
pub fn ip_version(
config: Config,
ip_version: IpVersion,
) -> Config
Which internet protocol to use for this connection
pub fn named_connection(
name: process.Name(Message),
) -> Connection
Create a reference to a pool using the pool’s name.
If no pool has been started using this name then queries using this connection will fail.
pub fn nullable(
inner_type: fn(a) -> Value,
value: option.Option(a),
) -> Value
pub fn numeric_decoder() -> decode.Decoder(Float)
Decode a PostgreSQL numeric, which is a union of PostgreSQL integers and float types. Int values are decoded as floats.
pub fn parameter(query: Query(t1), parameter: Value) -> Query(t1)
Push a new query parameter value for the query.
pub fn password(
config: Config,
password: option.Option(String),
) -> Config
Password for the user.
pub fn pool_size(config: Config, pool_size: Int) -> Config
Number of connections to keep open with the database
default: 10
pub fn query(sql: String) -> Query(Nil)
Create a new query to use with the execute, returning, and parameter
functions.
pub fn queue_interval(
config: Config,
queue_interval: Int,
) -> Config
Checking out connections is handled through a queue. If it takes longer than queue_target to get out of the queue for longer than queue_interval then the queue_target will be doubled and checkouts will start to be dropped if that target is surpassed.
default: 1000
pub fn queue_target(config: Config, queue_target: Int) -> Config
Checking out connections is handled through a queue. If it takes longer than queue_target to get out of the queue for longer than queue_interval then the queue_target will be doubled and checkouts will start to be dropped if that target is surpassed.
default: 50
pub fn returning(
query: Query(t1),
decoder: decode.Decoder(t2),
) -> Query(t2)
Set the decoder to use for the type of row returned by executing this query.
If the decoder is unable to decode the row value then the query will return
an error from the exec function, but the query will still have been run
against the database.
pub fn rows_as_map(config: Config, rows_as_map: Bool) -> Config
By default, pgo will return a n-tuple, in the order of the query.
By setting rows_as_map to True, the result will be Dict.
pub fn start(
config: Config,
) -> Result(actor.Started(Connection), actor.StartError)
Start a database connection pool. Most the time you want to use
supervised and add the pool to your supervision tree instead of using this
function directly.
The pool is started in a new process and will asynchronously connect to the PostgreSQL instance specified in the config. If the configuration is invalid or it cannot connect for another reason it will continue to attempt to connect, and any queries made using the connection pool will fail.
An exception: with SslVerifiedCaFile or SslVerifiedChainOnlyCaFile,
start reads the CA file first, and returns an error at once when the
file cannot be read or holds no PEM certificate. The error reason is a
String that names the file.
pub fn supervised(
config: Config,
) -> supervision.ChildSpecification(Connection)
Start a database connection pool by adding it to your supervision tree.
Use the named_connection function to create a connection to query this
pool with if your supervisor does not pass back the return value of
creating the pool.
The pool is started in a new process and will asynchronously connect to the PostgreSQL instance specified in the config. If the configuration is invalid or it cannot connect for another reason it will continue to attempt to connect, and any queries made using the connection pool will fail.
pub fn timeout(query: Query(t1), timeout: Int) -> Query(t1)
Use a custom timeout for the query, in milliseconds. the default connection timeout.
If this function is not used to give a timeout then default of 5000 ms is used.
pub fn timestamp(timestamp: timestamp.Timestamp) -> Value
pub fn timestamp_decoder() -> decode.Decoder(timestamp.Timestamp)
pub fn trace(config: Config, trace: Bool) -> Config
Trace pgo is instrumented with OpenTelemetry and when this option is true a span will be created (if sampled).
default: False
pub fn transaction(
pool: Connection,
callback: fn(Connection) -> Result(t, error),
) -> Result(t, TransactionError(error))
Runs a function within a PostgreSQL transaction.
If the function returns an Ok then the transaction is committed.
If the function returns an Error or panics then the transaction is rolled
back.
pub fn url_config(
name: process.Name(Message),
database_url: String,
) -> Result(Config, Nil)
Parse a database url into configuration that can be used to start a pool.