summary refs log tree commit diff stats
path: root/lib/preposition.cpp
blob: c619bbfebb29cdec75afe395a286bbbe2e9780d1 (plain) (blame)
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
#include "verbly.h"

namespace verbly {
  
  std::string preposition::get_form() const
  {
    return form;
  }
  
  preposition_query::preposition_query(const data& _data) : _data(_data)
  {
    
  }
  
  preposition_query& preposition_query::limit(int _limit)
  {
    this->_limit = _limit;
    
    return *this;
  }
  
  preposition_query& preposition_query::random()
  {
    _random = true;
    
    return *this;
  }
  
  preposition_query& preposition_query::in_group(std::string _arg)
  {
    _in_group.push_back(_arg);
    
    return *this;
  }
  
  std::list<preposition> preposition_query::run() const
  {
    std::stringstream construct;
    construct << "SELECT form FROM prepositions";
    
    if (!_in_group.empty())
    {
      std::list<std::string> clauses(_in_group.size(), "groupname = @GNAME");
      construct << " WHERE preposition_id IN (SELECT preposition_id FROM preposition_groups WHERE ";
      construct << verbly::implode(std::begin(clauses), std::end(clauses), " OR ");
      construct << ")";
    }
    
    if (_random)
    {
      construct << " ORDER BY RANDOM()";
    }
    
    if (_limit != unlimited)
    {
      construct << " LIMIT " << _limit;
    }
    
    sqlite3_stmt* ppstmt;
    std::string query = construct.str();
    if (sqlite3_prepare_v2(_data.ppdb, query.c_str(), query.length(), &ppstmt, NULL) != SQLITE_OK)
    {
      throw std::runtime_error(sqlite3_errmsg(_data.ppdb));
    }
    
    for (auto& group : _in_group)
    {
      sqlite3_bind_text(ppstmt, sqlite3_bind_parameter_index(ppstmt, "@GNAME"), group.c_str(), group.length(), SQLITE_STATIC);
    }
    
    std::list<preposition> output;
    while (sqlite3_step(ppstmt) == SQLITE_ROW)
    {
      preposition pp;
      pp.form = std::string(reinterpret_cast<const char*>(sqlite3_column_text(ppstmt, 0)));
      
      output.push_back(pp);
    }
    
    return output;
  }

};