diff --git a/Makefile b/Makefile index 6fe4151..2ef696b 100644 --- a/Makefile +++ b/Makefile @@ -97,7 +97,7 @@ clean: -e "s!@CGIURI@!$(CGIURI)!g" $< >$@ $(TARGET): $(OBJS) - $(CC) $(STATIC) -o $@ $(OBJS) $(LDFLAGS) -lkcgi -lkcgijson -lz -lsqlite3 -pthread + $(CC) $(STATIC) -o $@ $(OBJS) ksql.o $(LDFLAGS) -lkcgi -lkcgijson -lz -lsqlite3 -pthread $(OBJS): extern.h diff --git a/db.c b/db.c index 6f62570..d3c7447 100644 --- a/db.c +++ b/db.c @@ -28,6 +28,39 @@ #include "extern.h" +enum stmt { + STMT_BOOK, + STMT__MAX +}; + +static const char *const stmts[STMT__MAX] = { + /* STMT_BOOK */ + "SELECT books.id AS id,title FROM books WHERE books.id = ?", +}; + +struct book * +db_book_load(struct kreq *r, int64_t id) +{ + struct ksqlstmt *stmt; + struct book *book; + int i = 0; + + ksql_stmt_alloc(r->arg, &stmt, + stmts[STMT_BOOK], + STMT_BOOK); + ksql_bind_int(stmt, 0, id); + if (KSQL_ROW != ksql_stmt_step(stmt)) { + ksql_stmt_free(stmt); + return(NULL); + } + book = kcalloc(1, sizeof(struct book)); + book->id = ksql_stmt_int(stmt, i++); + book->title = kstrdup(ksql_stmt_str(stmt, i++)); + ksql_stmt_free(stmt); + return book; +} + + /* * Open the database and stash the resulting handle in the d */ diff --git a/extern.h b/extern.h index 9c421d7..918f809 100644 --- a/extern.h +++ b/extern.h @@ -17,8 +17,18 @@ #ifndef EXTERN_H #define EXTERN_H +/* + * A book. + */ +struct book { + int64_t id; /* unique identifier */ + char *title; +}; + __BEGIN_DECLS +struct book * db_book_load(struct kreq *r, int64_t id); + void db_close(struct kreq *); int db_open(struct kreq *, const char *); diff --git a/main.c b/main.c index e9cbe3f..fa92e7d 100644 --- a/main.c +++ b/main.c @@ -101,8 +101,10 @@ sendbooks(struct kreq *r) id = r->fieldmap[KEY_ID]->parsed.i; if (r->path[0] != '\0') id = strtonum(r->path, INT64_MIN, INT64_MAX, &errid); - if (id > 0) + if (id > 0) { kjson_putintp(&req, "id", id); + db_book_load(r, id); + } kjson_putstringp(&req, "_path", r->path); kjson_putstringp(&req, "_pname", r->pname);