Initial commit - basic implementation

This commit is contained in:
Bob Farrell 2024-06-16 10:43:10 +01:00
commit 81f7f8799c
6 changed files with 325 additions and 0 deletions

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
zig-out/
zig-cache/
*.core
.zig-cache/

7
LICENSE Normal file
View File

@ -0,0 +1,7 @@
Copyright 2023-2024 Robert Farrell
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

3
README.md Normal file
View File

@ -0,0 +1,3 @@
# JetQuery
Database query library for [Jetzig](https://github.com/jetzig-framework/jetzig), a web framework written in [Zig](https://ziglang.org/).

26
build.zig Normal file
View File

@ -0,0 +1,26 @@
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const lib = b.addStaticLibrary(.{
.name = "jetquery",
.root_source_file = b.path("src/jetquery.zig"),
.target = target,
.optimize = optimize,
});
b.installArtifact(lib);
const lib_unit_tests = b.addTest(.{
.root_source_file = b.path("src/jetquery.zig"),
.target = target,
.optimize = optimize,
});
const run_lib_unit_tests = b.addRunArtifact(lib_unit_tests);
const test_step = b.step("test", "Run unit tests");
test_step.dependOn(&run_lib_unit_tests.step);
}

72
build.zig.zon Normal file
View File

@ -0,0 +1,72 @@
.{
// This is the default name used by packages depending on this one. For
// example, when a user runs `zig fetch --save <url>`, this field is used
// as the key in the `dependencies` table. Although the user can choose a
// different name, most users will stick with this provided value.
//
// It is redundant to include "zig" in this name because it is already
// within the Zig package namespace.
.name = "jetquery",
// This is a [Semantic Version](https://semver.org/).
// In a future version of Zig it will be used for package deduplication.
.version = "0.0.0",
// This field is optional.
// This is currently advisory only; Zig does not yet do anything
// with this value.
//.minimum_zig_version = "0.11.0",
// This field is optional.
// Each dependency must either provide a `url` and `hash`, or a `path`.
// `zig build --fetch` can be used to fetch all dependencies of a package, recursively.
// Once all dependencies are fetched, `zig build` no longer requires
// internet connectivity.
.dependencies = .{
// See `zig fetch --save <url>` for a command-line interface for adding dependencies.
//.example = .{
// // When updating this field to a new URL, be sure to delete the corresponding
// // `hash`, otherwise you are communicating that you expect to find the old hash at
// // the new URL.
// .url = "https://example.com/foo.tar.gz",
//
// // This is computed from the file contents of the directory of files that is
// // obtained after fetching `url` and applying the inclusion rules given by
// // `paths`.
// //
// // This field is the source of truth; packages do not come from a `url`; they
// // come from a `hash`. `url` is just one of many possible mirrors for how to
// // obtain a package matching this `hash`.
// //
// // Uses the [multihash](https://multiformats.io/multihash/) format.
// .hash = "...",
//
// // When this is provided, the package is found in a directory relative to the
// // build root. In this case the package's hash is irrelevant and therefore not
// // computed. This field and `url` are mutually exclusive.
// .path = "foo",
// // When this is set to `true`, a package is declared to be lazily
// // fetched. This makes the dependency only get fetched if it is
// // actually used.
// .lazy = false,
//},
},
// Specifies the set of files and directories that are included in this package.
// Only files and directories listed here are included in the `hash` that
// is computed for this package. Only files listed here will remain on disk
// when using the zig package manager. As a rule of thumb, one should list
// files required for compilation plus any license(s).
// Paths are relative to the build root. Use the empty string (`""`) to refer to
// the build root itself.
// A directory listed here means that all files within, recursively, are included.
.paths = .{
"build.zig",
"build.zig.zon",
"src",
// For example...
//"LICENSE",
//"README.md",
},
}

213
src/jetquery.zig Normal file
View File

