fd3a083af0e21991f53915ab38c0e07c8bf02e19
[cascardo/avaliacao2008.git] / helper.c
1 /*
2  *  Copyright (C) 2009  Thadeu Lima de Souza Cascardo <cascardo@holoscopio.com>
3  *
4  *  This program is free software; you can redistribute it and/or modify
5  *  it under the terms of the GNU General Public License as published by
6  *  the Free Software Foundation; either version 2 of the License, or
7  *  (at your option) any later version.
8  *
9  *  This program is distributed in the hope that it will be useful,
10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *  GNU General Public License for more details.
13  *
14  *  You should have received a copy of the GNU General Public License along
15  *  with this program; if not, write to the Free Software Foundation, Inc.,
16  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17  */
18
19 /*
20  * Somer helper functions to get some fields from the sqlite database.
21  */
22
23 #define _GNU_SOURCE
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <sqlite3.h>
28
29 static char * talker_user_query = "select %s from auth_user,"
30         "events_speaker where auth_user.id = events_speaker.user_id "
31         "and events_speaker.id = %d;";
32
33 static char * get_oneliner(sqlite3 *db, char *query, size_t qlen)
34 {
35         sqlite3_stmt *stmt;
36         int r;
37         char *value = NULL;
38         if (!qlen)
39                 qlen = strlen(query);
40         r = sqlite3_prepare_v2(db, query, qlen, &stmt, NULL);
41         while (sqlite3_step(stmt) == SQLITE_ROW) {
42                 if (value)
43                         free(value);
44                 value = strdup(sqlite3_column_text(stmt, 0));
45         }
46         sqlite3_finalize(stmt);
47         return value;
48 }
49
50 static char * get_oneliner_field_by_id(sqlite3 *db, char *query,
51                                        char *field, int id)
52 {
53         char *s;
54         int r;
55         char *value;
56         r = asprintf(&s, query, field, id);
57         value = get_oneliner(db, s, r);
58         free(s);
59         return value;
60 }
61
62 char * get_talker_email(sqlite3 *db, int id)
63 {
64         return get_oneliner_field_by_id(db, talker_user_query, "email", id);
65 }
66
67 char * get_talker_name(sqlite3 *db, int id)
68 {
69         return get_oneliner_field_by_id(db, talker_user_query, "first_name",
70                                         id);
71 }
72
73