aboutsummaryrefslogtreecommitdiff
path: root/odb/relational/sqlite/context.cxx
blob: 710e9fbfbafb6b48a0fddf5c2bba21fc13550647 (plain)
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
// file      : odb/relational/sqlite/context.cxx
// author    : Boris Kolpackov <boris@codesynthesis.com>
// copyright : Copyright (c) 2009-2011 Code Synthesis Tools CC
// license   : GNU GPL v3; see accompanying LICENSE file

#include <vector>
#include <cassert>
#include <sstream>

#include <odb/sql-token.hxx>
#include <odb/sql-lexer.hxx>

#include <odb/relational/sqlite/context.hxx>
#include <odb/relational/sqlite/common.hxx>

using namespace std;

namespace relational
{
  namespace sqlite
  {
    namespace
    {
      struct type_map_entry
      {
        const char* const cxx_type;
        const char* const db_type;
        const char* const db_id_type;
      };

      type_map_entry type_map[] =
      {
        {"bool", "INTEGER", 0},

        {"char", "INTEGER", 0},
        {"signed char", "INTEGER", 0},
        {"unsigned char", "INTEGER", 0},

        {"short int", "INTEGER", 0},
        {"short unsigned int", "INTEGER", 0},

        {"int", "INTEGER", 0},
        {"unsigned int", "INTEGER", 0},

        {"long int", "INTEGER", 0},
        {"long unsigned int", "INTEGER", 0},

        {"long long int", "INTEGER", 0},
        {"long long unsigned int", "INTEGER", 0},

        {"float", "REAL", 0},
        {"double", "REAL", 0},

        {"::std::string", "TEXT", 0}
      };
    }

    context* context::current_;

    context::
    ~context ()
    {
      if (current_ == this)
        current_ = 0;
    }

    context::
    context (ostream& os,
             semantics::unit& u,
             options_type const& ops,
             sema_rel::model* m)
        : root_context (os, u, ops, data_ptr (new (shared) data (os))),
          base_context (static_cast<data*> (root_context::data_.get ()), m),
          data_ (static_cast<data*> (base_context::data_))
    {
      assert (current_ == 0);
      current_ = this;

      generate_grow = true;
      need_alias_as = true;
      insert_send_auto_id = true;
      data_->bind_vector_ = "sqlite::bind*";
      data_->truncated_vector_ = "bool*";

      // Populate the C++ type to DB type map.
      //
      for (size_t i (0); i < sizeof (type_map) / sizeof (type_map_entry); ++i)
      {
        type_map_entry const& e (type_map[i]);

        type_map_type::value_type v (
          e.cxx_type,
          db_type_type (e.db_type, e.db_id_type ? e.db_id_type : e.db_type));

        data_->type_map_.insert (v);
      }
    }

    context::
    context ()
        : data_ (current ().data_)
    {
    }

    namespace
    {
      struct has_grow: traversal::class_
      {
        has_grow (bool& r)
            : r_ (r)
        {
          *this >> inherits_ >> *this;
        }

        virtual void
        traverse (type& c)
        {
          // Ignore transient bases.
          //
          if (!(context::object (c) || context::composite (c)))
            return;

          if (c.count ("sqlite-grow"))
            r_ = c.get<bool> ("sqlite-grow");
          else
          {
            // r_ should be false.
            //
            inherits (c);

            if (!r_)
              names (c);

            c.set ("sqlite-grow", r_);
          }
        }

      private:
        bool& r_;
        traversal::inherits inherits_;
      };

      struct has_grow_member: member_base
      {
        has_grow_member (bool& r,
                         semantics::type* type = 0,
                         string const& key_prefix = string ())
            : relational::member_base (type, string (), key_prefix),
              r_ (r)
        {
        }

        virtual void
        traverse_composite (member_info& mi)
        {
          // By calling grow() instead of recursing, we reset any overrides.
          //
          r_ = r_ || context::grow (dynamic_cast<semantics::class_&> (mi.t));
        }

        virtual void
        traverse_string (member_info&)
        {
          r_ = true;
        }

      private:
        bool& r_;
      };
    }

    bool context::
    grow_impl (semantics::class_& c)
    {
      if (c.count ("sqlite-grow"))
        return c.get<bool> ("sqlite-grow");

      bool r (false);
      has_grow ct (r);
      has_grow_member mt  (r);
      traversal::names names;
      ct >> names >> mt;
      ct.traverse (c);
      return r;
    }

    bool context::
    grow_impl (semantics::data_member& m)
    {
      bool r (false);
      has_grow_member mt  (r);
      mt.traverse (m);
      return r;
    }

