File: db_plugin_be.cpp

package info (click to toggle)
mysql-workbench 6.3.8%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 113,932 kB
  • ctags: 87,814
  • sloc: ansic: 955,521; cpp: 427,465; python: 59,728; yacc: 59,129; xml: 54,204; sql: 7,091; objc: 965; makefile: 638; sh: 613; java: 237; perl: 30; ruby: 6; php: 1
file content (592 lines) | stat: -rw-r--r-- 20,114 bytes parent folder | download
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
/* 
 * Copyright (c) 2009, 2016, Oracle and/or its affiliates. All rights reserved.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; version 2 of the
 * License.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301  USA
 */

#include <ostream>
#include <sstream>
#include <memory>

#include "db_plugin_be.h"
#include "grtsqlparser/sql_facade.h"
#include "grt/icon_manager.h"
#include "grts/structs.db.h"
#include "base/string_utilities.h"
#include "db.mysql/src/module_db_mysql.h"
#include "base/log.h"

#include <glib.h>

DEFAULT_LOG_DOMAIN("Db Plugin")

void Db_plugin::grtm(bec::GRTManager *grtm, bool reveng)
{
  Wb_plugin::grtm(grtm);

  if (_grtm)
  {
    grt::GRT *grt= _grtm->get_grt();

    _doc= workbench_DocumentRef::cast_from(_grtm->get_grt()->get("/wb/doc"));

    db_mgmt_ManagementRef mgmt= workbench_WorkbenchRef::cast_from(_doc->owner())->rdbmsMgmt();
    // don't need schema box for reverse engineer, but need it for fwd/sync (in case OmitQualifiers is on)
    _db_conn = new DbConnection(mgmt, db_mgmt_DriverRef(), reveng ? true : false); 

    _tables.icon_id(table_icon_id(bec::Icon16));
    _views.icon_id(view_icon_id(bec::Icon16));
    _routines.icon_id(routine_icon_id(bec::Icon16));
    _triggers.icon_id(trigger_icon_id(bec::Icon16));
    _users.icon_id(user_icon_id(bec::Icon16));

    _catalog= db_CatalogRef(grt);
  }
}


std::string Db_plugin::task_desc()
{
  return _("Apply SQL script to server");
}


db_mgmt_RdbmsRef Db_plugin::selected_rdbms()
{
  return db_mgmt_RdbmsRef::cast_from(_db_conn->get_connection()->driver()->owner());
}

db_CatalogRef Db_plugin::model_catalog()
{
  db_mgmt_RdbmsRef rdbms= selected_rdbms();

  // find first appropriate model catalog for selected rdbms
  grt::ListRef<workbench_physical_Model> physicalModels= _doc->physicalModels();
  for (size_t n= 0, count= physicalModels.count(); n < count; ++n)
  {
    workbench_physical_ModelRef model= physicalModels.get(n);
    if (model->rdbms().id() == rdbms.id())
    {
      _catalog= model->catalog();
      break;
    }
  }

  return _catalog;
}


Db_plugin::Db_objects_setup * Db_plugin::db_objects_setup_by_type(Db_object_type db_object_type)
{
  switch (db_object_type)
  {
  case dbotTable: return &_tables;
  case dbotView: return &_views;
  case dbotRoutine: return &_routines;
  case dbotTrigger: return &_triggers;
  case dbotUser: return &_users;
  default: return NULL;
  }
}


const char * Db_plugin::db_objects_type_to_string(Db_object_type db_object_type)
{
  switch (db_object_type)
  {
  case dbotTable: return "table";
  case dbotView: return "view";
  case dbotRoutine: return "routine";
  case dbotTrigger: return "trigger";
  case dbotUser: return "user";
  default: return NULL;
  }
}


std::string Db_plugin::db_objects_struct_name_by_type(Db_object_type db_object_type)
{
  grt::ObjectRef obj= _grtm->get_grt()->create_object<grt::internal::Object>(model_catalog().get_metaclass()->get_member_type("schemata").content.object_class);
  std::string attr_name= db_objects_type_to_string(db_object_type);
  attr_name.append("s"); // suffix denoting multiple objects
  if (attr_name.compare("triggers") == 0)
    obj= _grtm->get_grt()->create_object<grt::internal::Object>(obj.get_metaclass()->get_member_type("tables").content.object_class);
  else if (attr_name.compare("users") == 0)
    obj= model_catalog();
  return obj.get_metaclass()->get_member_type(attr_name).content.object_class;
}

