aboutsummaryrefslogtreecommitdiff
path: root/odb/relational/sqlite/context.cxx
blob: faaa3b55d71204e5920e2064e73f284ca958eb6e (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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
// file      : odb/relational/sqlite/context.cxx
// copyright : Copyright (c) 2009-2012 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,
             features_type& f,
             sema_rel::model* m)
        : root_context (os, u, ops, f, 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;
      delay_freeing_statement_result = false;
      need_image_clone = false;
      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_)
    {
    }

    string const& context::
    convert_expr (string const& sqlt, semantics::data_member& m, bool to)
    {
      sql_type const& t (parse_sql_type (sqlt, m));
      return to ? t.to : t.from;
    }

    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 (custom_db_types const* ct): ct_ (ct) {}

        sql_type
        parse (string sql)
        {
          sql_type r;

          // First run the type through the custom mapping, if requested.
          //
          if (ct_ != 0)
          {
            for (custom_db_types::const_iterator i (ct_->begin ());
                 i != ct_->end (); ++i)
            {
              custom_db_type const& t (*i);

              if (t.type.match (sql))
              {
                r.to = t.type.replace (sql, t.to);
                r.from = t.type.replace (sql, t.from);
                sql = t.type.replace (sql, t.as);
                break;
              }
            }
          }

          // Parse the type into a sequence of identifiers.
          //
          try
          {
            l_.lex (sql);

            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)
              {
                ids_.push_back (context::upcase (t.identifier ()));
                t = l_.next ();

                if (t.punctuation () == sql_token::p_lparen)
                {
                  if (!parse_range ())
                    return error (m_);

                  t = l_.next ();
                }
              }
              else
                return error ("expected SQLite type name instead of '" +
                              t.string () + "'");
            }
          }
          catch (sql_lexer::invalid_input const& e)
          {
            return error ("invalid SQLite type declaration: " + e.message);
          }

          if (ids_.empty ())
            return error ("expected SQLite type name");

          // 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
              return error ("unknown SQLite type '" + id + "'");
          }

          return r;
        }

        bool
        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)
            {
              m_ = "missing ')' in SQLite type declaration";
              return false;
            }
          }

          return true;
        }

      private:
        sql_type
        error (string const& m)
        {
          if (ct_ == 0)
            return sql_type ();
          else
            throw invalid_sql_type (m);
        }

        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:
        custom_db_types const* ct_;
        sql_lexer l_;
        string m_; // Error message.

        typedef vector<string> identifiers;
        identifiers ids_;
      };
    }

    sql_type const& context::
    parse_sql_type (string const& t, semantics::data_member& m, bool custom)
    {
      // If this proves to be too expensive, we can maintain a cache of
      // parsed types across contexts.
      //
      data::sql_type_cache::iterator i (data_->sql_type_cache_.find (t));

      if (i != data_->sql_type_cache_.end ()
          && (custom ? i->second.custom_cached : i->second.straight_cached))
      {
        return (custom ? i->second.custom : i->second.straight);
      }
      else
      {
        try
        {
          sql_type st (
            parse_sql_type (
              t,
              custom ? &unit.get<custom_db_types> ("custom-db-types") : 0));

          if (custom)
            return data_->sql_type_cache_[t].cache_custom (st);
          else
            return data_->sql_type_cache_[t].cache_straight (st);
        }
        catch (invalid_sql_type const& e)
        {
          cerr << m.file () << ":" << m.line () << ":" << m.column ()
               << ": error: " << e.message () << endl;

          throw operation_failed ();
        }
      }
    }

    sql_type context::
    parse_sql_type (string const& sqlt, custom_db_types const* ct)
    {
      sql_parser p (ct);
      return p.parse (sqlt);
    }
  }
}