SQL load book

This commit is contained in:
Meutel 2016-12-29 21:02:58 +01:00
parent 09d594bdee
commit 9d876bdb7c
4 changed files with 47 additions and 2 deletions

View File

@ -97,7 +97,7 @@ clean:
-e "s!@CGIURI@!$(CGIURI)!g" $< >$@ -e "s!@CGIURI@!$(CGIURI)!g" $< >$@
$(TARGET): $(OBJS) $(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 $(OBJS): extern.h

33
db.c
View File

@ -28,6 +28,39 @@
#include "extern.h" #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 * Open the database and stash the resulting handle in the d
*/ */

View File

@ -17,8 +17,18 @@
#ifndef EXTERN_H #ifndef EXTERN_H
#define EXTERN_H #define EXTERN_H
/*
* A book.
*/
struct book {
int64_t id; /* unique identifier */
char *title;
};
__BEGIN_DECLS __BEGIN_DECLS
struct book * db_book_load(struct kreq *r, int64_t id);
void db_close(struct kreq *); void db_close(struct kreq *);
int db_open(struct kreq *, const char *); int db_open(struct kreq *, const char *);

4
main.c
View File

@ -101,8 +101,10 @@ sendbooks(struct kreq *r)
id = r->fieldmap[KEY_ID]->parsed.i; id = r->fieldmap[KEY_ID]->parsed.i;
if (r->path[0] != '\0') if (r->path[0] != '\0')
id = strtonum(r->path, INT64_MIN, INT64_MAX, &errid); id = strtonum(r->path, INT64_MIN, INT64_MAX, &errid);
if (id > 0) if (id > 0) {
kjson_putintp(&req, "id", id); kjson_putintp(&req, "id", id);
db_book_load(r, id);
}
kjson_putstringp(&req, "_path", r->path); kjson_putstringp(&req, "_path", r->path);
kjson_putstringp(&req, "_pname", r->pname); kjson_putstringp(&req, "_pname", r->pname);