-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathblog.zig
More file actions
198 lines (166 loc) · 5.88 KB
/
blog.zig
File metadata and controls
198 lines (166 loc) · 5.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
const panic = @import("builtin").panic;
const std = @import("std");
const sqlite = @import("sqlite");
const SQL_CREATE_TABLE =
\\ CREATE TABLE IF NOT EXISTS posts(
\\ id INTEGER PRIMARY KEY AUTOINCREMENT,
\\ title TEXT NOT NULL,
\\ content TEXT NOT NULL
\\ );
;
const SQL_GET_POSTS = "SELECT id, title, content FROM posts;";
const SQL_GET_POST_BY_ID = "SELECT id, title, content FROM posts WHERE id = ?;";
const SQL_GET_LAST_INSERTED = "SELECT id, title, content FROM posts WHERE id = last_insert_rowid();";
const SQL_INSERT_POST =
\\ INSERT INTO
\\ posts(title, content)
\\ VALUES
\\ (?, ?)
\\ ;
;
const SQL_UPDATE_POST =
\\ UPDATE
\\ posts
\\ SET
\\ title = ?,
\\ content = ?
\\ WHERE id = ?;
;
const SQL_DELETE_POST = "DELETE FROM posts WHERE id = ?;";
const CMD_CREATE_POST = "create";
const CMD_READ_POSTS = "read";
const CMD_UPDATE_POST = "update";
const CMD_DELETE_POST = "delete";
pub fn main() !void {
const alloc = std.heap.c_allocator;
const db = try sqlite.SQLite3.open("blog.db");
defer db.close() catch unreachable;
// Create the posts table if it doesn't exist
db.exec(SQL_CREATE_TABLE, null, null, null) catch |e| return printSqliteErrMsg(db, e);
// Get commandline arguments
const args = try std.process.argsAlloc(alloc);
defer std.process.argsFree(alloc, args);
if (args.len < 2) {
std.log.warn(
\\ Incorrect usage.
\\ Usage: {s} <cmd>
\\ Possible commands:
\\ {s}
\\ {s}
\\ {s}
\\ {s}
\\
, .{ args[0], CMD_CREATE_POST, CMD_READ_POSTS, CMD_UPDATE_POST, CMD_DELETE_POST });
return;
}
var readOpts = ReadOptions{};
if (std.mem.eql(u8, args[1], CMD_READ_POSTS) and args.len == 3) {
const postId = std.fmt.parseInt(i64, args[2], 10) catch {
std.log.warn("Invalid post id\nUsage: {s} read [post-id]", .{args[0]});
return error.NotAnInt;
};
readOpts.singlePost = GetPostBy{ .Id = postId };
} else if (std.mem.eql(u8, args[1], CMD_CREATE_POST)) {
if (args.len != 4) {
std.log.warn("Error: wrong number of args\nUsage: {s} create <title> <content>\n", .{args[0]});
return;
}
var stmt = (try db.prepare_v2(SQL_INSERT_POST, null)).?;
try stmt.bindText(1, args[2], .static);
try stmt.bindText(2, args[2], .static);
std.debug.assert((try stmt.step()) == .Done);
try stmt.finalize();
readOpts.singlePost = GetPostBy{ .LastInserted = {} };
} else if (std.mem.eql(u8, args[1], CMD_UPDATE_POST)) {
if (args.len != 5) {
std.log.warn("Not enough arguments\nUsage: {s} update <post-id> <title> <content>\n", .{args[0]});
return error.NotEnoughArguments;
}
const id = std.fmt.parseInt(i64, args[2], 10) catch {
std.log.warn("Invalid post id\nUsage: {s} update <post-id> <title> <content>\n", .{args[0]});
return error.NotAnInt;
};
const title = args[3];
const content = args[4];
var stmt = (try db.prepare_v2(SQL_UPDATE_POST, null)).?;
try stmt.bindText(1, title, .static);
try stmt.bindText(2, content, .static);
try stmt.bindInt64(3, id);
std.debug.assert((try stmt.step()) == .Done);
try stmt.finalize();
readOpts.singlePost = GetPostBy{ .Id = id };
} else if (std.mem.eql(u8, args[1], CMD_DELETE_POST)) {
if (args.len != 3) {
std.log.warn("Not enough arguments\nUsage: {s} delete <post-id>\n", .{args[0]});
return error.WrongNumberOfArguments;
}
const id = std.fmt.parseInt(i64, args[2], 10) catch {
std.log.warn("Invalid post id\nUsage: {s} delete <post-id>\n", .{args[0]});
return error.NotAnInt;
};
var stmt = (try db.prepare_v2(SQL_DELETE_POST, null)).?;
try stmt.bindInt64(3, id);
std.debug.assert((try stmt.step()) == .Done);
try stmt.finalize();
}
const stdout = &std.io.getStdOut().writer();
try read(stdout, db, readOpts);
}
fn printSqliteErrMsg(db: *sqlite.SQLite3, e: sqlite.Error) !void {
std.log.warn("sqlite3 errmsg: {s}\n", .{db.errmsg()});
return e;
}
const GetPostByTag = enum {
Id,
LastInserted,
};
const GetPostBy = union(GetPostByTag) {
Id: i64,
LastInserted: void,
};
const ReadOptions = struct {
singlePost: ?GetPostBy = null,
};
fn read(out: anytype, db: *sqlite.SQLite3, opts: ReadOptions) !void {
if (opts.singlePost) |post| {
const sql = switch (post) {
.Id => SQL_GET_POST_BY_ID,
.LastInserted => SQL_GET_LAST_INSERTED,
};
var stmt = (try db.prepare_v2(sql, null)).?;
defer stmt.finalize() catch {};
if (post == .LastInserted) {
try stmt.bindInt64(1, post.Id);
}
switch (try stmt.step()) {
.Ok, .Row => {},
.Done => {
std.log.warn("No post with id '{}'\n", .{post});
return error.InvalidPostId;
},
}
try displaySinglePost(out, stmt);
} else {
var stmt = (try db.prepare_v2(SQL_GET_POSTS, null)).?;
defer stmt.finalize() catch {};
try out.print("Posts:\n", .{});
while ((try stmt.step()) == .Row) {
const id = stmt.columnInt64(0);
const title = stmt.columnText(1);
const content = stmt.columnText(2);
try out.print("\t{}\t{s}\t{s}\n", .{ id, title, content });
}
}
}
fn displaySinglePost(out: anytype, stmt: *sqlite.Stmt) !void {
const id = stmt.columnInt64(0);
const title = stmt.columnText(1);
const content = stmt.columnText(2);
try out.print(
\\ Id: {}
\\ Title: {s}
\\
\\ {s}
\\
, .{ id, title, content });
}