/**
 * Check if on the server we're connecting we can expirence some case sensitivity problems,
 * return -1 if it's impossible to check
 * return 0 if everything is ok
 * return 1 if there can be some problems
 */
int Db_plugin::check_case_sensitivity_problems()
{

  sql::ConnectionWrapper dbc_conn = _db_conn->get_dbc_connection();
  boost::scoped_ptr<sql::Statement> statement(dbc_conn->createStatement());

  std::string compile_os;
  int lower_case_table_names = -1;
  {
    boost::scoped_ptr<sql::ResultSet> rs(statement->executeQuery("SELECT @@version_compile_os"));
    if (rs->next())
    {
      compile_os = rs->getString(1);
    }
  }
  {
    boost::scoped_ptr<sql::ResultSet> rs(statement->executeQuery("SELECT @@lower_case_table_names"));
    if (rs->next())
    {
      lower_case_table_names = rs->getInt(1);
    }
  }
  if (compile_os.empty() || lower_case_table_names == -1)
    return -1;

  if (lower_case_table_names == 0 && (base::starts_with(compile_os, "Win") || base::starts_with(compile_os, "osx")))
    return 1;

  if (lower_case_table_names == 2 && base::starts_with(compile_os, "Win"))
    return 1;

  return 0;
}

void Db_plugin::load_schemata(std::vector<std::string> &schemata)
{
  _schemata.clear();
  _schemata_ddl.clear();

  sql::ConnectionWrapper dbc_conn= _db_conn->get_dbc_connection();
  sql::DatabaseMetaData *dbc_meta(dbc_conn->getMetaData());

  _grtm->get_grt()->send_info(_("Fetching schema list."));
  _grtm->get_grt()->send_progress(0.0, _("Fetching schema list..."));

  const unsigned int major = dbc_meta->getDatabaseMajorVersion();
  const unsigned int minor = dbc_meta->getDatabaseMinorVersion();
  const unsigned int revision = dbc_meta->getDatabasePatchVersion();

  DbMySQLImpl *diffsql_module= _grtm->get_grt()->find_native_module<DbMySQLImpl>("DbMySQL");
  _db_options = diffsql_module->getTraitsForServerVersion(major, minor, revision);
  _db_options.set("CaseSensitive", grt::IntegerRef(dbc_meta->storesMixedCaseIdentifiers()));

  std::auto_ptr<sql::ResultSet> rset(dbc_meta->getSchemaObjects("", "", "schema"));
  _schemata.reserve(rset->rowsCount());
  float total= (float)rset->rowsCount();
  int current= 0;
  while (rset->next())
  {
    std::string name = rset->getString("name");
    if (name != "mysql" && name != "information_schema" && name != "performance_schema")
    {
      _schemata.push_back(name);
      _schemata_ddl[name]= rset->getString("ddl");
    }
    _grtm->get_grt()->send_progress(current++/total, name, "");
  }

  _grtm->get_grt()->send_progress(1.0, _("Fetch finished."));
  _grtm->get_grt()->send_info("OK");

  schemata= _schemata;
}

//
//void Db_plugin::default_schemata_selection(std::vector<std::string> &selection)
//{
//  grt::ListRef<db_Schema> model_schemata= model_catalog()->schemata();
//
//  for (grt::ListRef<db_Schema>::const_iterator It= model_schemata.begin(); It != model_schemata.end(); ++It)
//  {
//    selection.push_back((*It)->name());  
//  }
//  return;
///*
////select only schemas thet exists both in  DB and model
//  for (size_t n= 0, count= _schemata.size(); n < count; ++n)
//  {
//    db_SchemaRef model_schema= grt::find_named_object_in_list(model_schemata, _schemata[n].c_str());
//    if (model_schema.is_valid())
//      selection.push_back(_schemata[n]);
//  }
//  */
//}


void Db_plugin::schemata_selection(const std::vector<std::string> &selection, bool sel_none_means_sel_all)
{
  _schemata_selection= selection;

  if (sel_none_means_sel_all && !_schemata_selection.size())
    _schemata_selection= _schemata;
}


