source: trunk/FACT++/src/rootifysql.cc@ 19134

Last change on this file since 19134 was 19134, checked in by tbretz, 6 years ago
Skip empty lines reading an environment file.
File size: 30.8 KB
Line 
1#include "Database.h"
2
3#include <regex>
4
5#include <boost/algorithm/string/join.hpp>
6#include <boost/tokenizer.hpp>
7#include <boost/algorithm/string.hpp>
8
9#include "tools.h"
10#include "Time.h"
11#include "Configuration.h"
12
13#include <TROOT.h>
14#include <TSystem.h>
15#include <TFile.h>
16#include <TTree.h>
17
18using namespace std;
19
20// ------------------------------------------------------------------------
21
22void SetupConfiguration(Configuration &conf)
23{
24 po::options_description control("Rootify SQL");
25 control.add_options()
26 ("uri,u", var<string>()->required(), "Database link as in\n\tuser:password@server[:port]/database[/comp].")
27 ("query,q", var<string>(""), "MySQL query (overwrites --file)")
28 ("file", var<string>("rootify.sql"), "An ASCII file with the MySQL query (overwrites --query)")
29 ("ignore-null,i", po_switch(), "Do not skip rows containing any NULL field")
30 ("out,o", var<string>("rootify.root"), "Output root file name")
31 ("force,f", po_switch(), "Force overwriting an existing root file ('RECREATE')")
32 ("update", po_switch(), "Update an existing root file with the new tree ('UPDATE')")
33 ("compression,c", var<uint16_t>(1), "zlib compression level for the root file")
34 ("tree,t", var<string>("Result"), "Name of the root tree")
35 ("ignore", vars<string>(), "Ignore the given columns")
36 ("display,d", po_switch(), "Displays contents on the screen (most usefull in combination with mysql statements as SHOW or EXPLAIN)")
37 ("write", var<string>(""), "Write output to an ascii file")
38 ("null,n", po_switch(), "Redirect the output file to /dev/null (mainly for debugging purposes, e.g. performance studies)")
39 ("no-fill", po_switch(), "Do not fill events into the root file (mainly for debugging purposes, e.g. performance studies)")
40 ("delimiter", var<string>(""), "The delimiter used if contents are displayed with --display (default=\\t)")
41 ("explain", po_switch(), "Requests an EXPLAIN from the server (shows the server optimized query)\nsee also https://dev.mysql.com/doc/refman/explain-output.html")
42 ("profiling", po_switch(), "Turn on profiling and print profile")
43 ("var.*", var<string>(), "Predefined SQL user variables (@VAR)")
44 ("env.*", vars<string>(), "Predefined environment for substitutions in the query ($ENV)")
45 ("list.*", var<string>(), "Predefined environment for substitutions in the query ($ENV). The list is read from the given file (one list entry per line)")
46 ("print-connection", po_switch(), "Print database connection information")
47 ("verbose,v", var<uint16_t>(1), "Verbosity (0: quiet, 1: default, 2: more, 3, ...)")
48 ;
49
50 po::positional_options_description p;
51 p.add("file", 1); // The 1st positional options (n=1)
52 p.add("out", 1); // The 2nd positional options (n=1)
53
54 conf.AddOptions(control);
55 conf.SetArgumentPositions(p);
56}
57
58void PrintUsage()
59{
60 cout <<
61 "rootifysql - Converts the result of a mysql query into a root file\n"
62 "\n"
63 "For convenience, this documentation uses the extended version of the options, "
64 "refer to the output below to get the abbreviations.\n"
65 "\n"
66 "Writes the result of a mysql query into a root file. For each column, a branch is "
67 "created of type double with the field name as name. This is usually the column name "
68 "if not specified otherwise by the AS mysql directive.\n"
69 "\n"
70 "Columns with CHAR or VARCHAR as field type are ignored. DATETIME, DATE and TIME "
71 "columns are converted to unix time (time_t). Rows containing any file which is "
72 "NULL are skipped if not suppressed by the --ignore-null option. Ideally, the query "
73 "is compiled in a way that no NULL field is returned. With the --display option the "
74 "result of the request is printed on the screen (NULL skipping still in action). "
75 "This can be useful to create an ascii file or to show results as 'SHOW DATABASES' "
76 "or 'EXPLAIN table'. To redirect the contents into an ascii file, the option -v0 "
77 "is useful. To suppredd writing to an output file --null can be used.\n"
78 "\n"
79 "The default is to read the query from a file called rootify.sql. Except if a different "
80 "filename is specified by the --file option or a query is given with --query.\n"
81 "\n"
82 "As a trick, the rootify.sql file can be made excutable (chmod u+x rootify.sql). "
83 "If the first line contains '#!rootifysql', the script can be executed directly.\n"
84 "\n"
85 "Columns whose name start with @ are skipped. If you want them in your output file "
86 "give them a name using AS, e.g. 'SELECT @A:=5 AS A'.\n"
87 "\n"
88 "You can use variables in your sql query like @MyVar and define them on the "
89 "command line. In this example with --var.MyVar=5\n"
90 "\n"
91 "You can use environment definitions for substitutions in your SQL query. "
92 "For example --env.TEST=5 would replace $TEST or ${TEST} in your query by 5."
93 "If you specifiy one environmentvariable more than once, a list is created. "
94 "For example --env.TEST=1 --env.TEST=2 --env.TEST=3 would substitute "
95 "$TEST or ${TEST} by '1, 2, 3'. This is useful for the SQL `IN` keyword. "
96 "You can also read the values for an enviroment substitution from a file "
97 "(one element per line), e.g. --env.TEST=file.txt. Empty lines and lines "
98 "starting with a # are skipped.\n"
99 "\n"
100 "Comments in the query-file can be placed according to the SQL standard inline "
101 "/*comment*/ or introduced with # (shell script style) or -- (SQL style).\n"
102 "\n"
103 "In case of succes, 0 is returned, a value>0 otherwise.\n"
104 "\n"
105 "Usage: rootifysql [rootify.sql [rootify.root]] [-u URI] [-q query|-f file] [-i] [-o out] [-f] [-cN] [-t tree] [-vN]\n"
106 "\n"
107 ;
108 cout << endl;
109}
110
111struct ExplainParser
112{
113 string sql;
114
115 vector<string> vec;
116
117 string substitute(string _str, const regex &expr)
118 {
119 smatch match;
120 while (regex_search(_str, match, expr, regex_constants::format_first_only))
121 {
122 const auto &len = match.length(0);
123 const auto &pos = match.position(0);
124 const auto &str = match.str(0);
125
126 const auto it = find(vec.cbegin(), vec.cend(), str);
127 const size_t id = it==vec.cend() ? vec.size() : it-vec.cbegin();
128
129 _str.replace(pos, len, "{"+to_string(id)+"}");
130
131 if (it==vec.cend())
132 vec.push_back(str);//.substr(1, str.size()-2));
133 }
134
135 return _str;
136 }
137
138 string substitute(const string &str, const string &expr)
139 {
140 return substitute(str, regex(expr));
141 }
142
143 vector<string> queries;
144
145 string resub(string str)
146 {
147 // search for "KEYWORD expression"
148 regex reg("\\{[0-9]+\\}");
149
150 //smatch match;
151 smatch match;
152 while (regex_search(str, match, reg, regex_constants::format_first_only))
153 {
154 const auto &len = match.length(0);
155 const auto &pos = match.position(0);
156 const auto &arg = match.str(0); // Argument
157
158 const auto idx = atoi(arg.c_str()+1);
159
160 str.replace(pos, len, resub(vec[idx]));
161 }
162
163 return str;
164 }
165
166 void expression(string expr, size_t indent=0)
167 {
168 if (expr[0]=='{')
169 {
170 const auto idx = atoi(expr.c_str()+1);
171
172 // This is a subquery
173 if (vec[idx].substr(0,3)=="(/*")
174 {
175 cout << setw(indent) << ' ' << "(\n";
176 find_tokens(vec[idx], indent+4);
177 cout << setw(indent) << ' ' << ") ";
178 }
179 else
180 // This is just something to substitute back
181 if (vec[idx].substr(0,2)=="({")
182 {
183 cout << setw(indent) << ' ' << "(" << resub(vec[idx]) << ") ";
184 }
185 else
186 {
187 if (indent>0)
188 cout << setw(indent) << ' ';
189 cout << resub(vec[idx]);
190 }
191 }
192 else
193 {
194 if (indent>0)
195 cout << setw(indent) << ' ';
196 cout << resub(expr);
197 }
198 }
199
200 void find_tokens(string str, size_t indent=0)
201 {
202 // ( COMMENT )?( TOKEN )?(( {NNN} | NNN )( AS|ON ( {NNN}) ))?(,)?)
203 //regex reg("(\\/\\*\\ select\\#[0-9]+\\ \\*\\/\\ *)?([a-zA-Z ]+)?((\\{[0-9]+\\}|[0-9]+)(\\ ?([Aa][Ss]|[Oo][Nn])\\ ?(\\{[0-9]+\\}))?(,)?)");
204
205 const string _com = "\\/\\*\\ select\\#[0-9]+\\ \\*\\/\\ *";
206
207 const string _tok = "[a-zA-Z_ ]+";
208
209 const string _nnn = "\\{[0-9]+\\}|[0-9]+";
210
211 const string _as = "\\ ?([Aa][Ss])\\ ?";
212
213 // ( _nnn ) ( _as ( _nnn ))?(,)? // can also match noting in between two {NNN}
214 const string _exp = "("+_nnn+")" + "("+_as+"("+_nnn+"))?(,)?";
215
216 // Matche: ( _com )? ( ( _tok )? ( _exp ) | ( _tok ) )
217 regex reg("("+_com+")?" + "(" + "("+_tok+")?"+"("+_exp+")" + "|" + "("+_tok+")" + ")");
218
219 smatch match;
220 while (regex_search(str, match, reg, regex_constants::format_first_only))
221 {
222
223 const auto &com = match.str(1); // comment
224 const auto &tok1 = Tools::Trim(match.str(3)); // token with expression
225 const auto &arg1 = match.str(5); // argument 1
226 const auto &as = match.str(7); // as
227 const auto &arg2 = match.str(8); // argument 2
228 const auto &comma = match.str(9); // comma
229 const auto &tok2 = Tools::Trim(match.str(10)); // token without expression
230
231 if (!com.empty())
232 cout << setw(indent) << ' ' << "\033[34m" << com << "\033[0m" << '\n';
233
234 if (!tok1.empty())
235 cout << setw(indent) << ' ' << "\033[32m" << tok1 << "\033[0m" << '\n';
236 if (!tok2.empty())
237 cout << setw(indent) << ' ' << "\033[32m" << tok2 << "\033[0m" << '\n';
238
239 if (!arg1.empty())
240 {
241 expression(arg1, indent+4);
242
243 if (!as.empty())
244 cout << " \033[33m" << as << "\033[0m ";
245
246 if (!arg2.empty())
247 expression(arg2);
248
249 if (!comma.empty())
250 cout << ',';
251
252 cout << '\n';
253 }
254
255 str = str.substr(match.position(0)+match.length(0));
256 }
257 }
258
259
260 ExplainParser(const string &_sql) : sql(_sql)
261 {
262 // substitute all strings
263 sql = substitute(sql, "'[^']*'");
264
265 // substitute all escaped sequences (`something`.`something-else`)
266 sql = substitute(sql, "`[^`]*`(\\.`[^`]*`)*");
267
268 // substitute all paranthesis
269 sql = substitute(sql, "[a-zA-Z0-9_]*\\([^\\(\\)]*\\)");
270
271 //cout << sql << "\n\n";
272 find_tokens(sql);
273 cout << endl;
274 }
275};
276
277// Remove queries...
278void format(string sql)
279{
280 ExplainParser p(sql);
281
282 /*
283
284 SELECT
285 [ALL | DISTINCT | DISTINCTROW ]
286 [HIGH_PRIORITY]
287 [STRAIGHT_JOIN]
288 [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
289 [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
290 select_expr [, select_expr ...]
291 [FROM table_references
292 [PARTITION partition_list]
293 [WHERE where_condition]
294 [GROUP BY {col_name | expr | position}, ... [WITH ROLLUP]]
295 [HAVING where_condition]
296 [WINDOW window_name AS (window_spec)
297 [, window_name AS (window_spec)] ...]
298 [ORDER BY {col_name | expr | position}
299 [ASC | DESC], ... [WITH ROLLUP]]
300 [LIMIT {[offset,] row_count | row_count OFFSET offset}]
301 [INTO OUTFILE 'file_name'
302 [CHARACTER SET charset_name]
303 export_options
304 | INTO DUMPFILE 'file_name'
305 | INTO var_name [, var_name]]
306 [FOR {UPDATE | SHARE} [OF tbl_name [, tbl_name] ...] [NOWAIT | SKIP LOCKED]
307 | LOCK IN SHARE MODE]]
308 */
309
310 /*
311table_references:
312 escaped_table_reference [, escaped_table_reference] ...
313
314escaped_table_reference:
315 table_reference
316 | { OJ table_reference }
317
318table_reference:
319 table_factor
320 | join_table
321
322table_factor:
323 tbl_name [PARTITION (partition_names)]
324 [[AS] alias] [index_hint_list]
325 | table_subquery [AS] alias [(col_list)]
326 | ( table_references )
327
328join_table:
329 table_reference [INNER | CROSS] JOIN table_factor [join_condition]
330 | table_reference STRAIGHT_JOIN table_factor
331 | table_reference STRAIGHT_JOIN table_factor ON conditional_expr
332 | table_reference {LEFT|RIGHT} [OUTER] JOIN table_reference join_condition
333 | table_reference NATURAL [INNER | {LEFT|RIGHT} [OUTER]] JOIN table_factor
334
335join_condition:
336 ON conditional_expr
337 | USING (column_list)
338
339index_hint_list:
340 index_hint [, index_hint] ...
341
342index_hint:
343 USE {INDEX|KEY}
344 [FOR {JOIN|ORDER BY|GROUP BY}] ([index_list])
345 | IGNORE {INDEX|KEY}
346 [FOR {JOIN|ORDER BY|GROUP BY}] (index_list)
347 | FORCE {INDEX|KEY}
348 [FOR {JOIN|ORDER BY|GROUP BY}] (index_list)
349
350index_list:
351 index_name [, index_name] ...
352 */
353
354}
355
356int main(int argc, const char* argv[])
357{
358 Time start;
359
360 gROOT->SetBatch();
361
362 Configuration conf(argv[0]);
363 conf.SetPrintUsage(PrintUsage);
364 SetupConfiguration(conf);
365
366 if (!conf.DoParse(argc, argv))
367 return 127;
368
369 // ----------------------------- Evaluate options --------------------------
370 const string uri = conf.Get<string>("uri");
371 const string out = conf.Get<string>("out");
372 const string file = conf.Get<string>("file");
373 const string tree = conf.Get<string>("tree");
374 const bool force = conf.Get<bool>("force");
375 const bool ignorenull = conf.Get<bool>("ignore-null");
376 const bool update = conf.Get<bool>("update");
377 const bool display = conf.Get<bool>("display");
378 const string write = conf.Get<string>("write");
379 const bool noout = conf.Get<bool>("null");
380 const bool nofill = conf.Get<bool>("no-fill");
381 const bool explain = conf.Get<bool>("explain");
382 const bool profiling = conf.Get<bool>("profiling");
383 const uint16_t verbose = conf.Get<uint16_t>("verbose");
384 const uint16_t compression = conf.Get<uint16_t>("compression");
385 const string delimiter = conf.Get<string>("delimiter");
386 const vector<string> _ignore = conf.Vec<string>("ignore");
387 const bool print_connection = conf.Get<bool>("print-connection");
388 //const vector<Map> mymap = conf.Vec<Map>("map");
389
390 // -------------------------------------------------------------------------
391
392 const auto vars = conf.GetWildcardOptions("var.*");
393
394 vector<string> variables;
395 for (const auto &var : vars)
396 variables.emplace_back('@'+var.substr(4)+":="+Tools::Trim(conf.Get<string>(var)));
397
398 // -------------------------------------------------------------------------
399
400 if (verbose>0)
401 cout << "\n------------------------ Rootify SQL -------------------------" << endl;
402
403 string query = conf.Get<string>("query");
404 if (query.empty())
405 {
406 if (verbose>0)
407 cout << "Reading query from file '" << file << "'." << endl;
408
409 ifstream fin(file);
410 if (!fin)
411 {
412 cerr << "Could not open query in '" << file << "': " << strerror(errno) << endl;
413 return 1;
414 }
415 getline(fin, query, (char)fin.eof());
416 }
417
418 if (query.empty())
419 {
420 cerr << "No query specified." << endl;
421 return 2;
422 }
423
424 // -------------------------------------------------------------------------
425
426 map<string, vector<string>> envs;
427
428 for (const auto &env : conf.GetWildcardOptions("env.*"))
429 envs[env.substr(4)] = conf.Vec<string>(env);
430
431 for (const auto &env : conf.GetWildcardOptions("list.*"))
432 {
433 const string fname = conf.Get<string>(env);
434 const string &ident = env.substr(5);
435
436 ifstream fin(fname);
437 if (!fin)
438 {
439 cerr << "Could not open environment in '" << fname << "' for ${" << ident << "}: " << strerror(errno) << endl;
440 return 3;
441 }
442
443 for (string line; getline(fin, line); )
444 {
445 const auto &l = Tools::Trim(line);
446 if (!l.empty() && l[0]!='#')
447 envs[ident].push_back(line);
448
449 if (verbose>0)
450 cout << "Found " << envs[ident].size() << " list element(s) for ${" << ident << "}" << endl;
451 }
452
453 for (const auto &env : envs)
454 {
455 regex rexpr("\\$(\\{"+env.first+"\\}|"+env.first+"\\b)");
456 query = regex_replace(query, rexpr, boost::join(env.second, ", "));
457 }
458
459 // -------------------------- Check for file permssion ---------------------
460 // Strictly speaking, checking for write permission and existance is not necessary,
461 // but it is convenient that the user does not find out that it failed after
462 // waiting long for the query result
463 //
464 // I am using root here instead of boost to be
465 // consistent with the access pattern by TFile
466 TString path(noout?"/dev/null":out.c_str());
467 gSystem->ExpandPathName(path);
468
469 if (!noout)
470 {
471 FileStat_t stat;
472 const Int_t exist = !gSystem->GetPathInfo(path, stat);
473 const Bool_t _write = !gSystem->AccessPathName(path, kWritePermission) && R_ISREG(stat.fMode);
474
475 if ((update && !exist) || (update && exist && !_write) || (force && exist && !_write))
476 {
477 cerr << "File '" << path << "' is not writable." << endl;
478 return 3;
479 }
480
481 if (!update && !force && exist)
482 {
483 cerr << "File '" << path << "' already exists." << endl;
484 return 4;
485 }
486 }
487
488 Time start2;
489
490 // --------------------------- Connect to database -------------------------------------------------
491
492 if (query.back()!='\n')
493 query += '\n';
494
495 if (verbose>0)
496 cout << "Connecting to database..." << endl;
497
498
499 Database connection(uri); // Keep alive while fetching rows
500
501 if (print_connection)
502 {
503 try
504 {
505 const auto &res1 = connection.query("SHOW STATUS LIKE 'Compression'").store();
506 cout << "Compression of databse connection is " << string(res1[0][1]) << endl;
507
508 const auto &res2 = connection.query("SHOW STATUS LIKE 'Ssl_cipher'").store();
509 cout << "Connection to databases is " << (string(res2[0][1]).empty()?"UNENCRYPTED":"ENCRYPTED ("+string(res2[0][1])+")") << endl;
510 }
511 catch (const exception &e)
512 {
513 cerr << "\nSHOW STATUS LIKE COMPRESSION\n\n";
514 cerr << "SQL query failed:\n" << e.what() << endl;
515 return 6;
516 }
517 }
518
519 try
520 {
521 if (profiling)
522 connection.query("SET PROFILING=1").execute();
523 }
524 catch (const exception &e)
525 {
526 cerr << "\nSET profiling=1\n\n";
527 cerr << "SQL query failed:\n" << e.what() << endl;
528 return 6;
529 }
530
531 // -------------------------- Set user defined variables -------------------
532 if (variables.size()>0)
533 {
534 if (verbose>0)
535 cout << "Setting user defined variables..." << endl;
536
537 const string varset =
538 "SET\n "+boost::algorithm::join(variables, ",\n ");
539
540 try
541 {
542 connection.query(varset).execute();
543 }
544 catch (const exception &e)
545 {
546 cerr << '\n' << varset << "\n\n";
547 cerr << "SQL query failed:\n" << e.what() << endl;
548 return 7;
549 }
550
551 if (verbose>2)
552 cout << '\n' << varset << '\n' << endl;
553 }
554
555 // ------------------------- Explain query if requested --------------------
556
557 if (explain)
558 {
559 try
560 {
561 const auto res0 =
562 connection.query("EXPLAIN FORMAT=JSON "+query).store();
563
564 cout << res0[0][0] << endl;
565 cout << endl;
566
567 const mysqlpp::StoreQueryResult res1 =
568 connection.query("EXPLAIN "+query).store();
569
570 for (size_t i=0; i<res1.num_rows(); i++)
571 {
572 const mysqlpp::Row &row = res1[i];
573
574 cout << "\nid : " << row["id"];
575 cout << "\nselect type : " << row["select_type"];
576
577 if (!row["table"].is_null())
578 cout << "\ntable : " << row["table"];
579
580 if (!row["partitions"].is_null())
581 cout << "\npartitions : " << row["partitions"];
582
583 if (!row["key"].is_null())
584 cout << "\nselected key : " << row["key"] << " [len=" << row["key_len"] << "] out of (" << row["possible_keys"] << ")";
585
586 if (!row["type"].is_null())
587 cout << "\njoin type : " << row["type"];
588
589 //if (!row["possible_keys"].is_null())
590 // cout << "\npossible_keys: " << row["possible_keys"];
591
592 //if (!row["key_len"].is_null())
593 // cout << "\nkey_len : " << row["key_len"];
594
595 if (!row["ref"].is_null())
596 cout << "\nref : (" << row["ref"] << ") compared to the index";
597
598 if (!row["rows"].is_null())
599 cout << "\nrows : " << row["rows"];
600
601 if (!row["filtered"].is_null())
602 cout << "\nfiltered : " << row["filtered"];
603
604 if (!row["extra"].is_null())
605 cout << "\nExtra : " << row["extra"];
606
607 cout << endl;
608 }
609
610 cout << endl;
611
612 const mysqlpp::StoreQueryResult res2 =
613 connection.query("SHOW WARNINGS").store();
614
615 for (size_t i=0; i<res2.num_rows(); i++)
616 {
617 const mysqlpp::Row &row = res2[i];
618
619 // 1003 //
620 cout << row["Level"] << '[' << row["Code"] << "]:\n";
621 if (uint32_t(row["Code"])==1003)
622 format(row["Message"].c_str());
623 else
624 cout << row["Message"] << '\n' << endl;
625
626 }
627
628 }
629 catch (const exception &e)
630 {
631 cerr << '\n' << query << "\n\n";
632 cerr << "SQL query failed:\n" << e.what() << endl;
633 return 8;
634 }
635
636 return 0;
637 }
638
639 // -------------------------- Request data from database -------------------
640 if (verbose>0)
641 cout << "Requesting data..." << endl;
642
643 if (verbose>2)
644 cout << '\n' << query << endl;
645
646 const mysqlpp::UseQueryResult res =
647 connection.query(query).use();
648
649 // -------------------------------------------------------------------------
650
651 if (verbose>0)
652 cout << "Opening file '" << path << "' [compression=" << compression << "]..." << endl;
653
654 // ----------------------------- Open output file --------------------------
655 TFile tfile(path, update?"UPDATE":(force?"RECREATE":"CREATE"), "Rootify SQL", compression);
656 if (tfile.IsZombie())
657 return 9;
658
659 // -------------------------------------------------------------------------
660
661 // get the first row to get the field description
662 mysqlpp::Row row = res.fetch_row();
663 if (!row)
664 {
665 cerr << "Empty set returned... nothing to write." << endl;
666 return 10;
667 }
668
669 if (verbose>0)
670 cout << "Trying to setup " << row.size() << " branches..." << endl;
671
672 if (verbose>1)
673 cout << endl;
674
675 const mysqlpp::FieldNames &l = *row.field_list().list;
676
677 vector<double> buf(l.size());
678 vector<uint8_t> typ(l.size(),'n'); // n=number [double], d is used for DateTime
679
680 UInt_t cols = 0;
681
682
683 // -------------------- Configure branches of TTree ------------------------
684 TTree *ttree = new TTree(tree.c_str(), query.c_str());
685
686 size_t skipat = 0;
687 size_t skipreg = 0;
688 for (size_t i=0; i<l.size(); i++)
689 {
690 const string t = row[i].type().sql_name();
691
692 if (t.find("DATETIME")!=string::npos)
693 typ[i] = 'd';
694 else
695 if (t.find("DATE")!=string::npos)
696 typ[i] = 'D';
697 else
698 if (t.find("TIME")!=string::npos)
699 typ[i] = 'T';
700 else
701 if (t.find("VARCHAR")!=string::npos)
702 typ[i] = 'V';
703 else
704 if (t.find("CHAR")!=string::npos)
705 typ[i] = 'C';
706
707 bool found = false;
708 for (const auto &pattern: _ignore)
709 {
710 if (regex_match(l[i], regex(pattern)))
711 {
712 found = true;
713 typ[i] = '-';
714 skipreg++;
715 break;
716 }
717 }
718
719 if (l[i][0]=='@')
720 {
721 typ[i] = '@';
722 skipat++;
723 }
724
725 const bool use = l[i][0]!='@' && typ[i]!='V' && typ[i]!='C' && !found;
726
727 if (verbose>1)
728 cout << (use?" + ":" - ") << l[i].c_str() << " [" << t << "] {" << typ[i] << "}\n";
729
730 if (use)
731 {
732 // string name = l[i];
733 // for (const auto &m: mymap)
734 // name = boost::regex_replace(l[i], boost::regex(m.first), m.second);
735
736 ttree->Branch(l[i].c_str(), buf.data()+i);
737 cols++;
738 }
739 }
740 // -------------------------------------------------------------------------
741
742 if (verbose>1)
743 cout << endl;
744 if (verbose>0)
745 {
746 if (skipreg)
747 cout << skipreg << " branches skipped due to ignore list." << endl;
748 if (skipat)
749 cout << skipat << " branches skipped due to name starting with @." << endl;
750 cout << "Configured " << cols << " branches.\nFilling branches..." << endl;
751 }
752
753 ofstream fout(write);
754 if (!write.empty() && !fout)
755 cout << "WARNING: Writing to '" << write << "' failed: " << strerror(errno) << endl;
756
757 if (display)
758 {
759 cout << endl;
760 cout << "#";
761 for (size_t i=0; i<l.size(); i++)
762 cout << ' ' << l[i].c_str();
763 cout << endl;
764 }
765
766 if (!write.empty())
767 {
768 fout << "#";
769 for (size_t i=0; i<l.size(); i++)
770 fout << ' ' << l[i].c_str();
771 fout << endl;
772 }
773
774 // ---------------------- Fill TTree with DB data --------------------------
775 size_t count = 0;
776 size_t skip = 0;
777 do
778 {
779 count++;
780
781 ostringstream sout;
782
783 size_t idx=0;
784 for (auto col=row.begin(); col!=row.end(); col++, idx++)
785 {
786 if (display || !write.empty())
787 {
788 if (idx>0)
789 sout << (delimiter.empty()?"\t":delimiter);
790 sout << col->c_str();
791 }
792
793 if (!ignorenull && col->is_null())
794 {
795 skip++;
796 break;
797 }
798
799 switch (typ[idx])
800 {
801 case 'd':
802 buf[idx] = time_t((mysqlpp::DateTime)(*col));
803 break;
804
805 case 'D':
806 buf[idx] = time_t((mysqlpp::Date)(*col));
807 break;
808
809 case 'T':
810 buf[idx] = time_t((mysqlpp::Time)(*col));
811 break;
812
813 case 'V':
814 case 'C':
815 case '-':
816 case '@':
817 break;
818
819 default:
820 buf[idx] = atof(col->c_str());
821 }
822 }
823
824 if (idx==row.size())
825 {
826 if (!nofill)
827 ttree->Fill();
828
829 if (display)
830 cout << sout.str() << endl;
831 if (!write.empty())
832 fout << sout.str() << '\n';
833 }
834
835 row = res.fetch_row();
836
837
838 } while (row);
839
840 // -------------------------------------------------------------------------
841
842 if (display)
843 cout << '\n' << endl;
844
845 if (verbose>0)
846 {
847 cout << count << " rows fetched." << endl;
848 if (skip>0)
849 cout << skip << " rows skipped due to NULL field." << endl;
850
851 cout << ttree->GetEntries() << " rows filled into tree." << endl;
852 }
853
854 ttree->Write();
855 tfile.Close();
856
857 if (verbose>0)
858 {
859 const auto sec = Time().UnixTime()-start.UnixTime();
860
861 cout << Tools::Scientific(tfile.GetSize()) << "B written to disk.\n";
862 cout << "File closed.\n";
863 cout << "Execution time: " << sec << "s ";
864 cout << "(" << Tools::Fractional(sec/count) << "s/row)\n";
865 cout << "--------------------------------------------------------------" << endl;
866
867 try
868 {
869 const auto resw =
870 connection.query("SHOW WARNINGS").store();
871
872 if (resw.num_rows()>0)
873 cout << "\n" << resw.num_rows() << " Warning(s) issued:\n\n";
874
875 for (size_t i=0; i<resw.num_rows(); i++)
876 {
877 const mysqlpp::Row &roww = resw[i];
878
879 cout << roww["Level"] << '[' << roww["Code"] << "]: ";
880 cout << roww["Message"] << '\n';
881 }
882 cout << endl;
883
884 }
885 catch (const exception &e)
886 {
887 cerr << "\nSHOW WARNINGS\n\n";
888 cerr << "SQL query failed:\n" << e.what() << endl;
889 return 6;
890 }
891 }
892
893 if (profiling)
894 {
895 try
896 {
897 const auto N =
898 connection.query("SHOW PROFILES").store().num_rows();
899
900 const auto resp =
901 connection.query("SHOW PROFILE ALL FOR QUERY "+to_string(verbose?N-1:N)).store();
902
903 cout << '\n';
904 cout << left;
905 cout << setw(26) << "Status" << ' ';
906 cout << right;
907 cout << setw(11) << "Duration" << ' ';
908 cout << setw(11) << "CPU User" << ' ';
909 cout << setw(11) << "CPU System" << '\n';
910 cout << "--------------------------------------------------------------\n";
911 for (size_t i=0; i<resp.num_rows(); i++)
912 {
913 const mysqlpp::Row &rowp = resp[i];
914
915 cout << left;
916 cout << setw(26) << rowp["Status"] << ' ';
917 cout << right;
918 cout << setw(11) << rowp["Duration"] << ' ';
919 cout << setw(11) << rowp["CPU_user"] << ' ';
920 cout << setw(11) << rowp["CPU_system"] << '\n';
921 }
922 cout << "--------------------------------------------------------------\n";
923 cout << endl;
924 }
925 catch (const exception &e)
926 {
927 cerr << "\nSHOW PROFILE ALL\n\n";
928 cerr << "SQL query failed:\n" << e.what() << '\n' <<endl;
929 return 11;
930 }
931 }
932
933 return 0;
934}
Note: See TracBrowser for help on using the repository browser.