zpg Logo thienpow / zpg Connections

Connections

zpg provides two ways to manage database connections: direct connections and connection pooling.

Direct Connections (zpg.Connection)

A zpg.Connection represents a single, direct connection to the PostgreSQL server. It’s suitable for simple applications or scenarios where manual connection management is preferred.

Initialization and Connection:

const std = @import("std");
const zpg = @import("zpg");

const allocator = std.testing.allocator; // Or your application's allocator

// 1. Create Config
const config = zpg.Config{
    .host = "127.0.0.1",
    .port = 5432,
    .username = "postgres",
    .database = "zui",
    .password = "postgres",
    .tls_mode = .disable,
};

// 2. Initialize Connection
var conn = try zpg.Connection.init(allocator, config);
defer conn.deinit(); // Ensure connection is closed

// 3. Connect to the database
try conn.connect();

// Check if connected
if (conn.isAlive()) {
    std.debug.print("Successfully connected!\n", .{});
    // ... use the connection ...
} else {
    std.debug.print("Connection failed.\n", .{});
}

Key Methods:

Limitations:

Connection Pooling (zpg.ConnectionPool)

zpg.ConnectionPool manages a pool of reusable database connections, providing thread-safe access and automatic handling of basic connection health checks and reconnections. This is the recommended approach for most applications, especially multi-threaded ones.

Initialization:

const pool_size = 5;
var pool = try zpg.ConnectionPool.init(allocator, config, pool_size);
defer pool.deinit(); // Closes all connections in the pool

Getting Connections (zpg.PooledConnection)

The preferred way to work with the pool is through zpg.PooledConnection. This wrapper acquires a connection from the pool upon initialization and automatically returns it when deinit is called (typically via defer).

// Get a connection with default pool timeout
var pconn = try zpg.PooledConnection.init(&pool, null); // null for no RLS context
defer pconn.deinit(); // Connection automatically returned here

// Get the underlying *Connection if needed (less common)
// const raw_conn = pconn.connection();

// Create a Query or QueryEx object using the pooled connection
var query = pconn.createQuery(allocator);
defer query.deinit();

// ... execute queries using 'query' ...
try query.run("SELECT 1", zpg.types.Empty);

// pconn.deinit() is called automatically by defer

Pool Management Methods

Using PooledConnection simplifies acquiring and releasing connections, making pool usage safer and less error-prone.

On This Page