void Db_plugin::load_db_objects(Db_object_type db_object_type)
{
  Db_objects_setup *setup= db_objects_setup_by_type(db_object_type);
  setup->reset();

  _grtm->get_grt()->send_info(std::string("Fetching ").append(db_objects_type_to_string(db_object_type)).append(" list."));
  
  _grtm->get_grt()->send_progress(0.0, std::string("Fetching ").append(db_objects_type_to_string(db_object_type)).append(" list."));
  
  sql::ConnectionWrapper dbc_conn= _db_conn->get_dbc_connection();
  sql::DatabaseMetaData *dbc_meta(dbc_conn->getMetaData());
  std::string db_object_type_name= db_objects_type_to_string(db_object_type);
  std::list<Db_obj_handle> db_objects;
  std::list<std::string> db_obj_names;
  
  float total_schemas= (float)_schemata_selection.size();
  int current_schema= 0;
  
  for (std::vector<std::string>::const_iterator iter= _schemata_selection.begin(); 
    iter != _schemata_selection.end(); ++iter)
  {
    const std::string &schema_name= *iter;
    float total_objects;
    int count= 0;
    
    _grtm->get_grt()->send_progress((current_schema / total_schemas), 
                                    std::string("Fetch ").append(db_objects_type_to_string(db_object_type)).append(" objects from ").append(schema_name));

    if (!schema_name.empty())
    {
      try
      {
        std::auto_ptr<sql::ResultSet> rset(dbc_meta->getSchemaObjects("", schema_name, db_object_type_name));
        total_objects= (float)rset->rowsCount();
        while (rset->next())
        {
          Db_obj_handle db_obj;
          db_obj.schema= schema_name;
          db_obj.name= rset->getString("name");
          db_obj.ddl= rset->getString("ddl");
          setup->all.push_back(db_obj);
          
          // prefixed by schema name
          db_obj_names.push_back(std::string(schema_name).append(".").append(db_obj.name));
          
          _grtm->get_grt()->send_progress((current_schema / total_schemas) + (count / total_objects)/total_schemas,
                                          db_obj_names.back());
          
          count++;
        }
      }
      catch(std::exception &e)
      {
        std::string msg = base::strfmt("Failed to fetch %s objects from %s: %s", db_objects_type_to_string(db_object_type), schema_name.c_str(), e.what());
        _grtm->get_grt()->send_info(msg);
        log_error("Failed to fetch %s objects from %s: %s", db_objects_type_to_string(db_object_type), schema_name.c_str(), e.what());
      }
    }

    current_schema++;
    _grtm->get_grt()->send_info(base::strfmt("    %i items from %s", count, schema_name.c_str()));
  }
  
  // copy from temp list (used for performance optimization)
  setup->all.reserve(db_objects.size());
  std::copy(db_objects.begin(), db_objects.end(), setup->all.begin());
  db_objects.clear();

  // initialize db obj selection
  setup->selection.reset(db_obj_names);
  db_obj_names.clear();

  _grtm->get_grt()->send_progress(1.0, "Finished.");
  _grtm->get_grt()->send_info("OK");
}


/** read_back_view_ddl()
 
 Load back VIEW code from the database for everything we created, so that we know how it was normalized.

 This will go through the whole catalog and read the SQL definition for each view. This is needed because
 the server stores the view definition in a canonical form, which is quite different from what the user
 types (not only formatting is stripped, but object names are expanded and expressions are rewritten).
 That makes it impossible for us to synchronize by comparing the definition in the model with the
 definition in the server. So we need to store the server version of the view right after we create it in
 there and a snapshot of the view that was used to create that view. 
 
 During synchronization, we can detect changes in the model by comparing the model version of the snapshot with 
 the model SQL definition and detect server changes by comparing the server version of the definition with 
 the snapshot for the server. We need to do that separately for every target server that synchronization is 
 used with (using the db.SyncProfile object).
 */