    bool context::
    grow_impl (semantics::data_member& m, semantics::type& t, string const& kp)
    {
      bool r (false);
      has_grow_member mt  (r, &t, kp);
      mt.traverse (m);
      return r;
    }

    string context::
    database_type_impl (semantics::type& t, semantics::names* hint, bool id)
    {
      string r (base_context::database_type_impl (t, hint, id));

      if (!r.empty ())
        return r;

      using semantics::enum_;

      if (t.is_a<semantics::enum_> ())
        r = "INTEGER";

      return r;
    }

    //
    // SQL type parsing.
    //

    namespace
    {
      struct sql_parser
      {
        typedef context::invalid_sql_type invalid_sql_type;

        sql_parser (std::string const& sql)
            : l_ (sql)
        {
        }

        sql_type
        parse ()
        {
          try
          {
            for (sql_token t (l_.next ()); t.type () != sql_token::t_eos;)
            {
              sql_token::token_type tt (t.type ());

              if (tt == sql_token::t_identifier)
              {
                string const& id (context::upcase (t.identifier ()));

                // Column constraints start with one of the following
                // keywords. Use them to determine when to stop parsing.
                //
                if (id == "CONSTRAINT" ||
                    id == "PRIMARY" ||
                    id == "NOT" ||
                    id == "UNIQUE" ||
                    id == "CHECK" ||
                    id == "DEFAULT" ||
                    id == "COLLATE" ||
                    id == "REFERENCES")
                {
                  break;
                }

                ids_.push_back (id);
                t = l_.next ();

                if (t.punctuation () == sql_token::p_lparen)
                {
                  parse_range ();
                  t = l_.next ();
                }
              }
              else
              {
                throw invalid_sql_type (
                  "expected SQLite type name instead of '" + t.string () +
                  "'");
              }
            }
          }
          catch (sql_lexer::invalid_input const& e)
          {
            throw invalid_sql_type (
              "invalid SQLite type declaration: " + e.message);
          }

          if (ids_.empty ())
            throw invalid_sql_type ("expected SQLite type name");

          sql_type r;

          // Apply the first four rules of the SQLite type to affinity
          // conversion algorithm.
          //
          if (find ("INT"))
            r.type = sql_type::INTEGER;
          else if (find ("TEXT") || find ("CHAR") || find ("CLOB"))
            r.type = sql_type::TEXT;
          else if (find ("BLOB"))
            r.type = sql_type::BLOB;
          else if (find ("REAL") || find ("FLOA") || find ("DOUB"))
            r.type = sql_type::REAL;
          else
          {
            // Instead of the fifth rule which maps everything else
            // to NUMERICAL (which we don't have), map some commonly
            // used type names to one of the above types.
            //
            string const& id (ids_[0]);

            if (id == "NUMERIC")
              r.type = sql_type::REAL;
            else if (id == "DECIMAL")
              r.type = sql_type::TEXT;
            else if (id == "BOOLEAN" || id == "BOOL")
              r.type = sql_type::INTEGER;
            else if (id == "DATE" || id == "TIME" || id == "DATETIME")
              r.type = sql_type::TEXT;
            else
            {
              throw invalid_sql_type ("unknown SQLite type '" + id + "'");
            }
          }

          return r;
        }

        void
        parse_range ()
        {
          // Skip tokens until we get the closing paren.
          //
          for (sql_token t (l_.next ());; t = l_.next ())
          {
            if (t.punctuation () == sql_token::p_rparen)
              break;

            if (t.type () == sql_token::t_eos)
            {
              throw invalid_sql_type (
                "missing ')' in SQLite type declaration");
            }
          }
        }

        bool
        find (string const& str) const
        {
          for (identifiers::const_iterator i (ids_.begin ());
               i != ids_.end (); ++i)
          {
            if (i->find (str) != string::npos)
              return true;
          }

          return false;
        }

      private:
        typedef vector<string> identifiers;

      private:
        sql_lexer l_;
        identifiers ids_;
      };
    }

    sql_type const& context::
    column_sql_type (semantics::data_member& m, string const& kp)
    {
      string key (kp.empty ()
                  ? string ("sqlite-column-sql-type")
                  : "sqlite-" + kp + "-column-sql-type");

      if (!m.count (key))
      {
        try
        {
          m.set (key, parse_sql_type (column_type (m, kp)));
        }
        catch (invalid_sql_type const& e)
        {
          cerr << m.file () << ":" << m.line () << ":" << m.column ()
               << ": error: " << e.message () << endl;

          throw operation_failed ();
        }
      }

      return m.get<sql_type> (key);
    }

    sql_type context::
    parse_sql_type (string const& t)
    {
      sql_parser p (t);
      return p.parse ();
    }
  }
}