sqlite3_database.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /* SQLite3 database backend. */
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <unistd.h>
  5. #include <sqlite3.h>
  6. #include "database.h"
  7. #include "utils.h"
  8. /* sqlite3_busy_timeout sleeps for a *second*. What a piece of shit. */
  9. static int busy(void *unused __attribute__((unused)), int count)
  10. {
  11. usleep(50000);
  12. /* If we've been stuck for 1000 iterations (at least 50
  13. * seconds), give up. */
  14. return (count < 1000);
  15. }
  16. void *db_open(const char *file)
  17. {
  18. sqlite3 *handle;
  19. int err = sqlite3_open(file, &handle);
  20. if (err != SQLITE_OK)
  21. printf("Error %i from sqlite3_open of db '%s'\n", err, file);
  22. sqlite3_busy_handler(handle, busy, NULL);
  23. return handle;
  24. }
  25. static int query_cb(void *data, int num, char**vals,
  26. char**names __attribute__((unused)))
  27. {
  28. int i;
  29. struct db_query *query = data;
  30. query->rows = realloc_array(query->rows, query->num_rows+1);
  31. query->rows[query->num_rows] = new_array(char *, num);
  32. for (i = 0; i < num; i++) {
  33. /* We don't count rows with NULL results
  34. * (eg. count(*),player where count turns out to be
  35. * zero. */
  36. if (!vals[i])
  37. return 0;
  38. query->rows[query->num_rows][i] = strdup(vals[i]);
  39. }
  40. query->num_rows++;
  41. return 0;
  42. }
  43. /* Runs query (SELECT). Fails if > 1 row returned. Fills in columns. */
  44. struct db_query *db_query(void *h, const char *query)
  45. {
  46. struct db_query *ret;
  47. char *err;
  48. ret = (struct db_query*) palloc(sizeof(struct db_query));
  49. ret->rows = NULL;
  50. ret->num_rows = 0;
  51. if (sqlite3_exec(h, query, query_cb, ret, &err) != SQLITE_OK)
  52. printf("Failed sqlite3 query '%s': %s", query, err);
  53. return ret;
  54. }
  55. /* Runs command (CREATE TABLE/INSERT) */
  56. void db_command(void *h, const char *command)
  57. {
  58. char *err;
  59. if (sqlite3_exec(h, command, NULL, NULL, &err) != SQLITE_OK)
  60. printf("Failed sqlite3 command '%s': %s", command, err);
  61. }
  62. /* Closes database (only called when everything OK). */
  63. void db_close(void *h)
  64. {
  65. sqlite3_close(h);
  66. }