aboutsummaryrefslogtreecommitdiff
path: root/migrate/migrate.cxx
blob: 4001bf983490583903ed5d48b5ffd8c31ba1928a (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
// file      : migrate/migrate.cxx -*- C++ -*-
// copyright : Copyright (c) 2014-2017 Code Synthesis Ltd
// license   : MIT; see accompanying LICENSE file

#include <strings.h> // strcasecmp()

#include <sstream>
#include <iostream>

#include <odb/database.hxx>
#include <odb/transaction.hxx>
#include <odb/schema-catalog.hxx>

#include <odb/pgsql/database.hxx>

#include <butl/pager>

#include <brep/types>
#include <brep/utility>
#include <brep/version>

#include <brep/database-lock>

#include <migrate/migrate-options>

using namespace std;
using namespace odb::core;
using namespace brep;

// Operation failed, diagnostics has already been issued.
//
struct failed: std::exception {};

static const char* help_info (
  "  info: run 'brep-migrate --help' for more information");

// Helper class that encapsulates both the ODB-generated schema and the
// extra that comes from a .sql file (via xxd).
//
class schema
{
public:
  explicit
  schema (const char* extra);

  void
  create (database&) const;

  void
  drop (database&) const;

private:
  strings drop_statements_;
  strings create_statements_;
};

schema::
schema (const char* s)
{
  // Remove comments, saving the cleaned SQL code into statements.
  //
  string statements;
  for (istringstream i (s); i; )
  {
    // Skip leading spaces (including consequtive newlines). In case we
    // hit eof, keep c set to '\n'.
    //
    char c;
    static const string spaces (" \t\n\r");
    for (c = '\n'; i.get (c) && spaces.find (c) != string::npos; c = '\n')
      ;

    // First non-space character (or '\n' for eof). See if this is a comment.
    //
    bool skip (c == '\n' || (c == '-' && i.peek () == '-'));

    // Read until newline (and don't forget the character we already have).
    //
    do
    {
      if (!skip)
        statements.push_back (c);

    } while (c != '\n' && i.get (c));
  }

  istringstream i (move (statements));

  // Build CREATE and DROP statement lists.
  //
  while (i)
  {
    string op;
    if (i >> op) // Get the first word.
    {
      string statement (op);

      auto read_until = [&i, &statement](const char stop[2]) -> bool
        {
          for (char prev ('\0'), c; i.get (c); prev = c)
          {
            statement.push_back (c);

            if (stop[0] == prev && stop[1] == c)
              return true;
          }

          return false;
        };

      if (strcasecmp (op.c_str (), "CREATE") == 0)
      {
        string kw;
        i >> kw;
        statement += " " + kw;

        if (strcasecmp (kw.c_str (), "FUNCTION") == 0)
        {
          if (!read_until ("$$") || !read_until ("$$"))
          {
            cerr << "error: function body must be defined using $$-quoted "
              "strings" << endl;
            throw failed ();
          }
        }
        else if (strcasecmp (kw.c_str (), "TYPE") == 0)
        {
          // Fall through.
        }
        else
        {
          cerr << "error: unexpected CREATE statement" << endl;
          throw failed ();
        }

        if (!read_until (";\n"))
        {
          cerr << "error: expected ';\\n' at the end of CREATE statement"
               << endl;
          throw failed ();
        }

        assert (!statement.empty ());
        create_statements_.emplace_back (move (statement));
      }
      else if (strcasecmp (op.c_str (), "DROP") == 0)
      {
        if (!read_until (";\n"))
        {
          cerr << "error: expected ';\\n' at the end of DROP statement"
               << endl;
          throw failed ();
        }

        assert (!statement.empty ());
        drop_statements_.emplace_back (move (statement));
      }
      else
      {
        cerr << "error: unexpected statement starting with '" << op << "'"
             << endl;
        throw failed ();
      }
    }
  }
}

void schema::
drop (database& db) const
{
  for (const auto& s: drop_statements_)
    // If the statement execution fails, the corresponding source file line
    // number is not reported. The line number could be usefull for the
    // utility implementer only. The errors seen by the end-user should not be
    // statement-specific.
    //
    db.execute (s);

  schema_catalog::drop_schema (db);
}

void schema::
create (database& db) const
{
  drop (db);

  schema_catalog::create_schema (db);

  for (const auto& s: create_statements_)
    db.execute (s);
}

// main() function
//
int
main (int argc, char* argv[])
try
{
  cli::argv_scanner scan (argc, argv, true);
  options ops (scan);

  // Version.
  //
  if (ops.version ())
  {
    cout << "brep-migrate " << BREP_VERSION_STR << endl
         << "libbrep " << LIBBREP_VERSION_STR << endl
         << "libbpkg " << LIBBPKG_VERSION_STR << endl
         << "libbutl " << LIBBUTL_VERSION_STR << endl
         << "Copyright (c) 2014-2017 Code Synthesis Ltd" << endl
         << "MIT; see accompanying LICENSE file" << endl;

    return 0;
  }

  // Help.
  //
  if (ops.help ())
  {
    butl::pager p ("brep-migrate help",
                   false,
                   ops.pager_specified () ? &ops.pager () : nullptr,
                   &ops.pager_option ());

    print_usage (p.stream ());

    // If the pager failed, assume it has issued some diagnostics.
    //
    return p.wait () ? 0 : 1;
  }

  if (argc > 1)
  {
    cerr << "error: unexpected argument encountered" << endl
         << help_info << endl;
    return 1;
  }

  if (ops.recreate () && ops.drop ())
  {
    cerr << "error: inconsistent options specified" << endl
         << help_info << endl;
    return 1;
  }

  odb::pgsql::database db (
    ops.db_user (),
    ops.db_password (),
    ops.db_name (),
    ops.db_host (),
    ops.db_port (),
    "options='-c default_transaction_isolation=serializable'");

  // Prevent several brep-migrate/load instances from updating DB
  // simultaneously.
  //
  database_lock l (db);

  // Need to obtain schema version out of the transaction. If the
  // schema_version table does not exist, the SQL query fails, which makes the
  // transaction useless as all consequitive queries in that transaction will
  // be ignored by PostgreSQL.
  //
  schema_version schema_version (db.schema_version ());

  // It is impossible to operate with the database which is out of the
  // [base_version, current_version] range due to the lack of the knowlege
  // required not just for migration, but for the database wiping as well.
  //
  if (schema_version > 0)
  {
    if (schema_version < schema_catalog::base_version (db))
    {
      cerr << "error: database schema is too old" << endl;
      throw failed ();
    }

    if (schema_version > schema_catalog::current_version (db))
    {
      cerr << "error: database schema is too new" << endl;
      throw failed ();
    }
  }

  bool drop (ops.drop ());
  bool create (ops.recreate () || (schema_version == 0 && !drop));
  assert (!create || !drop);

  // The database schema recreation requires dropping it initially, which is
  // impossible before the database is migrated to the current schema version.
  // Let the user decide if they want to migrate or just drop the entire
  // database (followed with the database creation for the --recreate option).
  //
  if ((create || drop) && schema_version != 0 &&
      schema_version != schema_catalog::current_version (db))
  {
    cerr << "error: database schema requires migration" << endl
         << "  info: either migrate the database first or drop the entire "
            "database using, for example, psql" << endl;
    throw failed ();
  }

  transaction t (db.begin ());

  if (create || drop)
  {
    static const char extras[] = {
#include <brep/package-extra>
      , '\0'};

    schema s (extras);

    if (create)
      s.create (db);
    else if (drop)
      s.drop (db);
  }
  else
  {
    // Register the data migration functions.
    //
    // static const data_migration_entry<2, LIBBREP_SCHEMA_VERSION_BASE>
    // migrate_v2_entry (&migrate_v2);
    //
    schema_catalog::migrate (db);
  }

  t.commit ();
  return 0;
}
catch (const database_locked&)
{
  cerr << "brep-migrate or brep-load instance is running" << endl;
  return 2;
}
catch (const recoverable& e)
{
  cerr << "database recoverable error: " << e.what () << endl;
  return 3;
}
catch (const cli::exception& e)
{
  cerr << "error: " << e << endl << help_info << endl;
  return 1;
}
catch (const failed&)
{
  return 1; // Diagnostics has already been issued.
}
// Fully qualified to avoid ambiguity with odb exception.
//
catch (const std::exception& e)
{
  cerr << "error: " << e.what () << endl;
  return 1;
}