@ -0,0 +1,213 @@
const std = @import("std");
const TableOptions = struct {};
/// Abstraction of a database table. Define a schema with:
/// ```zig
/// const Schema = struct {
/// pub const Cats = Table("cats", struct { name: []const u8, paws: usize }, .{});
/// };
/// ```
pub fn Table(name: []const u8, T: type, options: TableOptions) type {
_ = options;
return struct {
pub const Definition = T;
pub const table_name = name;
};
}
/// Create a new query by passing a table definition.
/// ```zig
/// const query = Query(Schema.Cats).init(allocator);
/// ```
pub fn Query(T: type) type {
return struct {
const Self = @This();
allocator: std.mem.Allocator,
where_nodes: []const WhereNode = &.{},
select_columns: []const Column = &.{},
limit_bound: ?usize = null,
/// Initialize a new Query.
pub fn init(allocator: std.mem.Allocator) Self {
return .{ .allocator = allocator };
}
/// Free resources associated with this query.
pub fn deinit(self: Self) void {
self.allocator.free(self.where_nodes);
self.allocator.free(self.select_columns);
}
/// Specify columns to select in the query.
pub fn select(self: Self, columns: []const std.meta.FieldEnum(T.Definition)) Self {
return self.merge(.{ .select_columns = columns });
}
/// Specify a where clause for the query.
pub fn where(self: Self, args: anytype) Self {
inline for (std.meta.fields(@TypeOf(args))) |field| {
if (!@hasField(T.Definition, field.name)) @compileError("Unknown field: " ++ field.name);
}
var nodes: [std.meta.fields(@TypeOf(args)).len]WhereNode = undefined;
inline for (std.meta.fields(@TypeOf(args)), 0..) |field, index| {
if (!@hasField(T.Definition, field.name)) @compileError("Unknown field: " ++ field.name);
const value = switch (@typeInfo(@TypeOf(@field(args, field.name)))) {
.Pointer, .Array => .{ .string = @field(args, field.name) },
.Int, .ComptimeInt => .{ .integer = @field(args, field.name) },
.Float, .ComptimeFloat => .{ .float = @field(args, field.name) },
else => @compileError("Unsupported type for field: " ++ field.name),
};
nodes[index] = .{ .name = field.name, .value = value };
}
return self.merge(.{ .where_nodes = &nodes });
}
/// Apply a limit to the query's results.
pub fn limit(self: Self, bound: usize) Self {
return self.merge(.{ .limit_bound = bound });
}
/// Render the currenty query as SQL.
pub fn toSql(self: Self, buf: []u8) ![]const u8 {
var stream = std.io.fixedBufferStream(buf);
const writer = stream.writer();
try writer.print("select ", .{});
for (self.select_columns, 0..) |column, index| {
try writer.print("{s}{s} ", .{
column.name,
if (index < self.select_columns.len - 1) "," else "",
});
}
try writer.print("from {s}", .{T.table_name});
if (self.where_nodes.len > 0) try writer.print(" where ", .{});
for (self.where_nodes, 0..) |node, index| {
try writer.print("{s} = ?{s}", .{
node.name,
if (index < self.select_columns.len - 1) " and " else "",
});
}
if (self.limit_bound) |bound| try writer.print(" limit {}", .{bound});
return stream.getWritten();
}
// Merge the current query with given arguments.
fn merge(self: Self, args: anytype) Self {
defer self.deinit();
var where_nodes = std.ArrayList(WhereNode).init(self.allocator);
for (if (@hasField(@TypeOf(args), "where_nodes")) args.where_nodes else &.{}) |new_node| {
for (self.where_nodes) |node| {
if (std.mem.eql(u8, node.name, new_node.name)) break;
} else {
where_nodes.append(new_node) catch @panic("OOM");
}
}
if (!@hasField(@TypeOf(args), "where_nodes")) where_nodes.appendSlice(self.where_nodes) catch @panic("OOM");
var select_columns = std.ArrayList(Column).init(self.allocator);
for (if (@hasField(@TypeOf(args), "select_columns")) args.select_columns else &.{}) |name| {
for (self.select_columns) |column| {
if (std.mem.eql(u8, column.name, @tagName(name))) break;
} else {
inline for (std.meta.fields(T.Definition)) |field| {
if (std.mem.eql(u8, field.name, @tagName(name))) {
const column = Column{
.name = @tagName(name),
.type = switch (@typeInfo(field.type)) {
.Pointer, .Array => .string,
.Int, .ComptimeInt => .integer,
.Float, .ComptimeFloat => .float,
else => @compileError("Unsupported type " ++ @typeName(field.type)),
},
};
select_columns.append(column) catch @panic("OOM");
break;
}
}
}
}
if (!@hasField(@TypeOf(args), "select_columns")) select_columns.appendSlice(self.select_columns) catch @panic("OOM");
const cloned: Self = .{
.allocator = self.allocator,
.where_nodes = where_nodes.toOwnedSlice() catch @panic("OOM"),
.select_columns = select_columns.toOwnedSlice() catch @panic("OOM"),
.limit_bound = if (@hasField(@TypeOf(args), "limit_bound")) args.limit_bound else null,
};
return cloned;
}
};
}
// Abstraction of a database column.
const Column = struct {
name: []const u8,
type: enum { string, integer, float },
};
// Abstraction of a bound parameter (e.g. used in a where clause).
const Value = union(enum) {
string: []const u8,
integer: usize,
float: f64,
};
// A node in a where clause, e.g. `x = 10`.
const WhereNode = struct {
name: []const u8,
value: Value,
};
test "select" {
const Schema = struct {
pub const Cats = Table("cats", struct { name: []const u8, paws: usize }, .{});
};
const query = Query(Schema.Cats).init(std.testing.allocator)
.select(&.{ .name, .paws });
defer query.deinit();
var buf: [1024]u8 = undefined;
const sql = try query.toSql(&buf);
try std.testing.expectEqualStrings("select name, paws from cats", sql);
}
test "where" {
const Schema = struct {
pub const Cats = Table("cats", struct { name: []const u8, paws: usize }, .{});
};
const paws = std.crypto.random.int(usize);
const query = Query(Schema.Cats).init(std.testing.allocator)
.select(&.{ .name, .paws })
.where(.{ .name = "bar", .paws = paws });
defer query.deinit();
var buf: [1024]u8 = undefined;
const sql = try query.toSql(&buf);
try std.testing.expectEqualStrings("select name, paws from cats where name = ? and paws = ?", sql);
try std.testing.expectEqualStrings(query.where_nodes[0].name, "name");
try std.testing.expectEqualStrings(query.where_nodes[0].value.string, "bar");
try std.testing.expectEqualStrings(query.where_nodes[1].name, "paws");
try std.testing.expect(query.where_nodes[1].value == .integer);
}
test "limit" {
const Schema = struct {
pub const Cats = Table("cats", struct { name: []const u8, paws: usize }, .{});
};
const query = Query(Schema.Cats).init(std.testing.allocator)
.select(&.{ .name, .paws })
.limit(100);
defer query.deinit();
var buf: [1024]u8 = undefined;
const sql = try query.toSql(&buf);
try std.testing.expectEqualStrings("select name, paws from cats limit 100", sql);
}