void Db_plugin::read_back_view_ddl()
{
  Db_objects_setup *setup= db_objects_setup_by_type(dbotView);
  setup->reset();

  _grtm->get_grt()->send_info(std::string("Fetching back view definitions in final form."));

  _grtm->get_grt()->send_progress(0.0, std::string("Fetching back view definitions in final form."));

  sql::ConnectionWrapper dbc_conn= _db_conn->get_dbc_connection();
  sql::DatabaseMetaData *dbc_meta(dbc_conn->getMetaData());
  std::list<Db_obj_handle> db_objects;

  float total_views = 0;

  for (size_t sc = model_catalog()->schemata().count(), s = 0; s < sc; ++s)
  {
    db_SchemaRef schema(model_catalog()->schemata()[s]);
    total_views += schema->views().count();
  }
  if (total_views == 0)
  {
    _grtm->get_grt()->send_progress(1.0, "Finished.");
    _grtm->get_grt()->send_info("Nothing to fetch");
    return;
  }

  int current_view = 0;
  for (size_t sc = model_catalog()->schemata().count(), s = 0; s < sc; ++s)
  {
    db_SchemaRef schema(model_catalog()->schemata()[s]);
    for (size_t vc = schema->views().count(), v = 0; v < vc; ++v)
    {
      db_ViewRef view(schema->views()[v]);

      _grtm->get_grt()->send_progress((current_view / total_views),
                                      std::string("Fetch back database view code for ").append(schema->name()).append(".").append(view->name()));
      std::auto_ptr<sql::ResultSet> rset(dbc_meta->getSchemaObjects("", *schema->name(), "view", true, *view->name()));

      // take a snapshot of the server version of the SQL
      if (rset->next())
        view->oldServerSqlDefinition(grt::StringRef(rset->getString("ddl")));
      else
        _grtm->get_grt()->send_info(base::strfmt("Could not get definition for %s.%s from server", schema->name().c_str(), view->name().c_str()));

      // take a snapshot of the model version of the SQL
      view->oldModelSqlDefinition(view->sqlDefinition());

      current_view++;
    }
  }
  _grtm->get_grt()->send_progress(1.0, "Finished.");
  _grtm->get_grt()->send_info(base::strfmt("%i views were read back.", current_view));
}


bool Db_plugin::validate_db_objects_selection(std::list<std::string> *messages)
{
  // check if there are selected triggers without selected owner table
  Db_objects_setup *tables_setup= db_objects_setup_by_type(dbotTable);
  Db_objects_setup *triggers_setup= db_objects_setup_by_type(dbotTrigger);

  if (!triggers_setup->activated)
    return true;

  std::vector<std::string> triggers= _triggers.selection.items();
  std::vector<std::string> tables= _tables.selection.items();

  typedef std::vector<std::string>::iterator Iterator;
  for (Iterator tr_i= triggers.begin(), tr_i_end= triggers.end(); tr_i != tr_i_end; ++tr_i)
  {
    bool owner_table_selected= false;
    if (tables_setup->activated)
    {
      for (Iterator tbl_i= tables.begin(), tbl_i_end= tables.end(); tbl_i != tbl_i_end; ++tbl_i)
      {
        std::string table_dot= *tbl_i + ".";
        if (0 == tr_i->compare(0, table_dot.size(), table_dot, 0, std::string::npos))
        {
          owner_table_selected= true;
          break;
        }
      }
    }
    if (!owner_table_selected)
    {
      if (messages)
      {
        std::string err_msg;
        err_msg= "Owner table for trigger `" + *tr_i + "` was not selected.";
        messages->push_back(err_msg);
        err_msg= "Please either select the table or deselect triggers owned by that table.";
        messages->push_back(err_msg);
      }
      return false;
    }
  }

  return true;
}


void Db_plugin::dump_ddl(Db_object_type db_object_type, std::string &sql_script)
{
  std::string _non_std_sql_delimiter;
  {
    SqlFacade::Ref sql_facade= SqlFacade::instance_for_rdbms(selected_rdbms());
    Sql_specifics::Ref sql_specifics= sql_facade->sqlSpecifics();
    _non_std_sql_delimiter= sql_specifics->non_std_sql_delimiter();
  }

  Db_objects_setup *setup= db_objects_setup_by_type(db_object_type);
  if (setup->activated)
  {
    bec::GrtStringListModel::Items_ids items_ids= setup->selection.items_ids();
    for (size_t n= 0, count= items_ids.size(); n < count; ++n)
    {
      Db_obj_handle &db_obj= setup->all[items_ids[n]];

      sql_script
        .append("USE `")
        .append(db_obj.schema)
        .append("`;\n");

      if (dbotRoutine == db_object_type || dbotTrigger == db_object_type)
        sql_script.append(base::strfmt("DELIMITER %s\n", _non_std_sql_delimiter.c_str()));

      if (g_utf8_validate(db_obj.ddl.c_str(), -1, NULL))
        sql_script.append(db_obj.ddl);
      else
        sql_script
        .append("CREATE ... ")
        .append(db_objects_struct_name_by_type(db_object_type))
        .append(" `")
        .append(db_obj.schema)
        .append("`.`")
        .append(db_obj.name)
        .append("`: DDL contains non-UTF symbol(s)");

      if (dbotRoutine == db_object_type || dbotTrigger == db_object_type)
        sql_script.append(base::strfmt(" %s\nDELIMITER ;\n", _non_std_sql_delimiter.c_str()));

      sql_script.append(";\n\n");
    }
  }
}


void Db_plugin::dump_ddl(std::string &sql_script)
{
  /*
  alter/diff/sync module requirement: create selected schemata first.
  even if schema is empty the corresponding object must be created.
  */
  // process only selected objects
  for (std::vector<std::string>::const_iterator iter= _schemata_selection.begin();
    iter != _schemata_selection.end(); ++iter)
  {
    sql_script
      .append(_schemata_ddl[*iter])
      .append(";\n\n");
  }

  dump_ddl(dbotTable, sql_script);
  dump_ddl(dbotView, sql_script);
  dump_ddl(dbotRoutine, sql_script);
  dump_ddl(dbotTrigger, sql_script);
}


db_CatalogRef Db_plugin::db_catalog()
{
  db_CatalogRef mod_cat= model_catalog();

  if(!mod_cat.is_valid())
    throw std::runtime_error(_("Internal error. Catalog is invalid"));

  workbench_physical_ModelRef pm= workbench_physical_ModelRef::cast_from(mod_cat->owner());

  std::string sql_input_script;
  dump_ddl(sql_input_script);

  db_CatalogRef catalog= _grtm->get_grt()->create_object<db_Catalog>(mod_cat.get_metaclass()->name());
  catalog->version(pm->rdbms()->version());
  grt::replace_contents(catalog->simpleDatatypes(), pm->rdbms()->simpleDatatypes());
  catalog->name("default");
  catalog->oldName(catalog->name());

  SqlFacade::Ref sql_parser= SqlFacade::instance_for_rdbms(pm->rdbms());
  grt::DictRef parse_options(_grtm->get_grt());
  parse_options.set("case_sensitive_identifiers", _db_options.get("CaseSensitive", grt::IntegerRef(1)));
  sql_parser->parseSqlScriptStringEx(catalog, sql_input_script, parse_options);

  return catalog;
}


void Db_plugin::set_task_proc()
{
  _task_proc_cb= boost::bind(&Db_plugin::apply_script_to_db, this, _1);
}


grt::StringRef Db_plugin::apply_script_to_db(grt::GRT *grt)
{
  sql::ConnectionWrapper conn= db_conn()->get_dbc_connection();
  std::auto_ptr<sql::Statement> stmt(conn->createStatement());

  grt->send_info(_("Executing SQL script in server"));
  
  std::list<std::string> statements;
  SqlFacade::Ref sql_splitter= SqlFacade::instance_for_rdbms(selected_rdbms());
  sql_splitter->splitSqlScript(_sql_script, statements);

  sql::SqlBatchExec sql_batch_exec;

  sql_batch_exec.error_cb(boost::bind(&Db_plugin::process_sql_script_error, this, _1, _2, _3));
  sql_batch_exec.batch_exec_progress_cb(boost::bind(&Db_plugin::process_sql_script_progress, this, _1));
  sql_batch_exec.batch_exec_stat_cb(boost::bind(&Db_plugin::process_sql_script_statistics, this, _1, _2));

  sql_batch_exec(stmt.get(), statements);

  return grt::StringRef(_("The SQL script was successfully applied to server"));
}


int Db_plugin::process_sql_script_error(long long err_no, const std::string &err_msg, const std::string &statement)
{
  std::ostringstream oss;
  std::string stmt = base::trim(statement, "\n");

  base::replace(stmt, "\n", "\n        ");
  stmt = "        " + stmt;

  oss << _("Error ") << err_no << ": " << err_msg << std::endl << _("SQL Code:") << std::endl << stmt << std::endl;
  _grtm->get_grt()->send_error(oss.str());
  return 0;
}


int Db_plugin::process_sql_script_progress(float progress_state)
{
  _grtm->get_grt()->send_progress(progress_state, "");
  return 0;
}


int Db_plugin::process_sql_script_statistics(long success_count, long err_count)
{
  std::ostringstream oss;
  oss << _("SQL script execution finished: statements: ") << success_count << _(" succeeded, ")
    << err_count << _(" failed") << std::endl;
  _grtm->get_grt()->send_progress(1.f, "");
  _grtm->get_grt()->send_info(oss.str());
  return 0;
}