|
| 1 | +(connect-zig)= |
| 2 | + |
| 3 | +# Zig |
| 4 | + |
| 5 | +:::{div} sd-text-muted |
| 6 | +Connect to CrateDB from Zig applications. |
| 7 | +::: |
| 8 | + |
| 9 | +:::{rubric} About |
| 10 | +::: |
| 11 | + |
| 12 | +[pg.zig] is a native PostgreSQL driver / client for Zig. |
| 13 | + |
| 14 | +:::{rubric} Synopsis |
| 15 | +::: |
| 16 | + |
| 17 | +`build.zig` |
| 18 | +```zig |
| 19 | +const std = @import("std"); |
| 20 | +
|
| 21 | +pub fn build(b: *std.Build) void { |
| 22 | +
|
| 23 | + const target = b.standardTargetOptions(.{}); |
| 24 | + const optimize = b.standardOptimizeOption(.{}); |
| 25 | +
|
| 26 | + const exe = b.addExecutable(.{ |
| 27 | + .name = "example", |
| 28 | + .root_module = b.createModule(.{ |
| 29 | + .root_source_file = b.path("example.zig"), |
| 30 | + .target = b.graph.host, |
| 31 | + }) |
| 32 | + }); |
| 33 | +
|
| 34 | + const pg = b.dependency("pg", .{ |
| 35 | + .target = target, |
| 36 | + .optimize = optimize, |
| 37 | + }); |
| 38 | + exe.root_module.addImport("pg", pg.module("pg")); |
| 39 | +
|
| 40 | + b.installArtifact(exe); |
| 41 | +} |
| 42 | +``` |
| 43 | +`example.zig` |
| 44 | +```zig |
| 45 | +const std = @import("std"); |
| 46 | +const builtin = @import("builtin"); |
| 47 | +
|
| 48 | +const pg = @import("pg"); |
| 49 | +
|
| 50 | +pub fn main() !void { |
| 51 | +
|
| 52 | + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; |
| 53 | + const allocator = if (builtin.mode == .Debug) gpa.allocator() else std.heap.c_allocator; |
| 54 | +
|
| 55 | + const uri = try std.Uri.parse("postgresql://crate:crate@localhost/doc?sslmode=disable"); |
| 56 | + var pool = try pg.Pool.initUri(allocator, uri, .{.size=5, .timeout=5_000}); |
| 57 | + defer pool.deinit(); |
| 58 | +
|
| 59 | + var result = try pool.query("SELECT mountain, height FROM sys.summits ORDER BY height DESC LIMIT 3", .{}); |
| 60 | + defer result.deinit(); |
| 61 | +
|
| 62 | + while (try result.next()) |row| { |
| 63 | + const mountain = row.get([]u8, 0); |
| 64 | + const height = row.get(i32, 1); |
| 65 | + std.debug.print("{s}: {d}\n", .{mountain, height}); |
| 66 | + } |
| 67 | +
|
| 68 | +} |
| 69 | +``` |
| 70 | +```shell |
| 71 | +zig fetch --save git+https://github.com/karlseguin/pg.zig#master |
| 72 | +zig build |
| 73 | +./zig-out/bin/hello |
| 74 | +``` |
| 75 | + |
| 76 | + |
| 77 | +[pg.zig]: https://github.com/karlseguin/pg.zig |
0 commit comments