This repository was archived by the owner on Sep 16, 2023. It is now read-only.
forked fromtonis2/zig-postgres
- Notifications
You must be signed in to change notification settings - Fork1
jane0009/zig-postgres
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Light bindings around Postgreslibpq
This is tested with zig0.8
Installinglibpg
on debian linux
sudo apt-get install libpq-dev
Add this repository as submodule
git submodule add git@github.com:tonis2/zig-postgres.git dependencies/zig-postgres
Add following code lines into your projectbuild.zig
This code adds the package and links required libraries.
exe.addPackage(.{ .name="postgres", .path="/dependencies/zig-postgres/src/postgres.zig" });exe.linkSystemLibrary("c");exe.linkSystemLibrary("libpq");
Running examples or tests requiresdb
url attribute, for example
zig build test -Ddb=postgresql://db_url
zig build main -Ddb=postgresql://db_url
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");
constschema=\\CREATE DATABASE IF NOT EXISTS root;\\CREATE TABLE IF NOT EXISTS users (id INT, name TEXT, age INT); ;_=trydb.exec(schema);
Be mindful that this query, usesstruct name
as lowercase letters fortable
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 }, });
_=trydb.execValues("SELECT * FROM users WHERE name = {s}", .{"Charlie"});_=trydb.execValues("INSERT INTO users (id, name, age) VALUES ({d}, {s}, {d})", .{5,"Tom",32 });
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 thisrepository