Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

History

97 Commits

Repository files navigation

zig-postgres

Light bindings around Postgres libpq

This is tested with zig 0.8

Installing libpq on debian linux

sudo apt-get install libpq-dev

There is also native zig client in pre-alpha status https://github.com/star-tek-mb/pgz

Import this module

Example of importing and using https://github.com/zig-postgres/zig-postgres-template

Run test

Running examples or tests requires db url attribute, for example

zig build test -Ddb=postgresql://db_url/mydb

How to use


Connecting to database

constPg=@import("postgres").Pg;
vargpa=std.heap.GeneralPurposeAllocator(.{}){};
constallocator=&gpa.allocator;
deferstd.debug.assert(!gpa.deinit());
vardb=tryPg.connect(allocator, "postgresql://root@postgresURL:26257?sslmode=disable");

Executing SQL

constschema=\\CREATE DATABASE root;\\CREATE TABLE IF NOT EXISTS users (id INT, name TEXT, age INT);
;
_=trydb.exec(schema);

Inserting data

Be mindful that this query, uses struct name as lowercase letters for table name.

constUsers=struct {
id: i16,
name: []constu8,
age: i16,
};
_=trydb.insert(Users{ .id=1, .name="Charlie", .age=20 });
_=trydb.insert(Users{ .id=2, .name="Steve", .age=25 });
_=trydb.insert(Users{ .id=3, .name="Karl", .age=25 });
_=trydb.insert(&[_]Users{
Users{ .id=4, .name="Tony", .age=25 },
Users{ .id=5, .name="Sara", .age=32 },
Users{ .id=6, .name="Fred", .age=11 },
});

Exec query with values

_=trydb.execValues("SELECT * FROM users WHERE name = {s}", .{"Charlie"});
_=trydb.execValues("INSERT INTO users (id, name, age) VALUES ({d}, {s}, {d})", .{ 5, "Tom", 32 });

Read query results

varresult=trydb.execValues("SELECT * FROM users WHERE id = {d}", .{2});
varuser=result.parse(Users, null).?;
print("{d} \n", .{user.id});
print("{s} \n", .{user.name});
varresults=trydb.execValues("SELECT * FROM users WHERE age = {d}", .{25});
while (results.parse(Users, null)) |user| {
print("{s} \n", .{user.name});
}
varresult=trydb.execValues("SELECT * FROM users WHERE name = {s}", .{"Charlie"});
varuser=result.parse(Users, null}).?;
if(user) print("{s} \n", .{user.name});

Many thanks for this repository

About

Zig wrapper for postgres

Resources

Stars

20 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages