source: trunk/FACT++/src/root2sql.cc@ 19806

Last change on this file since 19806 was 19804, checked in by tbretz, 5 years ago
Unified the use of the mapping for the entry type in a file or database, moved the code to FileEntry.h, added the misisng 'unique' resource in fits2sql
File size: 30.4 KB
Line 
1#include <boost/regex.hpp>
2#include <boost/filesystem.hpp>
3#include <boost/algorithm/string/join.hpp>
4
5#include "Database.h"
6
7#include "tools.h"
8#include "Time.h"
9#include "Configuration.h"
10
11#include <TROOT.h>
12#include <TFile.h>
13#include <TTree.h>
14#include <TLeaf.h>
15#include <TError.h>
16
17#include "FileEntry.h"
18
19using namespace std;
20namespace fs = boost::filesystem;
21
22// ------------------------------------------------------------------------
23
24/*
25struct Map : pair<string, string>
26{
27 Map() { }
28};
29
30std::istream &operator>>(std::istream &in, Map &m)
31{
32 const istreambuf_iterator<char> eos;
33 string txt(istreambuf_iterator<char>(in), eos);
34
35 const boost::regex expr("((.*)[^\\\\])/(.*)");
36 boost::smatch match;
37 if (!boost::regex_match(txt, match, expr))
38 throw runtime_error("Could not evaluate map argument: "+txt);
39
40 m.first = match[1].str();
41 m.second = match[3].str();
42
43 return in;
44}
45*/
46
47void SetupConfiguration(Configuration &conf)
48{
49 po::options_description control("Root to SQL");
50 control.add_options()
51 ("uri,u", var<string>()->required(), "Database link as in\n\tuser:password@server[:port]/database[?compress=0|1].")
52 ("file", var<string>()->required(), "The root file to read from")
53 ("create", po_switch(), "Create the database if not existing")
54 ("drop", po_switch(), "Drop the table (implies create)")
55 ("tree,t", var<string>("Events"), "Name of the root tree to convert")
56 ("table", var<string>(""), "Name of the table to use (default is the tree name)")
57 ("map", vars<Configuration::Map>(),"A regular expression which is applied to the leaf name befoee it is used as SQL column name)")
58 ("sql-type", vars<Configuration::Map>(),"Allows to overwrite the calculated SQL type for a given column e.g. 'sql-column-name/UNSIGNED IN'")
59 ("ignore", vars<string>(), "Ignore the given leaf, if the given regular expression matches")
60 ("primary", vars<string>(), "List of columns to be used as primary keys during table creation (in connection with --create)")
61 ("first", var<int64_t>(int64_t(0)), "First event to start with (default: 0), mainly for test purpose")
62 ("max", var<int64_t>(int64_t(0)), "Maximum number of events to process (0: all), mainly for test purpose")
63 ("engine", var<string>(""), "Database engine to be used when a new table is created")
64 ("row-format", var<string>(""), "Defines the ROW_FORMAT keyword for table creation")
65 ("duplicate", vars<string>(), "Specifies an assignment_list for an 'ON DUPLICATE KEY UPDATE' expression")
66 ("ignore-errors", po_switch(), "Adds the IGNORE keyword to the INSERT query (turns errors into warnings, ignores rows with errors)")
67 ("const.*", var<string>(), "Insert a constant number into the given column (--const.mycolumn=5). A special case is `/.../.../`")
68 ("conditional", po_switch(), "Conditional insert. Only insert if no entry exists yet with the constants defined by --const")
69 ("delete", po_switch(), "Delete all entries first which fit all constant columns defined by --const")
70 ("index", po_switch(), "If a table is created, all const columns are used as a single index (INDEX)")
71 ("unique", po_switch(), "If a table is created, all const columns are used as a unqiue index (UNIQUE)")
72 ;
73
74 po::options_description debug("Debug options");
75 debug.add_options()
76 ("no-insert", po_switch(), "Does not insert any data into the table")
77 ("dry-run", po_switch(), "Skip any query which changes the databse (might result in consecutive failures)")
78 ("print-connection", po_switch(), "Print database connection information")
79 ("print-ls", po_switch(), "Calls TFile::ls()")
80 ("print-branches", po_switch(), "Print the branches found in the tree")
81 ("print-leaves", po_switch(), "Print the leaves found in the tree (this is what is processed)")
82 ("print-insert", po_switch(), "Print the INSERT query (note that it contains all data)")
83 ("print-create", po_switch(), "Print the CREATE query")
84 ("print-select", po_switch(), "Print the SELECT query for the conditional execution")
85 ("print-delete", po_switch(), "Print the DELETE query")
86 ("verbose,v", var<uint16_t>(1), "Verbosity (0: quiet, 1: default, 2: more, 3, ...)")
87 ;
88
89 po::positional_options_description p;
90 p.add("file", 1); // The 1st positional options (n=1)
91
92 conf.AddOptions(control);
93 conf.AddOptions(debug);
94 conf.SetArgumentPositions(p);
95}
96
97void PrintUsage()
98{
99 cout <<
100 "root2sql - Fills the data from a root file into a database\n"
101 "\n"
102 "For convenience, this documentation uses the extended version of the options, "
103 "refer to the output below to get the abbreviations.\n"
104 "\n"
105 "This is a general purpose tool to fill the contents of a root file into a database "
106 "as long as this is technically possible and makes sense. Note that root can even "
107 "write complex data like a TH1F into a database, this is not the purpose of this "
108 "program.\n"
109 "\n"
110 "Each root tree has branches and leaves (the basic data types). These leaves can "
111 "be read independently of the classes which were used to write the root file. "
112 "The default tree to read from is 'Events' but the name can be overwritten "
113 "using --tree. The default table name to fill the data into is identical to "
114 "the tree name. It can be overwritten using --table.\n"
115 "\n"
116 "To get a list of the contents (keys and trees) of a root file, you can use --print-ls. "
117 "The name of each column to which data is filled from a leave is obtained from "
118 "the leaves' names. The leave names can be checked using --print-leaves. "
119 "A --print-branches exists for convenience to print only the high-level branches. "
120 "Sometimes these names might be quite unconvenient like MTime.fTime.fMilliSec or "
121 "just MHillas.fWidth. To allow to simplify column names, regular expressions "
122 "(using boost's regex) can be defined to change the names. Note that these regular "
123 "expressions are applied one by one on each leaf's name. A valid expression could "
124 "be:\n"
125 " --map=MHillas\\.f/\n"
126 "which would remove all occurances of 'MHillas.f'. This option can be used more than "
127 "once. They are applied in sequence. A single match does not stop the sequence.\n"
128 "\n"
129 "Sometimes it might also be convenient to skip a leaf. This can be done with "
130 "the --ignore resource. If the given regular expresion yields a match, the "
131 "leaf will be ignored. Note that the regular expression works on the raw-name "
132 "of the leaf not the readily mapped SQL column names. Example:\n"
133 " --ignore=ThetaSq\\..*\n"
134 "will skip all leaved which start with 'ThetaSq.'. This option can be used"
135 "more than once.\n"
136 "\n"
137 "The data type of each column is kept as close as possible to the leaves' data "
138 "types. If for some reason this is not wanted, the data type of the SQL column "
139 "can be overwritten with --sql-type sql-column/sql-ytpe, for example:\n"
140 " --sql-type=FileId/UNSIGNED INT\n"
141 "while the first argument of the name of the SQL column to which the data type "
142 "should be applied. The second column is the basic SQL data type. The option can "
143 "be given more than once.\n"
144 "\n"
145 "Database interaction:\n"
146 "\n"
147 "To drop an existing table, --drop can be used.\n"
148 "\n"
149 "To create a table according to theSQL column names and data types, --create "
150 "can be used. The query used can be printed with --print-create even --create "
151 "has not been specified.\n"
152 "\n"
153 "To choose the columns which should become primary keys, use --primary, "
154 "for example:\n"
155 " --primary=col1\n"
156 "To define more than one column as primary key, the option can be given more than "
157 "once. Note that the combination of these columns must be unique.\n"
158 "\n"
159 "All columns are created as NOT NULL as default. To force a database engine "
160 "and/or a storage format, use --engine and --row-format.\n"
161 "\n"
162 "Usually, the INSERT query would fail if the PRIMARY key exists already. "
163 "This can be avoided using the 'ON DUPLICATE KEY UPDATE' directive. With the "
164 "--duplicate, you can specify what should be updated in case of a duplicate key. "
165 "To keep the row untouched, you can just update the primary key "
166 "with the identical primary key, e.g. --duplicate='MyPrimary=VALUES(MyPrimary)'. "
167 "The --duplicate resource can be specified more than once to add more expressions "
168 "to the assignment_list. For more details, see the MySQL manual.\n"
169 "\n"
170 "For debugging purpose, or to just create or drop a table, the final insert "
171 "query can be skipped using --no-insert. Note that for performance reason, "
172 "all data is collected in memory and a single INSERT query is issued at the "
173 "end.\n"
174 "\n"
175 "Another possibility is to add the IGNORE keyword to the INSERT query by "
176 "--ignore-errors, which essentially ignores all errors and turns them into "
177 "warnings which are printed after the query succeeded.\n"
178 "\n"
179 "Using a higher verbosity level (-v), an overview of the written columns or all "
180 "processed leaves is printed depending on the verbosity level. The output looks "
181 "like the following\n"
182 " Leaf name [root data type] (SQL name)\n"
183 "for example\n"
184 " MTime.fTime.fMilliSec [Long64_t] (MilliSec)\n"
185 "which means that the leaf MTime.fTime.fMilliSec is detected to be a Long64_t "
186 "which is filled into a column called MilliSec. Leaves with non basic data types "
187 "are ignored automatically and are marked as (-n/a-). User ignored columns "
188 "are marked as (-ignored-).\n"
189 "\n"
190 "A constant value for the given file can be inserted by using the --const directive. "
191 "For example --const.mycolumn=42 would insert 42 into a column called mycolumn. "
192 "The column is created as INT UNSIGNED as default which can be altered by "
193 "--sql-type. A special case is a value of the form `/regex/format/`. Here, the given "
194 "regular expression is applied to the filename and it is newly formated with "
195 "the new format string. Uses the standard formatting rules to replace matches "
196 "(those used by ECMAScript's replace method).\n"
197 "\n"
198 "Usually the previously defined constant values are helpful to create an index "
199 "which relates unambiguously the inserted data to the file. It might be useful "
200 "to delete all data which belongs to this particular file before new data is "
201 "entered. This can be achieved with the `--delete` directive. It deletes all "
202 "data from the table before inserting new data which fulfills the condition "
203 "defined by the `--const` directives.\n"
204 "\n"
205 "The constant values can also be used for a conditional execution (--conditional). "
206 "If any row with the given constant values are found, the execution is stopped "
207 "(note that this happend after the table drop/create but before the delete/insert.\n"
208 "\n"
209 "To ensure efficient access for a conditonal execution, it makes sense to have "
210 "an index created for those columns. This can be done during table creation "
211 "with the --index option.\n"
212 "\n"
213 "To create the index as a UNIQUE INDEX, you can use the --unique option which "
214 "implies --index.\n"
215 "\n"
216 "If a query failed, the query is printed to stderr together with the error message. "
217 "For the main INSERT query, this is only true if the verbosity level is at least 2 "
218 "or the query has less than 80*25 bytes.\n"
219 "\n"
220 "In case of success, 0 is returned, a value>0 otherwise.\n"
221 "\n"
222 "Usage: root2sql [options] -uri URI rootfile.root\n"
223 "\n"
224 ;
225 cout << endl;
226}
227
228void ErrorHandlerAll(Int_t level, Bool_t abort, const char *location, const char *msg)
229{
230 if (string(msg).substr(0,24)=="no dictionary for class ")
231 return;
232 if (string(msg).substr(0,15)=="unknown branch ")
233 return;
234
235 DefaultErrorHandler(level, abort, location, msg);
236}
237
238int main(int argc, const char* argv[])
239{
240 Time start;
241
242 gROOT->SetBatch();
243 SetErrorHandler(ErrorHandlerAll);
244
245 Configuration conf(argv[0]);
246 conf.SetPrintUsage(PrintUsage);
247 SetupConfiguration(conf);
248
249 if (!conf.DoParse(argc, argv))
250 return 127;
251
252 // ----------------------------- Evaluate options --------------------------
253 const string uri = conf.Get<string>("uri");
254 const string file = conf.Get<string>("file");
255 const string tree = conf.Get<string>("tree");
256 const string table = conf.Get<string>("table").empty() ? tree : conf.Get<string>("table");
257
258 const uint16_t verbose = conf.Get<uint16_t>("verbose");
259 const int64_t first = conf.Get<int64_t>("first");
260 const int64_t max = conf.Get<int64_t>("max");
261
262 const bool drop = conf.Get<bool>("drop");
263 const bool create = conf.Get<bool>("create") || drop;
264 const bool noinsert = conf.Get<bool>("no-insert");
265 const bool dry_run = conf.Get<bool>("dry-run");
266 const bool conditional = conf.Get<bool>("conditional");
267 const bool run_delete = conf.Get<bool>("delete");
268 const bool index = conf.Get<bool>("index");
269 const bool unique = conf.Get<bool>("unique");
270
271 const string engine = conf.Get<string>("engine");
272 const string row_format = conf.Get<string>("row-format");
273
274 const vector<string> duplicate = conf.Vec<string>("duplicate");
275
276 const bool ignore_errors = conf.Get<bool>("ignore-errors");
277
278 const bool print_connection = conf.Get<bool>("print-connection");
279 const bool print_ls = conf.Get<bool>("print-ls");
280 const bool print_branches = conf.Get<bool>("print-branches");
281 const bool print_leaves = conf.Get<bool>("print-leaves");
282 const bool print_create = conf.Get<bool>("print-create");
283 const bool print_insert = conf.Get<bool>("print-insert");
284 const bool print_select = conf.Get<bool>("print-select");
285 const bool print_delete = conf.Get<bool>("print-delete");
286
287 const auto mymap = conf.Vec<Configuration::Map>("map");
288 const auto sqltypes = conf.Vec<Configuration::Map>("sql-type");
289
290 const vector<string> _ignore = conf.Vec<string>("ignore");
291 const vector<string> primary = conf.Vec<string>("primary");
292
293 // -------------------------------------------------------------------------
294
295 if (verbose>0)
296 {
297 cout << "\n-------------------------- Evaluating file -------------------------\n";
298 cout << "Start Time: " << Time::sql << Time(Time::local) << endl;
299 }
300
301 TFile f(file.c_str());
302 if (f.IsZombie())
303 {
304 cerr << "Could not open file " << file << endl;
305 return 1;
306 }
307
308 if (verbose>0 && !print_ls)
309 cout << "File: " << file << endl;
310
311 if (print_ls)
312 {
313 cout << '\n';
314 f.ls();
315 cout << '\n';
316 }
317
318 TTree *T = 0;
319 f.GetObject(tree.c_str(), T);
320 if (!T)
321 {
322 cerr << "Could not open tree " << tree << endl;
323 return 2;
324 }
325
326 if (verbose>0)
327 cout << "Tree: " << tree << endl;
328
329 T->SetMakeClass(1);
330
331 TObjArray *branches = T->GetListOfBranches();
332 TObjArray *leaves = T->GetListOfLeaves();
333
334 if (print_branches)
335 {
336 cout << '\n';
337 branches->Print();
338 }
339
340 if (verbose>0)
341 cout << T->GetEntriesFast() << " events found." << endl;
342
343
344 if (verbose>0)
345 cout << branches->GetEntries() << " branches found." << endl;
346
347 if (print_leaves)
348 {
349 cout << '\n';
350 leaves->Print();
351 }
352 if (verbose>0)
353 cout << leaves->GetEntries() << " leaves found." << endl;
354
355 string query =
356 "CREATE TABLE IF NOT EXISTS `"+table+"`\n"
357 "(\n";
358
359 vector<FileEntry::Container> vec;
360
361 const auto fixed = conf.GetWildcardOptions("const.*");
362
363 string where;
364 vector<string> vindex;
365 for (auto it=fixed.cbegin(); it!=fixed.cend(); it++)
366 {
367 const string name = it->substr(6);
368 string val = conf.Get<string>(*it);
369
370 boost::smatch match;
371 if (boost::regex_match(val, match, boost::regex("\\/(.+)(?<!\\\\)\\/(.*)(?<!\\\\)\\/")))
372 {
373 const string reg = match[1];
374 const string fmt = match[2];
375
376 val = boost::regex_replace(file, boost::regex(reg), fmt.empty()?"$0":fmt,
377 boost::regex_constants::format_default|boost::regex_constants::format_no_copy);
378
379 if (verbose>0)
380 {
381 cout << "Regular expression detected for constant column `" << *it << "`\n";
382 cout << "Filename converted with /" << reg << "/ to /" << fmt << "/\n";
383 cout << "Filename: " << file << '\n';
384 cout << "Result: " << val << endl;
385 }
386 }
387
388 if (verbose>2)
389 cout << "\n" << val << " [-const-]";
390 if (verbose>1)
391 cout << " (" << name << ")";
392
393 string sqltype = "INT UNSIGNED";
394
395 for (auto m=sqltypes.cbegin(); m!=sqltypes.cend(); m++)
396 if (m->first==name)
397 sqltype = m->second;
398
399 if (!vec.empty())
400 query += ",\n";
401 query += " `"+name+"` "+sqltype+" NOT NULL COMMENT '--user--'";
402
403 vec.emplace_back(name, val);
404 where += " AND `"+name+"`="+val;
405 vindex.emplace_back(name);
406 }
407
408 const size_t nvec = vec.size();
409
410 TIter Next(leaves);
411 TObject *o = 0;
412 while ((o=Next()))
413 {
414 TLeaf *L = T->GetLeaf(o->GetName());
415
416 if (verbose>2)
417 cout << '\n' << L->GetTitle() << " {" << L->GetTypeName() << "}";
418
419 if (L->GetLenStatic()!=L->GetLen())
420 {
421 if (verbose>2)
422 cout << " (-skipped-)";
423 continue;
424 }
425
426
427 string name = o->GetName();
428
429 bool found = false;
430 for (auto b=_ignore.cbegin(); b!=_ignore.cend(); b++)
431 {
432 if (boost::regex_match(name, boost::regex(*b)))
433 {
434 found = true;
435 if (verbose>2)
436 cout << " (-ignored-)";
437 break;
438 }
439 }
440 if (found)
441 continue;
442
443 const string tn = L->GetTypeName();
444
445 const auto it = FileEntry::LUT.root(tn);
446 if (it==FileEntry::LUT.cend())
447 {
448 if (verbose>2)
449 cout << " (-n/a-)";
450 continue;
451 }
452
453 if (verbose==2)
454 cout << '\n' << L->GetTitle() << " {" << L->GetTypeName() << "}";
455
456 for (auto m=mymap.cbegin(); m!=mymap.cend(); m++)
457 name = boost::regex_replace(name, boost::regex(m->first), m->second);
458
459 if (verbose>1)
460 cout << " (" << name << ")";
461
462 string sqltype = it->sql;
463
464 for (auto m=sqltypes.cbegin(); m!=sqltypes.cend(); m++)
465 if (m->first==name)
466 sqltype = m->second;
467
468 if (!vec.empty())
469 query += ",\n";
470
471 const size_t N = L->GetLenStatic();
472 for (size_t i=0; i<N; i++)
473 {
474 query += " `"+name;
475 if (N>1)
476 query += "["+to_string(i)+"]";
477 query += "` "+sqltype+" NOT NULL COMMENT '"+o->GetTitle()+"'";
478 if (N>1 && i!=N-1)
479 query += ",\n";
480 }
481
482 vec.emplace_back(o->GetTitle(), name, it->type, L->GetLenStatic());
483 T->SetBranchAddress(o->GetTitle(), vec.back().ptr);
484 }
485
486 if (verbose>1)
487 cout << "\n\n";
488 if (verbose>0)
489 {
490 if (nvec>0)
491 cout << nvec << " constant value column(s) configured." << endl;
492 cout << vec.size()-nvec << " leaf/leaves setup for reading." << endl;
493 }
494
495 UInt_t datatype = 0;
496 const bool has_datatype = T->SetBranchAddress("DataType.fVal", &datatype) >= 0;
497
498 // Setiing up branch status (must be after all SetBranchAddress)
499 T->SetBranchStatus("*", 0);
500 for (auto c=vec.cbegin(); c!=vec.cend(); c++)
501 if (c->type!=FileEntry::kConst)
502 T->SetBranchStatus(c->branch.c_str(), 1);
503
504 if (has_datatype)
505 {
506 T->SetBranchStatus("DataType.fVal", 1);
507 if (verbose>0)
508 cout << "Rows with DataType.fVal!=1 will be skipped." << endl;
509 }
510
511
512 // -------------------------------------------------------------------------
513 // Checking for database connection
514
515 if (verbose>0)
516 {
517 cout << "Connecting to database...\n";
518 cout << "Client Version: " << mysqlpp::Connection().client_version() << endl;
519 }
520
521 Database connection(uri);
522
523 if (verbose>0)
524 cout << "Server Version: " << (connection.connected()?connection.server_version():"<n/a>") << endl;
525
526 if (print_connection && connection.connected())
527 {
528 try
529 {
530 const auto &res1 = connection.query("SHOW STATUS LIKE 'Compression'").store();
531 cout << "Compression of databse connection is " << string(res1[0][1]) << endl;
532
533 const auto &res2 = connection.query("SHOW STATUS LIKE 'Ssl_cipher'").store();
534 cout << "Connection to databases is " << (string(res2[0][1]).empty()?"UNENCRYPTED":"ENCRYPTED ("+string(res2[0][1])+")") << endl;
535 }
536 catch (const exception &e)
537 {
538 cerr << "\nSHOW STATUS LIKE COMPRESSION\n\n";
539 cerr << "SQL query failed:\n" << e.what() << endl;
540 return 3;
541 }
542 }
543
544 // -------------------------------------------------------------------------
545
546 if (verbose>0)
547 cout << "\n--------------------------- Database Table -------------------------" << endl;
548
549 if (!primary.empty())
550 query += ",\n PRIMARY KEY USING BTREE (`"+boost::algorithm::join(primary, "`, `")+"`)";
551
552 if (!vindex.empty() && (index || unique))
553 query += ",\n "+string(unique?"UNIQUE ":"")+"INDEX USING BTREE (`"+boost::algorithm::join(vindex, "`, `")+"`)";
554
555 query +=
556 "\n)\n"
557 "DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci\n";
558 if (!engine.empty())
559 query += "ENGINE="+engine+"\n";
560 if (!row_format.empty())
561 query += "ROW_FORMAT="+row_format+"\n";
562 query += "COMMENT='created by "+fs::path(conf.GetName()).filename().string()+"'\n";
563
564 // FIXME: Can we omit the catching to be able to print the
565 // query 'autmatically'?
566 try
567 {
568 if (drop)
569 {
570 // => Simple result
571 if (!dry_run)
572 connection.query("DROP TABLE `"+table+"`").execute();
573 if (verbose>0)
574 {
575 if (!dry_run)
576 cout << "Table `" << table << "` dropped." << endl;
577 else
578 cout << "Dropping table `" << table << "`skipped!" << endl;
579 }
580
581 }
582 }
583 catch (const exception &e)
584 {
585 cerr << "DROP TABLE `" << table << "`\n\n";
586 cerr << "SQL query failed:\n" << e.what() << '\n' << endl;
587 return 4;
588 }
589
590 try
591 {
592 if (create && !dry_run)
593 connection.query(query).execute();
594 }
595 catch (const exception &e)
596 {
597 cerr << query << "\n\n";
598 cerr << "SQL query failed:\n" << e.what() << '\n' << endl;
599 return 5;
600 }
601
602 if (print_create)
603 cout << query << endl;
604
605 if (create && verbose>0)
606 {
607 if (!dry_run)
608 cout << "Table `" << table << "` created." << endl;
609 else
610 cout << "Creating table `" << table << "`skipped!" << endl;
611 }
612
613 try
614 {
615 if (conditional && !fixed.empty() && !drop)
616 {
617 const mysqlpp::StoreQueryResult res =
618 connection.query("SELECT 1 FROM `"+table+"` WHERE 1"+where+" LIMIT 1").store();
619
620 if (res.num_rows()>0)
621 {
622 if (verbose>0)
623 {
624 cout << "Conditional execution... detected existing rows!\n";
625 cout << "Exit.\n" << endl;
626 }
627 return 0;
628 }
629 }
630 }
631 catch (const exception &e)
632 {
633 cerr << "SELECT 1 FROM `" << table << "` WHERE 1" << where << " LIMIT 1\n\n";
634 cerr << "SQL query failed: " << e.what() << endl;
635 return 6;
636 }
637
638 if (print_select)
639 cout << "SELECT 1 FROM `" << table << "` WHERE 1" << where << " LIMIT 1" << endl;
640
641 try
642 {
643 if (run_delete)
644 {
645 if (verbose>0)
646 cout << "Deleting rows...";
647
648 if (!fixed.empty() && !drop && !dry_run)
649 {
650 if (verbose>0)
651 cout << endl;
652
653 const mysqlpp::SimpleResult res =
654 connection.query("DELETE FROM `"+table+"` WHERE 1"+where).execute();
655
656 if (verbose>0)
657 cout << res.rows() << " row(s) deleted.\n" << endl;
658 }
659 else
660 if (verbose>0)
661 cout << " skipped." << endl;
662 }
663 }
664 catch (const exception &e)
665 {
666 cerr << "DELETE FROM `"+table+"` WHERE 1" << where << "\n\n";
667 cerr << "SQL query failed: " << e.what() << endl;
668 return 7;
669 }
670
671 if (print_delete)
672 cout << "DELETE FROM `"+table+"` WHERE 1" << where << endl;
673
674
675 // -------------------------------------------------------------------------
676
677 if (verbose>0)
678 cout << "\n---------------------------- Reading file --------------------------" << endl;
679
680 //query = update ? "UPDATE" : "INSERT";
681 query = "INSERT ";
682 if (ignore_errors)
683 query += "IGNORE ";
684 query += "`"+table+"`\n"
685 "(\n";
686
687 for (auto c=vec.cbegin(); c!=vec.cend(); c++)
688 {
689 if (c!=vec.cbegin())
690 query += ",\n";
691
692 const size_t N = c->num;
693 for (size_t i=0; i<N; i++)
694 {
695 if (N==1)
696 query += " `"+c->column+"`";
697 else
698 query += " `"+c->column+"["+to_string(i)+"]`";
699
700 if (N>1 && i!=N-1)
701 query += ",\n";
702 }
703 }
704
705 query +=
706 "\n)\n"
707 "VALUES\n";
708
709 size_t count = 0;
710
711 const size_t num = max>0 && (max-first)<T->GetEntriesFast() ? (max-first) : T->GetEntriesFast();
712 for (size_t j=first; j<num; j++)
713 {
714 T->GetEntry(j);
715 if (has_datatype && datatype!=1)
716 continue;
717
718 if (count>0)
719 query += ",\n";
720
721 query += "(\n";
722
723 for (auto c=vec.cbegin(); c!=vec.cend(); c++)
724 {
725 if (c!=vec.cbegin())
726 query += ",\n";
727
728 const size_t N = c->num;
729 for (size_t i=0; i<N; i++)
730 {
731 query += " "+c->fmt(i);
732
733 if (print_insert && i==0)
734 query += " /* "+c->column+" -> "+c->branch+" */";
735
736 if (N>1 && i!=N-1)
737 query += ",\n";
738 }
739 }
740 query += "\n)";
741
742 count ++;
743 }
744
745 if (!duplicate.empty())
746 query += "\nON DUPLICATE KEY UPDATE\n " + boost::join(duplicate, ",\n ");
747
748 if (verbose>0)
749 cout << count << " out of " << num << " row(s) read from file [N=" << first << ".." << num-1 << "]." << endl;
750
751 if (count==0)
752 {
753 if (verbose>0)
754 {
755 cout << "Total execution time: " << Time().UnixTime()-start.UnixTime() << "s.\n";
756 cout << "Success.\n" << endl;
757 }
758 return 0;
759 }
760
761 // -------------------------------------------------------------------------
762
763 if (verbose>0)
764 {
765 cout << "\n--------------------------- Inserting data -------------------------" << endl;
766 cout << "Sending INSERT query (" << query.length() << " bytes)" << endl;
767 }
768
769 try
770 {
771 if (!noinsert && !dry_run)
772 {
773 auto q = connection.query(query);
774 q.execute();
775 cout << q.info() << '\n' << endl;
776 }
777 else
778 cout << "Insert query skipped!" << endl;
779
780 if (print_insert)
781 cout << query << endl;
782 }
783 catch (const exception &e)
784 {
785 if (verbose>1 || query.length()<80*25)
786 cerr << query << "\n\n";
787 cerr << "SQL query failed (" << query.length() << " bytes):\n" << e.what() << '\n' << endl;
788 return 8;
789 }
790
791 if (verbose>0)
792 {
793 const auto sec = Time().UnixTime()-start.UnixTime();
794 cout << "Total execution time: " << sec << "s ";
795 cout << "(" << Tools::Fractional(sec/count) << "s/row)\n";
796
797 try
798 {
799 const auto resw =
800 connection.query("SHOW WARNINGS").store();
801
802 for (size_t i=0; i<resw.num_rows(); i++)
803 {
804 const mysqlpp::Row &roww = resw[i];
805
806 cout << roww["Level"] << '[' << roww["Code"] << "]: ";
807 cout << roww["Message"] << '\n';
808 }
809 cout << endl;
810
811 }
812 catch (const exception &e)
813 {
814 cerr << "\nSHOW WARNINGS\n\n";
815 cerr << "SQL query failed:\n" << e.what() << '\n' <<endl;
816 return 9;
817 }
818 }
819
820 if (print_connection)
821 {
822 try
823 {
824 // Exchange _send and _received as it is the view of the server
825 const auto &res1 = connection.query("SHOW STATUS LIKE 'Bytes_%'").store();
826 cout << left << setw(16) << res1[1]["Variable_name"] << ' ' << Tools::Scientific(res1[0]["Value"]) << endl;
827 cout << left << setw(16) << res1[0]["Variable_name"] << ' ' << Tools::Scientific(res1[1]["Value"]) << endl;
828 cout << endl;
829 }
830 catch (const exception &e)
831 {
832 cerr << "\nSHOW STATUS LIKE 'Bytes_%'\n\n";
833 cerr << "SQL query failed:\n" << e.what() << endl;
834 return 10;
835 }
836 }
837
838 cout << "Success!\n" << endl;
839 return 0;
840}
Note: See TracBrowser for help on using the repository browser.