A PostgreSQL binding for Zig.

Status: Experimental

Not even Alpha!


Using zigmod, add a line to the dependencies (or root_dependencies) in your zig.mod file:

      - src: http

then in your source code:

    const Pg = @import("pgzig");


Create a DB object passing a connection string specifying the host, user, and database:

    var db = try Pg.DB.connect("host=<host> user=<username> database=<dbname>");

For SQL commands that don't produce a return value, use the simpleQuery() method:

    try db.simpleQuery(
        \\ DROP TABLE IF EXISTS students;
        \\ CREATE TABLE students (id BIGINT, name VARCHAR, year INTEGER);

Prepared statements are pre-parsed and stored in the database server. Use the .finalize() method to release them.

    var stmt = try client.prepare("SELECT name, year FROM students WHERE year < $1");
    defer stmt.finalize();

The .exec() method receives arguments (written as $1, $2 in the prepared statement's SQL text) as a tuple, and a struct to define the type of each returned row.

    const Row = struct { name: []const u8, year: i64 }
    var curs = try stmt.exec(.{2010}, Row);             // "... WHERE year < $1"
    defer curs.deinit();

To retrieve all responses as a slice of rows, use .fetchAll():

    const data = try curs.fetchAll();

Or get each row in a while loop with .fetch():

    while (try curs.fetch()) |row| {